text
stringlengths 180
608k
|
---|
[Question]
[
There are [several questions regarding this game](https://codegolf.stackexchange.com/search?q=rock%20paper%20scissors), even a [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") contest [here](https://codegolf.stackexchange.com/q/35079/70347). But I think all those challenges and contests need a way to automatically determine the winner of a game. So:
**Challenge**
Given two inputs in the range `["rock", "paper", "scissors", "lizard", "spock"]` representing the selections for player 1 and player 2, determine the winner of the match.
**Rules**
```
[Winner] [action] [loser]
-----------------------------
scissors cut paper
paper covers rock
rock crushes lizard
lizard poisons spock
spock smashes scissors
scissors decapitates lizard
lizard eats paper
paper disproves spock
spock vaporizes rock
rock crushes scissors
```
**Restrictions**
* Input will be a pair of strings in the given range (no other strings can be used). You can use arrays of chars if you want, as long as they represent any of the mentioned values.
* You can choose whether to use lowercase, uppercase (`"ROCK"`) or camel case (`"Rock"`) for the input strings, as long as the chosen case is the same for all inputs.
* Output will be a trio of values that determine the winner, which can be anything you want as long as the answers are consistent. Example: `1` if the first input wins, `2` if the second input wins, `0` if there is a tie. Or maybe `A` if the first input wins, `B` if the second input wins, `<empty string>` if there is a tie.
**Goal**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/method/function/lambda for each language win!
**Tests**
```
[Input 1] [Input 2] [Output: 1/2/0]
-----------------------------------
rock paper 2
rock scissors 1
lizard spock 1
spock rock 1
spock paper 2
rock rock 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~68~~ ~~50~~ 48 bytes
EDIT: Thanks to 3 tricks from Neil, and 2 from Mr. Xcoder
Each input string has a distinct fourth character, so I'm using that to distinguish them. If you arrange the elements in the cycle (scissors, paper, rock, lizard, spock), then each element beats the element directly after it and the element 3 spots to the right, cyclically. So we subtract the inputs' positions in the cycle. If that number is 0, it's a tie. If it's 1 or 3, it's a win for the first player. In my original solution, the cycle difference would index into the string "210100" to distinguish the results of the game. Neil somehow figured out this can be accomplished without indexing by adding 7 and taking the modulus by 3. Edit: Originally I used the second character to identify the string, but if you use the fourth and reverse the cycle, you get cake. And we could all use more cake.
```
lambda x,y,z="cake".find:(7+z(y[3])-z(x[3]))%5%3
```
[Try it online!](https://tio.run/##NYvRCoMgGIWv6yl@hEDJ7SbGIOhJnBdmxv5qKupF9fLOBrv6zvk4xx/p7WyXw/DKm/qMk4KdH/wciFarIfcZ7dTTZ3vSQ3SS3U66X2TNo@myHgSJGmN0IRJOvPImFAan14INTxWmEqK/hKxnFwABLei@rq6y/EvlA9pEEVoQBDYXTYTkoHxhNCrFX0pYLJEiUOQLk2W7sPwF "Python 3 – Try It Online")
Older version:
```
lambda x,y,z="caoip".index:(7+z(y[1])-z(x[1]))%5%3
```
[Try it online!](https://tio.run/##NYxBCsIwFETX7SlCoJBiFFREKPQkMYuYRvy1NuH/LNpcPiYLV2/ewEzY49uvl4zjIy/m@5wM2@Qu08it8RD4CdbJbYO4H5LY1Vn3xyS2yr67dddsR8XJApFH4pIHExwWorefggWSwakECrXQ7csjAwYrs0PbVJn/0gSENTKQii@eHLHoy@7pTKy/ERxxrVCAnHst5/wD "Python 2 – Try It Online")
Original version:
```
b="caoip"
def r(x,y):return"210100"[(b.index(y[1])-b.index(x[1]))%5]
```
[Try it online!](https://tio.run/##ZY/PasMwDMbPzVMIwcCm2Ug6einkSYwPjqNu6oJtZBeSvXzmlO6ynT7pJ336k9byGcP7to0Dehc5YTPRFUQt7aovQuUuAU9913cdGjW@cZhoUavprX79zZY90y9nu/nBYPacc5SMLSaXSKpK9F9VZv52MtUgpx3Y5hoFGDiAuPBBqmvP@tIcdnr7Rw9C@T4XGOpt3rBtvblZXXkSDuWB4AgKoTBlQOD6xNMxAJ4QaM6010dy5W8D9s86whxz9ZcIqHUd@Niy/QA "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 56 bytes
Takes input in currying syntax `(a)(b)`. Returns `0` if A wins, `1` if B wins, or `false` for a tie.
```
a=>b=>a!=b&&a>b^614>>((g=s=>parseInt(s,31)%9)(a)^g(b))&1
```
### Demo
```
let f =
a=>b=>a!=b&&a>b^614>>((g=s=>parseInt(s,31)%9)(a)^g(b))&1
console.log('[Tie]');
console.log(f("paper" )("paper" ))
console.log('[A wins]');
console.log(f("scissors")("paper" ))
console.log(f("paper" )("rock" ))
console.log(f("rock" )("lizard" ))
console.log(f("lizard" )("spock" ))
console.log(f("spock" )("scissors"))
console.log(f("scissors")("lizard" ))
console.log(f("lizard" )("paper" ))
console.log(f("paper" )("spock" ))
console.log(f("spock" )("rock" ))
console.log(f("rock" )("scissors"))
console.log('[B wins]');
console.log(f("paper" )("scissors"))
console.log(f("rock" )("paper" ))
console.log(f("lizard" )("rock" ))
console.log(f("spock" )("lizard" ))
console.log(f("scissors")("spock" ))
console.log(f("lizard" )("scissors"))
console.log(f("paper" )("lizard" ))
console.log(f("spock" )("paper" ))
console.log(f("rock" )("spock" ))
console.log(f("scissors")("rock" ))
```
### How?
We define the hash function **H()** as:
```
H = s => parseInt(s, 31) % 9
```
This gives:
```
s | H(s)
-----------+-----
"rock" | 2
"paper" | 8
"scissors" | 1
"lizard" | 3
"spock" | 4
```
Given two inputs **a** and **b**, we consider the following statements:
1. do we have **a > b**? (in lexicographical order)
2. does **b** win the game?
3. what's the value of **N = H(a) XOR H(b)**?
From (1) and (2), we deduce whether the result of **a > b** should be inverted to get the correct winner and we store this flag in the **N-th** bit of a lookup bitmask.
```
a | H(a) | b | H(b) | N | a > b | b wins | invert
---------+------+----------+------+----+-------+--------+-------
rock | 2 | paper | 8 | 10 | Yes | Yes | No
rock | 2 | scissors | 1 | 3 | No | No | No
rock | 2 | lizard | 3 | 1 | Yes | No | Yes
rock | 2 | spock | 4 | 6 | No | Yes | Yes
paper | 8 | rock | 2 | 10 | No | No | No
paper | 8 | scissors | 1 | 9 | No | Yes | Yes
paper | 8 | lizard | 3 | 11 | Yes | Yes | No
paper | 8 | spock | 4 | 12 | No | No | No
scissors | 1 | rock | 2 | 3 | Yes | Yes | No
scissors | 1 | paper | 8 | 9 | Yes | No | Yes
scissors | 1 | lizard | 3 | 2 | Yes | No | Yes
scissors | 1 | spock | 4 | 5 | No | Yes | Yes
lizard | 3 | rock | 2 | 1 | No | Yes | Yes
lizard | 3 | paper | 8 | 11 | No | No | No
lizard | 3 | scissors | 1 | 2 | No | Yes | Yes
lizard | 3 | spock | 4 | 7 | No | No | No
spock | 4 | rock | 2 | 6 | Yes | No | Yes
spock | 4 | paper | 8 | 12 | Yes | Yes | No
spock | 4 | scissors | 1 | 5 | Yes | No | Yes
spock | 4 | lizard | 3 | 7 | Yes | Yes | No
```
Hence the bits:
```
bit | value
----+-----------
0 | 0 (unused)
1 | 1
2 | 1
3 | 0
4 | 0 (unused)
5 | 1
6 | 1
7 | 0
8 | 0 (unused)
9 | 1
10 | 0
11 | 0
12 | 0
```
Reading this from bottom to top and ignoring leading zeros, this gives **1001100110**, or **614** in decimal.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
```
ε'³²s3èk}Æ7+5%3%
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3Fb1Q5sPbSo2Prwiu/Zwm7m2qaqx6v//0epF@cnZ6jrqBYkFqUXqsQA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##MzBNTDJM/V9zeHFZ5f9zW9UPbT60qdj48Irs2sNt5tqmqsaq/5WSUhNLihVy8otTi@NL8hVKMlOLlZSLD6@oTDi6QOnwfgUwUtL5X5SfnM1VkFiQWsRVnJxZXJxfVMyVk1mVWJTCVVwAlAMA)
**Explanation**
Uses the very nice `cake`-trick from [user507295](https://codegolf.stackexchange.com/a/149211/47066)
```
ε } # apply to each in the input pair
s3è # get the 4th letter
'³² k # get its cake-index
Æ # reduce by subtraction
7+ # add 7
5%3% # mod by 5 and then 3
```
[Answer]
## JavaScript (ES6), ~~63~~ ~~54~~ ~~53~~ 49 bytes
```
f=
(l,r,g=s=>"cake".search(s[3]))=>(7+g(r)-g(l))%5%3
```
```
<div onchange=o.textContent=`RLT`[f(a.selectedOptions[0].value,b.selectedOptions[0].value)]>L: <select id=a><option>Rock<option>Paper<option>Scissors<option>Lizard<option>Spock</select> R: <select id=b><option>Rock<option>Paper<option>Scissors<option>Lizard<option>Spock</select> Winner: <span id=o>T
```
Port of my golf to @WhatToDo's answer. Note: the snippet decodes the numeric result into something slightly less unreadable. Edit: Saved 1 byte thanks to @Arnauld. Saved 4 bytes thanks to @ovs.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 36 bytes
```
->a,b{(2+a.sum%88%6-b.sum%88%6)%5%3}
```
Returns `0` if 1st player wins, `1` if 2nd player wins, and `2` for a draw.
Based on user507295's answer but uses a mathematical formula to perform the hash. `a.sum` is the sum of all ASCII codes of the string `a`, mod `1<<16` and is intended as a rudimentary checksum. The hash was found using the following code:
```
1.upto(99){|j|p j,["scissors","paper","rock","lizard","spock"].map{|i|i.sum%j%6}}
```
This produced two values of `j` that gave a suitable hash for lowercase letters, namely 88 and 80, both of which gave the descending sequence `[3,2,1,0,4]` (or `[4,3,2,1,0]` if spock is cycled round to the beginning.)
As explained in other answers, a hash which gives a constant difference modulo 5 for consecutive elements in the above sequence is needed to make the `(h[a]-h[b])%5`formula work. Each element beats the element 1 or 3 places to the right and loses to the element 2 or 4 places to the right.
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6law0g7Ua@4NFfVwkLVTDcJztRUNVU1rv1foJAWrVSUn5ytpKNUkFiQWqQUqwACXMgSxcmZxcX5RcUgOYhETmZVYlEKSKoApARZD0REB6IXIoEmg9MeuJb/AA "Ruby – Try It Online")
[Answer]
## C, 53bytes
```
a="FÈ..J..ÁE";
z=*++y==*++x?0:a[*y&47>>1]>>*++x&7&1+1;
```
I've treated this problem as a state machine, of which there are 25 states as defined by the two, five state inputs.
By defining the results of the states within an an array of bits. I look the results up within by using unique markers within the inputs.
As noted in other solutions, characters 2, 3 and 4 are unique between the possible inputs. I have concentrated use on characters 2 and 3 which I use to select the appropriate bit within my answer array.
Within Character 2, bits 1 thru 4 clearly identify the input. By masking these bits and shifting appropriately [that's the "\*y&47>>1"], the input can be noted as 0, 1, 4, 7 or 8. Hence my answer string has 9 characters. (separated interesting bits)
```
character 2:
a 61 011 0000 1
c 63 011 0001 1
i 69 011 0100 1
p 70 011 1000 0
o 6f 011 0111 1
```
Within character 3, bits 0, 1 and 2 clearly identify the input. By Masking these bits (shifting not required) [that's the "\*x&7"], the input can be noted as 0, 1, 2, 3 or 7
. (separated interesting bits)
```
character 3
p 70 01110 000
i 69 01101 001
z 7a 01111 010
o 6f 01101 111
c 63 01100 011
```
The answer string can then be calculated by simply filling in the bits for the appropriate characters.
```
0th char represents X=paper
1st char represents X=scissors
4th char represents X=Lizard
7th char represents X=Rock
8th char represents X=Spock
0th bit represents Y=Paper
1st bit represents Y=Scissors
2nd bit represents Y=Lizard
3rd bit represents Y=Rock
7th bit represents Y=Spock
```
So, set bit in char where Y wins
```
char 7654 3210 in hex in ascii
0 0100 0110 46 F
1 1100 1000 c8 È
2 0100 0000 d/c .
3 0100 0000 d/c .
4 0100 1010 4a J
5 0100 0000 d/c .
6 0100 0000 d/c .
7 1100 0001 c1 Á
8 0100 0101 45 E
```
Then the logic is simply: if second char is same then draw, otherwise, get ascii char based on y's second character and shift bits by x's third character and add one. This makes the answers 0 for draw, 1 for x win and 2 for y win.
[Answer]
# Clojure, ~~130~~ 118 bytes
-12 bytes by getting rid of my weird usage of `comp`.
```
(fn[& m](let[[p q](map #(apply +(map int(take 2 %)))m)d(- p q)](cond(= d 0)0(#{5 -16 12 -14 13 1 4 -18 2 11}d)1 1 2)))
```
I thought I was being clever, but this ended up being naïve compared to some other answers, and *much* longer.
Takes the first 2 letters of each move string, gets the char codes, and sums them. It then subtracts the sums to get `d`. If `d` is 0, its a tie (0), if it's in the set of `#{5 -16 12 -14 13 1 4 -18 2 11}`, p1 wins (1), else, p2 wins (2).
```
(defn decide [& moves] ; Using varargs so I don't need to duplicate the steps.
; Pop the first 2 chars of each string, convert them to their ASCII code, and sum them.
(let [[p1 p2] (map #(apply + (map int (take 2 %))) moves)
d (- p1 p2)]
(cond
(= d 0) ; A tie
0
(#{5 -16 12 -14 13
1 4 -18 2 11} d) ; P1 Wins
1
:else ; P2 Wins
2)))
```
To get the "magic numbers" that define if P1 wins, I ran
```
(let [ms ["rock", "paper", "scissors", "lizard", "spock"]]
(for [p1 ms
p2 ms]
; Same as above
(let [[p q] (map #(apply + (map int (take 2 %))) [p1 p2])
d (- p q)]
[p1 p2 d])))
```
Which generates a list of `d` values for each possible scenario:
```
(["rock" "rock" 0]
["rock" "paper" 16]
["rock" "scissors" 11]
["rock" "lizard" 12]
["rock" "spock" -2]
["paper" "rock" -16]
["paper" "paper" 0]
["paper" "scissors" -5]
["paper" "lizard" -4]
["paper" "spock" -18]
["scissors" "rock" -11]
["scissors" "paper" 5]
["scissors" "scissors" 0]
["scissors" "lizard" 1]
["scissors" "spock" -13]
["lizard" "rock" -12]
["lizard" "paper" 4]
["lizard" "scissors" -1]
["lizard" "lizard" 0]
["lizard" "spock" -14]
["spock" "rock" 2]
["spock" "paper" 18]
["spock" "scissors" 13]
["spock" "lizard" 14]
["spock" "spock" 0])
```
Then I compared the win chart against this output. Luckily there weren't any "collisions" other than 0.
] |
[Question]
[
## How strings are twisted
The twisting algorithm is very simple. Each column is shifted down by its index (col 0 moves down 0, col 1 moves 1, ...). The column shift wraps to the top. It works like this:
```
aaaa
bbbb
cccc
```
Becomes:
```
a
ba
cba
----
cba
cb
c
```
With everything under the line wrapping to the top. Real example:
```
Original:
\\\\\\\\\\\\
............
............
............
Twisted:
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\
```
## Input
Input is either an array of strings, or a multi-line string. All lines have the same length.
## Output
The twisted string, multi-line output to std-out (or closest alternative).
## Examples:
(`>` denotes input, trailing space is important)
```
>Hello, world!
>I am another
>string to be
>twisted!
Hwrmoe oo br!
Ieii ,dttr e
s lsna !ohl
ttaltgnw ed
>\\\\\\\\\\\\
>............
>............
>............
\...\...\...
.\...\...\..
..\...\...\.
...\...\...\
>abcdefg
>.......
a.c.e.g
.b.d.f.
>abcdefghij
>..........
>..........
a..d..g..j
.b..e..h..
..c..f..i.
>\\\\.....././
>...../.......
>........././.
>..../.^\\....
\.........../
.\....^..../.
..\../.\../..
...\/...\/...
>cdeab
>deabc
>eabcd
>abcde
cbbbb
ddccc
eeedd
aaaae
>aeimquy37
>bfjnrvz48
>cgkosw159
>dhlptx260
ahknqx147
beloru258
cfipsvy69
dgjmtwz30
>abcdefghi
>jklmnopqr
>stuvwxyz1
>234567890
a3ume7yqi
jb4vnf8zr
skc5wog91
2tld6xph0
```
[Answer]
# Pyth, 11
```
jC.>R~hZC.z
```
[Try it here](http://pyth.herokuapp.com/?code=jC.%3ER~hZC.z&input=%5C%5C%5C%5C......%2F.%2F%0A.....%2F.......%0A.........%2F.%2F.%0A....%2F.%5E%5C%5C....&debug=0)
```
jC.>R~hZC.z ## implicit: .z = list of input split by lines
C.z ## transpose .z to get columns
.>R~hZ ## shift each column by it's index
## equivalent to .e.>bk
jC ## transpose back and join by newlines
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 7 bytes
```
⊖⊖⊖⍨⍬⍋⍉
```
Requires `⎕io←0`
[Try it online!](https://tio.run/##hVBLboMwEN3nFM7KmxTIP7lLFclgAyYGE@OEkANEaiuqdtGeoYueyheh49AooEbqyPKb5zfzPDbJxQOtiJBRY14/uDTnN68JYTfPn7@r/jL1t6lfTP3UNCEy53ccMyHkCJVSCTrECHNEUkQyqWOmEPBCK55FSEvkM8t1yQvN6BDZwAOMB63PYyegzOnEP/TmQfyAsjC6FfzVYp70@vukP0576Drutci90wTylbvOpm3q@MClxAfdQgBogQJexumOx3i621fTJWh@mGTqcJqtIA@irSzK8XxtPWKR6@Nk4d17FujJVqSZzHfq8u37Q3msTmPIJ9PZfLFcrT38Aw "APL (Dyalog Unicode) – Try It Online")
`⍬⍋⍉` gets the range from 0 to the number of columns
`⊖` reverses vertically
`⊖⊖⍨⍬⍋⍉` rotate (vertically) the (vertically) reversed input by `0,1..`
`⊖` reverse that, and return it.
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~111~~ ~~101~~ ~~92~~ 87 bytes
Byte count assumes ISO 8859-1 encoding.
```
(?<=((.))*)(?=(?<1>.*¶)*.*(?<=(?=(?<-2>.)*(.))(?<-1>.+¶)*.*(.(?<=^(?<-1>¶?.+)*))*)).
$3
```
Woo, solved it in a single regex substitution. :) (Chances are, there's a shorter solution by using several, but where's the fun in that...)
[Try it online!](http://retina.tryitonline.net/#code=KD88PSgoLikpKikoPz0oPzwxPi4qwrYpKi4qKD88PSg_PSg_PC0yPi4pKiguKSkoPzwtMT4uK8K2KSouKiguKD88PV4oPzwtMT7Ctj8uKykqKSkqKSkuCiQz&input=SGVsbG8sIHdvcmxkIQpJIGFtIGFub3RoZXIgCnN0cmluZyB0byBiZSAKdHdpc3RlZCEgICAgIA&debug=on)
### Explanation
This requires some basic knowledge of [balancing groups](https://stackoverflow.com/a/17004406/1633117). In short, .NET's regex flavour allows you to capture multiple times with a single group, pushing all captures onto a stack. That stack can also be popped from, which allows us to use it for counting things inside the regex.
```
(?<=((.))*)
```
This pushes one capture onto both groups `1` and `2` for each character in front of the match (in the current line). That is, it counts the horizontal position of the match.
The rest is in a lookahead:
```
(?=(?<1>.*¶)*.* [...] )
```
We match each line and *also* push it onto group `1`, such that group `1` is now the sum of the horizontal and vertical position (where the latter is counted *from the bottom*). This essentially labels the diagonals of the grid with increasing values starting from the bottom left corner. That `.*` then just moves the engine's cursor to the end of the string.
We now switch into a lookbehind, which is matched from right to left in .NET:
```
(?<= [...] (.(?<=^(?<-1>¶?.+)*))*)
```
This will repeatedly pop exactly `H` captures from group `1` (where `H` is the height of the input). The purpose of that is to take the group modulo `H`. Afterwards, group `1` contains the row (counted from the bottom) from which to pick the new character in the current column.
```
(?=(?<-2>.)*(.))(?<-1>.+¶)*.*
```
Another lookbehind, again starting from the right. `(?<-1>.+¶)*.+` now uses group `1` to find the row from which to pick the new character and then the lookahead finds the correct column using group `2`.
The desired character is captured into group `3` and written back by the substitution.
[Answer]
## CJam, 13 bytes
```
qN/zee::m>zN*
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2Fzee%3A%3Am%3EzN*&input=Hello%2C%20world!%0AI%20am%20another%20%0Astring%20to%20be%20%0Atwisted!%20%20%20%20%20)
### Explanation
```
q e# Read all input.
N/ e# Split into lines.
z e# Transpose to get an array of columns.
ee e# Enumerate, pairing each column with its index.
::m> e# Map: fold: rotate (cyclically shifting each column by its index).
z e# Transpose again.
N* e# Join with linefeeds.
```
[Answer]
# TeaScript, 10 bytes
```
xHl@C(r╢tD
```
Thanks to TeaScript 3's extremely concise syntax, this is *really* short :D
Would be 1-byte shorter if Sigma loop weren't buggy
[Try it online](http://vihan.org/p/TeaScript/#?code=%22xHl@C(r))tD%22&inputs=%5B%22%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5C%5Cn............%5Cn............%5Cn............%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false%7D)
## Explanation
```
// Implicit, x = input
xH // Transpose input
l@ // Loop
C(r╢ // Cycle column by index
// `╢` exits loop
t // Transpose
D // Join on \n
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
yÈéY
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ecjpWQ&input=IlxcXFxcXFxcXFxcXAouLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uLiI)
[Answer]
# Python 3, 164 bytes
Not the best answer by a long shot, but the first in Python...
```
s=list(zip(*open(0).readlines()))[:-1]
r=[[s[i][(j-i)%len(s[i])] for j in range(len(s[i]))] for i in range(len(s))]
print('\n'.join([''.join(l) for l in zip(*r)]))
```
[Answer]
# MATLAB, ~~92~~ 36 bytes
```
s=bsxfun(@circshift,s,0:size(s,2)-1)
```
Assuming that the input string `s` is already in the form of a 2D char array/ matrix, e.g.
```
s = ['abcdefg';'.......'];
s = ['\\\\.....././';'...../.......';'........././.';'..../.^\\....'];
```
Explanation: iterate through the columns of the matrix. For each column perform a circular shift of its elements by the number of characters that equals the column index (-1 because of MATLAB indexing).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
iᵇ↻₎ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P/Ph1vZHbbsfNfU93Drh//9opcSkZCUdBSxU7P8oAA "Brachylog – Try It Online")
Gets input as an array of columns (which seems to be within the question's specifications).
`iᵇ` - For each element in the array, pair it with its (0-based) index
`ᵐ` - map this predicate to each element of the result:
`↻₎` - permute (the column) circularly by the amount specified as the last element (the index)
Easily extended to a version that accepts a single multiline string:
### 13 bytes
```
ṇẹ\iᵇ↻₎ᵐ\cᵐ~ṇ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9oe7dsZkPtza/qht96OmvodbJ8QkA4k6oMz//0qJSckpqWnpGZlcWdk5uXn5BYVFXMUlpWXlFZVVhlxGxiamZuYWlgZK/6MA "Brachylog – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 96 bytes
```
$\:0{h_.|[M:I]hh:I{bh0,?h.|[C:I]h$)D,I-1=:Dr:2&.}C,I+1=J,Mb:J:1&:[C]rc.}$\{hA,[A]:"~s
"w,?b:3&;}
```
This expects a list of character codes strings as input and no output, e.g. `brachylog_main([`aaaa`,`bbbb`,`cccc`],_).`
That's one ridiculously long answer, and there's probably a much shorter way to do it.
### Explanation
```
§ Main Predicate
$\:0{}$\{} § Create a list containing the transposed input and 0
§ Call sub-predicate 1 with this list as input
§ Transpose its output and pass it as input to
§ sub-predicate 3
§ Sub-predicate 1
h_. § If the matrix is empty, output is empty list
| § Else
[M:I]hh:I{}C, § Input is [M,I], call sub-predicate 2 with the first
§ line of M and I as input. Its output is C.
I+1=J,Mb:J:1& § Call sub-predicate 1 with M minus the first line
§ and I+1 as input
:[C]rc. § Its output is appended after C, which is then
§ unified with the output of sub-predicate 1.
§ Sub-predicate 2
bh0,?h. § If the second element of the input list is 0,
§ output is the first element of the input
| § Else
[C:I] § Input is [C,I]
h$)D, § Perform a circular permutation of C from left to
§ right (e.g. [a,b,c] => [c,a,b]) and unify it with D
I-1=:Dr:2&. § Call sub-predicate 2 with D and I-1 as input, unify
§ its output with sub-predicate 2's output
§ Sub-predicate 3
hA,[A]:"~s\n"w, § Write the first line of the input as a char codes
§ string followed by a new line
?b:3&; § Call sub-predicate 3 with input minus the first
§ line. If it fails (empty input), terminate
```
[Answer]
# JavaScript, ~~92~~ 89 bytes
3 bytes off thanks [@Neil](https://codegolf.stackexchange.com/users/17602/neil).
```
s=>(z=s.split`
`).map((m,i)=>m.replace(/./g,(n,j)=>z[((l=z.length)*j+i-j)%l][j])).join`
`
```
```
f=s=>
(z=s.split`\n`).map((m,i)=>
m.replace(/./g,(n,j)=>
z[((l=z.length)*j+i-j)%l][j]
)
).join`\n`
Input.value = `abcdefghij
..........
..........`
```
```
textarea{display:block;width:250px;height:75px;}
```
```
<textarea id='Input'></textarea>
<button id='Run' onClick='Output.value=f(Input.value);'>Run</button>
<textarea id='Output'></textarea>
```
[Answer]
# Python 2, 115 bytes
```
lambda s:'\n'.join("".join(s)for s in zip(*[k[-i%len(k):]+k[:-i%len(k)]for i,k in enumerate(zip(*s.split('\n')))]))
```
Thanks to the wonder of `zip` managed to get this down to one line. See it in action [here](http://ideone.com/MOsH5r).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 18 ~~21~~ bytes
```
Zy2):"G@Z)@qYS]N$h
```
Input is of the form
```
['Hello, world!'; 'I am another '; 'string to be '; 'twisted!']
```
[**Try it online!**](http://matl.tryitonline.net/#code=WnkyKToiR0BaKUBxWVNdTiRo&input=WydIZWxsbywgd29ybGQhJzsgJ0kgYW0gYW5vdGhlciAnOyAnc3RyaW5nIHRvIGJlICc7ICd0d2lzdGVkISdd)
**How it works**:
```
Zy % implicitly take input: 2D char array. Get its size
2) % second element from size vector: number of columns, say n
: % create vector [1,2,...,n]
" % for each element k in that vector
G % push input
@ % push k
Z) % k-th column from input
@qYS % circularly shift k-1 positions
] % end for loop
N$h % concatenate all stack contents horizontally
% implicitly display
```
[Answer]
# F#, 105 bytes
My first stab at it (only a `\n` character is required):
```
let m x y=(x%y+y)%y
let f(a:string[])=Array.mapi(fun i x->String.mapi(fun j _->a.[m(i-j)a.Length].[j])x)a
```
Usage:
```
f [| @"\\\\\\\\\\\\"
"............"
"............"
"............" |]
```
[Answer]
# JavaScript (ES6), 73 bytes
```
t=>t.replace(/./g,(_,i)=>t[(i+s*l-i%l*l)%s],l=t.search`
`+1,s=t.length+1)
```
## Explanation
```
t=>
t.replace(/./g,(_,i)=> // replace each character at index i
t[ // get the character at index:
(i // start at i
+s*l // add s*l to ensure the result is always positive for %s
-i%l*l // move the index upwards the num of chars from start of the line
)%s // shift the index into the the range of s
],
l=t.search`
`+1, // l = line length
s=t.length+1 // s = input grid length (+1 for the missing newline at the end)
)
```
## Test
```
var solution = t=>t.replace(/./g,(_,i)=>t[(i+s*l-i%l*l)%s],l=t.search`
`+1,s=t.length+1)
```
```
<textarea id="input" rows="5" cols="40">\\\\.....././
...../.......
........././.
..../.^\\....</textarea><br>
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```
[Answer]
# Japt, 29 bytes
```
Uy £XsV=(Y*Xl -Y %Xl)+X¯V}R y
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VXkgo1hzVj0oWSpYbCAtWSAlWGwpK1ivVn1SIHk=&input=IlxcXFxcXFxcXFxcXAouLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uLiI=)
### How it works
```
Uy // Transpose rows and columns in the input string.
£ }R // Map each item X and index Y in the result, split at newlines, to:
Y*Xl -Y // Take Y times X.length and subtract Y.
%Xl) // Modulate the result by X.length.
XsV= // Set V to the result of this, and slice off the first V chars of X.
+X¯V // Concatenate this with the first V chars of X.
y // Transpose the result again.
// Implicit: output last expression
```
[Answer]
# Haskell, 81 bytes
```
let t=transpose in t.snd.mapAccumR(\c l -> 1+c,take(length l)(drop c$cycle l))0.t
```
reimplementation of the CJam example, though the reverse, map and enumerate is part of the mapAccumR, the snd removes the accumulator since we don't need it anymore, the reversal is just a side effect of the right fold.
[Answer]
## Haskell, 65 bytes
```
g l@("":_)=l;g l|t<-tail<$>l=zipWith(:)(head<$>l)$g$last t:init t
```
Usage example: `g ["1111","2222","3333"]` -> `["1321","2132","3213"]`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
Tzṙm→İ-T'
```
[Try it online!](https://tio.run/##yygtzv7/P6Tq4c6ZuY/aJh3ZoBuirnBo2////z1Sc3LydRTK84tyUhS5PBUScxUS8/JLMlKLFLiKS4oy89IVSvIVklIVuErKM4tLUlMUAQ "Husk – Try It Online")
(there's a space at the end.)
## Explanation
```
Tzṙm→İ-T'
T' transpose, padding with spaces
zṙ zip and rotate each column by
İ- negative integers
m→ each incremented
T transposed back
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
"@X@qYS&h
```
[Try it online!](https://tio.run/##y00syfn/X8khwqEwMlgt4///aHWP1JycfB2F8vyinBRFdWsFdU@FxFyFxLz8kozUIgWQQHFJUWZeukJJvkJSKligpDyzuCQVqDoWAA "MATL – Try It Online")
Pretty similar in core to Luis Mendo's [existing MATL answer](https://codegolf.stackexchange.com/a/70708/8774), but shorter by using features that were probably not in the language at that point: 1. `"` iterates through a matrix's columns automatically now, so no costly business of constructing column indices and indexing into them (this is the biggie), 2. `&h` as a shorthand way of saying `N$h`, and 3. implicit loop end if `]` is not specified.
Alternately, for the same bytecount:
```
tsn:ql&YS
```
[Try it on MATL Online](https://matl.io/?code=tsn%3Aql%26YS&inputs=%5B%27Hello%2C+world%21%27%3B+%27I+am+another+%27%3B+%27string+to+be+%27%3B+%27twisted%21%27%5D&version=20.9.2)
```
&YS % circularly shift the matrix
l % across rows (i.e. shift each column) by the amounts
% given by this array:
tsn % duplicate input, get the sum of each column, get the
% number of elements in that (which is the number of columns)
:q % construct range 1 to ncols, then decrement to start at 0
% (implicit output)
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 114 bytes
Works in GCC under MinGW. TIO's GCC gets confused by using `strlen` in the init expression of the first for loop.
```
f(L,n)char**L;{for(int l=strlen(*L),i=0,j,c;i<n;i++)for(j=c=0;j<=l;j++,c=c?c-1:n-1)putchar(l^j?L[(c+i)%n][j]:10);}
```
[Try it online!](https://tio.run/##jZDRasMgFIavk6c4DQw06kjKrmqltxvkDbIMMmtaxeowjl6UPHsWl8F6M9jvld85fHqOZNL27jTPA2qow/Lch7Js@G3wAWkXwYoxBqscKhtMtaiooZLrveOaEJyajJCi4mYvLDeEUCnkQbJ651iNPz5j8iH7Zg5NiyTR@MF1rel2dYX5NCf/pdcO4fyWZ6kVyqjGWLcdCFhQVjwraz2Fqw/2uCloQi/QX6B3Pp5VgBUtX9TuBNHDu/pB8arHqI4bSCkmfu/f/vpf/8gqebzLv0h6J8uXM6DvQSg84QUtixhRwRgr0m2tbdfaNH8B "C (clang) – Try It Online")
] |
[Question]
[
Your challenge is to write a program that is a quine, meaning it prints out its own source code.
For at least one individual character, when it is removed from the program's source, a single different character is removed from the output.
By different, I mean that the character removed from the code is distinct from the character removed from the output - not just in a different place, but a different character altogether.
Your program, modified or unmodified, may output to stderr as long as it also outputs the correct text to stdout.
# Scoring
Your score is the number of character this *doesn't* work for, with lower being better.
For example, if the program `abc` is a quine in your language, and the program `ac` prints `ab`, your score is 2, because removing one of the chars works and removing the other two doesn't.
~~I have a 200-point bounty for anyone who gets score = 0. This may be increased, depending on how hard it appears to be.~~ Bounty has been awarded to Jo King's answer.
### ***IMPORTANT***
I updated the criterion to reflect the fact that scores can converge to 1 by adding a large amount of characters.
[Answer]
# [Backhand](https://github.com/GrayJoKing/Backhand), Score 0, 137 bytes
```
""###:::[[[:::::::::)))))))))888999***EEE666***333+++ssscccjjjlll222%%%]]]333***xxx(((sss~~~rrr~~~''' sss---***333aaa000~~~rrr:::rrrHHH
```
[Try it online!](https://tio.run/##lVhtb9s2EP5s/wrGWSbJtmLL2bJEqLu1RboU6NoBK7APrhvIMmMzkyWNklJlL/nr3ZEUxRfLKWYgjsR77ni8dzp/KLdZevbl@AhNqoJOViSd5GKt3ye7PKMlKh4K@UijdJ3t@v04iYoC/VZG8R@uF/Z7a3yLbm5ISsqbG7fAyS1b7LGH04KB0Bwtln2By7NcQSguK5oihTxlZA@RW20N4aTAaCr5q2LLBYxRWu0KLgbg5UOOXb6ASIESUpSM0LvNKIMhknJ0qG8V5TlO14zJAyjb5AC58PryzC@BsgUr3LxJS0xz0B/TbhOMUZytsTLELgIdwBCN1eRyVm4x1Zblep4RtgNQpnKJyYN39k8u/VllJVt7HYH2cnFNGFugPIBzeD@T77iOcVG82kYM9S5LFR9eVRtbGMUbsCVuseKkWVXmVfk@xcqVGSAazXN@PHCKH6BnKIO/aR0EU/iELJpAozUIOP1MSYndeEvdzLM8gCnNqDv4QAleozJDOQVrgBPvo4SsEXxXGLknaw9FBYrhJFEMKn5MByeZZ2j4IkmUhp@3JMGodYZwc7OhOhDTRIgoCXhEcJNT2CXd4F@FV1zCrTokzNZjYTC5sQlsA3WM8H0CJvpAKy0opJdHc4aB1XiLebowWKsyX@ThLMnSRT2ZKFLQ8zlKcOq28cK32gspE4J85BoA3wIwxEzJEfHly2dOsPQGX9qaQRB06uLr7/9rE9gBbBqa2/hNFALPsA3/Q6VDCwZOE7lulSmkFymB5REucBtcslRSUSbPrdJMeE6mh1rv957ISJ4MLaNIGtia4mjtBp4kZHTtxrxcxqJK@oGqqrFS8V21W2FNybqpKyK@anQ0Z7kKdQ2xdKw9lGYs3ZAzDWZn331//sPFpcO1eQDGmj3U8jzSAE3KwzqT1VqNK5QCGNzjCuFe/wD7QW26NGEy02EwRSNLdLfsfUPXQmHG@OAxrR3fCRET66fKiGljRFqlynytM1l6LPT4W2oRwOsp15WXL9eqPJ5F4Z2gm8SzUK05yBma5cP55Iz1lfEB7bgQTUXeP8KmkMTcCAMnRJ29Ra/PKmVEBEq5x@gt1HQKHP2mBsSW86JVDOaUe3AR@9RTkq5x3chtxHTq1lQCBRk4g7DNK17Avfa11feQcUTph0PwZox2UUryKolKkqWmHo@t/k2v02jfGGdbKNhYY1laTOEhpuVwZkG/dUK98Lf9@UiUDr3GynLXgjxFtPt6Tys5e4hDZ6VOaPdTiVYrizD0g6XJmBjnbbuNlhzWTq7BoOUL18oCexLcQFqWLnCtn2GMjKFMvYwVRgbJqywtaZag10n22RT5TIpsmlhgkp@bZIv6t6Sag4QfWHr/242zYZ@cdqiFMXC0t90vNn1m0u8Nur/H/7tNt/h/7FZT3CRgMSMxdhd@MA6WtmfuHJXK5jhsz7m9jh0OOrwAjb7KM5Q7WMw/OW1nk3WRB8NLOFC8JenGhN8cciZS4xG77/DebbvuHyuM2ucOXm1O0iQcGVnDWgfr65plrB3f7uG1fZ49wfjzU4zPn2C8eopxPrc5ua1fwL1hu8NQ3c0mM5ycjHwRM9F4ZZStsVnCVLebNMHAW7ozmTj8BcgRI0/N68iLssS7vBRXkjW5J3AfWz2gvzDNBlabwXBHcYuSuitvFI/YQ7R39sV@TeMK7qX68gBwFLQ2efPeZCH7LO00ZEnPnM47kIZ40ymsmSltce@djkseM8DhIPiYOqGYbCzCtWNO3@pS5/HxUKagxrLVWL6mhSZDDXx8pBAzn3C7uDDsYHCMNnCfYuHSSAZ6I7mhwiw6gFsoP0VNSlaMc5ptaLSbDwaDL4PB8fFxGIaLBfTE5uPJz8XFxeXl5XA4vLq6Oj8/h4ezs7PRaFQURRzHd3d3SZLMZrOTk5PlcgkkANR17bouAB4fHyml8O04DkIIVnzfFxKiKIJ7twDAdvB9fX0NmgwWAW/LBOK@80eNRnGvf0zaXwa4bcSUTk7ZRAzmIM2Y9eU/ "Python 3 – Try It Online")
I've included the interpreter here because the version on TIO is a bit out of date (in this case missing the instructions `E`qual and `s`kip). `E` could be compensated for with `-!`, but you'd need to do a lot of fiddling around with `j`ump to replace `s`kip.
This code outputs itself if no changes are made, the original code missing a trailing `H` if any character other than `H` is removed, and if the `H` is removed, it removes the leading `"` instead.
### Explanation
Basically, each instruction is duplicated three times (except for the leading `"`, which is only doubled). This is used as a form of radiation hardening, so that even if one instruction is removed, it can still regenerate it from the others. Backhand is especially good at this, since by default it executes every third instruction. Removing the duplicates, we get:
```
"#:[:::)))89*E6*3+scjl2%]3*x(s~r~' s-*3a0~r:rH
" Push the rest of the code, forwards then backwards
# No-op
:[ Dupe the # and decrement it to get "
Start loop
::: Make three copies of the top of stack
))) Push those to the other stack
89*E Is the value a `H`?
3+scj If not, jump back to the start of the loop
End loop
l2%]3* If the length of the pushed code is odd (i.e. a character is missing)
x( Flip to the other stack
s~ and pop the H if so
r~ Reverse the stack and pop the extra "
' s Skip forwards 32 spaces, i.e. the instruction three from the end
This is the H if all Hs are still present, so it halts and outputs
:r Otherwise, reverse and duplicate the H
~r And pop the "
s-*3a0 And skip back to the H to halt and output
```
[Answer]
# [Python 2](https://docs.python.org/2/), 338 bytes, score = ~~16~~ 11
```
exec"aabb==''''''iimmppoorrtt ssyyss;;dd==cchhrr((3399))**33;;ssyyss..ssttddoouutt..wwrriittee((''eexxeecc''''%%cc''%%3344++''''..jjooiinn((ii**22ffoorr ii iinn''aabb==''++dd++aabb++dd++'';;aa==aabb[[::4466]]++aabb[[5533::]];;eexxeecc aa''))++''bb%%cc[[::::22]]''%%3344))'''''';;aa==aabb[[::4466]]++aabb[[5533::]];;eexxeecc aab"[::2]
```
[Try it online!](https://tio.run/##lVBbqsMgEN2KFIIawQ9NC1VcSfDDV4mFxqCWJqvPvTZkAR0Y5nXOzGGWrU5pZvse1uAuxlirFPxajK/XsqSUc60AlLJtpUjpvVLOTVPOCHF@v2Pc95xLecwpLaVW71N6v2ul9PPJOcZaQ0AIwhDWNQTn2vaua7HrOB8GQlqH0uczpRjnGaEY@56xx6NdByDG5vMM4amPEO8JadWRQSilMUq1zjgKMQy3m9YHYhyvV86F0FrKUwEAxkCIcWNa27Q0lhCMaX2qwvj4w@@b7eUfyPS@/wE "Python 2 – Try It Online")
when any of the char of inside the string is removed, then the first `"` is removed
## How it works :
* for a string like `"aabbccddee"`, when we take one char every two char, we get `"abcde"` even if it has a missing char.
I then applied this principle on the quine `a="print('a=%r;exec(a)'%a)";exec(a)`
* if the code has a deletion: the end of the string will be `exec a` instead of `exec ab` which result of the deletion of the first `"`.
Note: I could reduce the number of byte by using `input` instead of `sys.stdout.write` to print without a newline but it would throws an error (still valid but uglyer)
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 187 bytes, score = 16
```
exec(a:="pprriinntt((eenndd==''eexxeecc((aa::==''++((''%%rr[[::::22]]))''%%((''''..jjooiinn((ii**22ffoorr ii iinn aa iiff''##''!!==ii))++''##''))))[[aa[[--11]]====''))''::]]))#"[::2])
```
[Try it online!](https://tio.run/##JY3RCoQgEEV/xYqYMSnIfVkEv0R8kBpZe1CRHtqvbxv2wsCd83BP/Z6fkl/v2u6bLtowGNvX2lpKOZ8nIlHO@24tANF1EW0bYgjGMFEKEWAcW3POPNHaeymZMAdYluMohZcQU5omrWMspTUhUuLLWYgQuMUIMAwAXWdtSlIq9f/lE@dCcG6e19V7a9nLDmPYNfSPWHt53z8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), score: 206 - 178 = 28
If you remove any single character in the two long strings, the first `"` in the output is omitted.
```
a="print('a=%r,%r;exec max(a,key=len)'%((max(a,key=len),)*2)).replace(chr(34),'',a[0]!=a[1])","print('a=%r,%r;exec max(a,key=len)'%((max(a,key=len),)*2)).replace(chr(34),'',a[0]!=a[1])";exec max(a,key=len)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9FWqaAoM69EQz3RVrVIR7XIOrUiNVkhN7FCI1EnO7XSNic1T1NdVUMDVURHU8tIU1OvKLUgJzE5VSM5o0jD2ERTR11dJzHaIFbRNjHaMFZTSYeGZmMzi@v/fwA "Python 2 – Try It Online")
Based on this [quine](https://codegolf.stackexchange.com/a/51011/64121), this executes the longer, and therefore unmodified, string of `a`.
[Answer]
# [R](https://www.r-project.org/), 58 bytes; score = 58-2 = 56
```
'->a;cat(sQuote(a),a,2*11)#' ->a;cat(sQuote(a),a,2*11)# 22
```
[Try it online!](https://tio.run/##K/r/X13XLtE6ObFEoziwNL8kVSNRUydRx0jL0FBTWV0Bt5yCkdH//wA "R – Try It Online")
Pretty boring, but now scores better than my original version (below).
Either of the `1` characters near the end of the code can be deleted, resulting in deletion of one of teh two `2` characters at the end of the output.
---
# [R](https://www.r-project.org/), ~~271~~ 253 bytes; score = ~~101~~ 253-160 = 93
(Previous solution, better optimized for the initial 'code length divided by changeable characters' scoring method)
```
a=';`+`=nchar;`!`=sQuote;cat("a=",!(c<-`if`(+a>+b,a,b)),";b=",!c,c,"#"[a==b],sep="")';b=';`+`=nchar;`!`=sQuote;cat("a=",!(c<-`if`(+a>+b,a,b)),";b=",!c,c,"#"[a==b],sep="")';`+`=nchar;`!`=sQuote;cat("a=",!(c<-`if`(+a>+b,a,b)),";b=",!c,c,"#"[a==b],sep="")#
```
[Try it online!](https://tio.run/##tcxBDkAwEADAt1iHtul6Qa0/OItkt5sKF0R5f/EHzpPMUYqQCeyZVp3lCFwx5f7azhRUTgtCgJXVtuFlYuul8xEFo3MIIb6mqAg1DEIUR8xpJwBnHvtj/XqsS7kB "R – Try It Online")
If any of the two sets of 80 single-quoted non-`#` characters are removed from the code, the final `#` character is removed from the output.
] |
[Question]
[
## Definition
The rank of a word is defined as the position of the word when all the possible permutations (or arrangements) of its letters are arranged alphabetically, like in a dictionary, no matter if the words are meaningful or not.
Let us consider these two words - "blue" and "seen". To begin with, we would write all the possible arrangements of the letters of these words in alphabetical order:
```
"blue": "belu","beul","bleu","blue","buel","bule","eblu","ebul","elub","elbu","eubl",
"eulb","lbeu","lbue","lebu","leub","lube","lueb","ubel","uble","uebl","uelb",
"ulbe","uleb"
"seen": "eens","eesn","enes","ense","esen","esne","nees","nese","nsee","seen",
"sene","snee"
```
Now let's look from the left and find the position of the words we need. We see that the word "blue" is at the 4th position and "seen" is at 10th position. So the rank of the word "blue" is 4, and that of "seen" is 10. This is the general way of calculating the rank of a word. Make sure you start counting from 1 only.
## Task
Your task is to write a code to take any word as an input and display its rank. The rank should be the output.
Be careful about words containing repeated letters.
## Examples
```
"prime" -> 94
"super" -> 93
"bless" -> 4
"speech" -> 354
"earth" -> 28
"a" -> 1
"abcd" -> 1
"baa" -> 3
```
You can assume the input to be completely in lowercase and the input will only contain **alphabetical characters**. Also if a blank space or an invalid string is entered, you may return anything.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") , so the shortest code wins!
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
lambda s:sum(t<=(*s,)for t in{*permutations(s)})
from itertools import*
```
[Try it online!](https://tio.run/##HY27DoMwDEXn8hXekiA6IXWISr@kS4BERCIP2WaoEN@ehizW8dU9dv7xluJYHEzwLbsJ82qANB1B8nuSPQ3KJQQGH88@WwwHG/YpkiR1qc5hCuDZIqe0E/iQE3JfbqVuEURGH6wYQNBR7Rvm3RK1JFu7bDdZg9zAtDEvaysaI3T3qBciSydO0q8Lnh84Xf2tx0uo8gc "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
ϐsk>
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6OTDq4qz7f7/T8pJLS4GAA "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVln5/@jkw6uKs@3@Vyod3m@lcHi/ks7/gqLM3FSu4tKC1CKupJzU4mKu4oLU1OQMrtTEopIMrkSuxKTkFK6kxEQA)
**Explanation**
```
œ # get permutations of input
ê # sort and remove duplicates
s # swap input to top of stack
k # get index of input in the list
> # increment
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 4 bytes
```
fuȯI
```
[Try it online!](https://tio.run/##S0/MTPz/P630xHrP//@LC1JTkzMA "Gaia – Try It Online")
[Answer]
# [Pyth](https://pyth.readthedocs.io), 6 bytes
```
hxS{.p
```
**[Test suite.](https://pyth.herokuapp.com/?code=hxS%7B.p&input=%22earth%22&test_suite=1&test_suite_input=%22prime%22%0A%22super%22%0A%22bless%22%0A%22speech%22%0A%22earth%22%0A%22a%22%0A%22abcd%22%0A%22baa%22&debug=0)**
## Explanation
```
hxS{.p || Full program.
.p || All the permutations of the input.
{ || Deduplicate.
S || Sort.
x || Index of the input into this list.
h || Increment.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Œ!ṢQi
```
[Try it online!](https://tio.run/##y0rNyan8///oJMWHOxcFZv7//1@puCA1NTlDCQA "Jelly – Try It Online") or see the **[test suite](https://tio.run/##y0rNyan8///oJMWHOxcFZv4/uudw@6OmNVlA/KhhjoKuncKjhrmR//9HKxUUZeamKulwKRWXFqQWgRhJOanFxWCRgtTU5AwQKzWxqATMSAQTSckpYIWJiUqxAA "Jelly – Try It Online")**
## How it works
```
Œ!ṢQi - Main link. Argument: s (string) e.g. 'baa'
Œ! - All permutations ['baa', 'baa', 'aba', 'aab', 'aba', 'aab']
Ṣ - Sort ['aab', 'aab', 'aba', 'aba', 'baa', 'baa']
Q - Deduplicate ['aab', 'aba', 'baa']
i - 1-based index of s 3
```
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda s:-~sorted(set(permutations(s))).index(tuple(s))
from itertools import*
```
[Try it online!](https://tio.run/##bdDNSsUwEAXgfZ5i6CoVLNpewXuhr@ATuEnbKQ00P8xMQDe@eo00YMS7/c7JcEj8lC34/ljH92M3bloM8O3xiwMJLppRdERySYzY4Flz27ad9Qt@aElxxx9QKwUHVpAkhJ3BuphfPxyGOROsupn2hE0L4wgX9auM6E99flKVR7Ku1K9/@ilPKT6o@joy3zkfEeft9OGlTtCQlKB/rdyUNTVN8/JfJ1Oqg1J5rRdo3gKcef4mQKJA3DXHNw "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 73 bytes
* Thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for choosing Python 3; saving five bytes.
```
lambda s:-~sorted({*permutations(s)}).index((*s,))
from itertools import*
```
[Try it online!](https://tio.run/##bdBNCsIwEAXgfU4RukqKFrUKKvQKnsBNaqcYaH6YSUERvXoNNGBEt997GR7x93B1tp765jwNyrSd4nRcvshhgE48Sg9oxqCCdpYEyaestO3gJkRJCylZj85wHQCDcwNxbXx8WE6KKBLvRdEOIxSSNw3fso8SgJ11vWKZe9Qm1Q9f/THuSF6z/DoQ/TnvAS7X2etdnoDCkILNPnOV1uTUXrpfbVWq1ozFtTaI4uT4nMc/4oDokKpCTm8 "Python 3 – Try It Online")
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 8 bytes
```
q_e!\a#)
```
[Try it online!](https://tio.run/##S85KzP3/vzA@VTEmUVnz///igtTU5AwA "CJam – Try It Online")
+1 byte due to 1-indexed requirement.
[Answer]
# [Haskell](https://www.haskell.org/), 56 bytes
```
import Data.List
elemIndex<*>([]:).nub.sort.permutations
```
[Try it online!](https://tio.run/##RYyxDoMwDER3vsLKBFWVD6hKpy6VyhcgBgeMiJqEKDZS/z6NOpCb7t3ZtyF/yLmcrY97EniioH5blmbtyZF/hYW@98ujHadbp8NhNJczHSn5Q1DsHjh7tAF68BgHaGOyQUDD2kEDRSOoEnlSf7qC4qM8n2QcMdcuEs3biYRJKmF1Zl7qAqKCKf8A "Haskell – Try It Online")
+6 bytes because of 1-indexing requirement. :(
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~8~~ 10 bytes
~~0-indexed.~~ Poxy, unnecessary 1-indexing, increasing my byte count by 25%!
```
á â n bU Ä
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=4SDiIG4gYlUgxA==&input=InNwZWVjaCI=)
---
## Explanation
`á` gets all the permutations of the input, `â` removes duplicates, `n` sorts them and `b` gets the index of the first occurrence of the input, `U`.
[Answer]
# [J](http://jsoftware.com/), 28 23 bytes
-5 bytes thanks to FrownyFrog
```
1+/:~@~.@(A.~i.@!@#)i.]
```
## How it works?
```
] - the argument
(A.~ ) - permutations in the
i.@!@# - range 0 to factorial of the arg. length
/:~@~.@ - remove duplicates and sort
i. - index of arg. in the sorted list
1+ - add 1 (for 1-based indexing)
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbX1reoc6vQcNBz16jL1HBQdlDUz9WL/a3JxpSZn5CukKagXFGXmpqorKMAFiksLUouQBZJyUouLUVQUpAKZyCKpiUUlQAEY31DBUEU9EcFXT0xKTkHiJiUCJcHgPwA "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
S€(OuP
```
[Try it online!](https://tio.run/##yygtzv7/P/hR0xoN/9KA////KyUlJioBAA "Husk – Try It Online") I feel like there should be a way to drop `(`.
**Explanation:**
```
€ -- return index of the input
S ( -- in the list generated by applying the following functions to the input:
P -- permutations
u -- remove duplicates
O -- sort
```
[Answer]
# Tcl, 196 bytes
```
proc p {a p} {if {$a eq {}} {lappend ::p $p} {while {[incr n]<=[llength $a]} {p [lreplace $a $n-1 $n-1] $p[lindex $a $n-1]}}}
p [split $argv ""] ""
puts [expr [lsearch [lsort -unique $p] $argv]+1]
```
Tcl has no built-in method to compute the next lexicographic permutation, so we have to do it ourselves. But wait... it is *shorter* to do it with a simple recursive function that computes *all* possible permutations in any order.
Ungolfed:
```
# Compute all possible permutations of the argument list
# Puts the result in ::all_permutations
proc generate_all_permutations {xs {prefixes ""}} {
if {$xs eq {}} {
lappend ::all_permutations $prefixes
} else {
while {[incr n] <= [llength $xs]} {
generate_all_permutations [lreplace $xs $n-1 $n-1] $prefixes[lindex $xs $n-1]
}
}
}
# Get our input as command-line argument, turn it into a list of letters
generate_all_permutations [split $argv ""]
# Sort, remove duplicates, find the original argument, and print its 1-based index
puts [expr [lsearch [lsort -unique $all_permutations] $argv]+1]
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ 18 bytes
**Solution:**
```
1+*&x~/:?x@prm@<x:
```
[Try it online!](https://tio.run/##y9bNz/7/31BbS62iTt/KvsKhoCjXwabCSqm4IDU1OUPp/38A "K (oK) – Try It Online")
**Examples:**
```
1+*&x~/:?x@prm@<x:"seen"
10
1+*&x~/:?x@prm@<x:"blue"
4
```
**Explanation:**
Generate permutations of the indices of the sorted input string, use them to index back into the input string, take the distincts, see where the original string matched, and add one.
```
1+*&x~/:?x@prm@<x: / the solution
x: / save input string as x
< / return indices when sorting x ascending
prm@ / apply (@) function prm
x@ / index into x with these permutations
? / distinct (remove duplicates)
x~/: / apply match (~) between x and each-right (/:)
& / return indexes where true (ie the match)
* / take the first one
1+ / add 1 due to 1-indexing requirement
```
[Answer]
# Java 8, 211 bytes
```
import java.util.*;TreeSet q=new TreeSet();s->{p("",s);return-~q.headSet(s).size();}void p(String p,String s){int l=s.length(),i=0;if(l<1)q.add(p);for(;i<l;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,l)));}
```
**Explanation:**
[Try it online.](https://tio.run/##pVLdasIwGL33KT68StYa3XXXwR5gMnB3Yxdp@mnj0jQmXx1Ould3qdMxxkCwhRDOIeeHQ9dyKyeNQ7su3w66do0nWEdOtKSNuMkgftMpPMnIN0ugCqHYEU5U01oaKSNDgEep7X4EoC2hX0qFMO/hkQDFFuS1XUHgWSS7eJ494gIJNrnF9zNi/EIWwBws5HAIk/u9Y@NxGh09Uuvt5HMjKpRlbxO4CPoDo103OjvOGwL3v@u20SW4c0eX/pTd9@VNHoRBu6KK8VTns0wvmbm75Rshy5I5ni0bzzJ9ZzLHXBKEqqR/IKZ5GkRoi3A0Y7NU8@Q3kSQ6NZzHigcA1xZGKwgkKV7HPnUc9FTp5VXy7zH7laGOA/Sj9YAdBwVY7AJhLZqWhIsSMpbVwgrFxoVpccxPz2rxd@8L6oBor1dHWA8Jbx366@WFwRAGpDtEVV2vx/izDZDLAdJClQNmk@fobtQdvgA)
```
import java.util.*; // Required import for TreeSet
TreeSet q=new TreeSet(); // Sorted Set on class-level
s->{ // Method with String parameter and integer return-type
p("",s); // Save all unique permutations of the String in the sorted set
return-~q.headSet(s).size();}
// Return the 0-indexed index of the input in the set + 1
void p(String p,String s){ // Separated method with 2 String parameters and no return-type
int l=s.length(), // The length of the String `s`
i=0; // Index integer, starting at 0
if(l<1) // If String `s` is empty
q.add(p); // Add `p` to the set
for(;i<l; // Loop from 0 to `l` (exclusive)
p( // Do a recursive call with:
p+s.charAt(i), // `p` + the character at the current index of `s` as new `p`
s.substring(0,i)+s.substring(++i,l)));}
// And `s` minus this character as new `s`
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~183~~ 182 bytes
The first answer that run in polynomial time!
```
a=[*map(ord,input())]
f=lambda x:x and x*f(x-1)or 1
c=[0]*98
for C in a:c[C]+=1
l=len(a)
F=f(l)
for i in c:F//=f(i)
r=1
for x in a:F//=l;l-=1;r+=sum(c[:x])*F;F*=c[x];c[x]-=1
print(r)
```
[Try it online!](https://tio.run/##JYtBC8IgHMXvfgqP6hprdCnlfxoJHYLoKh7MJQnODdvAPv1ydXnwfu/3ps/8GuNhXQ0oNpiJjKnf@TgtM6FUIwfBDI/e4MwzNrHHmTmS65aOCbfIgtprdjoiV2qHfcSGW9XpCloUIDwjMRRJcCTQn@I3xXLZNIV5ilLxNp7/140HEWpoRargvQzEKp41ZVJIBlZlLbYoO5qSjzNJdF1v98v1/AU "Python 3 – Try It Online")
Require the input to be all upper-case, because... it saves a byte.
Full program, takes input from `stdin` and output to `stdout`.
---
Variable names: (sort of ungolfed code)
```
a : permu
f : factorial
c : count_num
C : char
l : n_num_left
F : factor
r : result
```
Unfortunately, `from math import factorial as f` takes exactly 1 more byte.
---
(Unrelated note: I checked the `Combinatorica`` package of Mathematica, nothing useful, including `RankPermutation`)
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~113~~ 111 bytes
```
import StdEnv,StdLib
?s=elemIndex s[[]:removeDup(foldr(\a b=sort[insertAt i a x\\x<-b,i<-[0..length x]])[[]]s)]
```
[Try it online!](https://tio.run/##JY49C4MwFEX3/oq3qaDSuShSaAfBzTFmiOZpA/mQJEr655sGnC53OPfcRSLTURl@SATFhI5C7cZ6GD1/67NMMYj51rkWJapecwzgCKEPi8qc@Dr2fDWS23xiMLcukURoh9Y/PQhgEKYpNNVciqYi97qWqDf/gUBpkUaoK2gcPUu6Fjog2SwPzGj8Latkm4tVP8TXVzMllqtcb/4 "Clean – Try It Online")
+3 bytes to handle 1-indexing :/
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 33 bytes (SBCS)
```
⎕CY'dfns'
{∪⊃∘(⍵[⍋⍵])¨¨↓pmat≢⍵}⍳⊂
```
[Try it online!](https://tio.run/##nVFNS8NAEL3nV4y9RKHtD/AqHv049CLiYZJMmpXNbshsKEG8KBStRAQRvHjxJF7FP9Cfsn9EJ6lNexZCsm923nvzJljoUVKjttOfH9@8wSQj4CrKFbOyBmI0oYOIgIyjkhLI5D0EJpKitrOdFev4ZHK4L1zFII8TjZJQbwntB0Hb5x9fDs7CJDUcdvjK3336xa2/e931zfe5bx7kc7G3/Fh@@PlzkaPz9@9SuvbNl1/crESOUBlIKxO7dsLdjcme3G8ZpODnT/@zmBBL3N5kVTzVhExgrCOJiA5SWwIrM9U0ijOUsysFscSOM0CGEEOobQUzW@lEeGWOWtdgiJJO0FlwdUEwGErnAJQRU0zApnBZsYNBWx2vttpy2tXmyqkpOgFR3e3ZdZN2cutpx0HQVrv0fvE@TCX7cJNL/ikT//WERalyCv8AVwWVaxBpYu5vCqI4WyPC0vUA@0MUJz0ZMfwF "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~105~~ ~~104~~ 103 bytes
```
f=lambda s:s==s*2or f(s[1:])+sum(f(sorted(s[:s.index(c)]+s[s.index(c)+1:])[::-1])for c in{*s}if c<s[0])
```
[Try it online!](https://tio.run/##RY7LCsMgEEXX7Ve4U5OmNC10IU1/JLgwPkggMeIYaAn5dqtuuhnOPVwu475hXO0jRtPNYhmUQMCg66C6rx4ZAn3LOK1hW0gKqw9aJcfgOlmlP0RSXkP/T3Vu94w1LacmDUg02b2CYzJIvqC/cRqzhqQRdn5aNL4gDJvTPsMwa4BinNZyzKSFDwVEOYNUpSgEZudTWrCBGLwDex6oeaM9PUnZ48A0/gA "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 49 bytes
```
->w{c=w.chars
1+c.sort.permutation.uniq.index(c)}
```
[Try it online!](https://tio.run/##XctBDoIwFATQPadocKMxNMFqogu4iHHRfj6hiUD9bYPGePZKhHbh7OZlhrx6hbYKRT29oZo4dJJsVu6B25EcN0i9d9LpceB@0A@uhwafW9h9gmHtNTeke8xvbMOKml2O2Q@tn28JxYLqjtZGjEODCF1EcVoZJbmkh/OCMkK5dgXNHymZRoLNCV8 "Ruby – Try It Online")
[Answer]
# JavaScript (ES6), ~~106~~ 100 bytes
```
w=>(P=(a,s)=>a[0]?a.map((_,i)=>P(b=[...a],s+b.splice(i,1))):P[s]=P[s]||++k)[P([...w].sort(),k=''),w]
```
### Test cases
```
let f =
w=>(P=(a,s)=>a[0]?a.map((_,i)=>P(b=[...a],s+b.splice(i,1))):P[s]=P[s]||++k)[P([...w].sort(),k=''),w]
console.log(f("prime")) // 94
console.log(f("super")) // 93
console.log(f("bless")) // 4
console.log(f("speech")) // 354
console.log(f("earth")) // 28
console.log(f("a")) // 1
console.log(f("abcd")) // 1
console.log(f("baa")) // 3
```
### How?
**P()** is our recursive permutation function. But the encompassing object of **P** is also used to store the ranks of the permutations.
```
P = (a, s) => // given an array of letters a[] and a string s
a[0] ? // if a[] is not empty:
a.map((_, i) => // for each entry at position i in a[]:
P( // do a recursive call to P() with:
b = [...a], // a copy b[] of a[], with a[i] removed
s + b.splice(i, 1) // the extracted letter appended to s
) // end of recursive call
) // end of map()
: // else:
P[s] = P[s] || ++k // if P[s] is not already defined, set it to ++k
```
The wrapping code now reads as:
```
w => // given the input word w
P[ // return the permutation rank for w
P( // initial call to P() with:
[...w].sort(), // the lexicographically sorted letters of w
k = '' // s = k = '' (k is then coerced to a number)
), // end of call
w // actual index used to read P[]
] // end of access to P[]
```
[Answer]
# C++, 230 bytes
```
#include<algorithm>
#include<iostream>
#include<string>
using namespace std;void R(string s){int n=1;auto p=s;sort(begin(p),end(p));do if(p==s)cout<<n;while(++n,next_permutation(begin(p),end(p)));}int main(int n,char**a){R(a[1]);}
```
As per my asking, the code definitely need to be executable as-is. The function-only clause is basically rubbish. :-@
Thank you to those who kindly answered the question of what can be cut out for me. In the interest of *valid* code, I’ve avoided the popular GCC-ism of including <bits/stdc++.h>, which I have always considered a bad loophole cheat.
What follows is what remains of my original posting:
---
I am always unsure when using C and C++ what counts towards the byte total. According to [Program, Function, or Snippet?](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) the answer is still vague (as long as it isn’t a snippet, I guess). So I am going with the shortest of the two possibilities.
Here it is ungolfed *with necessary headers, etc:*
```
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
void R( string s )
{
int n = 1;
auto p = s;
sort( begin(p), end(p) );
do if (p == s) cout << n;
while (++n, next_permutation( begin(p), end(p) ));
}
int main( int n, char** a )
{
R( a[1] );
}
```
That golfs down to 230 bytes, a third of that standard boilerplate required by *every* C++ program. (So, I don’t feel too bad not counting it, but as I haven’t ever seen a firm complaint either way, OP will have to tell me which he prefers to satisfy “write a code to take any word as an input and display its rank.”)
I am also unsure if this satisfies “the rank should be output.”
[Answer]
# [Perl 5](https://www.perl.org/), 98 + 3 (`-pF`) = 101 bytes
```
$"=',';@a=grep{++$k{$_}<=1&&"@F"eq join$",sort/./g}sort glob"{@F}"x(@F=sort@F);1while!/$a[$\++]/}{
```
[Try it online!](https://tio.run/##FcjBCsIgGADgV1kiW@E2t8NOS/DkrSeoiBU/zpJpOigQX70/dvv4PAQ7IFIiqroa5SR0AJ8Yo69Eb/ko@rIkUhF4F09nFkrq6MLKW67zhkJbdydJqky@e6nEdlIdxv4zGws7TqczvTB25TkhRg/wmH/Or8YtEZvT0HZ9h41Xfw "Perl 5 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 43 bytes
```
@(s)find(all(unique(perms(s),'rows')==s,2))
```
[**Try it online!**](https://tio.run/##LcvBCoAgDMbxey/iBuGhu9CrLJskmJrLenwT8rQff74le9PDzRmtdVtB0Pm4A4UANfqrMmQup/Q@q5JeUWiMzAtic6By8ScrnDql9t3PLbDIqJnZHr@Zyj1I42x2Hy/UU/sA "Octave – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 53 bytes
```
{1+first :k,$_,.comb.permutations».join.unique.sort}
```
[Try it online!](https://tio.run/##DcxNDoIwEAbQq3whxI2kiRsXKlyFTHEaqvTHTrsghJO582KV3Vu9yGm5VrfiZNDX7XI2NknG7d21Y6em4LSKnFzJlG3w8vuqV7BeFW8/hZWElPcqtKJpR/QDNoN23BuYkPDQS2EIs0dM1h0sRwW9sAgkMk8zmFKeQSA9PaGJhnv9Aw "Perl 6 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 275 bytes
```
param($s)function n($a){if($a-eq1){return}0..($a-1)|%{n($a-1);if($a-eq2){$b.ToString()}$p=($j-$a);[char]$t=$b[$p];for($z=($p+1);$z-lt$j;$z++){$b[($z-1)]=$b[$z]}$b[($z-1)]=$t}}if($s.length-eq1){1;exit}$b=New-Object Text.StringBuilder $s;(n($j=$s.length)|sort -u).indexOf($s)+1
```
[Try it online!](https://tio.run/##TY7BboMwEER/hcNWsYVslV4Rl35Ac2huiAOQJRg5htqLgiD@dtcUteppVzOzb2caH2hdj1qHMNW2vjNwvJtNS2o0iWFQ8011cQj8yvhmkWZr/KuUu5Tx58tmji3/Tb3xDRp5GT/JKnNj3MNUMBhEJOVl29e2AiqgKWGq8m60DNZoT2kkwCo0wRBnmu6QMnqRXP2k18r/V8j7/aGTGs2N@qNdluOiKOaKD3yIczNgS8kFF5JHmfdZ6SvaBFzOYu2h@LvnTzdaSsTMpTJXXM47m6dZCOHU1nT6Bg "PowerShell – Try It Online")
So, this is a bloody mess.
*PowerShell doesn't have any permutations built-in, so this code uses the algorithm from [here](https://learn-powershell.net/2013/02/21/fun-with-powershell-and-permutations/) (golfed heavily), which is available under the Microsoft Limited Public License ([Exhibit B](https://technet.microsoft.com/en-us/cc300389.aspx#P) on this licensing page).*
The program takes input `$s` as a string, then the actual program starts with `$b=New-Object ...`. We're constructing a new [StringBuilder](https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx) object, which is (essentially) a mutable string of characters. This will allow us to handle the permutations more easily. We then call the function `n` (setting `$j` along the way to be the length of the input string), `sort` with the `-u`nique flag the output, take the `.indexOf()` to find the input string, and add `1` because PowerShell is zero-indexed.
The function is the main part of the program. It takes as input a number, and will each iteration count down until we reach `1` (i.e., a single letter). The rest of the function essentially recursively calls the function as well as takes the current letter and iterates it through every position.
There's a single bit of additional logic `if($s.length-eq1){1;exit}` to account for input strings of length `1` due to how the permutations function works.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 5 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ĐᒆỤ≥Ʃ
```
Explanation:
```
Implicit input
Đ Duplicate input
ᒆ Get list of all permutations of input
Ụ Get unique permutations
≥ Does each permutation come before or is equal to the input?
Ʃ Sum of result of previous step (converts booleans to ints)
```
[~~Try it online!~~](https://tio.run/##ARoA5f9weXT//8SQ4ZKG4buk4omlxqn//3NwZWVjaA)
] |
[Question]
[
What general tips do you have for golfing in F#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to F# (e.g. "remove comments" is not an answer). Please post one tip per answer.
[Answer]
Need to provide a type annotation for a variable so that you can call a method on it? Just compare it against a literal of the type you want it to be then throw away the result:
```
let f (x:string)=x.Length
let f x=x="";x.Length
```
[Answer]
Use `function` instead of `match` when possible; it'll save 6 characters for 1-character variable names:
```
let f=function // ... (14 chars)
```
vs
```
let f x=match x with // ... (20 chars)
```
It can also replace any pattern match to consistently save 1 character:
```
match a with| // ... (13 chars)
a|>function| // ... (12 chars)
(function| (* ... *))a // (12 chars)
```
[Answer]
Use the prefix notation for infix operators when you can - it'll save you from having to define a function to use them.
For example, you can turn this:
```
List.map(fun i->i+2)[1;1;2;3;5;8]
```
into this:
```
List.map((+)2)[1;1;2;3;5;8]
```
[Answer]
# Tuple deconstruction
In case you can't get around to using variables, use tuple deconstruction instead of multiple let expressions
```
let a,b ="",[]
```
instead of
```
let a=""
let b=[]
```
# Reading from stdin
F# core library defines an alias for `System.Console.In` called `stdin`. These allow you to read input.
```
// Signature:
stdin<'T> : TextReader
```
[TextReader on msdn](https://msdn.microsoft.com/en-us/library/system.io.textreader(v=vs.110).aspx)
The big advantage aside the fact that it's shorter than `Console` is, you don't have to open System either
# Iterating over string
string is basically a `char seq`, this allows you to use `Seq.map` directly with strings. It's also possible to use them in comprehensions `[for c in "" do]`
# Mutables/Reference cells
Using reference cells is not always shorter as every read operation comes with an additional character to deref the cell.
# General tips
* It is possible to write the complete `match .. with` inline
```
function|'a'->()|'b'->()|_->()
```
* There is no need for white-space before and after non alphanumeric characters.
```
String.replicate 42" "
if Seq.exists((<>)'@')s then
if(Seq.exists((<>)'@')s)then
```
* In case you need to left or right pad a string with spaces, you can use [s]printf[n] flags for that.
```
> sprintf "%20s" "Hello, World!";;
val it : string = " Hello, World!"
```
[Core.Printf Module](https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/core.printf-module-[fsharp]#remarks)
[Answer]
# Use id instead of x->x
id is an operator standing for the identity function.
```
let u x=x|>Seq.countBy (fun x->x)
```
can be written
```
let u x=x|>Seq.countBy id
```
[source](https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/operators.id%5B't%5D-function-%5Bfsharp%5D)
I use it [here](https://codegolf.stackexchange.com/a/147073/15214)
[Answer]
# Eta-conversion for functions
Many thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) for this tip in one of [my solutions](https://codegolf.stackexchange.com/a/165246/78954).
Consider a function to, say, sum a string with 3 for upper-case letters and 1 for all other characters. So:
```
let counter input = Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1) input
```
By [eta-conversion](https://en.wiktionary.org/wiki/eta_conversion) this can be re-written as:
```
let counter = Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)
```
and called in the same way as before:
```
counter "Hello world!" |> printfn "%i"
```
# The function forward-composition operator `>>`
Now suppose our original challenge would be to sum a string with 3 for upper-case letters and 1 for lower-case letters, and all other characters are excluded.
We might write this as:
```
let counter input = Seq.filter Char.IsLetter input |> Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)
```
We can use the forward-composition operator (`>>`) to chain the two functions (`Seq.filter` and `Seq.sumBy`) together. With eta-conversion the function definition would become:
```
let counter = Seq.filter Char.IsLetter >> Seq.sumBy (fun x -> if Char.IsUpper x then 3 else 1)
```
Chris Smith did a great write-up on the `>>` operator on his [MSDN blog](https://blogs.msdn.microsoft.com/chrsmith/2008/06/14/function-composition/).
[Answer]
# Prefer new line string over "\n"
This will start to pay off at even a single new line character in your code. One use case might be:
### (18 bytes)
```
string.Concat"\n"
```
### (17 bytes)
```
string.Concat"
"
```
Inspired from [Chiru's answer for es6](https://codegolf.stackexchange.com/a/54368/15214).
Used [here](https://codegolf.stackexchange.com/a/180139/15214)
[Answer]
# Use .NET
.NET offers a lot of nice builtins. F# can use them, so dont forget them!
Example:
```
open System.Linq
```
It can be helpful!
[Answer]
When possible `Seq` is shorter than `List`:
```
[[1];[2;3];[4];[5]|>List.collect
```
```
[[1];[2;3];[4];[5]|>Seq.collect
```
is one char shorter...
[Answer]
# Avoid parenthesis when using one parameter and on tuple
```
let f = [(0,1);(1,4)]|>Seq.map(fst)
printfn "%A" f
```
can be written
```
let f = [0,1;1,4]|>Seq.map fst
printfn "%A" f
```
[Answer]
# Use for...to instead of for...in to walk a range
```
for i in[0..2]
for i=0 to 2
```
* [for in](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/loops-for-in-expression)
* [for to](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/loops-for-to-expression)
[Answer]
The `module` keyword can be used to shorten module names when used repeatedly. For example:
```
Array.fold ...
Seq.iter ...
List.map ...
```
can become
```
module A=Array
A.fold ...
module S=Seq
S.iter ...
module L=List
L.map ...
```
This is more useful for longer programs where module methods are used repeatedly (and must be fully named each time because they have the `RequireQualifiedAccess` modifier), and allows shaving a few chars off especially when it's more useful to use a regular CLR array (e.g., mutability) than an F# `seq` or `list`.
[Answer]
Use lambdas to save a byte. For example, this:
```
let f x=x*x
```
Can be expressed as this:
```
fun x->x*x
```
] |
[Question]
[
I'm a mentor at RubyLearning and one of the exercises we give to our students is the "Deaf Grandma" exercise from Chris Pine's book "[Learn to Program](http://pine.fm/LearnToProgram/)". Here's the description:
>
> Write a Deaf Grandma program. Whatever you say to grandma (whatever
> you type in), she should respond with:
> "Huh?! Speak up, sonny!", unless you
> shout it (type in all capitals). If
> you shout, she can hear you (or at
> least she thinks so) and yells back:
> "No, not since 1938!"
>
>
> To make your program really believable, have grandma shout a
> different year each time; maybe any
> year at random between 1930 and 1950.
> (This part is optional, and would be
> much easier if you read the section on
> Ruby's random number generator at the
> end of the methods chapter.) You can't
> stop talking to grandma until you
> shout "BYE".
>
>
>
After several course iterations I tried to see how small I can get this and now have it down to 112 characters:
```
puts (s||='').upcase==s ? "NO, NOT SINCE #{1930+rand(21)}!":"HUH?! SPEAK UP, SONNY!" until(s=gets.chomp)=="BYE"
```
I'm curious to see in how few characters this can be achieved in the language of your choice, because I think Ruby is already doing really well here.
**Edit:** The Perl solution posted below led to
```
ruby -nle 'puts($_=="BYE"?exit: $_.upcase!? "HUH?! SEPAK UP, SONNY!":"NO, NOT SINCE #{1930+rand(21)}!")'
```
which is 92 characters for the expression + 2 more for the `n` and `l` options.
[Answer]
## Perl, 85 ~~91~~
Run with `perl -nE '<code goes there>'` (`n` counted in program size):
```
$==1930+rand 21;say/^BYE$/?last:uc eq$_?"
NO, NOT SINCE $=!":"HUH?! SPEAK UP, SONNY!"
```
~~That trailing exclamation mark is *very* expensive...~~
Edits suggested by IK:
* Using a regexp instead of a string match spares the `-l` global option as well as two program characters: -3.
* Using an actual variable to save a value and use it later for interpolation (Genius! Who'd have thought of using a variable for that?): 0.
* Making that variable `$=`, constrained to be an integer: -4.
(and it still doesn't add up and I'm too sleepy to find out why. Oh well, the final count is right at least)
[Answer]
## Python 120 Characters
```
r=raw_input
s=r()
while'BYE'!=s:
print["HUH?! SPEAK UP, SONNY!","NO, NOT SINCE %d!"%(1930+id(s)%21)][s.isupper()];s=r()
```
Any hints to improve?
[Answer]
**131 characters in PowerShell:**
```
for(){$j=read-host;if($j-ceq"BYE"){break}if($j-ceq$j.ToUpper()){"No, not since 19$(10..90|random)!"}else{"Huh?! Speak up, sonny!"}}
```
W/ whitespace:
```
for(){
$j = read-host;
if ( $j -ceq "BYE" ) { break }
if ( $j -ceq $j.ToUpper() ) { "No, not since 19$(10..90|random)!" }
else { "Huh?! Speak up, sonny!" }
}
```
Squeezed 18 characters from Joey's suggestion.
BTW, 'Learn to Program' was the first programming book I ever read cover to cover.
[Answer]
**C# - 234 Chars**
```
using System;class P{static void Main(){for(;;){var s=Console.ReadLine();if(s!=s.ToUpper()){Console.WriteLine("Huh?! Speak up, sonny!");continue;}if(s=="BYE")break;Console.WriteLine("No, not since 19{0}!",new Random().Next(30,51));}}}
```
More readable:
```
using System;
class P
{
static void Main()
{
for(;;)
{
var s=Console.ReadLine();
if(s!=s.ToUpper())
{
Console.WriteLine("Huh?! Speak up, sonny!");
continue;
}
if(s=="BYE")
break;
Console.WriteLine("No, not since 19{0}!",new Random().Next(30,51));
}
}
}
```
[Answer]
## Befunge - 27x6 = 162 characters
```
> ~:0` #v _ vv<
>:"a"`!#v _:"z"`|
^ < <
v"Huh?! Speak up, sonny!"0<
v"No, not since 1938!"0 <
>:# #, _@
```
EDIT: Completely missed the "BYE" part. New version coming soon.
EDIT 2: Actually, that makes it a bit too complex for my meager Befunge skills. I might try again later, but I can't think of any simple way to implement it at the moment.
[Answer]
**C# - 194 CHARS**
```
using System;class P{static void Main(){var s=Console.ReadLine();if(s!="BYE"){Console.Write((s==s.ToUpper()?"No, not since 19"+new Random().Next(30, 51):"Huh?! Speak up, sonny")+"!");Main();}}}
```
With whitespaces:
```
using System;
class P
{
static void Main()
{
var s = Console.ReadLine();
if (s != "BYE")
{
Console.Write((s == s.ToUpper() ? "No, not since 19" + new Random().Next(30, 51) : "Huh?! Speak up, sonny") + "!");
Main();
}
}
}
```
With some inspiration from Nellius and fR0DDY.
Please let me know if it can be improved.
[Answer]
# D: 246 Characters
```
import std.random,std.stdio,std.string;void main(){auto r=rndGen();for(;;){auto t=strip(readln());if(t=="BYE")break;if(t.toupper()==t)writefln("No, not since %s!",{r.popFront();return r.front%20+1930;}());else writeln("Huh?! Speak up, sonny!");}}
```
More Legibly:
```
import std.random, std.stdio, std.string;
void main()
{
auto r = rndGen();
for(;;)
{
auto t = strip(readln());
if(t == "BYE")
break;
if(t.toupper() == t)
writefln("No, not since %s!", {r.popFront(); return r.front % 20 + 1930;}());
else
writeln("Huh?! Speak up, sonny!");
}
}
```
[Answer]
javascript, 142 characters, 29 of them perform random year
```
n='a'; while((/[a-z]/.test(n)?r="HUH?! SPEAK UP, SONNY!":n=="BYE"?r='':r="NO, NOT SINCE "+Math.floor(Math.random()*21+1930))!=''){n=prompt(r)}
```
[Answer]
## Windows PowerShell, ~~121~~ 117
Due to the nature of the task this looks pretty much identical to [Ty Auvil's solution](https://codegolf.stackexchange.com/questions/475/code-golf-chris-pines-deaf-grandma/576#576), although it was written independently:
```
for(;($j=read-host)-cne'BYE'){if($j-cmatch'[a-z]'){'Huh?! Speak up, sonny!'}else{"No, not since 19$(30..50|random)"}}
```
Thanks to SpellingD for the suggestion,
[Answer]
# Awk: ~~97~~ 95 characters
Thanks to
* [tail spark rabbit ear](https://codegolf.stackexchange.com/users/100411/tail-spark-rabbit-ear) for replacing string equality testing with regex matching (-2 characters)
```
/^BYE$/{exit}$0=toupper($0)==$0?"NO, NOT SINCE "int(rand()*21+1930)"!":"HUH?! SPEAK UP, SONNY!"
```
[Try it online!](https://tio.run/##Fc7dCoIwGADQ@z3F5xDSkrS6KhCxWhnBjMwLb4KBS4e2hc5@iJ7d6gEOHPao@t49LzNium/@FPpjer5W3e3GG8v0bN83vQDT2AEanyDZ0RUBLKS2GiZzyx5OJ6PJfObZ2MALHKVRYEByIOEe0oMDSUxpZuC@j3hdKwe2f3RlBorUY9DCS3UN5OwVoPBIIItTWJNwE6BTKVooFG9BKwUX1ozR74cSzv8EJH9q0CWTVVuIu5DF@As "AWK – Try It Online")
[Answer]
**Haskell (189)**
```
import Random
import Char
main=getLine>>=g
g"BYE"=return""
g s|s/=map toUpper s=putStrLn"HUH?! SPEAK UP SONNY!">>main|4>2=randomRIO(30,50::Int)>>=putStrLn.("NO, NOT SINCE 19"++).show>>main
```
The weird thing is, Haskell code is usually a lot shorter than comparable C code when writing a 'serious' program.
[Answer]
## APL (76)
```
{'BYE'≢A←⍞:∇⎕←{∧/⍵∊⎕A:'No, not since ',⍕1938+?20⋄'Huh?! Speak up sonny!'}A}⍬
```
[Answer]
**C# - 345 Chars**
```
using System;class Program{static void Main(){for(;;){if(!t(Console.ReadLine()))break;}}static bool t(string s){bool b=false;if(s=="BYE")return b;int i=0;for(;i<s.Length;i++){b=(s[i]>65&&s[i]<90)?true:false;if(!b)break;}if(b) p("NO, NOT SINCE 1938!");else p("HUH?! SPEAK UP, SONNY!");return true;}static void p(string s){Console.WriteLine(s);}}
```
Damn verbose language ... :-)
[Answer]
### C# - 196 chars (but leaky)
`using System;class P{static void Main(){var s=Console.ReadLine();if(s!="BYE"){Console.Write((s==s.ToUpper()?"No, not since 19"+new Random().Next(30, 51):"Huh?! Speak up, sonny")+"!\n");Main();}}}`
That's @Richard's (leaky) answer with two parens (see below) and a \n added in there to get the EOL in both cases. Otherwise the `" + "` is just wasted space.
**Formatted**
```
using System;
class P
{
static void Main() {
var s = Console.ReadLine();
if (s != "BYE") {
Console.Write((
s == s.ToUpper() ?
"No, not since 19" + new Random().Next(30, 51) :
"Huh?! Speak up, sonny"
) + "!\n");
Main();
}
}
}
```
UPDATE: to clarify my comment about the parens being needed, here's what i get without the parens (i.e. with @Richard's original solution):

And with the parens:

Neither of these use my additional `\n` though.
[Answer]
# Bash: ~~136~~ 128 characters
```
while read s
do
[[ $s = BYE ]]&&break
[[ ${s^^} = $s ]]&&echo NO, NOT SINCE $[RANDOM%21+1930]!||echo HUH?! SPEAK UP, SONNY!
done
```
## Limited alternative: ~~132~~ 123 characters
```
f(){
read s
[[ $s = BYE ]]||{
[[ ${s^^} = $s ]]&&echo NO, NOT SINCE $[RANDOM%21+1930]!||echo HUH?! SPEAK UP, SONNY!
f
}
}
f
```
You can talk to a deaf infinitely, but the conversation with this later code is limited by the call stack. (In my test it gets terminated after 4989 calls.)
[Answer]
# Javascript - 133 131 130 128 127 121 chars
**golfed version of www0z0ks solution**
```
g='';while((i=prompt(g))!='BYE'){/[a-z]/.test(i)?g='Huh?! Speak up, sonny!':g='No, not since '+Math.floor(Math.random()*21+1930)+'!'}
```
```
g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.floor(Math.random()*21+1930)+'!'}
```
```
g='';while((i=prompt(g))!='BYE'){g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!'}
```
```
for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+Math.ceil(Math.random()*21+1929)+'!');
```
```
for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+parseInt(Math.random()*21+1930)+'!');
```
```
for(g='';(i=prompt(g))!='BYE';g=/[a-z]/.test(i)?'Huh?! Speak up, sonny!':'No, not since '+(Math.random()*21+1930|0)+'!');
```
**Edit:** Saved another six chars with [this great tip](https://codegolf.stackexchange.com/questions/2682/tips-for-golfing-in-javascript/2686#2686)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 54 bytes
```
21X+⁽¤Ḷ“ЀÑƊʂ!ṡxẈ»,K”!
ɠ¢“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ṄßƊḟ⁻?“BYE
```
[Try it online!](https://tio.run/##AYsAdP9qZWxsef//MjFYK@KBvcKk4bi24oCcw5DigqzDkcaKyoIh4bmheOG6iMK7LEvigJ0hCsmgwqLigJzCrlbhurlRxp3Jl2nCs@G7pHfhuZZv4bu0wrvFknXGkT/huYTDn8aK4bif4oG7P@KAnEJZRf//SGVsbG8KSEVMTE8KQllFCklnbm9yZSB0aGlz "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 49 bytes
```
21X+⁽¤Ḷ“ЀÑƊʂ!ṡxẈ»,K”!µ“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ḟ⁻?“BYE
```
[Try it online!](https://tio.run/##AWoAlf9qZWxsef//MjFYK@KBvcKk4bi24oCcw5DigqzDkcaKyoIh4bmheOG6iMK7LEvigJ0hwrXigJzCrlbhurlRxp3Jl2nCs@G7pHfhuZZv4bu0wrvFknXGkT/huJ/igbs/4oCcQllF////QllF "Jelly – Try It Online")
# [Jelly](https://github.com/DennisMitchell/jelly), 51 bytes
```
21X+⁽¤Ḷ“ЀÑƊʂ!ṡxẈ»,K;”!µ“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ḟ⁻?“BYE”
```
[Try it online!](https://tio.run/##y0rNyan8/9/IMEL7UePeQ0se7tj2qGHO4QmPmtYcnnis61ST4sOdCyse7uo4tFvH2/pRw1zFQ1uBCg6tC3u4a2fgsbknp2ce2vxw95Lyhzun5T/cveXQ7qOTSo9NtH@4Y/6jxt32QKVOka5Abf8PtwONjPz/X8kDaGO@ko6Ckoerj48/iAFUoQQA "Jelly – Try It Online")
---
The first one is perhaps the most faithful interpretation of the question. It is a full program which reads input line by line from STDIN and acts on it line by line, terminating either when it reaches "BYE" or the end of STDIN (at which point it exits with an error).
The second is a full program which takes a single string as input (e.g. `Hello`, `HELLO`, `BYE`, etc.) and outputs the corresponding output (an empty output for `BYE`)
This third is a function which can be repeatedly called with arguments in a similar version to the second, but each argument is independent - calling it with `BYE` will not prevent you calling it again.
All three output not in uppercase, reflecting the text of the question rather than the sample program provided. [+5 bytes](https://tio.run/##y0rNyan8/9/IMEL7UePeQ0se7tj2qGHOocWHlgH5ux/uXG1/bE2U9eEdh3breD9qmKvIdXLBoUUgFevCHu7aGXhs7snpmYc2P9y9pPzhzmn5D3dvObT76KTSQ0uAxLGJ9g93thyef6zr4Y75QMPsgdqcIl2Bpvz/7wG0Np/Lw9XHx58rqTKVCyjO5Zmel1@UqlCSkVkMAA) to output in all uppercase
---
As they all have the same basic structure, I'll only explain the first one, and leave the other two as exercises for the reader
## How it works
```
21X+⁽¤Ḷ“ЀÑƊʂ!ṡxẈ»,K”! - Helper link. This takes no arguments, outputs a string and returns "!"
21 - Yield 21
X - Choose a random integer between 1 and 21 inclusive
⁽¤Ḷ - Compressed integer: 1929
+ - Add to the random integer. Call that Y
“ЀÑƊʂ!ṡxẈ» - Compressed string: "No, not since"
, - Pair; ["No, not since", Y]
K - Join the two with spaces
”! - Unparseable nilad; Output the space separated string and return "!"
ɠ¢“®VẹQƝɗi³ỤwṖoỴ»ŒuƑ?ṄßƊḟ⁻?“BYE - Main link f(). Takes no arguments
ɠ - Read a line of STDIN, L
? - If:
⁻ “BYE - Condition: L does not equal "BYE"
Ɗ - Then:
? - If:
Ƒ - Condition: L does not change when:
Œu - Converted to uppercase
¢ - Then: Call the helper link, yielding "!"
“®VẹQƝɗi³ỤwṖoỴ» - Else: Compressed string "Huh?! Speak up, sonny!"
Ṅ - Print with a trailing newline
ß - Recurse, calling f() again
ḟ - Else: Return the empty string and halt execution
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 57 bytes
```
{:‛Ṗ⊍⇧≠|aA[`No, λ† ∧Ṡ %!`»÷ḟ»21℅+%,|`Huh?! ∞⇧ up, ½Ŀny!`,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ7OuKAm+G5luKKjeKHp+KJoHxhQVtgTm8sIM674oCgIOKIp+G5oCAlIWDCu8O34bifwrsyMeKEhSslLHxgSHVoPyEg4oie4oenIHVwLCDCvcS/bnkhYCwiLCIiLCJIZWxsb1xuSEVMTE9cbkJZRSJd)
Vyxal's not particularly good at English compression.
```
{ # While...
: ≠| # Take an input, is it not equal to...
‛Ṗ⊍⇧ # "BYE"
aA[ # If all uppercase
`...` %, # Print "No, not since" formatted by
»÷ḟ»21℅+ # 1929 + random(1..21)
`...`, # Otherwise print "Huh?! Speak up, sonny!"
```
[Answer]
**Clojure - 160 154 Characters**
```
(#(if(= % "BYE")%(do(if(=(.toUpperCase %)%)(prn(str"No, not since "(+ 1930(rand-int 9))"!"))(prn"Huh?! Speak up, sonny!"))(recur(read-line))))(read-line))
```
Working on golfing it a bit more. Suggestions welcome.
Run through REPL
[Answer]
# Q, 115
```
{while[1;v:read0 0;$[v~"BYE";'`;v~upper v;-1"No, not since ",/:(($)1?1930+(!)20),'"!";-1"Huh?! Speak up, sonny!"]]}
```
usage
```
q){while[1;v:read0 0;$[v~"BYE";'`;v~upper v;-1"No, not since ",/:(($)1?1930+(!)20),'"!";-1"Huh?! Speak up, sonny!"]]}`
Hi
Huh?! Speak up, sonny!
Hello
Huh?! Speak up, sonny!
HELLO!
No, not since 1938!
Goodbye Grandma
Huh?! Speak up, sonny!
BYE
'
```
] |
[Question]
[
Given an expression like `4 / 2 + 3`, determine whether the expression has the same value in Python 2 and Python 3. Recall that in Python 2 division rounds down (so that `5 / 2 -> 2`), whereas in Python 3 division returns a float (so that `5 / 2 -> 2.5`).
For simplicity's sake, we will only consider expressions of the form:
```
a o1 b o2 c
```
Where
* `a`, `b`, and `c` are numbers between 1 and 5 inclusive; and
* `o1` and `o2` are either the addition, multiplication or division operators (`+`, `*`, `/`)
Note that the restrictions mean the expression will always be the same length and will never have any zero division issues.
Operator precedence is the same as in Python (`*` and `/` have equal and higher precedence to `+`, evaluated left to right).
Since this is in part a parsing challenge, you must take the input exactly as given including spacing in a string-like form appropriate for your language (and not, for example, a preparsed AST).
You can print or return any two distinct consistent values to indicate true or false.
## Test cases
```
1 + 2 + 3 -> true
2 * 3 + 5 -> true
3 / 3 + 3 -> true
4 / 2 * 2 -> true
2 * 2 / 4 -> true
4 / 2 / 1 -> true
5 + 4 / 2 -> true
1 / 2 + 3 -> false
5 / 2 * 2 -> false
3 / 2 * 4 -> false
2 + 3 / 5 -> false
4 / 4 / 4 -> false
```
## Scoring
This is code golf, shortest code in bytes wins.
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~121~~ \$\cdots\$ ~~119~~ 117 bytes
```
#define P(v)v=*x-47?*x-43?v*a:t?a:v:v/a
float d;b;t;a;f(*x){for(t=b=d=*x-48;*++x;t=!++x)a=x[1]-48,P(d),P(b);*x=d==b;}
```
[Try it online!](https://tio.run/##ZVBNc5swEL37V2zpeEYSeAhg2tSK4kOntxxy8M32QRYiZULAgzSE1uO/XrLmq3YLYnl6u/t256mFymXx0rafE51mhYZnUtNasGax/Lq@xGhdM7mya7mqV7UvZ2leSgsJP3DLJU8Ja@gpLStixUEkXd89Z67bcCs@4Y9K0WyDPbLeM0kohgPlrMFSceDnNissvMmsIBROM8AHCQZWG2u2exBwenICN3Qjx4MnJ2SRG3co8qOBW/ohC4ds6C9Hzg86FLuIOxT4o0o8dUSI@g7M@fHQi69z5uMyoJujVlYn/TqBB/@fu@sztKqyMBbUT1kxjFq96qpXcHbNj3DXfPuO32Xk9T0aB6OhQC7TsyLRDbbd8QE@gMl@6zIl417UHwg2MRxct6umnVhv7GTuBuV6g7uaPb9NW0y/yTwvFfnClvRv9l0ZdfxFrAebKzYllt4ogLnob@NbXdDITlb@O/hYYUlKnHluYPEI8wTmZlegORsPjDf5Z4TQ@@vZldbT@PPs3P5RaS5fTLt4/wA "C (clang) – Try It Online")
Inputs the Python expression as a wide string.
Parses the string and returns (at the end of the input string) \$1\$ if the expression is the same in both Python 2 and 3 or \$0\$ otherwise.
### Commented code
```
#define P(v) // Macros are type-less so will
// calculate both floating point
// and integral values
v= // set the parameter to:
*x-47? // is the char at *x not '/' ?
*x-42? // is the char at *x not '+' ?
v*a: // then it's '*' so multiply
t? // here it's '+' so check t
a: // t is only truthy at the start
// so set parameter to a
v: // after that t's 0 so leave
// parameter as is
v/a // here it's '/' so divide
float d; // floating point type for Python 3
// calculations
b; // integral type for Python 2
// calculations
t; // toggle for signalling first and
// second parts
a; // value in Python expression
f(*x) { // function taking wide string
// parameter
for( // loop over first and
// second part
t= // set t to non-zero value
b=d=*x-48; // set d and b to first number
*++x; // move pointer to next char and
// finish looping at the end of the
// input string
t=! // after first loop set t=0
++x) // bump x again
a=x[1]-48, // set a to next number
P(d), // parse with floating point type
P(b); // parse with integral type
*x=d==b; // set end of string to 1 if the
// floating point value is equal to
// integral or 0 otherwise
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes
```
lambda s:eval("1.*%s.>"%s+s)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKrUsMUdDyVBPS7VYz05JtVi7WPN/QVFmXolGGlBYQVvBCIiNlTQ1ueCiRgpaCsZAUVMUUWMFfbAoqloToChIvRGGCUZAGRMsavUVDFFETYFmgmVQRA3BatFtM8VqmzFU1ATNDUDdQBlTDDeYQF32HwA "Python 2 – Try It Online")
This saves a byte using that Python 2 value will always be less or equal within the constraints of this challenge. Inverted output: False means safe, True unsafe.
## Old [Python 2](https://docs.python.org/2/), 29 bytes
```
lambda s:eval("1.*%s.=="%s+s)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHYKrUsMUdDyVBPS7VYz9ZWSbVYu1jzf0FRZl6JRhpQXEFbwQiIjZU0NbngokYKWgrGQFFTFFFjBX2wKKpaE6AoSL0RhglGQBkTLGr1FQxRRE2BZoJlUEQNwWrRbTPFapsxVNQEzQ1A3UAZUww3mEBd9h8A "Python 2 – Try It Online")
Forces Python 3 semantics in Python 2 by converting terms 1 and 3 to float, evaluates and compares to the original.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 33 bytes
```
lambda s:eval(s)%1>eval(s[:5])%-1
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUaHYKrUsMUejWFPV0A7CirYyjdVU1TX8X1CUmVeikaahZKigrWAExMZKmppccFEjBS0FY6CoKYqosYI@WBRVrQlQFKTeCMMEI6CMCRa1@gqGKKKmQDPBMiiihmC16LaZYrXNGCpqguYGoG6gjCmGG0ygLvsPAA "Python 3.8 (pre-release) – Try It Online")
Port of tsh's Javascript answer.
### Old version
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 41 bytes
*Thanks [@Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string) for -2 bytes through some eval wizardry*
```
lambda s:eval(s+'=='+s.replace("/","//"))
```
[Try it online!](https://tio.run/##bY7NCsIwEITvPsWSS1MjhvyBCHkTL1FTFGIb0iL49HENRUjbw16@mZ2Z@JkeQ69OMeXOXnJwr@vdwXj2bxfoyBprGzYek4/B3TwlnBwI56Rtc0zPfqIdJQIYSDyFdPenEvagkJqKKuCF1l6N9OeXqwSJit7wchAVNZhZlIqK4l22mc02NVO92IDfqJjVBj0vy18 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), ~~122~~ 113 bytes
```
L=l-48
g(a,b,o,k)=\{o=-6:ab,o=-1:a/b,k=0:b,a\}
h(k)=mod(g(g(L[1],L[5],L[3],0),k,L[7],1),1)
F(l)=\{h(L[9])>-h(1)\}
```
Basically just a port of tsh's Javascript answer, though a bit more complicated (when was using Desmos in a string parsing challenge ever a good idea??).
Takes in input as a list of character codepoints. Returns `undefined` for truthy cases, and `1` for falsey cases.
Use this [TIO link](https://tio.run/##JYxBCsIwEEX3nmLIKqmuLIK4FbxE4yLaaROomWE6RYp49hjs8r/3@LxqpNyeWUphSVmtuRKvwGFWBI0ID5zoDU/qEaqmPxslcIQ6ZtwiWpQXvRi3204Gc/N@wkHtp2tegS1Jf0i5Nta5@9d7SWNUZ1wpR2ighT2cfg) to convert from string input (`2 * 3 + 5`) to list of codepoints wrapped in the output function (`F\left([50, 32, 42, 32, 51, 32, 43, 32, 53]\right)`) which can be copy pasted into Desmos directly.
[Try It On Desmos!](https://www.desmos.com/calculator/stjjiouqoe)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/lr08ez02pb)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 29 bytes
* Saved 1 bytes by [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)
```
s=>eval(s)%1>-eval(s+'**0')%1
```
[Try it online!](https://tio.run/##Xc7LDoIwEAXQPV9xN4aXUHm4IrDzL4yxweIjYA2tbIzfjiNVQBdt2tM7M73wjquyPd90cJUH0Vd5r/JCdLx2lLuIisAcfdvzVjZBr5Fjb0XwEdNKEBTQ7V1YMTy6@ViPkoANMmVSkncu/qmKSdO/DEM0ypp6GP0KjWfT@IrX6p2a9TaUfCidyBQx80tD6TCezVP7sOG6PDlstz0gxGdjzdHNLB1Wst1wehXICzwsoJRXJWsR1vLoVI5wlxAUfLpZ/wI "JavaScript (Node.js) – Try It Online")
[Try all testcases!](https://tio.run/##ZdrRjlTnEUXhez9F30QzNDEdV@19EwvyIEkkI2eIiMaAmLGlKMqzk8EEu7u/C8vWP/zM0vFZKp2l@tfrX14//Pjx7YfHb9@9/8fdpzcvPz28fHX3y@v724dnf/ju1bdf/vP5zfH4p5ung0@Ph5eHH7757vD88OWfb18dHj/@fPf/kyMnp4uTI7eO3Dpy68StE7dO3PpCOBAOhL@evHl9//A74oA4IF5cO3HtxLWT175ALpAL5Aq5QC6QK@QCuUCukAEyQEbIABkgI2SADJARskAWyApZIAtkhSyQBbKXkIM1gzWDNYM1gzWDNb/d@p36t2vnR6fLoy@QA@QAOUAOkAPkADlCjpAj5AK5QF6JM4gziDOK89u1S8wVc8UMmAEzYgbMgBkxI2bEjJgFs2BWzIJZMCtmxayYV/os@iz6LPos@iz6LPqs@qz6rPos@iz6rHNn8WfxZ507q0CrQKtAi0CLQPv1hb54lgvlQrk8yxVyhVwhA2SAjM8yUAbK@CwjZsSMmAWzYFbMglkwK2bFrJhX@gR9gj5Bn6BP0CfoE/WJ@kR9gj5BnzB9gj3BnjB9ojxRnihPkCfIE6dPsCfYE6dP1CfqE/UJ@gR98vV1vniWgTJQhmcZISNkhCyQBbI@y0JZKOuzrJgV80qeIk@Rp8hT5CnyFHmqPFWeKk@Rp8hTZ0@xp9hTZ0/Vp@pT9Sn6FH2qPkWfok/Vp@pT9an6FH2KPnX6FH@KP3X6VIGqQFWgIlARqF9f6Is3s1AWyvJmVsgKeXY09IKhFwy9YOgFQy8YesHQC4ZeMPSCoRcMvWDsBUMvGHrBnPeCC8QBcUAcEBfEBXFFXBAXxItrJ66duHby2nUtGGrBWAuGWjDUgrEWDLVgqAVjLRhqwVALxlow1IKhFoy1YKgFQy0Ya8FQC4ZaMNSCoRYMtWCoBXNeC85Ojpyc@O3XzgzOzNVrfOTWkVtHbp24deIWoWAIBUMoGEPBEAqGUDCGgjkPBReQC@QKGSADZIQMkAEyPMjAGBgjY2EsjJWxMBbG@iALZIG8UmZRZlFmUWZRZlFmUeaqEIyFYCwEQyEYCsFYCIZCMBSCOS8EF5Qj5Ug5Ui6UC@XyKBfIBXKBXCFXyBUyQAbI@CgDZaDMNcBzj44e4c7izuLO6s7izuLO6s5VIBgDwRgIhkAwBIIhEAyBYAgEQyAYA8EYCMZAMASCIRAMgWAIBEMgGALBGAjGQDAGgiEQDIFgDARDIBgCwRgIxkAwBoIxEAyBYAgEQyAYAsEQCIZAMAaCMRCMgWAIBEMgGAPBEAiGQDAGgjEQjIFgDARDIBgCwRAIhkAwBIIhEIyBYAwEYyAYAsEQCMZAMASCIRDMeSC4oBwpR8qRcqFcKFfKhXKh3GuA5x4dPcKeYk@xpw6fok/Rpw6f6k/1p/pT/Cn@XH7pD31g6ANDHxj7wNgHxj6w9IGlDyx9YOkDSx9Y@sDSB5Y@sPSBpQ8sfWDtA0sfWPrAuk@wBIIlEKz7BEshWArBWgiWQrAUgj0vBBfPcWFcGJfnGBADYkQMiAExPsfAGBjjcyyQBbJCFsgCWSELZIG8cmZwZnBmcGZwZnBmcOZqm2DdJli3CZZEsCSCJREsiWBJBEsiWLcJ1m2CNRIskWCJBGskWCLBEgn2PBJcUK6UK@VKGSgDZaQMlIEy1wDPPTp6hDuDO4M7ozuDO4M7oztXywTrMsGaCpZUsKSCJRUsqWBJBUsq2PNUcHZy5OTEb79WZ1FnnTiLO4s768RZJs4ycVZ1FnUWdfbKgSO3jtw6cuvErRO3iARLJFgiwRoJlkiwRII1Eux5JLiADJARskAWyApZIAtkhSyQBfLKmeBMcCY4E5wJzgRn4sSJEydOnKBN0CZMnGBNsCZMnDhx4sSJ2gRtgjZx4gRvgjfBmzhx4sSJ5gRzgjmXX/pLH1j6wNIH1j6w9oG1Dyx9YOkDax9Y@sDSB9Y@sPaBtQ@sfWDpA0sfWPrA0geWPrD0gbUPrH1g7QNLH1j6wNoHlj6w9IF1gWANBGsgWAPBEgiWQLAGgiUQLIFgzwPBxcNcKVfKlTJQBspIGSgDZXyYETNiRsyCWTDLi1koC2V5lhWyQp4dhT4Q@kDoA6EPhD4Q@kDoA6EPhD4Q@kDoA7EPhD4Q@kDYHwh5IOSBsD8Q6kCoA7EOhDoQ6kDcHwh5IOSBuD8Q@kDoA7EPhD4Q@kDO@8DFcwyMgTE8x4JYECtiQSyI9TkWxsJ4ZcxgzGDMYMxgzGDMYMxgzGDMYMxgzGDMXL3ER24duXXk1olbJ26duHXdBUIXiF0gdIHQBeLyQFgeCMsDMQuELBCyQMwCIQuELBCWB8LyQFgeiE0gNIHQBGITCE0gNIHYBMLyQFgeiEUgFIFQBEIRCEUgFIFQBOLyQFweiMsDIQqEKBCjQIgCIQqE5YG4PBCXB2IVCFUgVIFQBUIVCFUgVIG4PBCXB2IXCF0gdIHYBUIXCF0g513ggjJSRspIWSgLZaUslIWy1wDPPTp6hDxBniBPkCfIE@QJ8oRxE8ZNGDfBnGBOGDdBnCBOECeMmzBuojZBm6BNnDfBm@BNnDdh3oR5E7UJ2gRtcvX@H7l15NaRWydunbhFEghJICSBmARCEghJICaBnCeBC8gCeWVMMaYYU4wpxhRjijF13NRxU8dNkaZIU8dNsaZYU6yp46aOm@pN8aZ4U70p3hRvqjd14NSBU80p5hRz6sAp6hR1ijp14NSBU@Up8hR5Lr/sQw8IPSD0gNgDYg@IPaD0gNIDSg8oPaD0gNIDSg8oPaD0gNIDSg@oPaD0gNID6r5ACQIlCNR9gVIEShGoRaAUgVIEahEoRaAUgVoEShEoRaAWgVIEShGoGwMlCZQkUDcGShMoTaA2gdIEShPoeRO4eCMLY2G8/PWDM4MzgzODM4MzgzNX@wJ1X6DuC5QoUKJAiQIlCpQoUKJA3Reo@wJ1X6B0gdIFahcoXaB0gdoF6sJAXRioZaCUgVIGahkoZaCUgbowUBcG6sJAjQMlDpQ4UONAiQMlDvQ8Dlz8P6@UlfJq4iz2LPYs9iz2LPYs9qz2rPas9iz2LPasQ2fRZ9FnHTqrP6s/qz@LP4s/lx/6JQ@UPFDyQM0DNQ/UPFDyQMkDNQ@UPFDyQF0bqH2g9oHaB0ofKH2g9oHSB0of6HkfuHiYlbJSXtkT7An2BHuCPcGeYE@0J9oT7Qn2BHvC7AnyBHnC7InuRHeiO8Gd4E6cPUGeIE@cPdGeaE@0J9gT7Ln83i@VoFSCUgnq6kBdHaidoHSC0glqJyidoHSCnneCC8pKWSmv3CnuFHeKO8Wd4k5xp3zrlG@d8q1TxCni1LFTzCnm1LFTvnXKt04Vp4hTxKniFHGKOFWc8q1TvnWqNkWbok0dOsWb4k0dOuVbp3zrVG2KNkWbXr3/R24duXXk1olbJ27RB3548fjx7U@3z148fLh/@3h787d3N89e/PT6w@394eWrw/3X488Xbp49@/6bD68fHg4vD48v7n65@/jv29u/vv3j4e7vzz7/4f98czj8@P7dw@Ph/dOfeHP79un05csvv@f7p599vHv8@eO7px8@P9zcPP3o8HT636e/8vOd9/d3L@7f//P217/@L4ebz/@@Ofz5cPPm9dv7m2fff/of)
Basic idea: The expression is "Python 2 / 3 safe" iff both `a o1 b o2 c` and `a o1 b o2 1` is integer after evaluate.
[Answer]
# x86-64 machine code, ~~34~~ 33 bytes
```
B8 66 41 AD AC AC 24 07 9E 92 66 98 7A 0A 72 03 F6 E2 92 FF CF 7B EA B8 F6 F2 84 E4 74 F4 24 80 C3
```
[Try it online!](https://tio.run/##XVLLbtswEDxzv2KqwoBkK47fTe26QJtee@mpQJIDTVIWC5kyTLmRY/jX6y7V@JEeuMTszA6XS6r1@map1PEo/QoxfkQxdZdFuZAFMsqmorvYVQa9@usduQuaTFKOo36IX76RKErtF@dNOg1ZpPhAwss8I1GrfAmj6xRG1iTU4pnErzU0R4WKxGpbQBeC/PQ/aTUV2ijGNhSUcHTdkGbW/uZKEpXxFWSe8mLlC/yli1591yOxMRUlEZIZmboyG4foPsJ@67xdOqOhcrlBFltXgUtU6diuybV9MjsQvbdOFVtt8MlX2pbd/DPRtSqcr6Q3/uEJc@yjPjoY8BpGKaIB2hgyGAcwxG0DGmbEILCDk2zAidGFuUU/gDHrm0QA/YZ5NRhfGwxfweifG0s4MT65NSs6zChcciWtixPak8jKDeI3V8EU5@skJFgj1hsuyuKo5YGWfXTsWaU8r4@8JzxTcaCz5tF9lyq3zvAYtZlGgQ5H1jyYXoodQ11if5Kj1Rv8ZL/dPI7fPEc7yZKHutN54gfAc24Lg3iHd2xS3w@D6dkhblmEX@GTprOaycPx@EdlhVz6481qMuLA/3vOelP8BQ "C++ (gcc) – Try It Online")
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the string (9) in RDI and its address in RSI, and returns a value in AL, 128 if the expression is Python 2/3 safe and 0 if not.
In assembly:
```
f: .byte 0xB8
```
This will be explained later.
```
n: .byte 0x66, 0x41, 0xAD
```
When jumping to `n`, the current number will be in DL.
This is a `lodsw` instruction, encoded in a strange way for reasons to be explained later. This loads two bytes from the string into AX, advancing the pointer; in particular, the operation symbol goes into AH.
```
lodsb
```
Load another byte (a space) from the string into AL.
```
lodsb
```
Load another byte (a digit) from the string into AL.
```
and al, 7
```
Take the low three bits, obtaining the numerical value of the digit in AL.
```
sahf
```
Set certain flags based on certain bits of AH, which contains the operation symbol. In particular:
```
**PF** **CF**
+ 00101**0**1**1**
* 00101**0**1**0**
/ 00101**1**1**1**
```
```
xchg edx, eax
```
Exchange registers.
```
cbw
```
Sign-extend AL (previous number); this makes AH 0.
```
jp d
```
Jump if PF=1, which is true only for `/`.
```
jc t
```
Jump if CF is 1, which is true for `+` but not for `*`. An addition breaks a sequence of `*` and `/`, making the previous number irrelevant; the current number is correctly in DL.
Only `*` is left here.
```
mul dl
```
Multiply AL (previous number) by DL (new digit).
```
s: xchg edx, eax
```
Exchange registers. The product goes into DL.
```
t: dec edi
```
(`+` joins here.) Subtract 1 from EDI.
```
jpo n
```
Jump if the sum of the low 8 bits is odd. This is true the first two times, with 8 (1000₂) and 7 (111₂), but not true the third time, with 6 (110₂).
```
.byte 0xB8
```
If we get here, the expression is Python 2/3 safe.
This subsumes the next two instructions into `mov eax, 0xE484F2F6`.
```
d: div dl
```
(Recall that `/` jumps here.)
Divide AX by DL, putting the quotient in AL and the remainder in AH.
```
test ah, ah
```
Set flags based on the value of AH.
```
jz s
```
If the remainder is 0, jump (and next, exchange the quotient into DL and proceed).
Also, the success case joins here. In that case, the zero flag was last set by `dec edi`, which gave a nonzero result, so the jump is not taken.
```
and al, 0x80
```
Keep the high bit of AL.
In the success case, the high bit is 1 from the `mov`.
In the failure case, AL is the quotient, which is at most 12 (from 25/2), so the high bit is 0.
```
ret
```
Return.
---
Now, the start can be explained. The first byte 0xB8 subsumes the next four bytes into `mov eax, 0xACAD4166`. Those bytes include a `lodsw` instruction, which was encoded with a nonfunctional REX.B prefix (0x41) so that that value goes into AH. After that, the first digit is read by `lodsb`. The 0x41 value, which is in the same place as an operation symbol would be in later iterations, has a 1 in bit 0 and a 0 in bit 2, so it gets treated in the same way as a `+`, making the first digit alone become the current number.
[Answer]
# [Haskell](https://www.haskell.org/), 118 bytes
```
f.words
r=read
f(a:"/":b:t)|(q,m)<-r a`divMod`r b=m<1&&f(show q:t)
f(a:"*":b:t)=f$show(r a*r b):t
f(_:_:t)=f t
f _=1>0
```
[Try it online!](https://tio.run/##TYxLDoIwEIb3nGLSGFPwgeWxaaw38ARqsIBFIggWohvPbh0KMS4m@f7XXGV3u1SVKcTRqPWr0XnnaKEvMncUlZz4hKe8d9/0sazd7UqDPOflc9/kZw2pqLdsPle0uzYveGBt3HjjRqjZEFDceFh2eY9xwhMbAQpIBNttTC3Lu6hlu09oq8t7vy7cA2GwgAAvJEsSgAchcowcgm958CPkIQumToA6@vk@MOQYu1YjM@uP2/hvG04c2T@Yo46nP/bIyXwyVcmiM6usbb8 "Haskell – Try It Online")
Can certainly be outdone, but it's at least something. Core observation is simply that addition doesn't matter at all.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
ḣƬ5ŒV€ĊƑ
```
[Try it online!](https://tio.run/##y0rNyan8///hjsXH1pgenRT2qGnNka5jE/8/3L3l0Najkx/uXPyoYY6Crp3Co4a5D3csOtyuGfn/v6GCtoIREBuDJEqKSlO5jBS0gDxtBVO4iLGCPlgEocYEKAJSZ4SiywgoaoKmRl/BEC5iCjQDIgoTMQTzoCanJeYUgxQhGQ0RMoYKmSCEIJr0IY6ECJmAbddHUgUA "Jelly – Try It Online")
Port of [tsh's (old) JavaScript answer.](https://codegolf.stackexchange.com/a/246634/85334)
```
ḣ 5 Take the first 5 characters
Ƭ repeatedly while unique.
ŒV€ Eval each result as Python.
ĊƑ Are they the same if ceiled?
```
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
Ḥẹ¦”/ŒV=ŒV
```
[Try it online!](https://tio.run/##y0rNyan8///hjiUPd@08tOxRw1z9o5PCbIH4/8PdWw5tPTr54c7FjxrmKOjaKQAlH@5YdLhdM/L/f0MFbQUjIDYGSZQUlaZyGSloAXnaCqZwEWMFfbAIQo0JUASkzghFlxFQ1ARNjb6CIVzEFGgGRBQmYgjmQU1OS8wpBilCMhoiZAwVMkEIQTTpQxwJETIB266PpAoA "Jelly – Try It Online")
Have been trying to think of an *interesting* solution, but a Python eval builtin is a Python eval builtin. Was at least interesting to golf, starting from `”/=kj”/,¹ŒV€E`.
```
Ḥ Double the characters of the input
¦ at indices
ẹ ”/ of slash.
ŒV Concatenate and eval as Python.
=ŒV Is it equal to the input evaluated as Python?
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~38~~ 34 bytes
```
/. [\/*] ./;$_=(eval.eval$&)!~/\./
```
[Try it online!](https://tio.run/##Xc5LCsIwEAbgvacYoYi2JNO8VkVv4AmsSBcRhGBLU116dGMeta0uEpiPf/6k071RziKQA80RK4cUTjXmZ6BYZZf9Vj8bQ8OVbXbrF9YUnWNQAPdH@C0Y@odeccj9VICaRABGmTPSS8jxny3uVf5lENgkynck/QqL09h8bYwNoUV1IjGSnCktYfpkIhlfx0Xq3XbDrb1bR46Klqx0pDMf "Perl 5 – Try It Online")
*Simplified regex since the input format is very strict to save bytes.*
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 52 bytes
Inspired by des54321's comment that said:
>
> I'm waiting for a competitive solution to this that isnt simply "eval the string as a python expression"
>
>
>
I decided to "cheat" even further by actually running both Python versions:
```
f(){ p=python;r=print\($1;$p\3<<<$r==`$p<<<$r\)`\);}
```
[Try it online!](https://tio.run/##dZAxDoIwFEB3T/HTMICENBSYCo6ewJEBJBhMDDQtDsZ49loqlhZ0IJCXx//tO9eik/LiB09gBXuM3dBTXjB@7cfS92LqsTLJ89zjRVF5TH@VQVUG9CXbphsAnfi9hbEVIzS1aAXaaRz1gGIIgagngegAiMLFQpZGYK@UELJFM8jSEsCaWdMMsrRUsel3smgGrZYSxVN3qUabaRji9TSFLC1Th/hwoxk0a@j7PtY38TcY3gbDm2DZ9orZjysmM0vdYBo5JaaF2M0/o1WJ1A1mEJJv "Bash – Try It Online")
Simplified, it's essentially just doing:
```
f() { python3 <<< "print\($0 == `python <<< print\($0\)`\)"; }
```
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 68 bytes
Or **[R](https://www.r-project.org/)>=4.1, 54 bytes** by replacing two `function` occurrences with `\`s.
*Edit: -1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(s,`-`=function(x)eval(parse(t=x)))-s>-paste("`/`=`%/%`;",s)
```
[Try it online!](https://tio.run/##bY7RCoMgFIbve4qDI9AtkdSuhj2LMhQG0Uba6O2dSURJF174fef855@iU9HN4yu8PyP2jaZa7d@F2J8Z8NdM3uKgFkII9T39Gh8sRppppWtW6ydqPIkOoxYewNMTiNyA9hCm2VaJc7iDSLwruACWeTkvE193@EUOT05ezjNoC96l7OyOvMpF2amoM4PfNs6XdyE2IUuRY5LsSrEeloeyWcQ/ "R – Try It Online")
Outputs inversed `TRUE`/`FALSE`.
Compares results of evaluating the expression and evaluating the expression with ``/`=`%/%`;` prepended (which redefines division to be integer division). My first approach to simply substitute `/` with `%/%` in the expression fails due to `%/%` having higher precedence than `/` and `*`.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/): 24 65 Bytes
Realized my old code doesn't work, had to replace it with something more complicated. Also doesn't work on TIO.
`e="Python"~ExternalEvaluate~#&;e@StringReplace[#,"/"->"//"]==e@#&`
Uses the same trick as the 10-byte Jelly answer, but is significantly longer due to Mathematica's ExternalEvaluate taking almost 30 bytes instead of 2.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
'/x.:‚.EË
```
[Try it online](https://tio.run/##MzBNTDJM/f9fXb9Cz@pRwyw918Pd//@bKugrGCloKRgBAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXLf3X9Cj2rRw2z9FwPd//X@R@tZKigrWAExMZKOkpGCloKxkC2KZBtrKAPZoPETYBskJwRVI0RkG8CF9dXMASyTYFqwXwg2xAsDtFriqTXGMo2AZsDlAfyTaHmgLFSLAA).
**Explanation:**
Uses the legacy version of 05AB1E for two reasons:
1. It's build in Python 3, and `.E` is therefore an 'Eval as Python' builtin, whereas the new 05AB1E version is build in Elixir and `.E` is an 'Eval as Elixir' builtin.
2. Double works on strings in the legacy version of 05AB1E, so we can use `x` instead of `„//` to save 2 bytes.
**Explanation:**
```
'/ '# Push string "/"
x # Double it (without popping): "//"
.: # Replace all "/" for "//" in the (implicit) input-string
‚ # Pair it with the implicit input-string
.E # Evaluate both as Python
Ë # Check if the results in the pair are the same
# (after which the result is output implicitly)
```
[Answer]
# [R](https://www.r-project.org/), ~~61~~ 59 bytes
(or 52 bytes in R≥4.1 using `\` instead of `function`)
```
function(s,t=48-s,u=t<2)!(t[1]*t[5]^(-1)^u[3]/t[9]^u[7])%%1
```
[Try it online!](https://tio.run/##dZDNCsIwEITvfYpVKSStJeSnWMF49@6tRBAxIEgrZgO@fYxVai31ENjwzUwyew9WB@ubE17ahrglalUVbuk1bgSdEay5ybAuzYEUnB58LQ3Dem3itDI0TXm4Cel0H/Cgljjt0Vb7dtdgvNMkeUnInEMOIh4JcwoLKLaAd3/@QAFZBDmUU1AC6@CkU0X4cot/sSIK1H8nAz4Fy/jeW/AD@y5s1MUer@7rHX9pSOWHqkn6TmWDRQyp6rqwsTc8AQ "R – Try It Online")
Checks 'by hand' without using `eval`. Input is list of codepoints.
---
# [R](https://www.r-project.org), 64 bytes
(or 57 bytes in R≥4.1 using `\` instead of `function`)
```
function(s,`$`=sapply)any(substring(s,1,3*2:3)$str2lang$eval%%1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZBNCoMwEIXp1lMM1oK_BBOFUrD0KMaiIoRUjBY8Szd24aHa0zSallqriyEw37w3eXO7V11fYiKivqkzb_84ZQ0_18WFm8KNjTgStCxZa1HemqJJRF0VPJfId4mND8QyZAczynMjvVK22_mW8nluksHV1H1wAMsioFuwBe8IddWkmoIYbAkcCJcgATTCRWUg4aDGa7ZYDgTrSgT-EgzlPjXwA7VPFjTLklEmvtr5l6aUvGmwSJUrmhxiSoMxC_rTqlN3nXpf)
`eval` approach, but different to that used by [pajonk's R answer](https://codegolf.stackexchange.com/a/246687/95126): here we check that both `"a o1 b "` and `"a o1 b o2 c"` are integers when evaluated as expressions in R, which uses `/` for floating-point division. Output is reversed (`TRUE` indicates NOT python 2/3 safe).
[Answer]
# TI-Basic, 44 [bytes](https://codegolf.meta.stackexchange.com/a/4764/98541)
```
Input Str1
"0
For(I,1,9,2
Ans+sub(Str1,I,1
End
fPart(expr(Ans)) or fPart(expr(Ans+"^0
```
* uses the same approach than [tsh's answer](https://codegolf.stackexchange.com/a/246634/98541): *The expression is "Python 2 / 3 safe" iff both `a o1 b o2 c` and `a o1 b o2 1` is integer after evaluate*
* spaces are significant in TI-Basic, they produce a `Syntax Error` if evaluated, so the loop keeps only the relevant characters (starting with an extra zero because an empty string is not possible
* `fPart` keeps the fractional part of a number
* outputs `1` for not safe and `0` for safe
[Answer]
# [Julia 1.0](http://julialang.org/), ~~46~~ 40 bytes
```
~x=eval(Meta.parse(x))%1>0
!s=~s|~s[1:5]
```
[Try it online!](https://tio.run/##XY7LCsIwEEX3/YprQUi1WtPHRmj/wC8QFyNGiIRYkipdSH@9pk19DmQxJ2fuzOWmJPG277u2FHdSbCcaWtdkrGBtFM15tQlmtuzso7N7vi0O/flqICE1jKCTklpYFgVwRTGOKGFrJRsmY4RYVQj9X22kbpRmhLLCjKJA6FPPsUTqXjaIjbmJIMXCdUsUb5IhGcnHyR0ZvPRnKnU0/3MS8DcpXIanL8LHbko@k7KD9BXtUTah/IP8UOKP9Cgftydf1hM "Julia 1.0 – Try It Online")
port of [tsh's answer](https://codegolf.stackexchange.com/a/246634/98541)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 29 bytes
```
s->!(eval([s,Str(s"^0")])%1.)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9BCsIwEEWvMg4IibbWJA24sZdwWapkYaVQSkir4FncFEQ8hd7D2zhJW3QxzLz_Px_m9rTGVYeT7e8lbB_nrow3rzbOZux4MTXL22jXOdbifo284HOx4kPm8zbW1ldmIM7Auqrp6EQPCCUznEeQo4AlSBqFEaCEBSgC7UFBEiA4KYF35RSTJKQ_JwHhQVM-CB5EcMYC_V-gRkiHNoqQoKe2MFiMX_T9sL8)
A port of [tsh's JavaScript answer](https://codegolf.stackexchange.com/a/246634/9288).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 48 bytes
```
s->eval(Str(s"=="strjoin(strsplit(s,"/"),"\\")))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY9BCsIwEEWvMswq0ZTapAU37SVcWpEsrERKDU0UPIubgoi38B7exknaooth8v7_8yH3l9W92R_t8GigfF58k6w_K5dUh6tu2cb3zGFZovP96Ww6RtvZ1njmBKbIBdY1cs6nu7e2tr0xDUkFtjedpycGQGiY5lzAFjNYgqRRKAAlLEARFAEUpBGikxMEV84xSUL-c1LIAhSUj0KALDpTQfFfoCbIxzaKkFDMbXFwN_1iGMb9BQ)
A port of [Aiden Chow's Python answer](https://codegolf.stackexchange.com/a/246628/9288).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 73 bytes
```
\d
$*
^1+\+|[+*]1+$
1(?=1*\*(1+))|\*1+
$1
+r`^(\2)+/(1+)\b
$#1$*
^1+$
```
[Try it online!](https://tio.run/##PYu9DgIxDIP3PEUkitRLhir9GREvwUY5CoKBheHEeO9e0nBisGR/tpfn5/W@9b0/NWzXXh8MjmAWrryemS7CDkD88SBUyQtP01pJdCTAS5t9jROHwesd3E5@X9e7IGNUJYhImNQVSBjMJcjqBo/WRk15YwEFim4sgRgbj/J/pM1lsEZTsa/pCw "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: After reading the question more carefully, code now parses according to input rules, saving 1 byte because only digits `1`..`5` need to be supported (code actually supports `1`..`9`) but adding 3 bytes to delete spaces. Explanation:
```
```
Delete spaces.
```
\d
$*
```
Convert to unary.
```
^1+\+|[+*]1+$
```
Delete any additions and trailing multiplications as they have no effect.
```
1(?=1*\*(1+))|\*1+
$1
```
If there's still a multiplication left then perform it now.
```
+r`^(\2)+/(1+)\b
$#1$*
```
Perform divisions from left to right where possible.
```
^1+$
```
Check that all the divisions succeeded.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
¹Nθ≡S/«Nζ¿﹪θζ⎚≧÷ζθ»+Nθ≧×Nθ≡S/¿﹪θN⎚
```
[Try it online!](https://tio.run/##jU@7DoIwFJ3lK26YimKIjwkno4sDxqg/UKFAk/JqCyYYvr1ejCbA5HYf5xmmVIYFFcZcJM81WTk765SXtT7X2YNJUuGunlyHKZDP/aYRlxDHgZcVUsXA9mwf59mQ1SJrxmMgQRHVoiCVCy0yDoJRSfofE8gMaLlXiif5lSepRnl95A2PGIJd6I27r8MCHaahIhbTWmh/qnLnGVPuCO781P4oMg49UhkW6IzZgAdrmMPWLBvxBg "Charcoal – Try It Online") Link is to verbose version of code. Allows any sized integer inputs but only two space-separated operations and outputs a Charcoal boolean i.e. `-` for safe, nothing for unsafe. Explanation:
```
¹
```
Assume that the expression is safe.
```
Nθ
```
Input the first integer.
```
≡S
```
Switch over the first operator.
```
/«
```
If it's a `/`, then:
```
Nζ
```
Input the second integer.
```
¿﹪θζ⎚
```
If the second integer does not divide the first then clear the canvas.
```
≧÷ζθ»
```
Otherwise divide the second integer by the first.
```
+Nθ
```
If the first operator is a `+` then ignore the first integer and input the second integer.
```
≧×Nθ
```
Otherwise input the second integer and multiply the first integer by it. (This case is chosen as the default case because it can't parse as an expression.)
```
≡S/
```
If the second operator is a `/`, then...
```
¿﹪θN⎚
```
... if the third integer does not divide the current total then clear the canvas.
[Answer]
# [MATLAB](https://www.gnu.org/software/octave/), 72 bytes
```
function p(i),eval(i);eval(regexprep(['x=' i],'(\d)','int8($1)'));ans==x
```
pretty boring, eval the string as doubles and then again as integers. If the expression is different as an integer, then yeah. I don't know python, but I can guess how it works.
[Try it online!](https://tio.run/##y08uSSxL/f8/rTQvuSQzP0@hQCNTUye1LDEHSFuD6aLU9NSKgqLUAo1o9QpbdYXMWB11jZgUTXUd9cy8EgsNFUNNdU1N68S8Ylvbiv//jQE "Octave – Try It Online")
] |
[Question]
[
### Challenge
Implement the "greedy queens" sequence (OEIS: [A065188](https://oeis.org/A065188)).
### Details
*Taken from the [OEIS page](https://oeis.org/A065188).*
This permutation [of natural numbers] is produced by a simple greedy algorithm: starting from the top left corner, walk along each successive antidiagonal of an infinite chessboard and place a queen in the first available position where it is not threatened by any of the existing queens. In other words, this permutation satisfies the condition that \$p(i+d) \neq p(i) \pm d\$ for all \$i\$ and \$d \geq 1\$.
\$p(n) = k\$ means that a queen appears in column \$n\$ in row \$k\$.
**Visualisation**
```
+------------------------
| Q x x x x x x x x x ...
| x x x Q x x x x x x ...
| x Q x x x x x x x x ...
| x x x x Q x x x x x ...
| x x Q x x x x x x x ...
| x x x x x x x x x Q ...
| 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 Q x x x x ...
| ...
```
### Rules
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply, so you can:
* Take an index \$n\$ and output the \$n^{th}\$ term, either 0 or 1 indexing.
* Take a positive integer \$n\$ and output the first \$n\$ terms.
* Output whole sequence as an infinite list.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (per language) wins!
### Test cases
First `70` terms:
```
1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, 39, 41, 16, 18, 45, 17, 48, 20, 51, 53, 21, 56, 58, 60, 23, 63, 24, 66, 28, 26, 70, 72, 74, 76, 78, 30, 32, 82, 84, 86, 33, 89, 34, 92, 38, 36, 96, 98, 100, 102, 40, 105, 107, 42, 110, 43, 113
```
(See also: <https://oeis.org/A065188/b065188.txt>)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 38 [bytes](https://github.com/abrudz/SBCS)
```
1+{⍵,⊃⍸|⊃×/×(⌽⍳≢⍵)(⊢×+×-)⍵-⊂⍳3×≢⍵}⍣⎕⊢⍬
```
[Try it online!](https://tio.run/##JZA9TsNAEEZ7n2LLRNmIXY//chxLYJoIEFQoSQMSUiws0bkmtHQIiYbKN9mLmPeFYndm3nyzM7Pt3XZ9@dhub6/nLr287ea42qXh26f@OQ0/e8w0XkzjIr3@puErHU8kl4vUn6ZxNY3rJeE69U/kbBr/04c0fGDQpOFzPsydiyHrnIUM1N480KZz9Tm6v1LT6J15V3qXe1d4t/EugiIsAivvGjxojQJJDFipFYNNYnFqDW5wgxfiVEfKC3iEF/g59SW5kga5LJoSXuldWCXOWxU8lx5bk6vpUcNrxXCDGazRgTdwo7bRTNoDbtLBNzpaIwRdWvTsaKyguTS/Fiu0dbRM/3R853/@AA "APL (Dyalog Unicode) – Try It Online")
Kinda port of tsh's [JS](https://codegolf.stackexchange.com/a/235150/78410) and [Python](https://codegolf.stackexchange.com/a/235153/78410) answers. They actually need some explanation of *why* it works, rather than *how*.
Instead of going through antidiagonals, this solution simply goes through the columns and places a queen on the smallest available row number (testing up to `3×(current column number-1)`).
### Why it works
The first question is why generating by column works.
**Claim:** If the \$n\$-th column has its queen on the \$k\$-th row by generating by antidiagonals, it does so by generating by columns.
**Proof:** The premise means that all cells at \$(x,y)\$ (column, row) where \$x+y < n+k\$ or \$x+y = n+k \;\wedge\; x < n \$ are either occupied by a queen or attacked by an existing queen. Then, any queen placed up to the \$n-1\$-th column cannot attack \$(n,k)\$ since \$(n,k)\$ is strictly above the rightward attack vector of all available cells up to \$n-1\$-th column. Therefore, \$(n,k)\$ is guaranteed to be available when \$n-1\$ columns are filled, and therefore a queen is placed at that precise position. \${\blacksquare}\$
Now, let's dig into the magic formula `(u-=v)**3-u*m*m` in the JS answer. The entire `a.every(...)` part can be ungolfed into `a.every((u,i)=>(u-v)*(u-v+n-1-i)*(u-v-n+1+i))`. `1+i` part is induced by 0-indexing of JS, so let's adapt it to 1-indexing instead.
**Claim:** Given the current sequence \$a=(a\_1,a\_2,\cdots,a\_{n-1})\$, \$a\_n\$ is determined as the smallest integer \$k\$ that satisfies \$\forall i, (a\_i-k)(a\_i-k+n-i)(a\_i-k-n+i) \ne 0\$, i.e. \$(a\_i-k)^3 - (a\_i-k)(n-i)^2 \ne 0\$.
**Proof:** Since the column numbers are all distinct, it suffices to check the horizontal and two diagonal directions. The queen to place is at \$(n,k)\$ (again, column then row) and the queens already placed are at \$(i, a\_i)\$.
* Horizontal: row numbers should be distinct. \$a\_i \ne k\$; \$a\_i - k \ne 0\$
* Main diagonal: the difference between the row and column should be distinct. \$a\_i-i \ne k-n\$; \$a\_i-k+n-i \ne 0\$
* Antidiagonal: the sum of the row and column should be distinct. \$a\_i+i \ne k+n\$; \$a\_i-k-n+i \ne 0\$
Take the product of the three to get the inequality we want. \${\blacksquare}\$
Finally, I'm using `3(n-1)` as the search limit, instead of searching towards infinity. That is simply because each queen in the previous columns can attack at most 3 cells on the current column, and there are only `n-1` queens placed so far, and `(1,1)` can attack at most two. So at most `3n-3-1` cells can be attacked in total.
### The code
```
1+{⍵,⊃⍸|⊃×/×(⌽⍳≢⍵)(⊢×+×-)⍵-⊂⍳3×≢⍵}⍣⎕⊢⍬
1+{...}⍣⎕⊢⍬ Given input n, generate n terms
(1+ is to compensate the first term being 0
which is the result for empty list)
⍳3×≢⍵ Candidate row numbers
⍵-⊂ a_i - k
(⌽⍳≢⍵) n - i
(⊢×+×-) (a_i-k) × ((a_i-k) + (n-i)) × ((a_i-k) - (n-i))
|⊃×/× Test for each row number that all values are nonzero
⍵,⊃⍸ Take the first nonzero index and append to ⍵
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
f=n=>a=n?[...f(--n),(g=v=>a.every(u=>(u-=v)**3-u*m*m--,m=n)?v:g(v+1))(1)]:[]
```
[Try it online!](https://tio.run/##FcpNCoMwEEDhq8ymOJOaoLRQKoweokvrImgURSfiT6Cnt7p7fLzBBrvWSz9vWnzjjqNl4dyyFKUxpkWthWLsOJxoXHDLD3fOcdccSKmH3tWkJq3jiYWKkHUY7ikRplRlZXXUXlY/OjP6Dlt8JWQmOyNKDD0B54ACd4giMrNtPptdNnzSKdjDDdIEmOENBURfiSC7PjKD7wWvOv4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
Ṁ×3Rḟḟ+;_ɗJ$Ṃ;
1Ç¡Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8///hzobD042DHu6YD0Ta1vEnp3upPNzZZM1leLj90MKHOxb9///fyAAA "Jelly – Try It Online")
A full program taking a zero-indexed n as the argument and printing the relevant term.
[Here’s the first twenty terms](https://tio.run/##y0rNyan8///hzobD042DHu6YD0Ta1vEnp3upPNzZZM1leLj9UeOOQwsf7lj038jg4Y5tQH7Tmv8A "Jelly – Try It Online") with a slightly modified pair of links that can be passed an argument from within (rather than always using the command line argument).
## Explanation
### Helper link - extend sequence z
```
Ṁ | Max
×3 | Times 3
R | Range (1..this)
ḟ | Filter out existing sequence members z
ḟ $ | Filter out values guven by the following applied to the current sequence:
+;_ɗJ | - z plus indices of z concatenated to z minus indicies of z
Ṃ | Min
; | Concatenate existing sequence z
```
### Main link
```
1Ç¡ | Starting with 1, call the helper link the number of times indicated by the argument
Ḣ | Head
```
[Answer]
# JavaScript (ES6), ~~58~~ 55 bytes
Returns the \$n\$th term of the sequence, 0-indexed.
```
f=(n,x=0,y=1)=>n-x?f(n,++x*x/(d=y-f(n-x))^d?x:!++y,y):y
```
[Try it online!](https://tio.run/##FYxBCsIwEEWvMkIXGSfRdlsdexNpaFpRykRakQmlZ49x9XmPx3/5r1@H5fn@OIlhzHliI1a5tokb5Js47aZiiPSoZxM4uYJOEe@h0/ZAlGzCNuUpLkaAob6AwBWa/xIhDFHWOI@nOT5M7021yY4lq7Zyg3uP@Qc "JavaScript (Node.js) – Try It Online")
Because of the nested recursion, this is slow as hell for \$n>9\$. We can speed it up drastically [by adding a cache](https://tio.run/##FYzBCsIwEER/JUIPWTfRehKqaz9ElIamEUvZSCuS0PbbY3qaecxjevMzUzu@P1/N3nYpOZKsApUq0gno5u78INah3sqyuDwihn04SktRZ9QB4GnrUO0Qo4pQxeT8KFmQKC@CxVWct0QE0Xqe/NAdBv@SjZHFzCtkrZjzDawNpD8) (66 bytes).
### How?
Given a candidate value \$y>0\$ for a queen at column \$x>0\$, we compute the difference \$d\$ between \$y\$ and each previous value in the sequence.
The way the sequence is built, the queens are already guaranteed to be on different columns. But we additionally want:
* \$d\neq 0\$, meaning that the queens are on different rows.
* \$|d|\neq |x|\$, meaning that the queens are not on the same diagonal or anti-diagonal.
The second condition can also be written as \$d^2\neq x^2\$. If \$d\neq 0\$, it can be further modified into \$x^2/d\neq d\$.
In the JS code, we actually use a XOR:
```
x * x / d ^ d
```
The decimal part of the division is lost in the process. This is fine because the integer part of \$x^2/d\$ is guaranteed to be different from \$d\$ whenever we have \$x\neq d,\:d\neq 0\$.
If \$d=0\$, the above expression is `Infinity ^ 0`, which evaluates to \$0\$, forcing the solution to be rejected as expected. So we don't need to test \$d=0\$ explicitly and this works for all cases.
### Commented
```
f = ( // f is a recursive function taking:
n, // n = input
x = 0, // x = counter to test the solution against
// all previous terms
y = 1 // y = current solution for a(n)
) => //
n - x ? // if x is not equal to n:
f( // do a recursive call:
n, // pass n unchanged
++x * x / // increment x
( d = // compute:
y - f(n - x) // d = y - f(n - x)
) ^ d ? // if int(x²/d) is not equal to int(d):
x // leave x unchanged
: // else:
!++y, // increment y and reset x to 0
y // pass y
) // end of recursive call
: // else:
y // success: return y
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 64 [bytes](https://github.com/abrudz/SBCS)
```
{a←⍬⋄⍵↑1+-/¨a[⍋⌽¨a]⊣{a,←1↑(⍸∘.≥⍨w)~a∘.+(¯1+⍳3 2)∘.×w←⍳3×⍵}¨⍳3×⍵}
```
[Try it online!](https://tio.run/##RY8/SwNBEMX7fIotE7LR3Zv7l9pGW2MnFgtyNkEFiyBBGyWYxAtaSGxVhCuEFEGwsbl8k/ki53tpLHb3zW/ezM6Ey2Hv9DoML86aZhx08qTll87vtfzWybPv9nbrKhxrOdfHX6gTnX2Mg4XNI93W8kcfXnd0@qllNercBkbddr3yXS3XYqIOwWY52vZdy2aJvjd19a@bYpta6OyuXgl66uJlcLiH@2j/YNAUxrtWYcS1dPYezq9gLkzmWpTTN2@NWJNYE1kTW9O3xgN5MA@YWpNDgWZwwOIdXroZAwvN5KgVcAEX8Jgc1R7lMbgHj6Ej1CfIJfgg4gtPAp6yL1hKjl4peEQ/3gy5DH9k4BljcAETsJwHPAcX1OaciXuAC33gfR6u4RwvLroVHMtxLs7PxWJu7eUP "APL (Dyalog Unicode) – Try It Online")
tsh's arithmetic formula looks quite nice, I'll try to incorporate that in this answer later.
### How it works
In this code, each cell is labeled as `(antidiagonal number, horizontal coordinate)` so that the antidiagonals are generated and tested in a horizontal fashion (which suits well to APL primitives).
```
(1,1) (2,2) (3,3) (4,4)
(2,1) (3,2) (4,3)
(3,1) (4,2)
(4,1)
...to...
(1,1)
(2,1) (2,2)
(3,1) (3,2) (3,3)
(4,1) (4,2) (4,3) (4,4)
```
Then, instead of accumulating "until we have all coordinates for columns 1..n", it simply collects until 3n columns are available, and at k-th iteration, first 3k antidiagonals are tested for the new point to add to `a`.
In this new coordinate system, the Queen's attack vectors are signified with `(1,0)` (S), `(2,1)` (SE), `(1,1)` (E), and `(0,1)` (NE). NE is needed to prevent taking another coordinate from the same antidiagonal. I add `(0,0)` (staying still) and `(2,0)` (S twice) for the sake of golfiness, so that all the vectors are easily generated as `¯1+⍳3 2`.
When the accumulation ends, `a` is sorted by the column number, and row numbers are evaluated and the first n terms are extracted from that.
[Answer]
# [Python 3](https://docs.python.org/3/), 68 bytes
```
f=lambda n,i=1:i*all(n-m!=abs(i-f(m))>0for m in range(n))or f(n,i+1)
```
[Try it online!](https://tio.run/##jY5BCsIwEEX3OcVYKGRsKw26EuIRvICIxNrolGRS0hbUy9fWhbp0M3zm895M@@hvgdfjaLUz/nwxwDlptaWlcU5y4RfanDtJhZUecVfaEMEDMUTD11oy4rSwcoIyhWMbiXu5PCTp5pJAOhWEMCP0RVSJRxSCfBtiD3bgqg/BdcLqT165OJwqU91q6c29o2et94FrlBbFbGt@bTmo8j1w@8/5Jocme/8wvgA "Python 3 – Try It Online")
[Answer]
# [R](https://www.r-project.org/) >= 4.1, 68 bytes
```
\(n)Reduce(\(x,y)c(setdiff(1:(3*y),c(x,x+(a=seq(x)),x-a))[1],x),1:n)
```
[Try it online!](https://tio.run/##PcgxCoAwDAXQ6@RrBFs3wUu4ioO0DbhUtBXi6aOTb3yXyWRy51D3I1PGnOIdEv2j/CBQSTXuIuRGGpoHHL7XlrappJMUYO02YHErK9iNGSbke5j5/gU "R – Try It Online")
A function taking an integer n and returning the sequence of the first n terms in reverse order.
[Answer]
# [Perl 5](https://www.perl.org/), 103 bytes
```
$s{$i}=!grep{$t=$_;grep$s{$i-$_*$t},999..1001}1..$i++/1e3and say$r=$i%1e3and$i-=$r-1e3or redo for 1..$_
```
[Try it online!](https://tio.run/##JYxRCgIhFEW3YnD7adKUGELCJbQGGRgLIXR4ShCDW@/l1N85F85dAj1HZpQVsbndg8Kyojr464a/WcIfUNvRWquU0do0oxTiMJxMOE9pFmV6gxzi/u@9cCDZJZOgMGdx77A1nvmiP3mpMafCMrG8vcZ@@QU "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╙½#≡]☺è60S|f♣V♦i+é(ç░m
```
[Run and debug it](https://staxlang.xyz/#p=d3ab23f05d018a3630537c66055604692b822887b06d&i=)
Runs as an infinite loop producing output. It's very brute-force.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
+;_ɗJ;⁸1ḟ1#;
1Ç¡Ḣ
```
A full program that accepts a non-negative integer, \$n\$, and prints the sequence element at that (0-indexed) index.
**[Try it online!](https://tio.run/##ASYA2f9qZWxsef//KztfyZdKO@KBuDHhuJ8xIzsKMcOHwqHhuKL///83MA "Jelly – Try It Online")**
### How?
Keeps the natural numbers (i.e. 1-indexed row indices) in a list (initially `[1]` (well, `1` but Jelly :D)) and repeatedly finds the first row in which a queen may be placed in the next column by counting up from 1 until a number is reached that is not on an any, thus far, occupied row, leading diagonal, or trailing diagonal.
```
+;_ɗJ;⁸1ḟ1#; - Link 1, prefix with next element: list (current elements in reverse), E
J - range of length -> [1,2,...,length(E)]
ɗ - last three links as a dyad - f(E, J(E)):
+ - add (vectorises) -> occupied trailing diagonal row indices
_ - subtract (vectorises) -> occupied leading diagonal row indices
; - concatenate these together
;⁸ - concatenate E
1 1# - start with 1 and count up, collecting the first 1 that are truthy under:
ḟ - filter discard -> singleton list containing the next available row index
; - concatenate E -> a new, slightly longer, list of elements in reverse
1Ç¡Ḣ - Main Link: non-negative integer, n (0-indexed)
1 - start with 1
Ç¡ - repeat Link 1 n times
Ḣ - head of the resulting list
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
FN«≔¹θW⊙υ№×E³⊖ν⁻ιμ⁻θλ≦⊕θ⊞υθ»Iυ
```
[Try it online!](https://tio.run/##Rc29DoIwFIbhGa7ijOckNZE4MhFcGDAM3kDFKk3aA/RHY4zXXiEh@m3v8OXpB@n6UZqUbqMDbHiK4RTtRTkkgneeVd7rO2MhYKYyz56DNgqw4hdGAfUYOeBZW@WxlRMeBBxV75RVHNQVmUhAqzl61ALsv2YBhpbBctqAhn@/jeqiH1ZkjU/eOb1QtfQBI1GZUrFPu4f5Ag "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation:
```
FN«
```
Loop `n` times.
```
≔¹θ
```
Start by trying to place the queen in the first row.
```
W⊙υ№×E³⊖ν⁻ιμ⁻θλ
```
For each previously placed queen, check whether its row offset equals its column offset multiplied by any one of `-1`, `0` and `1`.
```
≦⊕θ
```
If any queen is in the same row or diagonal then try the next row.
```
⊞υθ
```
Push the newly placed queen to the predefined empty list.
```
»Iυ
```
Print the list of queens.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~104~~ 70 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⊢/↑⍸⍉{1@(⊂⊃{⍵[⍋⊢/↑⍵]}⍸~⊃∨/(≢⍵)∘{⊃∘.(=∨0=×)/|⍵-⊂⍳⍺}¨⍸⍵)⊢⍵}⍣⍵⊢1↑⍨2/2×⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37UtUj/UdvER707HvV2Vhs6aDzqanrU1Vz9qHdr9KPebrj01thaoJo6oNSjjhX6Go86FwHFNB91zKgGC83Q07AFShjYHp6uqV8DlNIFmdO7@VHvrtpDK8CmA1V3gTQBzVkMpIAcQ7DJK4z0jQ5PB0kAAA&f=S1MwNAQA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
A dfn submission which takes the number of terms to output.
A bit ungolfed, most of the bytecount is finding the cancelled out squares.
Instead of going by antidiagonal, goes column by column and places greedily.
[-34 bytes from dzaima.](https://chat.stackexchange.com/transcript/message/59090582#59090582)
] |
[Question]
[
Take a matrix **A** consisting positive integers, and a single positive integer **N** as input, and determine if there are at least **N** consecutive occurrences of the same number in any row or column in the matrix.
You need only test horizontally and vertically.
### Test cases
```
N = 1
A =
1
Result: True
----------------
N = 3
A =
1 1 1
2 2 3
Result: True
----------------
N = 4
A =
1 1 1
2 2 3
Result: False
----------------
N = 3
A =
3 2 3 4 2 1
4 1 4 2 4 2
4 2 3 3 4 1
1 1 2 2 3 4
3 2 3 1 3 1
1 1 2 2 3 4
Result: True
----------------
N = 1
A =
5 2 3 8
Result: True
----------------
N = 3
111 23 12 6
111 53 2 5
112 555 5 222
Result: False
----------------
N = 2
4 2 6 2 1 5
2 3 3 3 3 3
11 34 4 2 9 7
Result: True
```
Explanations are always a good thing :)
[Answer]
## [Husk](https://github.com/barbuz/Husk), 9 bytes
```
≤▲mLṁgS+T
```
Takes a 2D array and a number, returns `0` for falsy instances and a positive number for truthy instances.
[Try it online!](https://tio.run/##yygtzv7//1HnkkfTNuX6PNzZmB6sHfL////oaBMdIx0zIDbUMY3ViTbSMYZBIM/QUMfYRAekwlLHPDb2vxEA "Husk – Try It Online")
## Explanation
Husk is a functional language, so the program is just a composition of several functions.
```
≤▲mLṁgS+T
T Transpose the array
S+ and concatenate with original.
We get a list of the rows and columns of the input array.
ṁ Map and concatenate
g grouping of equal consecutive elements.
This gives all consecutive runs on rows and columns.
mL Map length over the runs,
▲ take the maximum of the results
≤ and see if it's at least the second input.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
;ZjṡƓE€S
```
Takes the matrix as arguments and reads the integer from STDIN.
[Try it online!](https://tio.run/##jU65DQIxEMxdxRbgxOvzASKmAiKwHJKcrgFSEgqgAnIaIEaiD2jE7GcHSEhI@87MjnY6zPOx1vV@et2vz8vmfbpt6@NMbVeDi26g5I41O8g5lOK8DB44Ci2Q0QNF/IeLunoYZDDRIBcKce2oalVuWnXH7qNo9w1af2jti9SQZf85kBAACYOAPMJoHsqkKLwwqTG8ppSEp4KIzY8fFvVonU3sTvb4nc2T/uLbdr@iXJBr@QA "Jelly – Try It Online")
### How it works
```
;ZjṡƓE€S Main link. Argument: M (matrix / row array)
Z Zip/transpose M.
; Concatenate the row array with the column array.
j Join the rows and columns, separating by M.
Ɠ Read an integer n from STDIN.
ṡ Split the result to the left into overlapping slices of length 2.
E€ Test the members of each resulting array for equality.
S Take the sum.
```
### Example run
```
;ZjṡƓE€S Argument: [[1, 2], [3, 2]]. STDIN: 2
Z [[1, 3], [2, 2]]
; [[1, 2], [3, 2], [1, 3], [2, 2]]
j [1, 2, [1, 2], [3, 2], 3, 2, [1, 2], [3, 2], 1, 3, [1, 2], [3, 2], 2, 2]
Ɠ 2
ṡ [[1, 2], [2, [1, 2]], [[1, 2], [3, 2]], [[3, 2], 3],
[3, 2], [2, [1, 2]], [[1, 2], [3, 2]], [[3, 2], 1],
[1, 3], [3, [1, 2]], [[1, 2], [3, 2]], [[3, 2], 2],
[2, 2] ]
E€ [ 0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
1 ]
S 1
```
[Answer]
# Dyalog APL, ~~27~~ ~~25~~ 23 bytes
```
{1∊∊⍷∘⍵¨(⊢,⍪¨)⍺/¨⍳⌈/∊⍵}
```
[Try It Online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4yrDR91dIFQ7/ZHHTMe9W49tELjUdcinUe9qw6t0HzUu0v/0IpHvZsf9XTog1VtrTVTMHvUu8VYwUjBWMEESBoCSUMwC4aNwTKGYGgEVQdRbwjGSOL//wMA)
Thanks to @MartinEnder and @Zgarb for -2 bytes each (composition removes the need to use `w` and pointless parens)
Alert me if there are any problems and/or bytes to golf. Left argument is **N**, right argument is **A**.
Explanation:
```
{1∊∊⍷∘⍵¨(⊢,⍪¨)⍺/¨⍳⌈/∊⍵}
⍵ - Right argument
∊ - Flatten the array
⍳⌈/ - 1 ... the maximum (inclusive)
⍺/¨ - Repeat each item ⍺ (left argument) times.
(⊢,⍪¨) - Argument concatenated with their transposes.
⍷∘⍵¨ - Do the patterns occur in ⍵?
∊ - Flatten (since we have a vector of arrays)
1∊ - Is 1 a member?
{ } - Function brackets
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
t!YdY'wg)>~a
```
[Try it online!](https://tio.run/##y00syfn/v0QxMiVSvTxd064u8f//aGMFIwVjBRMgaWgNpAzBTCC2BjOMwXJAGUMgNIIotVaA6DEEYRSZWC5jLgA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##XU6xCkIxDNzzFXESxybNUym8yU9weZSCDwQX3R64@ev1kk5KSHPN3XF5rduz3/q2W@7L/v04zJ@1X669pkaJamJUYUFpI/1fZKrqiDNerDNYh@gSQIMD4z4Z0sLDk7x/mEiwwKcRn8BBJTxBiI@51RxjmDHEImHztMmvcHoER7mWNcc1Zz42ki8).
### Explanation
A non-square matrix cannot be properly concatenated to its transpose, either vertically or horizontally. So the code concatenates them *diagonally*, by creating a block-diagonal matrix.
The resulting matrix is linearized in column-major order and run-length encoded. The zeros resulting from the block-diagonal concatenation serve to isolate the runs of actual values.
The results from run-length encoding are an array of values and an array of run-lengths. The run-lengths corresponding to non-zero values are kept. The output is `1` if some of those lengths is greater than or equal to the input number, and `0` otherwise.
Let's see the intermediate results to make it clearer. Consider inputs
```
[10 10 10;
20 20 30]
```
and
```
3
```
The block diagonal matrix containing the input matrix and its transpose (code `t!Yd`) is:
```
10 10 10 0 0
20 20 30 0 0
0 0 0 10 20
0 0 0 10 20
0 0 0 10 30
```
This matrix is implicit linearized in column-major order (down, then across):
```
10 20 0 0 0 10 20 0 0 0 10 30 0 0 0 0 0 10 10 10 0 0 20 20 30
```
Run-length encoding (code `Y'`) gives the following two vectors (shown here as row vectors; actually they are column vectors): vector with values
```
10 20 0 10 20 0 10 30 0 10 0 20 30
```
and vector with run lengths
```
1 1 3 1 1 3 1 1 5 3 2 2 1
```
Keeping only the lengths correspoinding to non-zero values (code `wg)`) gives
```
1 1 1 1 1 1 3 2 1
```
Comparing to see which lengths are greater than or equal to the input number (code `>~`) produces the vector
```
0 0 0 0 0 0 1 0 0
```
Finally, the output should be `true` (shown as `1`) if the above vector contains at least a `true` entry (code `a`). In this case the result is
```
1
```
[Answer]
# [Perl 6](http://perl6.org/), 60 bytes
```
{(@^m|[Z,] @^m).map(*.rotor($^n=>$^n-1).map({[==] $_}).any)}
```
[Try it online!](https://tio.run/##XYtBDoIwFESvMgti@k1tUkrcQNFzSMB0ISsLpLhpkLPXlu5czOS//zLLy72vwXqcRuiwsftgv92D94gHCWsWdhZu/syOFcOk21gXmf9bp3WP4rmTMJOnPdRYjcdtZKxRKKFQxZYtR1NBHhCTMdnkDyujLfMgYd7KlH9LHIrq8AM "Perl 6 – Try It Online")
* `@^m` is the input matrix (first argument) and `$^n` is the number of consecutive occurrences to check for (second argument).
* `[Z,] @^m` is the transpose of the input matrix.
* `(@^m | [Z,] @^m)` is an or-junction of the input matrix and its transpose. The following `map` evaluates to a truthy value if `$^n` consecutive equal values occur in any row of the invocant. Applied to the input matrix OR its transpose, it evaluates to a truthy value if either the input matrix or its transpose contain `$^n` consecutive equal values in any row; if the transpose meets that condition, that means the input matrix has `$^n` consecutive equal values in one of its columns.
* `*.rotor($^n => $^n - 1)` turns each row into a sequence of `$^n`-element slices. For example, if `$^n` is 3 and a row is `<1 2 2 2 3>`, this evaluates to `(<1 2 2>, <2 2 2>, <2 2 3>)`.
* `.map({ [==] $_ })` turns each slice into a boolean that indicates whether all elements of the slice are equal. Continuing the previous example, this becomes `(False, True, False)`.
* `.any` turns that sequence of booleans into an or-junction which is truthy if any of the booleans are true.
The output is a truthy or-junction value which is true if either the input matrix OR its transpose have ANY row where `$^n` consecutive values are equal.
[Answer]
# Octave, ~~77~~ 70 bytes
```
@(A,N)any(([x y]=runlength([(p=padarray(A,[1 1]))(:);p'(:)]))(!!y)>=N)
```
[Try it online!](https://tio.run/##TU5BDgIhDLz3Fd2TkHipcJJg3A/wAcKB6K4eDG7Y1cjrsRAPHmY6nU4mfV62@J5qPYtx72RMRQj/wRJsfqXHlG7bXXix2CVeY86xcMoTUpBSHKVZdsxND0ORJ@tknS3GtBoAhxaVgZGHB4UHVKiZCTRSVwzQ3W8XAm7lred@eWr49wP3zv3P@gU "Octave – Try It Online")
Explanation:
Since tha matrix only contains non-zero integers we can add a border of 0s around the matrix and compute runlength encoding of the matrix(reshaped to a vector)
```
@(A,N)any(([x y]=runlength([(p=padarray(A,[1 1]))(:);p'(:)]))(!!y)>=N)
p=padarray(A,[1 1]) % add a border of 0s around the matrix
( )(:) % reshape the matrix to a column vector
p'(:) % transpose of the matrix reshaped to a column vector
[ ; ] % concatenate two vectors vertically
[x y]=runlength( ) % runlength encoding of the vector[x=count,y=value]
( ) % take x,counts.
(!!y) % extrect those counts that their valuse aren't 0
any( >=N) % if we have at least a count that is greater than or equal to N
```
[Answer]
# [Python 3](https://docs.python.org/3/), 129 128 125 120 104 101 bytes
Huge thanks to @Zachary T, @Stewie Griffin, @Mr. Xcoder, @Rod, @totallyhuman for improving this by a lot.
```
def f(n,m):
a=b=c=0;m+=zip(*m)
for r in m:
for i in r:b,a=[1,b+1][a==i],i;c=max(c,b)
return n<=c
```
[Try it online!](https://tio.run/##XYsxDsMgEAR7v4IS4isCuHJyL0EUQIxCAbaQIyX5PDkoU5y0s3N7fM7nXnRrjy2yyAtksU7MoceA11ue8ZsOfsliYnGvrLJUWKaHQalTXT04NBL8LK1xiMlCugXM7s0DeBrW7XzVwsodQztqKiePXIExGiRoWECBtGAWop7pBily3XYnyanRLER6pL79d1aI9gM "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~60~~ ~~92~~ 91 bytes
```
def f(n,x):x=[map(str,i)for i in x];print any(`[i]*n`[1:-1]in`x+zip(*x)`for i in sum(x,[]))
```
[Try it online!](https://tio.run/##XU7LCgIxDLz7FT22Gg99@cQvKYUVtNiD3WVdoevPr0lWRCSUZmYyyXTjcGuLmabLNYkkC1R1qKdwP3fyMfSQVWp7kUUuosZj1@cyiHMZZRNyXJYm6MNax1yaunrlTi6rar7zj@ddVghRqSlJDSFoiFEtkrTcY0UIBrBm2iFtkbbgkCTRIaIeHyODGqmk0QLDjENkuSPvv8ar6bpnYvcTQeMUGgxsyIPI0xrPAH/vAT3mk86ggxJsKBsPzWm42ALWcdo9bNEyvQE "Python 2 – Try It Online")
Instead of counting, a list with size `n` (for each element in the matrix) is generated and checked if it's on the matrix
**Without strings, 94 bytes**
```
lambda n,x:any((e,)*n==l[i:i+n]for l in x+zip(*x)for i in range(len(l)-n+1)for e in sum(x,()))
```
[Try it online!](https://tio.run/##ZY7NbsIwEITvPIWPu2R7iH@AIuVJKIcgktaSs0QplUJfPt3dCglarSx75vPYM96uHxf2S9@8LaUdTufWMc37lm8AHeGam6Yc8j5XfOwvkysus5ur7zzCekZ1sjpTy@8dlI6h4AtXtZFOyefXADMBIi7jlPnqeqjpIAuPuLo7wRwZJPAk8wijwCAwUBSkV6IoPcsy5YUpVabPeHOiqGAnzf5lDx9on2T27l@pWhIS9rTRvKikTyYTsqdEkvRPfb3ktNNG29rV3342FqQQrf8rbSW4/AA "Python 2 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 59 bytes
```
@(A,N)any({[l,v]=runlength(blkdiag(A,A')(:)),l(v>=0)}{2}>=N)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQcNRx08zMa9Sozo6R6cs1raoNC8nNS@9JEMjKSc7JTMxHajAUV1Tw0pTUydHo8zOQLO22qjWztZP83@arUJiXrE1F5efgq2CsTWXI5CKNlYwUjBWMAGShlwKIGCiYAjmAjFMAKQCpAaqwhAIjSDaIAIQMwxBGENFLNC@NLCj/wMA "Octave – Try It Online") Or [verify all test cases](https://tio.run/##bU7LCoMwELz7FXtrAh6axNhHUOoP@APiIW3VlgYLrRWK@O12N4KlUJZNZndmkrmfOttX03RgWZhz277ZULiwL5PHq3VV23QXdnS389U2KMhWnO05Dx3r0zUfBzmmSc6nGhKw7dMENStEGYLgHgGWAYmlcKn@LSO/VDRBhCdSESoIYhsPlOeQIa@cpQZmj6D@YZaftJ@33zgCNaiWEKMBB01PaMJ4aQ1okHKx088xJSLJHMIX6UFFPtkONqiXPJg@).
This uses the same approach as my [MATL answer](https://codegolf.stackexchange.com/a/128715/36398) (see explanation there).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~18~~ ~~15~~ 14 bytes
```
cUy)d_ò¦ d_ʨV
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=Y1V5KWRf8qYgZF/KqFY=&input=W1szLDIsMyw0LDIsMV0sWzQsMSw0LDIsNCwyXSxbNCwyLDMsMyw0LDFdLFsxLDEsMiwyLDMsNF0sWzMsMiwzLDEsMywxXSxbMSwxLDIsMiwzLDRdXQoz)
* 3 bytes saved with some help from ETHproductions.
---
## Explanation
```
:Implicit input of 2D array U and integer V
c :Append to U...
Uy :U transposed.
d :Check if any of the elements (sub-arrays) in U return true when...
_ :Passed through a function that...
ò :Partitions the current element by...
¦ :Checking for inequality.
d :Check if any of the partitions return true when...
_ :Passed through a function that checks if...
Ê :The length of the current element...
¨V :Is greater than or equal to V.
:Implicit output of resulting boolean.
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 16 bytes
```
q~_z+N*e`:e>0=>!
```
[Try it online!](https://tio.run/##S85KzP3/v7AuvkrbTys1wSrVzsDWTvH/f2Ou6GhjBSMFYwUTIGkYy6UQbaJgCOYAMYQLkgXJg2UNgbJGEA0gLkSvIQijy8YCAA "CJam – Try It Online")
### Explanation
```
q~ e# Read and eval input.
_z+ e# Append the matrix's transpose to itself.
N* e# Join with linefeeds to flatten without causing runs across rows.
e` e# Run-length encode.
:e> e# Get maximum run (primarily sorted by length).
0= e# Get its length.
>! e# Check that it's not greater than the required maximum.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16 14~~ 12 bytes
```
Døìvyγ€gM²‹_
```
[Try it online!](https://tio.run/##ASUA2v8wNWFiMWX//0TDuMOsdnnOs@KCrGdNwrLigLlf//9bWzFdXQox "05AB1E – Try It Online")
```
Dø # Duplicate the input and transpose one copy
ì # Combine the rows of both matrixes into one array
vy # For each row...
γ # Break into chunks of the same element
€g # get the length of each chunk
M # Get the largest length so far
²‹_ # Check if that is equal to or longer than required
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
ŒrFUm2<⁴$ÐḟL
ZÇo³Ç
```
[Try it online!](https://tio.run/##y0rNyan8///opCK30Fwjm0eNW1QOT3i4Y74PV9Th9vxDmw@3////PzraUMdQxyBWB0gb6RgDaQMdYx2T2Nj/xgA "Jelly – Try It Online")
```
ŒrFUm2<⁴$ÐḟL Helper Link
Œr Run-length encode
F Flatten the whole thing, giving the numbers in the odd indices and the lengths of the runs in the even indices
U Reverse
m2 Take every other element (thus only keeping the run lengths)
Ðḟ Discard the elements that are
<⁴$ less than the required run length
L And find the length
ZÇo³Ç Main Link
Z Zip the matrix
Ç Call the helper link on it
³Ç Call the helper link on the original matrix
o Are either of these truthy?
```
Returns `0` for false and a non-zero integer for truthy.
Ew, this is bad. And very long. Golfing tips would be appreciated :)
[Answer]
## JavaScript (ES6), 99 bytes
Takes the matrix `m` and the expected number of occurrences `n` in currying syntax `(m)(n)`. Returns a boolean.
```
m=>n=>[',',`(.\\d+?){${m[0].length-1}}.`].some(s=>m.join`|`.match(`(\\b\\d+)(${s}\\1){${n-1}}\\b`))
```
### How?
This code is not particularly short, but I wanted to try an approach purely based on regular expressions.
**Conversion of the matrix to a string**
We use `m.join('|')` to transform the 2D-array into a string. This first causes an implicit coercion of the matrix rows to comma-separated strings.
For instance, this input:
```
[
[ 1, 2, 3 ],
[ 4, 5, 6 ]
]
```
will be transformed into:
```
"1,2,3|4,5,6"
```
**Row matching**
We look for consecutive occurrences in a row with:
```
/(\b\d+)(,\1){n-1}\b/
```
This is matching:
* `\b` a word boundary
* `\d+` followed by a number
* `(){n-1}` followed ***n-1*** times by:
+ `,` a comma
+ `\1` followed by our reference: a word boundary + the first number
* `\b` followed by a word boundary
**Column matching**
We look for consecutive occurrences in a column with:
```
/(\b\d+)((.\d+?){L-1}.\1){n-1}\b/
```
where `L` is the length of a row.
This is matching:
* `\b` a word boundary
* `\d+` followed by a number
* `(){n-1}` followed ***n-1*** times by:
+ `(){L-1}` ***L-1*** times:
- `.` any character (in effect: either a comma or a pipe)
- `\d+?` followed by a number (this one must be non-greedy)
+ `.` followed by any character (again: either a comma or a pipe)
+ `\1` followed by our reference: a word boundary + the first number
* `\b` followed by a word boundary
### Test cases
```
let f=
m=>n=>[',',`(.\\d+?){${m[0].length-1}}.`].some(s=>m.join`|`.match(`(\\b\\d+)(${s}\\1){${n-1}}\\b`))
console.log(f([
[ 1 ]
])(1))
console.log(f([
[ 1, 1, 1 ],
[ 2, 2, 3 ]
])(3))
console.log(f([
[ 1, 1, 1 ],
[ 2, 2, 3 ]
])(4))
console.log(f([
[ 3, 2, 3, 4, 2, 1 ],
[ 4, 1, 4, 2, 4, 2 ],
[ 4, 2, 3, 3, 4, 1 ],
[ 1, 1, 2, 2, 3, 4 ],
[ 3, 2, 3, 1, 3, 1 ],
[ 1, 1, 2, 2, 3, 4 ]
])(3))
console.log(f([
[ 5, 2, 3, 8 ]
])(1))
console.log(f([
[ 111, 23, 12, 6 ],
[ 111, 53, 2, 5 ],
[ 112, 555, 5, 222 ]
])(3))
console.log(f([
[ 4, 2, 6, 2, 1, 5 ],
[ 2, 3, 3, 3, 3, 3 ],
[ 11, 34, 4, 2, 9, 7 ]
])(2))
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 58 bytes
```
f=@(A)runlength([A;nan*A](:))
F=@(A,n)max([f(A),f(A')])>=n
```
[Try it online!](https://tio.run/##dZDNbsMgDMfP5SmsStVg4mII7RaUabn0JbIc0BK2KR2dkrSaVO3ZM0NarT1MgDE///0h9q@jO7ZT40ZXnBhAhbVEOfaH1qYX0LIKFOha6n94Jr3bDXNARwQZWbQZiaJHx2aJxwjamKxmnZ31GM81v2lmEnu4HQwRAJQGQEUOrO1MjI44EkOEHGNMfBBUKlb9GzVLwnWyGPV06@tNBUCTahY@AmxqqdII7MeyyRfPvBT9Ieza8Da@86q0wYX7sua5EGwbozKIT/fNK09CSeZO1OKpCJPf99AVmG/Yoizi3/NOojghlV2EC1Bn0LfDBekz8l/9Rxg9X66aHFYNHAeyL2EpO7lNXSUlCcva0LDpFw "Octave – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 21 bytes
```
-⊸≢1=⊣≠∘⍷˘∘↕˘⎊0¨⋈⟜⍉∘⊢
```
Anonymous tacit function; takes the number `n` as left argument and the 2D array `a` as right argument. [Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgLeKKuOKJojE94oqj4omg4oiY4o23y5jiiJjihpXLmOKOijDCqOKLiOKfnOKNieKImOKKogoK4oCiU2hvdyBuIOKGkCAzCuKAolNob3cgYSDihpAgW1sxLDEsMV0sWzIsMiwzXV0KCm4gRiBh)
### Explanation
So. Many. Modifiers. ○\_○
```
-⊸≢1=⊣≠∘⍷˘∘↕˘⎊0¨⋈⟜⍉∘⊢
∘⊢ With the right argument (a),
⋈⟜⍉ pair it with its transpose
¨ Apply this function to each of those arrays
⊣ and the original left argument (n):
˘ Within each row of the array,
↕ get all sublists of length n
˘∘ Then, with each of those sublists,
≠∘⍷ uniquify and get the length (1 iff all elements are equal)
⎊0 If that function errored because n is too big, use 0 instead
We now have a list of two elements, each of which is either
an array of integers or a 0
1= Compare each integer to 1 (0 if not equal, 1 if equal)
⊸≢ Is that nested list different from
- the same list with each integer negated?
```
If there are no sublists where all items are identical, we'll get a nested list containing only zeros, which remains the same under negation; thus, `≢` will return 0. If there is at least one sublist with identical items, we'll get a nested list that contains a 1 somewhere, which changes under negation; thus, `≢` will return 1.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
:∩JvøĖ≤fa
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI64oipSnbDuMSW4omkZmEiLCIiLCJbWzMsMiwzLDQsMiwxXSxbNCwxLDQsMiw0LDJdLFs0LDIsMywzLDQsMV0sWzEsMSwyLDIsMCw0XSxbMSwxLDIsMiwzLDRdLFszLDIsMywxLDMsMV0sWzEsMSwyLDIsMyw0XV1cbjMiXQ==)
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
lambda M,n:(', 0'*n)[5:]in`[map(cmp,l,l[1:])for l in M+zip(*M)]`
```
[Try it online!](https://tio.run/##bU/LjsMgDDw3X@FboeWwEOgjUj8hX8AiNfuIikQoqlKt2p/P2pCseljJQuOZ8WCnx3i5RjX1p/cpdMPHVwetiA1bC3hbbyK3pnE@nu3QJfY5JBFEsLJxvL/eIICP0G6fPrFNy915@rn48A2yqVaYcfIx3UfGq1W6@ThCz5DkE7NWOidA8oogAizsrRJARVqdtTpr@OqsZJPOXCHonTmVfcWafSVXLYomrl66kvq/D0mdfzcLd3jZVpKZZlHa5XliTEk2hSBkcJoC1Ms5Zc1duWV2/@09V0lAoJcjjwL2lKH4Lw "Python 2 – Try It Online")
[Answer]
## Clojure, 77 bytes
```
#((set(for[I[%(apply map vector %)]i I p(partition %2 1 i)](count(set p))))1)
```
Creates all consecutive partitions `p` of length `N` (symbol `%2`) and counts how many distinct values it has. Then it forms the set of these lengths and returns `1` if it is found from the set and `nil` otherwise. `for` construct was the perfect fit for this, my original attempt used `flatten`, `concat` or something of that short.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Dø«δÅγ›ß
```
First input is the matrix \$A\$, second is the integer \$N\$.
Outputs an inverted boolean: `0` for truthy and `1` for falsey.
[Try it online](https://tio.run/##yy9OTMpM/f/f5fCOQ6vPbTncem7zo4Zdh@f//x8dbaxjpGOsYwIkDWN1ok10DMFsIAbzQHIgWZCcIVDOCKIagwcxxRCE0eRiuYwB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVBsr6SQmJeioGQPZDxqmwRkVCa4FP13Obzj0OpzWw63ntv8qGHX4fn/df5HA4FhbKyOYayOAoipYwhiRhvpGOkYA4WNsQubQISNQVwdEyAJkjQBKgKxgRjMA8mBZEFyIAOMIKoxeBBTDEEYTQ5uvylYwALJnYZAVUANRjpmID1AninIGFMwB0ibmuoA9RgZIYwAuccM5FKwIojbwBCsRcfYBOx2Sx1zoBbT2FgA).
**Explanation:**
```
D # Duplicate the (implicit) input-matrix
ø # Zip/transpose its copy; swapping rows/columns
« # Merge it to the input-matrix
# (we now have a list of all rows and all columns)
# e.g. input=[[1,1,1],[2,2,3]] → [[1,1,1],[2,2,3],[1,2],[1,2],[1,3]]
δ # Map† over each inner list:
Åγ # Run-length encode it; pushing the list of items and list of lengths
# separately to the stack, only leaving the top list of lengths
# → [[3],[2,1],[1,1],[1,1],[1,1]]
› # Check for each inner-most length if it's smaller than the second (implicit)
# input-integer
ß # Pop and push the flattened minimum to check if any was falsey
# (after which the result is output implicitly)
```
† `δ` is technically an 'apply double-vectorized', which also uses the second (implicit) input-integer as argument. It's usually used to create tables from two lists, or to apply a builtin that takes a single argument on each inner item of a list.
In this case, the implicit input-integer is simply ignored since builtin `Åγ` takes no arguments, and `δ` therefore acts as a map. We use this, because map `εÅγ}` is 1 byte longer and map `€Åγ` would also keep the lists of items (so the example above would become `[[3],[1],[2,1],[2,3],[1,1],[1,2],[1,1],[1,2],[1,1],[1,3]]` instead).
[Answer]
# [Julia](https://julialang.org), ~~90,84~~ 70 bytes
```
A\n=(~X=occursin("0"^(n-1),[X;0X[1,:]'][:]|>diff.|>sign|>join);~A|~A')
```
(A>0 is exploited.)
[Attempt This Online!](https://ato.pxeger.com/run?1=bVJJasMwFIUucwo1XUQCJVge0jTBpt70DAbXBeGhdTBy8NASMNn3DN1kk0O1y56k-lKcmiRI-pbe8Afw12HdFjnf_9wECW-4G44QwiGLKKNN1aaE6jeSayWvCJlyWRG1hrQiLjU2zXhR9yILQGTLeFTZ0gBPeXoAFKA5KiClqW0a0DkYnAvFWU-OQhfngzAG_VnSaYJ_fkyjYMdSvcOth-XLcRxAJGOaUGM4k630cxXZyWZCo4OtUFnBsmFGoB8Quo-oOegsy4sCM8oMuQ0C4RoJLJBs2EWVblLeYLZU_DX_VQX7TxKN7pD_LFy8C1wutjgri6TC7zFvaMrjt6r8wAGZdd526tWbIm_wtvOSPMs6b13mgt66eGJMCCGz38_D2Bi_YDFlhKx2frfzJ-TQNtl08f3UVyjjuK3qXOCTlIbByghCRpfRJAqXkc4uC9b5q9BFzrORrKwQ9qmgVVoTF_5dOekjr-u0atQwriRGqUi0Yb_X3z8)
and a `StatsBase`-based vari:
### 16+54 bytes
```
using StatsBase
A\n=(~X=any(eachrow(X).|>x->any(rle(x)[2].≥n));~A|~A')
```
] |
[Question]
[
A function (or program) which takes inputs and provides outputs can be said to have a cycle if calling the function on its own output repeatedly eventually reaches the original number. For instance, take the following function:
```
Input: n 1 2 3 4 5 6
Output: f(n) 5 7 1 3 4 9
```
If we start with `n=1`, `f(n)=5`, `f(f(n))=f(5)=4`, `f(f(f(n)))=f(4)=3`, `f(f(f(f(n))))=f(3)=1`.
This is written `(1 5 4 3)`. Since there are 4 unique numbers in this loop, this is a cycle of length 4.
---
Your challenge is to write a program or function which has cycles of every possible length. That is, there must be a cycle of length 1, of length 2, and so on.
In addition, your function/program must be from the positive integers to positive integers, and it must be [bijective](https://en.wikipedia.org/wiki/Bijection), meaning that there must be a exactly one input value for every possible output value, over all positive integers. To put it another way, the function/program must compute a permutaion of the positive integers.
---
Details: Any standard input/output system is allowed, including STDIN, STDOUT, function argument, return, etc. Standard loopholes prohibited.
You do not need to worry about the limitations of your data types - the above properties need only hold under the assumption that an `int` or `float` can hold any value, for instance.
There are no restrictions on the behavior of the function on inputs which are not positive integers, and those inputs/outputs will be ignored.
---
Scoring is code golf in bytes, shortest code wins.
[Answer]
# Pyth, 11 8 bytes
```
.<W-0zz1
```
A lot more boring than my previous answer.
Every number that contains a 0 digit maps to itself. Any other number maps to the number that has its digits rotated by 1. So for example:
```
1 -> 1
10 -> 10
15 -> 51 -> 15
104 -> 104
123 -> 231 -> 312 -> 123
```
[Answer]
# Python 2, ~~56~~ ~~55~~ 54 bytes
```
n=input()
a=b=1
while a+b<=n:a+=b;b+=1
print(n+~a)%b+a
```
Here's the first 21 outputs:
```
[1, 3, 2, 6, 4, 5, 10, 7, 8, 9, 15, 11, 12, 13, 14, 21, 16, 17, 18, 19, 20]
```
The pattern is obvious if we break the list up into chunks like so:
```
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
[1] [3, 2] [6, 4, 5] [10, 7, 8, 9] [15, 11, 12, 13, 14] [21, 16, 17, 18, 19, 20]
```
[Answer]
# Pyth, 25 bytes
```
+hK/*J/h@h*8tQ2 2tJ2%-QKJ
```
This is the same sequence as @Sp3000, but with a closed form. The closed form is:



[Answer]
# Python3, 40 bytes
```
n=input();print([n[1:]+n[0],n]['0'in n])
```
Every number that contains a 0 digit maps to itself. Any other number maps to the number that has its digits rotated by 1. So for example:
```
1 -> 1
10 -> 10
15 -> 51 -> 15
104 -> 104
123 -> 231 -> 312 -> 123
```
[Answer]
# Ruby, 16+1=17
With command-line flag `-p`, run
```
$_=$_[/.0*$/]+$`
```
This is a more complicated function than my other answer, but happens to be more golfable (and tolerant to trailing newlines). It takes the last nonzero digit of the input, plus any trailing zeroes, and moves it to the beginning of the number. So `9010300` becomes `3009010`. Any number with n nonzero digits will be part of an n-length cycle.
Input is a string in any base via STDIN, output is a string in that base.
[Answer]
# Ruby, 22+1=23
With command-line flag `-p`, run
```
~/(.)(.?)/
$_=$1+$'+$2
```
When given as input a string representation of a number (with no trailing newline), it keeps the first digit constant, then rotates the remainder left, so `1234` becomes `1342`.
This can be reduced to 21 characters with
`$_=$1+$'+$2if/(.)(.)/`, but prints a warning.
[Answer]
# Pyth, 15 bytes
The shortest answer so far that uses numeric operations rather than string operations.
```
.|.&Q_=.&_=x/Q2
Q input
/Q2 input div 2
x Q that XOR input
= assign that to Q
_ negate that
.& Q that AND Q
= assign that to Q
_ negate that
.& input AND that
.| Q that OR Q
```
The effect of this function on the binary representation is to extend the rightmost block of 1s into the next 0; or if there is no 0, to reset it back to a single 1:
```
10010110100000 ↦
10010110110000 ↦
10010110111000 ↦
10010110111100 ↦
10010110111110 ↦
10010110111111 ↦
10010110100000
```
### Pyth, 26 bytes, fun variant
```
.|.&Q_h.&/Q2+Qy=.&/Q2_h.|y
Q input
/Q2 input div 2
Q input
/Q2 input div 2
yQ twice input
.| Q that OR input
_h NOT that
.& (input div 2) AND that
= assign that to Q
y twice that
+ input plus that
.& (input div 2) AND that
_h NOT that
.& input AND that
.| Q that OR Q
```
Performs the above operation simultaneously to *all* blocks of 1s, not just the rightmost one—still using only bitwise and arithmetic operations.
```
1000010001001 ↦
1100011001101 ↦
1110011101001 ↦
1111010001101 ↦
1000011001001 ↦
1100011101101 ↦
1110010001001 ↦
1111011001101 ↦
1000011101001 ↦
1100010001101 ↦
1110011001001 ↦
1111011101101 ↦
1000010001001
```
[Answer]
# Python, 43
The [inverse of Sp3000's function](https://codegolf.stackexchange.com/a/53648/20260), implemented recursively.
```
f=lambda n,k=1:n>k and k+f(n-k,k+1)or n%k+1
```
The function is a one-cycle followed by a two-cycle followed by a three-cycle, ...
```
(1)(2 3)(4 5 6)(7 8 9 10)(11 12 13 14 15)...
```
The operation `n%k+1` acts as a `k`-cycle on the numbers `1..k`. To find the appropriate `k` to use, shift everything down by `k=1`, then `k=2`, and so on, until `n<=k`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
∋0&|↺
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1sn/H/U0W2gVvOobdf//9GGOgqGBkBsqqNgCmabAAkjYx0FI2Mg19jQKPZ/FAA "Brachylog – Try It Online")
Port of @orlp's Pyth answer. Comes out simple and neat:
```
∋0 % If input contains a 0 (since input is a single number, "contains" ∋ treats it as an array
% of its digits, so this means "if any of input's digits are 0")
& % Then output is the input
| % Otherwise
↺ % Circularly shift the input once, and unify that with the output
```
I originally wanted to port @Sp3000's Python solution, but that took a whopping **23 bytes**:
```
⟧∋B-₁⟦++₁A≤?;A--₁;B%;A+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bGh1sn/H80f/mjjm4nXSD30fxl2tpA2vFR5xJ7a0ddkJi1k6q1o/b//9GGOgpGOgrGOgomOgqmOgpmOgqGBkAMFDY0iv0fBQA "Brachylog – Try It Online")
[Answer]
# x86 32-bit machine code, 16 bytes
```
0F BC C1 0F B3 C1 E3 01 40 0F AB C1 91 14 00 C3
```
[Try it online!](https://tio.run/##XVFNb8IwDD2TX@F1QiS0IAQ3oFw477LTpDGhkCZtphBQk25hiL@@zuFDY/PBsZ9f7Cdb7PeDUoi2fdRWmKaQMHe@0LthtSB/IKM3/7Fa2zJiRAYvawvJMoHjes09VjaNl@s1pYo7L7gxjIG2HhSNnrPZiXC3BQrPCSXD0uw23IAiako6G6dA8pCBFAEzX8cgixDpvGP4BY50UMUZcVNkuDtGEFV5l/JCADcZjEinlp6wBNiMkKhhy7W9iKlLkYGoeA39PiYfjBwJoMVigBxGGRziMzujn5U2EmiaBpjnMBmzMxptj/vwiiZdDYMFdPXKJhmgEEUDY5fPN8rKPnFRaStB7Ao5Ta7l8Dum2MHxxobuaPyCvQ45pY11urSyOAvuM8VeQ5q@4T5vwg7wgE3CcnIb2fhIpb2V7V0h3ESD58JJJ9K230IZXrp2sJ2M0eFZchwrzQ8 "C++ (gcc) – Try It Online")
Uses the `fastcall` calling convention – argument in ECX, result in EAX.
This function leaves values with only one 1 bit (powers of 2) unchanged; other values are modified by moving the lowest 1 bit one place up, or to the bottom if the position above it is already 1. Thus, a non-power-of-2 is in a cycle of length equal to the position of its second-lowest 1 bit.
In assembly:
```
.global f
f:
bsf eax, ecx # Set EAX to the position of the lowest 1 bit in ECX.
btr ecx, eax # Remove that 1 bit from ECX.
jecxz s # Jump if ECX is 0 (had only one 1 bit).
inc eax # (Otherwise) Increase EAX by 1.
s: bts ecx, eax # Set to 1 the bit in ECX at position EAX,
# and set the carry flag (CF) to its former value.
xchg ecx, eax # Exchange registers, moving the number into EAX.
adc al, 0 # Add 0+CF to the low byte of EAX.
ret # Return.
```
[Answer]
# Swift 1.2, 66 bytes
```
func a(b:Int){var c=0,t=1,n=b
while n>c{n-=c;t+=c++}
print(n%c+t)}
```
```
Input: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Output: 1, 3, 2, 5, 6, 4, 8, 9, 10, 7, 12, 13, 14, 15, 11
```
[Answer]
## JavaScript (ES6), 43 bytes
```
f=(n,i=1,j=1)=>n>j?f(n,++i,j+i):n++<j?n:n-i
```
[Answer]
## Matlab(189)
```
function u=f(n),if(~n|n==1)u=n;else,u=n;y=factor(n);z=y(y~=2);if ~isempty(z),t=y(y~=max(y));if isempty(t),u=y(end)*2^(nnz(y)-1);else,g=max(t);e=primes(g*2);u=n/g*e(find(e==g)+1);end,end,end
```
---
* **The function:**
Maps any integer according to its prime factors, if the number is nil or factorised into 2 or 1, the number is mapped to itself, otherwise we pick the biggest prime factor of this number, then we increment the remaining different prime factors by the closest bigger prime factor until we reach the number `biggest_prime^n` where `n` is the sum of all exponents of all factors, once we reach that amount, we turn to `max_prime*2^(n-1)` and we reproduce the same cycle again.
[Answer]
## Matlab(137)
```
function u=h(n),if(~n|n==1)u=n;else,u=n;y=factor(n);z=y(y~=2);if~isempty(z),e=nnz(y);f=nnz(z);if(~mod(e,f)&e-f)u=n/2^(e-f);else,u=u*2;end
```
---
* A slightly similar approach, multiplying gradually any number not equal to {0,1,2^n} by `2` until we stumble upon an exponent of `2` which is divisible by sum of exponents of other prime factors. then we move to the beginning of the cycle dividing by `2^(sum of exponents of other primes)`. the other numbes are mapped to themselves.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
WĀiÁ
```
Port of [*@orlp*'s Pyth answer](https://codegolf.stackexchange.com/a/53659/52210), so make sure to upvote him/her as well.
[Try it online](https://tio.run/##yy9OTMpM/f8//EhD5uHG//8NjYwB) or [verify some test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWX0//AjDZmHG//XHp5gXxmoDJOoPbTN/n@0oY6hgY6hKZA00TE0MgZhE1MzcwtLAwQzFgA).
**Explanation:**
```
W # Push the smallest digit of the (implicit) input-integer (without popping)
Āi # If this is NOT 0:
Á # Rotate the integer once towards the right
# (after which the resulting integer is output implicitly)
```
[Answer]
# x86 32-bit machine code, 11 bytes
```
0F BD C8 D1 E8 73 FC 0F AB C8 C3
```
[Try it online!](https://tio.run/##XVFBb8IgFD6XX/HWxQRsNZve1HrxvMtOS@bSUAotC1IDdKMx/vV11GqWyeEB3/fe@z4e7HicVYz1/aPUTLUlh411pWzm9Rb9g5Qs7jEjdTVgiHvHjYZ4F8Mpz6kLTNE6nucYC2odo0oRAlI7EHiIlKzPiNoDYHiNMZpXqimoAoHEKiqsAc58Cpx6ZFaRrc1wTOEZRZ@agUFR4ewIhTwUGe4QiYGsERp6H6jUo4ipWAqspgam03D5IuiEIKyB9JDBUwrdsK0v6HctFQecJB42GSwX5IIO6xje6QSOJxJmW5jIvY5TCOoCe0LG4lvKXr9QVkvNgTUlX8VX2v/JlA2cbtkweVq8hV5dhnGrraw0Ly@Gp0SQd58kH2FON2MdPIQmfre8kwQcfBWd45aMxq58GEsb/iTInlHf/zChaGX72WG5CCHMPgvlXP0C "C++ (gcc) – Try It Online")
Uses the `regparm(1)` calling convention – argument in EAX, result in EAX.
This function takes a number's binary digits (without leading zeroes) and rotates them right until the highest one is again a 1.
In assembly:
```
f: bsr ecx, eax # Set ECX to the highest position of a 1 bit in EAX.
r: shr eax, 1 # Shift EAX right by 1 bit, with the lowest bit going into CF.
jnc r # Repeat if CF=0.
bts eax, ecx # Set to 1 the bit in EAX at position ECX.
ret # Return.
```
] |
[Question]
[
The [Simpson index](https://en.wikipedia.org/wiki/Diversity_index#Simpson_index) is a measure of diversity of a collection of items with duplicates. It is simply the probability of drawing two different items when picking without replacement uniformly at random.
With `n` items in groups of `n_1, ..., n_k` identical items, the probability of two different items is

For example, if you have 3 apples, 2 bananas, and 1 carrot, the diversity index is
`D = 1 - (6 + 2 + 0)/30 = 0.7333`
Alternatively, the number of unordered pairs of different items is `3*2 + 3*1 + 2*1 = 11` out of 15 pairs overall, and `11/15 = 0.7333`.
**Input:**
A string of characters `A` to `Z`. Or, a list of such characters. Its length will be at least 2. You may not assume it to be sorted.
**Output:**
The Simpson diversity index of characters in that string, i.e., the probability that two characters taken randomly with replacement are different. This is a number between 0 and 1 inclusive.
When outputting a float, display at least 4 digits, though terminating exact outputs like `1` or `1.0` or `0.375` are OK.
You may not use built-ins that specifically compute diversity indices or entropy measures. Actual random sampling is fine, as long as you get sufficient accuracy on the test cases.
**Test cases**
```
AAABBC 0.73333
ACBABA 0.73333
WWW 0.0
CODE 1.0
PROGRAMMING 0.94545
```
**Leaderboard**
Here's a by-language leaderboard, courtesy of [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner).
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
```
function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/53455/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```
[Answer]
# Python 2, 72
The input may be a string or a list.
```
def f(s):l=len(s);return sum(s[i%l]<>s[i/l]for i in range(l*l))/(l-1.)/l
```
I already know that it would be 2 bytes shorter in Python 3 so please don't advise me :)
[Answer]
# J, 26 bytes
```
1-+/((#&:>@</.~)%&(<:*])#)
```
## the cool part
I found the counts of each character by keying `</.` the string against itself (`~` for reflexive) then counting the letters of each box.
[Answer]
# Pyth - 19 13 12 11 bytes
*Thanks to @isaacg for telling me about n*
Uses brute force approach with `.c` combinations function.
```
csnMK.cz2lK
```
[Try it here online](http://pyth.herokuapp.com/?code=csnMK.cz2lK&input=AAABBC&debug=1).
[Test suite](http://pyth.herokuapp.com/?code=V.zcsnMK.cN2lK&input=AAABBC%0AACBABA%0AWWW%0ACODE%0APROGRAMMING&debug=1).
```
c Float division
s Sum (works with True and False)
nM Map uniqueness
K Assign value to K and use value
.c 2 Combinations of length 2
z Of input
lK Length of K
```
[Answer]
# SQL (PostgreSQL), 182 Bytes
As a function in postgres.
```
CREATE FUNCTION F(TEXT)RETURNS NUMERIC AS'SELECT 1-sum(d*(d-1))/(sum(d)*(sum(d)-1))FROM(SELECT COUNT(*)d FROM(SELECT*FROM regexp_split_to_table($1,''''))I(S)GROUP BY S)A'LANGUAGE SQL
```
Explanation
```
CREATE FUNCTION F(TEXT) -- Create function f taking text parameter
RETURNS NUMERIC -- declare return type
AS' -- return definition
SELECT 1-sum(d*(d-1))/(sum(d)*(sum(d)-1)) -- Calculate simpson index
FROM(
SELECT COUNT(*)d -- Count occurrences of each character
FROM( -- Split the string into characters
SELECT*FROM regexp_split_to_table($1,'''')
)I(S)
GROUP BY S -- group on the characters
)A
'
LANGUAGE SQL
```
Usage and Test Run
```
SELECT S, F(S)
FROM (
VALUES
('AAABBC'),
('ACBABA'),
('WWW'),
('CODE'),
('PROGRAMMING')
)I(S)
S F
-------------- -----------------------
AAABBC 0.73333333333333333333
ACBABA 0.73333333333333333333
WWW 0.00000000000000000000
CODE 1.00000000000000000000
PROGRAMMING 0.94545454545454545455
```
[Answer]
# Python 3, ~~66~~ 58 Bytes
This is using the simple counting formula provided in the question, nothing too complicated. It's an anonymous lambda function, so to use it, you need to give it a name.
*Saved 8 bytes(!) thanks to Sp3000.*
```
lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s)
```
Usage:
```
>>> f=lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s)
>>> f("PROGRAMMING")
0.945454
```
or
```
>>> (lambda s:1-sum(x-1for x in map(s.count,s))/len(s)/~-len(s))("PROGRAMMING")
0.945454
```
[Answer]
# Javascript, 119 bytes
Today on "Komali sucks at code golf"...
```
s=>eval('q=[];for(i of new Set(s))q.push((r=s.split(i).length-1)*(r-1));1-(q.reduce((z,x)=>x+z)/((l=s.length)*(l-1)))')
```
Test cases:
```
let s1= "AAABBC"
let s2 = "ACBABA"
let s3 = "WWW";
let s4 = "CODE";
let s5 = "PROGRAMMING"
let f =
s=>eval('q=[];for(i of new Set(s))q.push((r=s.split(i).length-1)*(r-1));1-(q.reduce((z,x)=>x+z)/((l=s.length)*(l-1)))')
console.log(f(s1))
console.log(f(s2))
console.log(f(s3))
console.log(f(s4))
console.log(f(s5))
```
Came across this question while doing biology homework. There has to be ways to improve this; I only spent like half an hour golfing it...
[Answer]
# APL, ~~39~~ 36 bytes
```
{n←{≢⍵}⌸⍵⋄N←≢⍵⋄1-(N-⍨N×N)÷⍨+/n-⍨n×n}
```
This creates an unnamed monad.
```
{
n ← {≢⍵}⌸⍵ ⍝ Number of occurrences of each letter
N ← ≢⍵ ⍝ Number of characters in the input
1-(N-⍨N×N)÷⍨+/n-⍨n×n ⍝ Return 1 - sum((n*n-n)/(N*N-N))
}
```
You can [try it online](http://tryapl.org/?a=%7Bn%u2190%7B%u2262%u2375%7D%u2338%u2375%u22C4N%u2190%u2262%u2375%u22C41-+/%28%28n-%u2368n%D7n%29%F7%28N-%u2368N%D7N%29%29%7D%27PROGRAMMING%27&run)!
[Answer]
## Python 3, 56
```
lambda s:sum(a!=b for a in s for b in s)/len(s)/~-len(s)
```
Counts the pairs of unequal elements, then divides by the number of such pairs.
[Answer]
# Pyth, 13 bytes
```
csnM*zz*lztlz
```
Pretty much a literal translation of @feersum's solution.
[Answer]
# CJam, 25 bytes
```
l$_e`0f=_:(.*:+\,_(*d/1\-
```
[Try it online](http://cjam.aditsu.net/#code=l%24_e%600f%3D_%3A(.*%3A%2B%5C%2C_(*d%2F1%5C-&input=ACBABA)
Fairly direct implementation of the formula in the question.
Explanation:
```
l Get input.
$ Sort it.
_ Copy for evaluation of denominator towards the end.
e` Run-length encoding of string.
0f= Map letter/length pairs from RLE to only length.
We now have a list of letter counts.
_ Copy list.
:( Map with decrement operator. Copy now contains letter counts minus 1.
.* Vectorized multiply. Results in list of n*(n-1) for each letter.
:+ Sum vector. This is the numerator.
\ Bring copy of input string to top.
, Calculate length.
_( Copy and decrement.
* Multiply. This is the denominator, n*(n-1) for the entire string.
d Convert to double, otherwise we would get integer division.
/ Divide.
1\- Calculate one minus result of division to get final result.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 30 bytes
```
{1-+//((x=\:x)-=l)%(l-1)*l:#x}
```
33 bytes if you want it to be faster:
```
{1-(+/j x)%(j:{x*x-1})[+/x]}@#'=:
```
This is the part where not having combinators hurt k's expressiveness. Also the problem statement is wrong: the equation corresponds to taking elements *without* replacement.
[Try it online!](https://ngn.codeberg.page/k#eJxLs6o21NXW19fQqLDVt4qxqtDUtc3RVNXI0TXU1MqxUq6o5UoDKdHQ1s9SqABKZFlVV2hV6BrWakZr61fE1jooq9tacXGlKSg5Ojs5OjkqgZjh4eFKXFxcAGV2FvA=)
[Answer]
# **JavaScript, 105 bytes**
```
f=(r,f=[],n=0,a=0)=>{for(k in [...r].map(k=>f[k]=(f[k]||0)+ ++n/n),f)a+=f[k]*(f[k]-1);return 1-a/(n*n-n)}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 81 bytes
```
s=>s.map(t=>s[t]=-~s[t])&&s.map(x=>(n++,a=s[x],s[x]=0,q+=a--*a),n=q=0)&&1-q/n--/n
```
[Try it online!](https://tio.run/##JYpBDoMgEEVvo1AYtAcYE@wxCIuJ1aaNHURI48qro6ab/15e/od@lIb1vWTg8BzLhCVhl8yXFpFPcdkj7BdkVf3zhp1gpTRhcpvX12Cro0ICuJHUjBHb832H2DBAw2UInMI8mjm8xCScMaa21vb9o/ZSlgM "JavaScript (Node.js) – Try It Online")
Magic
The first part defines letters as keys of `s` by abusing that the default key is undefined, and `-~undefined` = 1. Then, we iteratively delete the dictionary entries after using them (the first time we encounter them) while incrementing `n` to count the length. Finally, we compute `1-q/n--/n`.
[Answer]
# J, 37 bytes
```
(1-([:+/]*<:)%+/*[:<:+/)([:+/"1~.=/])
```
but I believe it can be still shortened.
Example
```
(1-([:+/]*<:)%+/*[:<:+/)([:+/"1~.=/]) 'AAABBC'
```
This is just a tacit version of the following function:
```
fun =: 3 : 0
a1=.+/"1 (~.y)=/y
N=.(+/a1)*(<:+/a1)
n=.a1*a1-1
1-(+/n)%N
)
```
[Answer]
# C,89
Score is for the function `f` only and excludes unnecessary whitespace, which is only included for clarity. the `main` function is only for testing.
```
i,c,n;
float f(char*v){
n=strlen(v);
for(i=n*n;i--;)c+=v[i%n]!=v[i/n];
return 1.0*c/(n*n-n);
}
main(int C,char**V){
printf("%f",f(V[1]));
}
```
It simply compares every character with every other character, then divides by the total number of comparisons.
[Answer]
# CJam, 23 bytes
```
1r$e`{0=,~}%_:+\,,:+d/-
```
Byte-wise, this is a very minor improvement over [@RetoKoradi's answer](https://codegolf.stackexchange.com/a/53461), but it uses a neat trick:
The sum of the first **n** non-negative integers equals **n(n - 1)/2**, which we can use to calculate the numerator and denominator, both divided by **2**, of the fraction in the question's formula.
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=1r%24e%60%7B0%3D%2C~%7D%25_%3A%2B%5C%2C%2C%3A%2Bd%2F-&input=PROGRAMMING).
### How it works
```
r$ e# Read a token from STDIN and sort it.
e` e# Perform run-length encoding.
{ }% e# For each [length character] pair:
0= e# Retrieve the length of the run (L).
,~ e# Push 0 1 2 ... L-1.
e# Collect all results in an array.
_:+ e# Push the sum of the entries of a copy.
\, e# Push the length of the array (L).
,:+ e# Push 0 + 1 + 2 + ... + L-1 = L(L-1)/2.
d/ e# Cast to Double and divide.
1 - e# Subtract the result from 1.
```
[Answer]
# Haskell, 83 bytes
I know I'm late, found this, had forgotten to post. Kinda inelegant with Haskell requiring me to convert integers to numbers that you can divide by each other.
```
s z=(l(filter id p)-l z)/(l p-l z) where p=[c==d|c<-z,d<-z]
l=fromIntegral.length
```
[Answer]
# APL, 26 bytes
```
{1-+/÷/{⍵×⍵-1}({⍴⍵}⌸⍵),≢⍵}
```
Explanation:
* `≢⍵`: get the length of the first dimension of `⍵`. Given that `⍵` is supposed to be a string, this means the length of the string.
* `{⍴⍵}⌸⍵`: for each unique element in `⍵`, get the lengths of each dimension of the list of occurrences. This gives the amount of times an item occurs for each item, as a `1×≢⍵` matrix.
* `,`: concatenate the two along the horizontal axis. Since `≢⍵` is a scalar, and the other value is a column, we get a `2×≢⍵` matrix where the first column has the amount of times an item occurs for each item, and the second column has the total amount of items.
* `{⍵×⍵-1}`: for each cell in the matrix, calculate `N(N-1)`.
* `÷/`: reduce rows by division. This divides the value for each item by the value for the total.
* `+/`: sum the result for each row.
* `1-`: subtract it from 1
[Answer]
# Excel, 67 bytes
```
=LET(n,COUNTA(A:A),c,COUNTIF(A:A,UNIQUE(A:A)),1-SUM(c^2-c)/(n^2-n))
```
Input is a list of characters in the column A. One character per cell. Output is wherever the formula is which can be anywhere except in column A.
The [LET()](https://support.microsoft.com/en-us/office/let-function-34842dd8-b92b-4d3f-b325-b8b8f9908999) function allows you to define variables that can be referenced later and it saves most of the bytes here. The arguments are in pairs of `variable,value` except for the last argument which is not in a pair and is instead the output.
* `n,COUNTA(A:A)` stores the count of how many non-blank cells there are in column A.
* `c,COUNTIF(A:A,UNIQUE(A:A))` creates an array of all the unique items from column A and then counts how many times each of those unique values appear. Technically, the UNIQUE() array will include a `0` at the end (presuming there are blank cells in `A:A`) but COUNTIF() will return `0` for it's count so that doesn't impact the calculations.
* `1-SUM(c^2-c)/(n^2-n)` is the final output. Except for turning `a(a-1)` into `a^2-a` to save a byte, then is a straightforward implementation of the formula. The denominator could have also been `/n/(n-1)` for the same byte count but I chose the more aesthetically pleasing option.
[](https://i.stack.imgur.com/6hXn5.png)
[Answer]
## PHP 4 (72 chars)
Given *$argv[1]* as a command line argument :
```
foreach(count_chars($argv[1])as$c)@$r-=$c*$c+$g-$g+=$c;echo$r/$g/--$g+1;
```
[Try it Online](https://tio.run/##PY1BC4IwFMfP7lMMeeCWing2q81COljhxUNFjGHbSWVqENFnt3mwy/@994P3@3e6m6b1ttMderamFlITYYx4E48xxnnmBR7LOOPMLlVV2czO@4Mdl/Kcl6wojqfco1j0GIRRr2t8p@iDnFrqFrsLwukGuwlylgbZjs3wkFqYnvzfRA@S7sCEKcgVSB9UCMq3RzLLwESgonBGcbL4b81sHZu@HgiYABRN0BdN0w8)
[Answer]
# TI-Basic, 75 bytes
```
seq(inString(Ans,sub(Ans,I,1)),I,1,length(Ans→A
SortA(ʟA
augment({0},1 and ΔList(ʟA
seq(sum(cumSum(Ans)=I),I,0,sum(Ans
1-sum(Ans²-Ans)/(sum(Ans)²-sum(Ans
```
Takes input in `Ans` as a string. Output is stored in `Ans` and is displayed.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 31 bytes
A port of [xnor's Python answer](https://codegolf.stackexchange.com/a/53581/9288).
```
@(s)nnz(s!=s')/(l=nnz(s))/(l-1)
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKunp/ffQaNYMy@vSqNY0bZYXVNfI8cWzNMEMXUNNf@naSg5Ojo6OTkraXKB2M5Ojk6OEHZ4eDiE4ezv4gphBQT5uwc5@vp6@rkraf4HAA "Octave – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~24~~ 23 bytes
```
{1-/%/{x*x-1}(#'=x;#x)}
```
[Try it online!](https://ngn.codeberg.page/k/#eJx1j0FrwkAUhO/vVyyxpVpINsGE0iw9bNIiPVhFCjlIwJBsdFGzNrstG4L+9mY1FD103uUNM4dvyrD1bHyPW/2obe84HDy8aDLQoyOACtu7ZXOqwxIhpMlKbMlwVWZ8RzRpSD1KTWdpUUqjKLaI6zyNb+Sn5ziOaET/jZMkMZl7NvHs9c0iXu/mi9lkQafT94+JqTz7wc2lABg2Sh1kiHEuCrYWu9KRKsu3TOebrFozJxd7/PXNpOKikjgY+0GAJd8fpKjsgv+wWnLV2LwqmAb47HoozySTAJdRqIeGy4g/20F3vwuGF3W4cIWKelIw+gV/z15q)
An adaption of @marinus' [APL answer](https://codegolf.stackexchange.com/a/79623/98547).
* `(#'=x;#x)` create a two item list containing: a dictionary mapping each distinct character to the number of times it appears in the input; and the length of the input string
* `{x*x-1}` multiply each value in the above list by itself minus one
* `%/` divide the (adjusted) counts of characters by the (adjusted) length of the input
* `1-/` use a minus-reduce, seeded with 1, subtracting each of the above to (implicitly) return the metric
[Answer]
# JavaScript, 100 bytes
```
a=>(n=a.length,1-[...new Set(a)].map(b=>((c=a.split(b).length-1)-1)*c).reduce((a,b)=>a+b)/(n*(n-1)))
```
[Answer]
# JavaScript, 96 bytes
```
a=>eval('h=0,c=0,o=[];for(i of a)o[i]=o[i]+1||1,c++;for(i in o)h+=(v=o[i])*(v-1);1-h/(c*(c-1))')
```
Posted this as a seperate answer since it's not an update to my older one.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 16 bytes
```
ĐĐỤ⇹ɔ⁻△Ʃ⇹Ł⁻△ᵮ/⁻~
```
[Try it online!](https://tio.run/##K6gs@f//yIQjEx7uXvKofefJKY8adz@atvnYSiDnaCOE83DrOn0gq@7//2j1RHUdOE6C4mT1WAA "Pyt – Try It Online")
Takes a list of characters
```
ĐĐ implicit input; Đuplicates on the stack twice
Ụ get Ụnique elements
⇹ɔ get ɔount of each unique element in original list
⁻△ decrement count and get the corresponding triangular number n*(n-1)
Ʃ sum the triangular numbers
⇹Ł get Łength of original list
⁻△ decrement and get triangular number
ᵮ/ divide (cast to ᵮloat first due to bug in division coding)
⁻~ subtract one and negate (equivalent to subtracting from one)
implicit print
```
] |
[Question]
[
A follow-up to [this challenge](https://codegolf.stackexchange.com/q/144146/45941)
Given a set of mixed dice, output the frequency distribution of rolling all of them and summing the rolled numbers on each die.
For example, consider `1d12 + 1d8` (rolling 1 12-sided die and 1 8-sided die). The maximum and minimum rolls are `20` and `2`, respectively, which is similar to rolling `2d10` (2 10-sided dice). However, `1d12 + 1d8` results in a flatter distribution than `2d10`: `[1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 7, 6, 5, 4, 3, 2, 1]` versus `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`.
## Rules
* The frequencies must be listed in increasing order of the sum to which the frequency corresponds.
* Labeling the frequencies with the corresponding sums is allowed, but not required (since the sums can be inferred from the required order).
* You do not have to handle inputs where the output exceeds the representable range of integers for your language.
* Leading or trailing zeroes are not permitted. Only positive frequencies should appear in the output.
* You may take the input in any reasonable format (list of dice (`[6, 8, 8]`), list of dice pairs (`[[1, 6], [2, 8]]`), etc.).
* The frequencies must be normalized so that the GCD of the frequencies is 1 (e.g. `[1, 2, 3, 2, 1]` instead of `[2, 4, 6, 4, 2]`).
* All dice will have at least one face (so a `d1` is the minimum).
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/45941) are forbidden, as per usual.
## Test Cases
These test cases are given as `input: output`, where the input is given as a list of pairs `[a, b]` representing `a` `b`-sided dice (so `[3, 8]` refers to `3d8`, and `[[1, 12], [1, 8]]` refers to `1d12 + 1d8`).
```
[[2, 10]]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[[1, 1], [1, 9]]: [1, 1, 1, 1, 1, 1, 1, 1, 1]
[[1, 12], [1, 8]]: [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 7, 6, 5, 4, 3, 2, 1]
[[2, 4], [3, 6]]: [1, 5, 15, 35, 68, 116, 177, 245, 311, 363, 392, 392, 363, 311, 245, 177, 116, 68, 35, 15, 5, 1]
[[1, 3], [2, 13]]: [1, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 37, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 1]
[[1, 4], [2, 8], [2, 20]]: [1, 5, 15, 35, 69, 121, 195, 295, 423, 579, 761, 965, 1187, 1423, 1669, 1921, 2176, 2432, 2688, 2944, 3198, 3446, 3682, 3898, 4086, 4238, 4346, 4402, 4402, 4346, 4238, 4086, 3898, 3682, 3446, 3198, 2944, 2688, 2432, 2176, 1921, 1669, 1423, 1187, 965, 761, 579, 423, 295, 195, 121, 69, 35, 15, 5, 1]
[[1, 10], [1, 12], [1, 20], [1, 50]]: [1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 285, 360, 444, 536, 635, 740, 850, 964, 1081, 1200, 1319, 1436, 1550, 1660, 1765, 1864, 1956, 2040, 2115, 2180, 2235, 2280, 2316, 2344, 2365, 2380, 2390, 2396, 2399, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2400, 2399, 2396, 2390, 2380, 2365, 2344, 2316, 2280, 2235, 2180, 2115, 2040, 1956, 1864, 1765, 1660, 1550, 1436, 1319, 1200, 1081, 964, 850, 740, 635, 536, 444, 360, 285, 220, 165, 120, 84, 56, 35, 20, 10, 4, 1]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 bytes thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) (use of an implicit range to avoid leading `R`; replacement of reduce by the dyadic Cartesian product and flatten, `p/F€`, with the Cartesian product built-in for that very purpose, `Œp`.)
```
ŒpS€ĠL€
```
A monadic link taking a list of dice faces and returning the normalised distribution of the increasing sums.
**[Try it online!](https://tio.run/##y0rNyan8///opILgR01rjizwAZL///@PNjTQMTTSMTKIBQA "Jelly – Try It Online")**
### How?
Goes through the list of dice "sizes" (implicitly) makes them into their list of faces, then gets the Cartesian product of those lists (all possible rolls of the set of dice), then sums up those rolls, gets the groups of equal indices (by ascending value) and takes the length of each group.
```
ŒpS€ĠL€ - Link: list of numbers, dice e.g. [2,5,1,2]
Œp - Cartisian product (implicit range-ification -> [[1,2],[1,2,3,4,5],[1],[1,2]])
- -> [[1,1,1,1],[1,1,1,2],[1,2,1,1],[1,2,1,2],[1,3,1,1],[1,3,1,2],[1,4,1,1],[1,4,1,2],[1,5,1,1],[1,5,1,2],[2,1,1,1],[2,1,1,2],[2,2,1,1],[2,2,1,2],[2,3,1,1],[2,3,1,2],[2,4,1,1],[2,4,1,2],[2,5,1,1],[2,5,1,2]]
S€ - sum €ach -> [4,5,5,6,6,7,7,8,8,9,5,6,6,7,7,8,8,9,9,10]
Ġ - group indices -> [[1],[2,3,11],[4,5,12,13],[6,7,14,15],[8,9,16,17],[10,18,19],[20]]
L€ - length of €ach -> [1,3,4,4,4,3,1]
```
Note: there is only ever one way to roll the minimum (by rolling a one on each and every dice) and we are not double-counting any rolls, so there is no need to perform a GCD normalisation.
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
1%r=r
n%r=zipWith(+)(r++[0,0..])$0:(n-1)%r
foldr(%)[1]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/31C1yLaIKw9IVmUWhGeWZGhoa2oUaWtHG@gY6OnFaqoYWGnk6RpqqhZxpdmm5eekFGmoakYbxv7PTczMU7BVKCgtCS4p8slTUFEozsgvB1JpCtHGOmY6prH/AQ "Haskell – Try It Online")
---
**[Haskell](https://www.haskell.org/), 63 bytes**
```
f l=[sum[1|t<-mapM(\x->[1..x])l,sum t==k]|k<-[length l..sum l]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hxza6uDQ32rCmxEY3N7HAVyOmQtcu2lBPryJWM0cHKKVQYmubHVuTbaMbnZOal16SoZCjpwcSz4mN/Z@bmJmnYKtQUFoSXFLkk6egolCckV8OpNIUoo11zHRMY/8DAA "Haskell – Try It Online")
---
**[Haskell](https://www.haskell.org/), 68 bytes**
```
k%(h:t)=sum$map(%t)[k-h..k-1]
k%_=0^k^2
f l=map(%l)[length l..sum l]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1tVI8OqRNO2uDRXJTexQEO1RDM6WzdDTy9b1zCWK1s13tYgLjvOiCtNIccWLJ@jGZ2TmpdekqGQo6cH1KWQE/s/NzEzT8FWoaC0JLikyCdPQUWhOCO/HEilKUQb65jpmMb@BwA "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
1i"@:gY+
```
The input is an array of (possibly repeated) die sizes.
[Try it online!](https://tio.run/##y00syfn/3zBTycEqPVL7//9oQwMFQyMFIwMFU4NYAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8N8wU8nBKj1S@3@sQXKES8j/aEMDBUODWK5oQwVLEGmkYAGkTBRMFMxAEMg2VjAEIbCoBRAaGQARSClQoxGIZ2oQCwA).
### Explanation
```
1 % Push 1
i % Input: numeric array
" % For each k in that array
@ % Push k
: % Range: gives [1 2 ... k]
g % Convert to logical: gives [1 1 ... 1]
Y+ % Convolution, with full size
% End (implicit). Display (implicit)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
mLkΣΠmḣ
```
Input is a list of dice.
[Try it online!](https://tio.run/##yygtzv7/P9cn@9zicwtyH@5Y/P///2gTHRMdMxCMBQA "Husk – Try It Online")
## Explanation
```
mLkΣΠmḣ Implicit input, say x=[3,3,6].
mḣ Map range: [[1,2,3],[1,2,3],[1,2,3,4,5,6]]
Π Cartesian product: [[1,1,1],[1,1,2],..,[3,3,6]]
kΣ Classify by sum: [[[1,1,1]],[[1,1,2],[1,2,1],[2,1,1]],..,[[3,3,6]]]
mL Map length: [1,3,6,8,9,9,8,6,3,1]
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~88 69 58~~ 56 bytes
As mentioned in the Haskell answer, this uses the fact that the distribution of e.g. a 3-sided and a 5-sided dice is the discrete convolution of the two vectors `[1,1,1]` and `[1,1,1,1,1]`. Thanks @LuisMendo for -11 bytes worth of clever golfing!
```
function y=f(c);y=1:c;if d=c(2:end);y=conv(~~y,f(d));end
```
[Try it online!](https://tio.run/##FcgxCsAgDADArzgm4FKhi@JLSoeSGHDRQq3g4tdTO9xyldrVk6q8hVquxYwoQBhG3DyFLIYjgfOp8H9US4c5hxVgxLBWl8D5uUHgcNbZ/UTUDw "Octave – Try It Online")
This submission is using an recursive approach. But if you would use a loop it would be slightly longer:
```
function y=f(c);y=1;for k=cellfun(@(x)ones(1,x),c,'Un',0);y=conv(y,k{1});end
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 bytes
```
Tally[Tr/@Tuples@Range@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/T8kMSenMjqkSN8hpLQgJ7XYISgxLz3VQTlW7b@Cg0K1mY6FjkVt7H8A "Wolfram Language (Mathematica) – Try It Online")
A modification of [my answer to the previous challenge](https://codegolf.stackexchange.com/a/144148). This just generates all possible outcomes, adds them up, and tallies the results.
For fun, we could write it as `Tally@*Total@*Thread@*Tuples@*Range`, but that's longer.
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
CoefficientList[1##&@@((x^#-1)/(x-1)),x]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d85PzUtLTM5MzWvxCezuCTaUFlZzcFBQ6MiTlnXUFNfowJIaupUxKr9V3BQqDbTsdCxqI39DwA "Wolfram Language (Mathematica) – Try It Online")
This is the convolution-based approach (here, we take convolutions via the product of generating functions - `1+x+x^2+...+x^(N-1)` is the generating function for rolling a dN - and then take the list of coefficients). I include it because the first solution isn't practical for large inputs.
[Answer]
# Mathematica, 44 bytes
Outputs the frequencies labeled with the corresponding sums
```
Tally@*Fold[Join@@Table[#+i,{i,#2}]&]@*Range
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PyQxJ6fSQcstPycl2is/M8/BISQxKSc1Wlk7U6c6U0fZqDZWLdZBKygxLz31f0BRZl6JQ1p0taGBjqFBbSwXREBJiQsho2OJXdxIxwKrhImOiY4ZCGKVNdYxBCEcOi2A0MgAiLBbCXSkEUjeFCj/HwA "Wolfram Language (Mathematica) – Try It Online")
-5 bytes from Martin Ender
thanks to Misha Lavrov for letting me know that "labeled" is valid
[Answer]
# [Pyth](https://pyth.herokuapp.com/?code=lM.gs.nk%2aFSM&input=%5B10%2C12%2C20%5D&debug=0), 12 bytes
```
lM.gs.nk*FSM
```
**[Try it here!](https://pyth.herokuapp.com/?code=lM.gs.nk%2aFSM&input=%5B10%2C12%2C20%5D&debug=0)**
### How?
```
lM.gs.nk*FSM ~ Full program.
SM ~ Map with inclusive unary integer range [1, N].
*F ~ Fold (Reduce by) Cartesian product.
.g ~ Group by function result.
s.n ~ The sum of the list when flattened.
lM ~ Length of each group.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
R+Ѐ/FċЀSR$ḟ0
```
[Try it online!](https://tio.run/##y0rNyan8/z9I@/CER01r9N2OdIMZwUEqD3fMN/j//3@0sY4hCMUCAA "Jelly – Try It Online")
Input is a list of die values. I could golf this down by stealing `ĠL€` from the other Jelly answer but then I could also golf down the first half and end up with the same thing so I'll just leave it how it is
[Answer]
# [Haskell](https://www.haskell.org/), ~~80 78~~ 64 bytes
This solution ended up being almost the same as the one of [@Sherlock9](https://codegolf.stackexchange.com/a/144152/24877) in the previous challenge with the maybe more natural approach. @xnor has an even [shorter Haskell solution](https://codegolf.stackexchange.com/a/150314/24877)!
```
import Data.List
g x=[1..x]
map length.group.sort.map sum.mapM g
```
Explanation:
```
mapM g -- all possible outcomes
map sum -- the sums of all possible outcomes
map length.group.sort -- count the frequency of each sum
```
[Try it online!](https://tio.run/##Fcq9CoMwFIbh3av4ho5yoELHbB3t1FEczqBJaP7IOUHvPtXpgZfXsfy2EHr3seSqeLMyzV50sDjN8iQ612E3kQvClqw6sjW3QnLNdFdp8fYD2yP7BIPS9Kt1TnhAXD4udizTOI2vtf8B "Haskell – Try It Online")
**Previous solution:**
This is using the @AndersKaseorg [discrete convolution](https://codegolf.stackexchange.com/a/80036/24877) function. The observation here is that the distribution of e.g. a 3-sided and a 5-sided dice is the discrete convolution of the two vectors `[1,1,1]` and `[1,1,1,1,1]`.
```
foldl1(#).map(`take`l)
(a:b)#c=zipWith(+)(0:b#c)$map(a*)c++[]#b
_#c=0<$c
l=1:l
```
[Try it online!](https://tio.run/##Fc7RToMwFADQd77iJvDQilCmhi2NfIcPc3Hl0kLDpW1otxg/3jrfz8NZVFw1UTYwwGc2niY6sJK3mwrsmtSqr8QLpuTISxx@bPiwaWE1Z50cS@TVP1NPHOv6fCnH4uuBuvcKCxoOknLTwGQj7jppQO/unm7JegcxedIOzO43CUtKIUoh0E969mTamBSu@hsX5Wbdot@EEqeue@3Fy9vpeCw2Zd1jG3brElRg4Nw/95f8i4bUHHODIfwB "Haskell – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~120~~ 119 bytes
```
lambda v:[reduce(lambda a,c:sum([[b+y for b in a]for y in range(c)],[]),v,[0]).count(d)for d in range(sum(v)-len(v)+1)]
```
[Try it online!](https://tio.run/##RY3BDoIwDIbP8hQ7bqEaNtEgiVdeYu4wtqEkMMgEEp5@boIxbdKvf9u/4zq9Bst8c3/4Tva1lmgpuTN6VgbvggRVvucec16nK2oGh2rUWiRFxDWik/ZpsCICuCCwAM8EOalhthPWJG7p/1Z0WsixMzaUlBLhtWlQhSUpk8PoWjuFh6gJfZJUmNMMaHD7Itx2YFBslEMO1xhbewYa8zcrQrAs5H4WrFgULkHwHw "Python 2 – Try It Online")
Thks for Mego/Jonathon Allan for 1 byte.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
€L.«âOO{γ€g
```
[Try it online!](https://tio.run/##MzBNTDJM/f//UdMaH71Dqw8v8vevPrcZyEv//z/a0EDH0EjHyCAWAA "05AB1E – Try It Online")
**How it works**
```
€L.«âOO{γ€g - Full program.
€L - For each N in the list, get [1 .. N].
.« - Fold a dyadic function between each element in a list from right to left.
â - And choose cartesian product as that function.
O - Flatten each.
O - Sum each.
{γ - Sort, and group into runs of equal adjacent values.
€g - Get the lengths of each.
```
Saved 1 byte thanks to [Emigna](https://codegolf.stackexchange.com/users/47066/emigna)!
[Answer]
# [R](https://www.r-project.org/), 51 bytes
```
function(D){for(x in D)F=outer(F,1:x,"+")
table(F)}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NFszotv0ijQiEzT8FF0802v7QktUjDTcfQqkJHSVtJk6skMSknVcNNs/Z/mkayhqGRjoWm5n8A "R – Try It Online")
Takes a list of dice and returns a named vector of frequencies; the names (values of the dice sums) are printed above the frequencies.
# [R](https://www.r-project.org/), 59 bytes
```
function(D)table(Reduce(function(x,y)outer(x,1:y,"+"),D,0))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NFsyQxKSdVIyg1pTQ5VQMuXqFTqZlfWpJaBGQZWlXqKGkraeq46Bhoav5P00jWMDTSsQAyAQ "R – Try It Online")
A `Reduce` approach rather than the iterative one above.
# [R](https://www.r-project.org/), 62 bytes
```
function(D)Re(convolve(!!1:D,"if"(sum(x<-D[-1]),f(x),1),,"o"))
```
[Try it online!](https://tio.run/##DcaxCoAgEADQX8mb7uAcbIpw9Atao0k8EMqDSvHvrTe9e8jk7ZBa4pu1YKAtYdTS9GwJjXFrYMgC@NQLu7dht@4gFuzEjphBgWgIRnQzL38/ "R – Try It Online")
A convolution approach. It will give a few warnings that it's only using the first element of `D` for the expression `1:D` but it doesn't affect the output. If we didn't have to take the `Re`al part of the solution, it'd be 58 bytes.
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~12~~ 10 bytes
-2 thanks to @Adám
```
⊢∘≢⌸+/↑,⍳⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4/6lr0qGPGo85Fj3p2aOs/apuo86h3M1DNf6Ds/zQuQwMFQwMuIK1gCSKNFCyAlImCiYIZCALZxgqGIAQWtQBCIwMg4oJoNALxTA0A "APL (Dyalog Classic) – Try It Online")
the input `⎕` is a list of N dice
`⍳⍵` is an N-dimensional array of nested vectors - all possible die throws
`+/↑,` flattens the arrays and sums the throws
`⊢∘≢⌸` counts how many of each unique sum, listed in order of their first appearance, which fortunately coincides with their increasing order
[Answer]
# [Ruby](https://www.ruby-lang.org/), 72 bytes
```
->d{r=[0]*d.sum
[0].product(*d.map{|e|[*1..e]}){|e|r[e.sum-1]+=1}
r-[0]}
```
[Try it online!](https://tio.run/##PU7LCsMgELznK/bYphtR@yA9pD8iHtLE0EtosOZQ1G@3awyFGZgdZoa16/Obpi41j9HbTnFdj@yzzhUpttj3uA7uQNbcLz6YoGrBmNHxmA@rTI42Qp86ESvbUCcmVQEowREE17hphPuuJEJb5AWBcCso1pkqG/@JdoPkmftC3pXFu2ZPM9MPL/DBBVjAIUzK0RM/ "Ruby – Try It Online")
Takes a list of dice as input. No doubt it can be golfed down, but not too bad.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 35 bytes
```
v->Vec(prod(i=1,#v,1/(1-x)%x^v[i]))
```
[Try it online!](https://tio.run/##JYvhCsIwDIRfJUyEBlJsuinzx/YY/ikVhjopDA1Fynz62k4ucPcdF5li0E/JMwyQkx4vj5uS@L6rMDDtEvFBsV5xv16TCx4xTyLLVyXQI0gMr0@JTYUGZpUQCZxjQ2x8SUznzSz11Tvq6FRVoSVu/2VfZE25bVt@bcWj8R7zDw "Pari/GP – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~154~~ ~~142~~ ~~136~~ ~~107~~ ~~100~~ 85+13=98 bytes
Input is a list of dice.
```
\l#t=foldr(\a-> \b=[x+y\\x<-[1..a],y<-b])[0]l
=[length[v\\v<-t|u==v]\\u<-removeDup t]
```
Answer is in the form of a lambda.
**+13** bytes from `import StdEnv`, which imports the module needed for this to work.
[Try it online!](https://tio.run/##Dc2xDoIwFEDR3a94iYtGSgrGjTrhYKITY1@HAi2QtIVgaSDx261MN2e6jVHSRTu2i1Fg5eAOg53G2UPl24cLUQMDNEfP9Gja@YSS3AFrxtfLhrgWhGdpKkWyFaQWZ06FOTBulOt8zwNiKIj/LowFgbgUZFZ2DKpcJvAiVl7uGwYaeEYTyPIE8r03KuKv0UZ2n0ier1huTtqh2dHHK6XvPw "Clean – Try It Online")
[Answer]
## JavaScript (ES6), 83 bytes
```
f=(n,...a)=>n?f(...a).map((e,i)=>[...Array(n)].map(_=>r[i]=~~r[i++]+e),r=[])&&r:[1]
g=s=>o.textContent=f(...(s.match(/\d+/g)||[]).map(n=>+n)).join`, `
```
```
<input oninput=g(this.value)><p id=o>1
```
Takes input of each die as a separate parameter.
[Answer]
# JavaScript (ES6), ~~76~~ 74 bytes
Takes input as a list of dice.
```
a=>(g=k=>a.map(d=>(s+=n%d|0,n/=d),s=0,n=k)|n?x:g(k+1,x[s]=-~x[s]))(0,x=[])
```
### Test cases
Processing the last two test cases would require to enable TCO or increase the default stack size limit of the JS engine.
```
let f =
a=>(g=k=>a.map(d=>(s+=n%d|0,n/=d),s=0,n=k)|n?x:g(k+1,x[s]=-~x[s]))(0,x=[])
console.log(f([10,10]).join(', '))
console.log(f([1,9]).join(', '))
console.log(f([12,8]).join(', '))
console.log(f([4,4,6,6,6]).join(', '))
console.log(f([3,13,13]).join(', '))
```
### Formatted and commented
*NB: This is a commented version of my initial submission which was using reduce(). It's 2 bytes longer but easier to read.*
```
a => // given the list of dice a
(g = k => // g = recursive function taking k = counter
a.reduce((k, d) => // for each die d in a:
( // k % d represents the current face of d
s += k % d, // we add it to the total s
k / d | 0 // and we update k to pick the face of the next die
), // initialization:
k, // start with the current value of k
s = 0 // total = 0
) ? // reduce() returns 1 as soon as k = product of all dice
x // in which case we're done: stop recursion and return x
: // else:
g( // do a recursive call to g() with:
k + 1, // k incremented
x[s] = -~x[s] // x[s] incremented
) // end of recursive call
)(0, x = []) // initial call to g() with k = 0 and x = empty array
```
[Answer]
## Clojure, 96 bytes
```
#(sort-by key(frequencies(reduce(fn[R D](for[d(range D)r R](+ r d 1)))[0](mapcat repeat % %2))))
```
First input is a list of number of dice, and the second input is a list of number of sides on each dice.
[Answer]
# [Perl 5](https://www.perl.org/), 94 bytes
```
map$k{$_}++,map eval,glob join'+',map'{'.(join',',1..$_).'}',<>;say$k{$_}for sort{$a-$b}keys%k
```
[Try it online!](https://tio.run/##K0gtyjH9/z83sUAlu1olvlZbWwfIVkgtS8zRSc/JT1LIys/MU9dWB4mqV6vraYD5Ouo6hnp6KvGaeuq16jo2dtbFiZUQ/Wn5RQrF@UUl1SqJuipJtdmplcWq2f//GxpxWfzLLyjJzM8r/q/ra6pnYGgAAA "Perl 5 – Try It Online")
Input format is a list of dice separated by newlines. Thus, 1d10+2d8 would input as:
```
10
8
8
```
[Answer]
## SageMath, 46 bytes
```
lambda*a:reduce(convolution,[x*[1]for x in a])
```
[Try it online](http://sagecell.sagemath.org/?z=eJxLs81JzE1KSdRKtCpKTSlNTtVIzs8ry88pLcnMz9OJrtCKNoxNyy9SqFDIzFNIjNXk5eLlStMw0VEAIjMI0gQAJNIUOA==&lang=sage)
This is an adaptation of my solution to [the other challenge](https://codegolf.stackexchange.com/a/144301/45941). It takes in any number of dice as parameters (e.g. `f(4,4,6,6,6)` for `2d4+3d6`), and returns a list.
---
# [Python 2](https://docs.python.org/2/) + [NumPy](https://numpy.org), 62 bytes
```
lambda*a:reduce(numpy.convolve,[x*[1]for x in a])
import numpy
```
[Try it online!](https://tio.run/##HcoxCoAgFADQvVM4qkhQSEPQScrBUknI/0Us9PRG8dYXaz4RxuaWrV067EZzPSdr7sNSuEOs/YHw4PVYsRa@DsphIoV4IFqxzoeIKZM/tpg8ZOqoFFJMH8baCw "Python 2 – Try It Online")
As before, I've included this solution with the above one, since they're essentially equivalent. Note that this function returns a NumPy array and not a Python list, so the output looks a bit different if you `print` it.
`numpy.ones(x)` is the "correct" way to make an array for use with NumPy, and thus it could be used in place of `[x*[1]]`, but it's unfortunately much longer.
] |
[Question]
[
# Background
A **binary tree** is a rooted tree whose every node has at most two children.
A **labelled binary tree** is a binary tree whose every node is labelled with a positive integer; moreover, all labels are **distinct**.
A **BST** (binary search tree) is a labelled binary tree in which the label of each node is greater than the labels of all the nodes in its left subtree, and smaller than the labels of all the nodes in its right subtree. For instance, the following is a BST:
[](https://i.stack.imgur.com/i7c6d.png)
The **pre-order traversal** of a labelled binary tree is defined by the following pseudo-code.
```
function preorder(node)
if node is null then
return
else
print(node.label)
preorder(node.left)
preorder(node.right)
```
See the following image to get a better intuition:
[](https://i.stack.imgur.com/kUMw1.png)
The vertices of this binary tree are printed in the following order:
```
F, B, A, D, C, E, G, I, H
```
You can read more about BSTs [here](https://en.wikipedia.org/wiki/Binary_search_tree), and more about pre-order traversal [here](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR)).
# Challenge
Given a list of integers \$a\$, your task is to determine whether there is a BST whose pre-order traversal prints exactly \$a\$.
## Input
* A non-empty **list** of distinct positive integers \$a\$.
* Optionally, the length of \$a\$.
## Output
* A **truthy** value if \$a\$ is the pre-order traversal of some BST.
* A **falsey** value otherwise.
# Rules
* **Standard rules** for [valid submissions](https://codegolf.meta.stackexchange.com/q/2419/82619), [I/O](https://codegolf.meta.stackexchange.com/q/2447/82619), [loopholes](https://codegolf.meta.stackexchange.com/q/1061/82619) apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **shortest solution** (in bytes) wins. As usual, don't let ridiculously short solutions in golfy languages discourage you from posting a longer answer in your language of choice.
* This is not a rule, but your answer will be better received if it includes a link to test the solution and an explanation of how it works.
# Examples
```
Input ----> Output
[1] ----> True
[1,2,3,4] ----> True
[5,1,4,2,3] ----> True
[5,4,3,2,1,6,7,8,9] ----> True
[4,2,1,3,6,5,7] ----> True
[8,3,1,6,4,7,10,14,13] ----> True
[2,3,1] ----> False
[6,3,2,4,5,1,8,7,9] ----> False
[1,2,3,4,5,7,8,6] ----> False
[3,1,4,2] ----> False
```
Check out [this link](https://pastebin.com/BFrtiM6Q) (courtesy of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)) to have a visual look at the examples.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
a=>!a.some((p,i)=>a.some((q,j)=>q>p&a[j+=j>i]<p))
```
[Try it online!](https://tio.run/##fZFNS8MwGMfv@xTx4hL2LLNb9yKzuQgeRPSgtxlYqJm0dE3WxCmIn70@2VpBqcslBH7/X56XXO2VS6vM@mFpXnS9SWqViDPFndlqSi1kLBHtawc5vnbCnqtVPkhykckry1idmtJ54rXzqXLakYSse6tIkq4zxCPwfqreNEIwhgnE8iQ0hQjiAMqTUIymMaIzmMMCLmUHFB@ACSJTmMt/TAsEgiVGT3QBUQxR@Pk3FMru6LCFblThkJodSoohdLBA3Z@iGqoZQqgJqZnsdK2XvZ8Bc19lW8q4s0Xmaf@57DO@VZYWWalJIshnj5DjTlZtBoj@sDr1EpcTsCY7Gg7E6Bjeh@Tt48M9t6pymu65N3fmXVfXGKeMsWVjNYXmhXmlG9rKWWtH5ost628 "JavaScript (Node.js) – Try It Online")
Using the fact that for array \$a\_0 ... a\_{n-1}\$, \$a\$ is the pre-order traversal of some BST iff \$ \forall 0\le i<j<n; a\_i<a\_{j-1} \implies a\_i<a\_j \$ holds.
Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld), save 1 byte.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ŒPŒ¿€4ḟ
```
[Try it online!](https://tio.run/##y0rNyan8///opICjkw7tf9S0xuThjvn/D7cDWUcnPdw54///6GjDWAUsgEsn2lDHSMdYxyQWQ8JUx1DHBCQZiyZsAlRvBJQ00zHXsdCxjIWIm4DFjIGipjrmsQj1FkAxkFoToGpDAx1DEx1D41igOMhWDEcBxc3AppvogKy3AOoBmo9wJchsoKhZbCwA "Jelly – Try It Online")
Returns `[4]` for traversals, otherwise `[]`.
Essentially uses tsh's algorithm: the "disqualifying" condition for a pre-order traversal is a [subsequence](https://en.wikipedia.org/wiki/Subsequence) of 3 elements that looks like **[mid, high, low]**. (For example, [20, 30, 10].)
We equivalently check for any subsequences of *any* length that have index **4** in their permutation lists, which are all lists sorted like **[a1 … ak c d b]** where the **ai** are sorted and **ai < b < c < d**. (Each such list is disqualifying if we look at the last three elements, and each disqualifying list is obviously of this form.)
```
ŒP All subsequences.
Œ¿€ Permutation index of each.
4ḟ Set difference of {4} and this list.
```
# Proof
>
> ## A pre-order traversal contains no disqualifying subsequences
>
>
> Base case: **traversal(•)** is the empty list. ✓
>
>
> Induction: **traversal(t)** is: **t.root** ++ **traversal(t.left)** ++ **traversal(t.right)**.
>
>
> Let **[a, b, c]** be a subsequence hereof. We'll show **c < a < b** is impossible.
>
>
> * If **t.root = a**, then **c < a < b** requires **c ∈ t.left** and **b ∈ t.right**, so **[a, b, c]** is the wrong order.
> * If **a, b, c ∈ t.left** or **a, b, c ∈ t.right**, use the induction hypothesis.
> * If **a ∈ t.left** and **c ∈ t.right** then **c > a**.
>
>
>
#
>
> ## A list of distinct integers without disqualifying subsequences is the pre-order traversal of a BST
>
>
> If the list is empty, it's the traversal of the trivial BST •.
>
>
> If the list is **head** followed by **tail**:
>
>
> * Let **less** be the longest prefix of **tail** of elements less than **head**, and let **more** be the rest of the list.
> * Then **more[1] > head**, and all other **more[i]** are greater than **head** too (otherwise **[head, more[1], more[i]]** would be a disqualifying subsequence).
> * Recurse: turn **less** and **more** into BSTs.
> * Now our list is the traversal of
>
>
>
> ```
> head
> / \
> BST(less) BST(more),
>
> ```
>
> and this tree is a valid BST.
>
>
>
[Answer]
# Java 10, 94 bytes
```
a->{var r=0>1;for(int j=a.length-1,i;j-->0;)for(i=0;i<j;)r|=a[j]>a[i]&a[j+1]<a[i++];return!r;}
```
Port of [*@tsh*' JavaScript answer](https://codegolf.stackexchange.com/a/174295/52210).
[Try it online.](https://tio.run/##bZFNb8IwDIbv/ArvMrUiLQ2Ur4X2uNu4sBvqIZQA6UqK0hQJMX5752SwddKkRIr9xn4f2QU/86DYfrR5yesa3rhU1x6AVEboHc8FLG0IsKmqUnAFuYfSOgPuM8zf8OKpDTcyhyUoSKDlQXo9cw06iVLKdpW2JVAkPCyF2ptDQIlkRRCkEfOdmkRMLgrm68@Er4ss5WuZPeOrT7MFvvv9jGlhGq2eNLu1rIeOp2ZTouPd@FzJLRwR3VsZLdXe8X1zDwbwrhtzuLy40IjaeNSxPwIyJCMSd1NjQkls03@TMf4bojQhUzIj864YO2GE0phMu8IMk7YixhoaERoTars@0F55WYsummX5gzdxpjGxTDNsMv@H3ZqiOLmv5Hchbi7uJ24gDMOfqawutRHHsGpMeMKBmVJ5Ksw97t9b3Nov)
**Explanation:**
```
a->{ // Method with integer-array parameter and boolean return-type
var r=0>1; // Result-boolean, starting at false
for(int j=a.length-1,i;j-->0;)
// Loop `j` in the range (length-1, 0]:
for(i=0;i<j;) // Inner loop `i` in the range [0, j):
r|= // If any are true, change the result to true as well:
a[j]>a[i] // The `j`'th item is larger than the `i`'th item
&a[j+1]<a[i++]; // And the `j+1`'th item is smaller than the `i`'th item
return!r;} // After the nested loop, check if the boolean is still false
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46 40~~ 38 bytes
```
f=->r{a,*b=r;!a||b==b&[*0..a]|b&&f[b]}
```
[Try it online!](https://tio.run/##fdCxDoIwEAbg3adAByLkqFYqYkx18wnc6g2tkUmNKcHEUJ8drwQHDXJLly9//ztbmWfTFDLZ2lpDbKTdjLVzRkoTqnjOmEZnwrBQBl/NZKQ4Bn2T0GzpPdjqTAgWkILAQbQEDsJDHESCkhZEM1hBDmvsQaIFKZElrPBPUk7ApwjK4XPgArj/@Rv52j0bftBeX0pSWVtJgN8gp7ifUp3qjuA7kcqwN2vCypO@TWdHxeLdEWcRu@p77Up3D5SV54e@TMsICmWRzv8G "Ruby – Try It Online")
This works by recursively taking the first element `a` as a pivot, and checking if the rest of the array can be split in two (using intersection and union: first remove all elements >a, then add them again on the right and check if something has changed).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes
```
\d+
$*
M`\b((1+)1+,).*\1\2\b
^0
```
[Try it online!](https://tio.run/##NYwxDoMwEAT7e0ciGbxCnH0Y8wKq/OAUEZQUaVJE/N@5Q0o3s6vd7@t4fx7tGtat6TPSpafbpnsIHDuO6IZeWZPudB9bY2IkZAhNYIizkViSzAtmVCwkp2XzCTNVI@/EWh7BAs7kJ0zlHAr8rFq9/O99aEn5AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Uses @tsh's algorithm. Explanation:
```
\d+
$*
```
Convert to unary.
```
M`\b((1+)1+,).*\1\2\b
```
Find numbers that lie between two subsequent consecutive descending numbers.
```
^0
```
Check that the number of matches is zero.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 38 bytes
```
!*.combinations(3).grep:{[>] .[1,0,2]}
```
[Try it online!](https://tio.run/##TY3dCoJAEIXvfYoNIjQO4uq6alIvIktYuCHkD9qNRM@@zWw33QxzPs58M3fLU7thEwcrzm53jO/TcOvH9tVP4xpmUfxYuvn0bi5GxI1EgtR8XB2s7SZsuL9Gwk5L0EgDGkiRQfGaQ0Jx/AVFPCWkUaBExVB5kBHKUTAoKXBDUUcmkArSX7PT67WXKLC7pFL195MlBLWp3Rc "Perl 6 – Try It Online")
### Explanation
```
*.combinations(3) # All combinations of 3 elements a,b,c
! .grep:{ } # Return false if check succeeds for any combination
[>] .[1,0,2] # Check whether b>a>c, that is b>a and c<a
```
[Answer]
# [Haskell](https://www.haskell.org/), 50 bytes
```
f[]=1<3
f(x:r)|(a,b)<-span(<x)r=all(>x)b&&f a&&f b
```
[Try it online!](https://tio.run/##jZDPCoJAEMbvPcUeQlYYodX1T6Uee4JusoeVWpI2Ey3w0LtvsxKBZeSwDHv4fvPNNyfZnY9aG6MKkbE02Crab1r3QSWUbup1jaxp2rttJrWmee@WjqOItK00F1nVJCOH64KQpq3qG1kSVTBBpsrz8OX42bf34xgAHwLgYjYQAgNuITEb4OjgIxZBDAmsxR@AD@IA5SHEYoZDgmI7neN8tgLGgdntfgM28sSl3sBO6m5MREMEDjZ9gjafIb6J12FtBiQiMelhng "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~15~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒεD{3.IÊ}P
```
Port of [*@Lynn*'s Jelly answer](https://codegolf.stackexchange.com/a/174306/52210).
-5 bytes thanks to *@Emigna*.
[Try it online](https://tio.run/##yy9OTMpM/f//6KRzW12qjfU8D3fVBvz/H22hY6xjqGOmY6JjrmNooGNoomNoHAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/o5PObXWpNtbzPNxVG/Bf5390tGGsjkK0oY6RjrGOCYhpqmOoYwLiQjgmQHEjoJCZjrmOhY4lSNAELGAMFDLVMQcJWAA5IBUmQDWGBjqGJjqGYN0gM8HGm4ENMdEBmW0BVGSJZCfIEKCgWWwsAA).
**Explanation:**"
```
Œ # Take all sublists of the (implicit) input-list
# i.e. [2,3,1] → [[2],[2,3],[2,3,1],[3],[3,1],[1]]
# i.e. [1,2,3,4]
# → [[1],[1,2],[1,2,3],[1,2,3,4],[2],[2,3],[2,3,4],[3],[3,4],[4]]
ε } # Map each to:
D # Duplicate the current sublist on the stack
{ # Sort the copy
# i.e. [2,3,1] → [1,2,3]
# i.e. [2,3,4] → [2,3,4]
3.I # Get the 4th (3rd 0-indexed) permutation of this list
# i.e. [1,2,3] → [2,3,1]
# i.e. [2,3,4] → [3,4,2]
Ê # Check that the lists are NOT equal
# i.e. [2,3,1] and [2,3,1] → 0 (falsey)
# i.e. [2,3,4] and [3,4,2] → 1 (truthy)
P # Check whether all are truthy (and output implicitly)
# i.e. [1,1,0,1,1,1] → 0 (falsey)
# i.e. [1,1,1,1,1,1,1,1,1,1] → 1 (truthy)
```
[Answer]
# Scala (68 67 Bytes)
```
def%(i:Seq[Int])= !i.combinations(3).exists(c=>c(0)<c(1)&c(0)>c(2))
```
[Try it online](https://tio.run/##dY8/D4IwEMV3P0VdTJtcCIXyz4iJo4OTo3HAUpIaLGg7kBg/O14ZBbfr/d6792pl1VZjd7sr6cip0oaowSlTW3Loe/Iea9WQhurtWT0vR@OurCRrHcjucdOmcrozlsYsUIO2zlJZ7iUN2U5SzjZ@wmfE2Ni/tHGtoQ3FM8gYW/2sIIIYxBwkwEF4uIQEeiIUpJBBDsVcIiYcoyCBbI5zRN4t0M9D4AL4Qo5vtlA5ncIF@IY5Hij@/sqHoyT1gs/4BQ)
Port of @nwellnhof's [answer](https://codegolf.stackexchange.com/a/174310/83520).
# Scala (122 103 bytes)
```
def f(i:Seq[Int]):Boolean=if(i.size<1)1>0 else{val(s,t)=i.tail.span(_<i(0));t.forall(_>i(0))&f(s)&f(t)}
```
Thanks to @Laikoni for the suggestions to make both solutions shorter.
[Try it online](https://tio.run/##dY/NasMwEITvfQqdygoWYyWK4/xCeuuhpx5LCUqyAgUhO5EIoSHP7q58rN2LDvPNaGbj0XjTNYczHZP4MC4IuicKpyh2bSse3YmssOCWn3T5eg/pWy7fmsaTCRvHchHdD62VVNtSkI/0uBkPEZPcuCIZ54vYmgD7tYNSylUqbHM13sN@2wuvFmJ@knx27dWF5ANY4CZQUsqXPxJOcIp6CGaoUGc4hjRnJmyocI41LoYW3eMpG2Y4H@KaUU5rzqsSlUY10pOXjUyu@nKNeWHNHyz@vSqXs6XKhmf3Cw)
### Explanation:
1. slice (using Scala's `span`) the array using array's head as the slicing criteria.
2. Confirm that the first slice of the array is less than the head and the second slice is greater than the head.
3. recursively check that each slice also satisfies (2)
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
f(h:t)=t==[]||all(>h)(snd$span(<h)t)&&f t
```
[Try it online!](https://tio.run/##jZDNDoIwEITvPkUPhtBkSSyUH41w9Am8kR6aAIFYkUC98e64RWOCotDsoYf5dnamlN0lV2oYCrs8aBrrOE5F30ul7KSkdldn266RtX0sqaaWVRA9XGVVk5hktw0hTVvVmmxJkTJB5p7j4CT4Obf3fAqACx5wsRrwgQE3kFgNcHRwEQsghAj2YgHgo9hDuQ@hWOEQodhs57if7YBxYOa634CJPNPUGzhJ1U2JYIzAwaSP0OYzxDfxKtZkQCIQyx7es1nx96rhAQ "Haskell – Try It Online")
Uses [Lynn's observation](https://codegolf.stackexchange.com/a/174306/20260) that it suffices to check that there's no subsequence of the for **mid..high..low**. This means that for each element `h`, the list of elements `t` that comes after is a block of elements `<h` followed by a block of elements `>h` (both blocks may be empty). So, the code checks that after we drop the prefix of elements `<h` in `t`, the remaining elements are all `>h`. Recursing checks this for each initial element `h` until the list is length 1.
A potential simplification is that it suffices to check for subpatterns **mid..high,low** where the last two are consecutive. Unfortunately, Haskell's doesn't have an short way to extract the last two elements, as can be done from the front with a pattern match `a:b:c`. I found a shorter solution that checks for **mid,high..low**, but this fails to reject inputs like `[3,1,4,2]`.
Formatted test cases taken [from Laikoni](https://codegolf.stackexchange.com/a/174318/20260).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 14 bytes
```
d@sY ð_§XÃxÈ-Y
```
[Japt Interpreter](https://ethproductions.github.io/japt/?v=1.4.6&code=ZEBzWSDwX6dYw3jILVk=&input=WzYsMywyLDQsNSwxLDgsNyw5XQ==)
Outputs `false` for BST, `true` for no BST.
Explanation:
```
d@ Run on each item X, return true if any aren't 0:
sY Ignore the numbers before this index
ð_§XÃ Get the indexes of numbers less than or equal to X
If it is a BST, this list will be e.g. [0,1,2...]
-Y Subtract the position within the index list from each index
eg. [0,1,2] -> [0,0,0] , [0,1,4] -> [0,0,2]
xÈ Sum the resulting array
```
[Answer]
# Scala
All approaches are implementations of the rule shown by tsh.
# 109
```
l.zipWithIndex.foldLeft(1>0){case(r,(v,i))=>r&l.zip(l.tail).slice(i+1,l.size).forall(x=>l(i)>x._1|l(i)<x._2)}
```
# 101
```
(for(i<-l.indices)yield l.zip(l.tail).slice(i+1,l.size).forall(x =>l(i)>x._1|l(i)<x._2)).forall(x=>x)
```
# 98
```
l.indices.foldLeft(1>0)((r,i)=>r&(l.zip(l.tail).slice(i+1,l.size).forall(x=>l(i)>x._1|l(i)<x._2)))
```
# 78
```
(for(i<-l.indices;j<-i+1 to l.size-2)yield l(i)>l(j)|l(i)<l(j+1)).forall(x=>x)
```
If it must be a function and not just an expression then each line have to start with (17 bytes)
```
def%(l:Seq[Int])=
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
Λo≠4Ṡ€oPOQ
```
[Try it online!](https://tio.run/##yygtzv7//9zs/EedC0we7lzwqGlNfoB/4P///6ONdIx1DGMB "Husk – Try It Online")
Same idea as Kevin Cruijssen's answer.
[Answer]
# Oracle SQL, 177 bytes
```
with r(i,v)as(select rownum,value(t)from table(a)t)
select nvl(min(case when r.v<p.l and r.v>p.v then 0end),1)from r,(select i,lag(v)over(order by i)l,v from r)p where r.i+1<p.i
```
Since there is no boolean type in Oracle SQL, query returns either 1 or 0.
# Oracle SQL 12c, 210 bytes
```
with function f(n ku$_objnumset,i int)return int as begin return n(i);end;
select min(case when f(c,1)>f(c,2)or f(c,1)<f(c,3)then 1else 0end)from(select value(t)c from table(powermultiset_by_cardinality(a,3))t)
```
It's not possible access element of the array in SQL the same way as in PL/SQL - i.e. a(i), thus function `f` was declared in `with clause` for that purpose. Otherwise solution would have been much shorter.
Other limitations
* throws an exception for arrays shorter than 3 elements (instead of returning 1)
* there is an assumption that powermultiset\_by\_cardinality preserves order even though it's not explicitly stated in the documentation
**sqlplus** listing
```
SQL> set heading off
SQL> with r(i,v)as(select rownum,value(t)from table(ku$_objnumset(6,3,2,4,5,1,8,7,9))t)
2 select nvl(min(case when r.v<p.l and r.v>p.v then 0end),1)from r,
3 (select i,lag(v)over(order by i)l,v from r)p where r.i+1<p.i
4 /
0
SQL> with function f(n ku$_objnumset,i int)return int as begin return n(i);end;
2 select min(case when f(c,1)>f(c,2)or f(c,1)<f(c,3)then 1else 0end)
3 from(select value(t)c from table(powermultiset_by_cardinality(ku$_objnumset(6,3,2,4,5,1,8,7,9),3))t)
4 /
0
SQL> with r(i,v)as(select rownum,value(t)from table(ku$_objnumset(8,3,1,6,4,7,10,14,13))t)
2 select nvl(min(case when r.v<p.l and r.v>p.v then 0end),1)from r,
3 (select i,lag(v)over(order by i)l,v from r)p where r.i+1<p.i
4 /
1
SQL> with function f(n ku$_objnumset,i int)return int as begin return n(i);end;
2 select min(case when f(c,1)>f(c,2)or f(c,1)<f(c,3)then 1else 0end)
3 from(select value(t)c from table(powermultiset_by_cardinality(ku$_objnumset(8,3,1,6,4,7,10,14,13),3))t)
4 /
1
```
Online verification [apex.oracle.com](http://apex.oracle.com)
**Update**
# Oracle SQL, 155 bytes
```
with r(i,v)as(select rownum,value(t)from table(a)t)select nvl(min(case when a.v<b.v and a.v>c.v then 0end),1)r from r a,r b,r c where a.i<b.i and b.i+1=c.i
```
[Answer]
# **C, 823 bytes** (not counting whitespace characters); 923 bytes (including whitespace)
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree
{struct tree * left;struct tree * right;int val;}tree;static int * test_p = 0;
void insert_root(tree ** root, int in)
{if (*root == NULL){*root = (tree *)calloc(1,sizeof(tree));(*root)->val = in;return;}else if (in < (*root)->val){insert_root(&((*root)->left),in);}else{insert_root(&((*root)->right),in);}}
void preorder(tree * root)
{if ( root == 0x0 ) { return; }*test_p++ = root->val;preorder(root->left);preorder(root->right);}
int main(int argc, char ** argv)
{int test_list[argc-1];memset(test_list,0,argc*sizeof(int));test_p = test_list;tree * root = (tree *)calloc(1,sizeof(tree));root->val = strtol(argv[1],0x0,10);int i = 1;while ( argv[++i] != 0x0 ){insert_root(&root,strtol(argv[i],0x0,10));}preorder(root);test_p = test_list;i = 1;while ( ( i < argc ) ){if ( *test_p != strtol(argv[i],0x0,10) ){return 0;}test_p++;i++;}return 1;}
```
The readable version of the program is below:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree
{
struct tree * left;
struct tree * right;
int val;
} tree;
static int * test_p = 0;
void insert_root(tree ** root, int in)
{
if (*root == NULL)
{
*root = (tree *)calloc(1,sizeof(tree));
(*root)->val = in;
return;
}
else if (in < (*root)->val)
{
insert_root(&((*root)->left),in);
}
else
{
insert_root(&((*root)->right),in);
}
}
void preorder(tree * root)
{
if ( root == 0x0 ) { return; }
*test_p++ = root->val;
preorder(root->left);
preorder(root->right);
}
int main(int argc, char ** argv)
{
int test_list[argc-1];
memset(test_list,0,argc*sizeof(int));
test_p = test_list;
tree * root = (tree *)calloc(1,sizeof(tree));
root->val = strtol(argv[1],0x0,10);
int i = 1;
while ( argv[++i] != 0x0 )
{
insert_root(&root,strtol(argv[i],0x0,10));
}
preorder(root);
test_p = test_list;
i = 1;
while ( ( i < argc ) )
{
if ( *test_p != strtol(argv[i],0x0,10) )
{
return 0;
}
test_p++;
i++;
}
return 1;
}
```
The main method in this program reads the list of numbers that are (allegedly) a legitimate preorder traversal.
The function insert\_root that is called inserts the integers into a binary search tree where previous nodes contain lesser values and next nodes contain larger int values.
The function preorder(root) traverses the tree in a preorder traversal and simultaneously concatenates each integer the algorithm comes across to the int array **test\_list**.
A final while loop tests if each of the int values in the **stdin** list and those in **test\_list** are equivalent at each index. If there is a list element from **stdin** that fails to match the corresponding element in test\_list at the respective index, the main function **returns 0.** Else the main method **returns 1**.
To determine what main returned, type **echo $status** into the bash terminal. BASH will either print out a 1 or a 0.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
¬ṁ§=Oṙ2Ṗ3
```
[Try it online!](https://tio.run/##RY2xDQIxDEUX@gVOfLlcwQwMEKU/CVEhBjiGQGICGhZIe5uERcx3KOj@f7af19v1bJfPfbP93du2v46n3p6ht0c0s1KkoggCIpRpgkC9jaykgSRhRsZCpqNHkgkze2b2uXJDDhCF@KnrXJyGQOHazJXl/8wFZIkk/p7W@gU "Husk – Try It Online")
Uses 'disqualifying condition' of any subsequence mid...high...low from [tsh's](https://codegolf.stackexchange.com/a/174295/95126) and [Lynn's](https://codegolf.stackexchange.com/a/174306/95126) answers.
```
¬ṁ§=Oṙ2Ṗ3
Ṗ3 # consider all subsequences of length 3:
ṙ2 # check whether rotating 2 to the left
§=O # is the same as sorting;
¬ṁ # total of subsequences that satisfy this should be zero
```
] |
[Question]
[
## Question
`Given the atomic number of an element` in the range [1-118] output the `group and period`, of that element as given by the following Periodic Table Of Elements.
For elements in the Lanthanide and Actinide series, (ranges [57-71] and [89-103]), you should instead return `L` for the Lanthanides and `A` for the Actinides
>
> You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the our [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output.
>
>
> You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default.
>
>
>
[](https://i.stack.imgur.com/nJm2q.png)
[[Source]](https://en.wikipedia.org/wiki/Periodic_table#/media/File:18-column_medium-long_periodic_table.png)
## Test Cases
Since there are only 118 possible inputs, a full list of the expected inputs and outputs is given below.
*Created by hand, let me know if there's a mistake!*
```
1,1,1
2,18,1
3,1,2
4,2,2
5,13,2
6,14,2
7,15,2
8,16,2
9,17,2
10,18,2
11,1,3
12,2,3
13,13,3
14,14,3
15,15,3
16,16,3
17,17,3
18,18,3
19,1,4
20,2,4
21,3,4
22,4,4
23,5,4
24,6,4
25,7,4
26,8,4
27,9,4
28,10,4
29,11,4
30,12,4
31,13,4
32,14,4
33,15,4
34,16,4
35,17,4
36,18,4
37,1,5
38,2,5
39,3,5
40,4,5
41,5,5
42,6,5
43,7,5
44,8,5
45,9,5
46,10,5
47,11,5
48,12,5
49,13,5
50,14,5
51,15,5
52,16,5
53,17,5
54,18,5
55,1,6
56,2,6
57,L,
58,L,
59,L,
60,L,
61,L,
62,L,
63,L,
64,L,
65,L,
66,L,
67,L,
68,L,
69,L,
70,L,
71,L,
72,4,6
73,5,6
74,6,6
75,7,6
76,8,6
77,9,6
78,10,6
79,11,6
80,12,6
81,13,6
82,14,6
83,15,6
84,16,6
85,17,6
86,18,6
87,1,7
88,2,7
89,A,
90,A,
91,A,
92,A,
93,A,
94,A,
95,A,
96,A,
97,A,
98,A,
99,A,
100,A,
101,A,
102,A,
103,A,
104,4,7
105,5,7
106,6,7
107,7,7
108,8,7
109,9,7
110,10,7
111,11,7
112,12,7
113,13,7
114,14,7
115,15,7
116,16,7
117,17,7
118,18,7
```
## Scoring
Simple [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest number of bytes wins
[Answer]
## [CJam](https://sourceforge.net/p/cjam), ~~64~~ ~~59~~ ~~58~~ ~~56~~ 54 bytes
*Thanks to Dennis for saving 2 bytes.*
```
{_80-zG-z8<{80>"LA"=}{_"X8
"f>[-14_AAGH].*+:+Imd)}?}
```
[Try it online!](https://tio.run/nexus/cjam#MzS0qNaMLzYOTo3OV7JSUMr/Xx1vYaBb5a5bZWFTbWFgp@TjqGRbWx2vFGHBw8KolGYXrWtoEu/o6O4Rq6elbaXtmZuiWWtf@78utqBW/z8A "CJam – TIO Nexus")
Leaves either period and group or a single character on the stack.
### Explanation
There are two main ideas here:
* First, we deal with the Lanthanides and Actinides. We have the condition **56 < x < 72** for Lanthanides and **88 < x < 104** for Actinides. Both of these can be expressed as a single comparison by taking an absolute difference to the centre of the range: the inequalities become **|x - 64| < 8** and **|x - 96| < 8**, respectively. But these are still very similar, and doing the two comparisons separately is expensive. So we apply the same idea of checking a symmetric range, by taking another absolute difference with the centre *between* the two ranges, **80**, first: **||x-80| - 16| < 8**. This condition indicates that the atom is either a Lanthanide or an Actinide, but distinguishing between these two cases is then as trivial as comparing against 80 (or some other value between the ranges).
* Since the output is really an index in a table of width 18, an obvious approach is to try base-converting the value to base 18, so that the two digits give group and period. To do that, we need to shift some values around though. All the we really need to do is to add the gaps in periods 1, 2 and 3 and close the gaps in periods 6 and 7. It's easiest to do this from the end, so that the values of the other gaps aren't affected (and keep their values).
```
_ e# Make a copy of the input, to figure out whether the output
e# should be L or A.
80-z e# Absolute difference from 80.
G-z e# Absolute difference from 16.
8< e# Check whether the result is less than 8.
{ e# If so...
80> e# Check whether the input is greater than 80.
"LA"= e# Select 'L or 'A accordingly.
}{ e# ...otherwise...
_ e# Duplicate input again.
"X8" e# Push a string with character codes [88 56 12 4 1].
e# These are the values just before the gaps.
f> e# Compare the input to each of these.
[-14_AAGH] e# Push [-14 -14 10 10 16 17]. These are the changes we need to
e# make to remove or insert the gaps corresponding to the above
e# positions. Note that the 17 doesn't get paired with an offset.
e# It's a constant offset to itself, which is equivalent to
e# decrementing the input (to make it zero based) and adding 18
e# to make the increment the period and make it 1-based.
.* e# Multiply each gap by whether it's before the input value.
+:+ e# Add all of the applicable gaps to the input value.
Imd e# Divmod 18, gives 1-based period and 0-based group.
) e# Increment the group to make it one-based.
}?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~113~~ ~~102~~ 99 bytes
```
X18©XY‚Dˆ13®Ÿ¯13®Ÿ®LD¯15'L×S15L3+©¯15'A×S®)˜¹<è,XXY8×SD>4 18×SD>S66Sð14×S6 15×S77Sð15×S7 15×S)˜¹<è,
```
Explanation:
```
(start to construct the period part)
X18 ~ push 1 and 18
© ~ store 18 in register_c without p-opping
XY ~ push 1 and 2
13® ~ push 13 and the top element in register_c (18)
Ÿ ~ range - pop 2 values and push [a .. b]
XY ~ push 1 and 2
13®Ÿ ~ range - 13 to 18
XY ~ push 1, 2
13®Ÿ ~ range - 13 to 18
®LD ~ range - 1 to 18 (twice)
2L ~ range - 1 to 2
15'L×S ~ push 'L' 15 times
15L ~ range - 1 to 15
3+ ~ add 3 to each value in topmost element in stack
© ~ store in register-c without popping
2L ~ range - 1 to 2
15'A×S ~ push 'A' 15 times
® ~ push topmost value in register_c
) ~ wrap stack to array
˜ ~ deep flatten
¹<è ~ 1-indexed value of input in array
, ~ print & pop
(start to construct the group part)
XX ~ push 1 twice
Y8×SD ~ push 2 eight times (twice)
> ~ increment each value by 1
4 18×S ~ push 4 eighteen times (twice)
> ~ increment each value by one
66S ~ push 6 twice
ð15×S ~ push a space character 15 times
6 15×S ~ push 6 fifteen times
77S ~ push 7 two times
ð15×S ~ push a space character 15 times
7 15×S ~ push 7 fifteen times
)˜ ~ wrap stack to array and deep flatten
¹<è, ~ get 1-indexed value of input in array, then pop & print
```
[Try it online!](https://tio.run/nexus/05ab1e#@x9haHFoZUTko4ZZLqfbDI0PrTu649B6KL3OxwXINlX3OTw92NDUx1j70Eow3xHIP7RO8/ScQzttDq/QiYiItACKuNiZKBhCGMFmZsGHNxiaADlmCoamQMrcHCQAZkEE4Lr//7c0AAA)
[Answer]
## Mathematica, 77 bytes
```
e=ElementData;Which[56<#<72,"L",88<#<104,"A",1>0,{#~e~"Group",#~e~"Period"}]&
```
It would also be quite easy to use `ElementData` to determine whether the input is a Lanthanide or Actinide, but it would take about 20 more bytes.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~205~~ 136 bytes
-26 bytes thanks to @Dead Possum
```
def f(x):a=(x>71)+(x>99);print((((x-2*(x>1)-8*(x>4)-8*(x>12)+4*a-1)%18+1,(x-(x>17)-14*a)/18+(x>2)+(x>10)+1),'L'),'A')[88<x<104][56<x<72]
```
[Try it online!](https://tio.run/nexus/python2#LY7BDoIwDIbP8BS7GPazLdJlykA08e4bEA4kMrMLGuJhb4@F2EO/v1@aputzCiLIhHa8ynSrCYrRNLh8ljh/JVcytmRHMH6j@5MslCtHQziQV6R5b7M1DLHGkSXPdr9HFRRBF4@C271A732XOqrc0J/OnGo7rOG9iCjiLNIyzq9JkiZq0ObZ/oiIOs@CjFh/ "Python 2 – TIO Nexus")
[Answer]
# PHP, 144 bytes
Note: uses IBM-850 encoding
```
$x=($a=$argn-1)<57|$a>70?$a>88&$a<103?A:0:L;foreach([16,19=>10,37=>10,92=>-14,110=>-14]as$l=>$m)$a>$l&&$a+=$m;echo$x?:$a%18+1 .~Ë.ceil(++$a/18);
```
Run like this:
```
echo 118 | php -nR '$x=($a=$argn-1)<57|$a>70?$a>88&$a<103?A:0:L;foreach([16,19=>10,37=>10,92=>-14,110=>-14]as$l=>$m)$a>$l&&$a+=$m;echo$x?:$a%18+1 .~Ë.ceil(++$a/18);';echo
> 18,7
```
# Explanation
Check whether input is within the ranges for `L` or `A`; the "exception" ranges. Then modify the input to fill the missing cells in the grid (or get rid of the extra cells). Finally, print the exception (unless that is falsy `0`) or convert the position to grid coordinates.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 57 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“9Ḳ*!}ḣE’ṃ“¢£Æ¥Ø‘r2/;€"“ⱮḶıð’ḃ7¤µ⁵,12Ṭœṗ;"⁾LAṁ€15¤j“”$⁺³ị
```
Full program that prints the desired output.
**[Try it online!](https://tio.run/nexus/jelly#@/@oYY7lwx2btBRrH@5Y7PqoYebDnc1AsUOLDi0@3HZo6eEZjxpmFBnpWz9qWqMEFH@0cd3DHduObDy8AaR0R7P5oSWHtj5q3KpjaPRw55qjkx/unG6t9Khxn4/jw52NQD2GpoeWZIH0NcxVedS469Dmh7u7////b2hgDAA "Jelly – TIO Nexus")** (A slightly modified program which prints all `input : output` may be seen [here](https://tio.run/nexus/jelly#@/@oYY7lwx2btBRrH@5Y7PqoYebDnc1AsUOLDi0@3HZo6eEZjxpmFBnpWz9qWqMEFH@0cd3DHduObDy8AaR0R7P5oSWHtj5q3KpjaPRw55qjkx/unG6t9Khxn4/jw52NQD2GpoeWZIH0NcxVedS4i@vQoiPTsoDiQCEroJj7////AQ)).
### How?
Builds a list of the 118 possible outputs and then picks the entry at the index of the input.
Some prep:
```
“9Ḳ*!}ḣE’ - base 250 number: 14334152882934570 (call this A)
“¢£Æ¥Ø‘ - a list using Jelly's code page: [1, 2, 13, 4, 18] (call this B)
“ⱮḶıð’ - base 250 number: 2354944025 (call this C)
```
The program (shortened by substituting `A`, `B`, and `C`) :
```
AṃBr2/;€"Cḃ7¤µ⁵,12Ṭœṗ;"⁾LAṁ€15¤j“”$⁺³ị - Main link: atomicNumber
AṃB - number A with digits B: [1,1,18,18,1,2,13,18,1,2,13,18,1,18,1,18,1,2,4,18,1,2,4,18]
2/ - pair-wise reduce with
r - inclusive range: [[1],[18],[1,2],[13,14,15,16,17,18],[1,2],[13,14,15,16,17,18],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],[1,2],[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18],[1,2],[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]]
¤ - nilad followed by link(s) as a nilad:
C - number C
ḃ7 - converted to bijective base 7: [1,1,2,2,3,3,4,5,6,6,7,7]
" - zip with:
,€ - pair each: [[1,1],[18,1],[[1,2],[2,2]],[[13,2],[14,2],[15,2],[16,2],[17,2],[18,2]],[[1,3],[2,3]],[[13,3],[14,3],[15,3],[16,3],[17,3],[18,3]],[[1,4],[2,4],[3,4],[4,4],[5,4],[6,4],[7,4],[8,4],[9,4],[10,4],[11,4],[12,4],[13,4],[14,4],[15,4],[16,4],[17,4],[18,4]],[[1,5],[2,5],[3,5],[4,5],[5,5],[6,5],[7,5],[8,5],[9,5],[10,5],[11,5],[12,5],[13,5],[14,5],[15,5],[16,5],[17,5],[18,5]],[[1,6],[2,6]],[[4,6],[5,6],[6,6],[7,6],[8,6],[9,6],[10,6],[11,6],[12,6],[13,6],[14,6],[15,6],[16,6],[17,6],[18,6]],[[1,7],[2,7]],[[4,7],[5,7],[6,7],[7,7],[8,7],[9,7],[10,7],[11,7],[12,7],[13,7],[14,7],[15,7],[16,7],[17,7],[18,7]]]
µ - monadic chain separation (call the result x)
⁵ - 10
,12 - pair with 12: [10,12] 10↓ 12↓
Ṭ - truthy indexes: [0,0,0,0,0,0,0,0,0,1,0,1]
œṗ - partition x at the truthy indexes
- (the locations of the runs of L's and A's)
¤ - nilad followed by link(s) as a nilad:
⁾LA - ['L','A']
ṁ€15 - mould each like 15: [['L','L','L','L','L','L','L','L','L','L','L','L','L','L','L'],['A','A','A','A','A','A','A','A','A','A','A','A','A','A','A']]
" - zip with:
; - concatenation: [[[1,1],[18,1],[[1,2],[2,2]],[[13,2],[14,2],[15,2],[16,2],[17,2],[18,2]],[[1,3],[2,3]],[[13,3],[14,3],[15,3],[16,3],[17,3],[18,3]],[[1,4],[2,4],[3,4],[4,4],[5,4],[6,4],[7,4],[8,4],[9,4],[10,4],[11,4],[12,4],[13,4],[14,4],[15,4],[16,4],[17,4],[18,4]],[[1,5],[2,5],[3,5],[4,5],[5,5],[6,5],[7,5],[8,5],[9,5],[10,5],[11,5],[12,5],[13,5],[14,5],[15,5],[16,5],[17,5],[18,5]],[[1,6],[2,6]],'L','L','L','L','L','L','L','L','L','L','L','L','L','L','L'],[[[4,6],[5,6],[6,6],[7,6],[8,6],[9,6],[10,6],[11,6],[12,6],[13,6],[14,6],[15,6],[16,6],[17,6],[18,6]],[[1,7],[2,7]],'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A'],[[4,7],[5,7],[6,7],[7,7],[8,7],[9,7],[10,7],[11,7],[12,7],[13,7],[14,7],[15,7],[16,7],[17,7],[18,7]]]
µ⁵,12Ṭœṗ;"⁾LAṁ€15¤j“”$⁺³ị
$ - last two links as a monad:
j“” - join with [''] (a workaround for no "flatten by 1")
⁺ - repeat last link (flatten once more): [[1,1],[18,1],[1,2],[2,2],[13,2],[14,2],[15,2],[16,2],[17,2],[18,2],[1,3],[2,3],[13,3],[14,3],[15,3],[16,3],[17,3],[18,3],[1,4],[2,4],[3,4],[4,4],[5,4],[6,4],[7,4],[8,4],[9,4],[10,4],[11,4],[12,4],[13,4],[14,4],[15,4],[16,4],[17,4],[18,4],[1,5],[2,5],[3,5],[4,5],[5,5],[6,5],[7,5],[8,5],[9,5],[10,5],[11,5],[12,5],[13,5],[14,5],[15,5],[16,5],[17,5],[18,5],[1,6],[2,6],'L','L','L','L','L','L','L','L','L','L','L','L','L','L','L',[4,6],[5,6],[6,6],[7,6],[8,6],[9,6],[10,6],[11,6],[12,6],[13,6],[14,6],[15,6],[16,6],[17,6],[18,6],[1,7],[2,7],'A','A','A','A','A','A','A','A','A','A','A','A','A','A','A',[4,7],[5,7],[6,7],[7,7],[8,7],[9,7],[10,7],[11,7],[12,7],[13,7],[14,7],[15,7],[16,7],[17,7],[18,7]]
³ - program's first input
ị - index into the list
```
[Answer]
# Perl5, 202 bytes
```
$x=substr(" !2ABMNOPQRabmnopqr\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\301\302LLLLLLLLLLLLLLL\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\341\342KKKKKKKKKKKKKKK\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362",$ARGV[0],1);print$x=~/K/?"A":$x=~/L/?$x:(ord($x)&31).",".(ord($x)>>5)
```
[Answer]
# Ruby, 130 bytes
```
->a{(w=32767)[a-57]>0??L:w[a-89]>0??A:([[1,2],[20,8],[38,8],[107,32],[125,32]].map{|x,y|a>x&&a+=18-y};[(b=a%18)>0?b:18,~-a/18+1])}
```
First get the 'A' and 'L' with the bitmask trick, then try to fit into a 18\*7 rectangle and use a div/mod.
[Answer]
# [Python 2](https://docs.python.org/2/), 137 bytes
```
lambda x:[(1+(x>2)+(x>10)+min((~-x/18),3)+(x>86),(x+(x>1)*15+((x>4)+(x>12))*10-((x>71)+(x>103))*14)%18+1),"AL"[89<x]][57<x<72or 89<x<104]
```
[Try it online!](https://tio.run/nexus/python2#LcxNCsIwEAXgtZ4iBIQZk2qnPzYtUXDvDWoXFa0EbJTSRaDUq9dG3QxvPt5Msz9Pj7q9XGvmihJIgDtE6CeFKFpjAd6B25JCGX9Z7VCC@xZwTamAOSW/gwhnCQMvGf1/xN4SXJEShJIfT7xUuXZVVaaZdjqLnh3zoClMqqmZN8OMZV1t7zcgSZRjsVy8OmN7xoexGEa@mVtt3YORDRjE6QM "Python 2 – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), 115 bytes
```
def f(n):n+=([0,17]+[33]*3+[43]*8+[53]*45+[200]*14+[39]*18+[400]*14+[25]*15)[n];print[(n%18+1,n/18),'L','A'][n/200]
```
[Try it online!](https://tio.run/nexus/python2#NY7BCsIwEETP@hW5lCTdQLNNgm3Fg3f/YMlBsJFeVgn9/7g9eHowbximvdaiimG7MNwMeYeXDBRC7gNQFExASRAT0Oh97jGKnoUi4j8YkzBZ4nz91o13MtxJAR0POFmnH9rpu87Ew7HRyqcqVhur@uT3atAhznY5n44f7Qc "Python 2 – TIO Nexus")
The idea is to div-mod the grid position to get the group and period. The grid position is the input `n` adjusted by a displacement to account for gaps and the L/A contraction. These are extracted from a list.
The Lanthanide and Actinide handling is ugly. These are assigned large displacements 200 and 400 that can be detected with `/200`. I'd like to put the characters `L` and `A` here, but then `n+=...` will add a char to a number, giving an error even if `n` is not used. If not for the 1-indexing, `divmod` could be used to refer to `n` only once, and then it could be replaced with its expression,
[Answer]
## JavaScript (ES7), ~~100~~ 98 bytes
```
f=(n,p=1,x=0,y=x+2*(p+2>>1)**2)=>(n-57&95)<15?n>71?'A':'L':n>y?f(n,p+1,y):[n-x-1>p/2?n-y+18:n-x,p]
```
```
<input type=number min=1 max=118 oninput=o.textContent=f(this.value)><pre id=o>
```
Explanation: The 'L' and 'A' series are special-cased, using some bitwise logic that saved me 3 bytes over direct comparisons. Otherwise the function recursively finds the period `p` containing the desired atomic number, the number of the last element in the previous period `x`, and the number of the last element in the period `y` which is computed each time by noting that the differences are 2, 2, 8, 8, 18, 18 i.e. repeated doubled square numbers. The group is then found by offsetting from the left or right of the table depending on whether the element lies under the Beryllium-Scandium diagonal or not.
[Answer]
## JavaScript (ES6), 136 bytes
```
n=>[...'112626ii2ff2fff'].reduce((p,i,j)=>(n-=parseInt(i,36))>0?n:+p?+(x='112233456L67A7'[j])?[p+(9258>>j&1?j>5?3:j>2?12:17:0),x]:x:p,n)
```
### Test
```
let f =
n=>[...'112626ii2ff2fff'].reduce((p,i,j)=>(n-=parseInt(i,36))>0?n:+p?+(x='112233456L67A7'[j])?[p+(9258>>j&1?j>5?3:j>2?12:17:0),x]:x:p,n)
```
```
<input oninput="o.innerHTML=f(+value)" type="number" min=1 max=118/>
<pre id="o"></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~264~~ ~~227~~ 217 bytes
```
lambda x:((((((((((((((1,1),(18,1))[x>1],(x-2,2))[x>2],(x+8,2))[x>4],(x-10,3))[x>10],(x,3))[x>12],(x-18,4))[x>18],(x-36,5))[x>36],(x-54,6))[x>54],'L')[x>56],(x-68,6))[x>71],(x-86,7))[x>86],'A')[x>88],(x-100,7))[x>103]
```
[Try it online!](https://tio.run/nexus/python2#Vc/BCgIhEIDhV/Gm0gSO7rrTQkH33iD2YNTGQlksHXz7bR3tkBf9@EXGZdw/wvNyDSL16m8hoAaFtG76nA44gEpbC5ZlszZU1XBDA65cNdk/2BIJmmJiOw8t23l224Bnt@tj8iT5WJKnmroyA3no2LR2eeSrRHUEUxsaNyzjaxZJTFHMId5v@Ue40/17nuJHJBhV0ssX "Python 2 – TIO Nexus")
Way too many brackets. It looks more like Brain-Flak.
[Answer]
# Excel, 192 bytes
Far from pretty. Borrows from existing Python answers
```
=SUBSTITUTE(SUBSTITUTE(IF(ABS(ABS(A1-80)-16)<8,IF(A1<80,"L","A"),MOD(A1-2*(A1>1)-8*(A1>4)-8*(A1>12)+4*((A1>71)+(A1>99)),18)&" ,"&1+(A1>2)+(A1>10)+(A1>18)+(A1>36)+(A1>54)+(A1>86)),0,18),118,10)
```
Struggling to handle the case where `MOD(x,18)=0` for Group value gracefully.
[Answer]
# Ruby, 116 bytes
```
->n{a=(17..143).map{|i|"#{[i%18+1,i/18]}"}
a[2..17]=a[21..30]=a[39..48]=[]
a[57]=[?L]*15
a[75]=[?A]*15
a.flatten[n]}
```
**Commented in test program**
```
f=->n{
a=(17..143).map{|i|"#{[i%18+1,i/18]}"} #Make an array with strings "[18,0]" to "[18,7]" (first value required as input is 1 indexed.)
a[2..17]=a[21..30]=a[39..48]=[] #Delete "missing" elements from first three periods.
a[57]=[?L]*15 #Replace position 57 in the table with a 15-element array ["L".."L"]
a[75]=[?A]*15 #Replace the correct position in the table with a 15-element array ["A".."A"]
a.flatten[n]} #Flatten the array (break the two above elements into 15) and output element n of the array.
1.upto(118){|n|print n,f[n],$/}
```
[Answer]
# PHP, 120 bytes
```
echo(($n=--$argn)-56&95)<15?LA[$n>70]:(($n-=14*($n>88)+14*($n>56)-10*($n>11)-10*($n>3)-16*!!$n)%18+1).",".(($n/18|0)+1);
```
takes input from STDIN, run with `-nR`.
some bitwise magic for the Lanthanides and Actinides,
the `$n-=` part adds and subtracts offsets for the gaps and Lanthanides/Actinides,
the rest is simple mod/div.
An iterative port of [Neil´s answer](https://codegolf.stackexchange.com/a/113201/55735) takes **108 bytes**:
```
for(;(95&71+$n=$argn)>14&&$n>$y+=2*(++$p+2>>1)**2;)$x=$y;
echo$p?$n-$x>$p/2+1?$n-$y+18:$n-$x:LA[$n>70],",$p";
```
[Answer]
# Perl, 169 bytes
```
90>($n-=14)&&($g=A)if($n=$v=pop)>88;58>($n-=14)&&($g=L)if$n>56;if(!$g){$c+=vec"\1\0\xe\xc0?\0".("\xff"x9)."?",$i++,1
while$c<$n;$p=1+($i-($g=$i%18||18))/18}say"$v,$g,$p"
```
Using:
```
perl -E '90>($n-=14)&&($g=A)if($n=$v=pop)>88;58>($n-=14)&&($g=L)if$n>56;if(!$g){$c+=vec"\1\0\xe\xc0?\0".("\xff"x9)."?",$i++,1 while$c<$n;$p=1+($i-($g=$i%18||18))/18}say"$v,$g,$p"' 103
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~49~~ ~~43~~ ~~42~~ ~~41~~ 39 bytes
```
45“ÞØ\€a€⁶;l;i‘bx/€F’ḣ¹Sḃ18µV=“?I‘⁾LAxȯ
```
[Try it online!](https://tio.run/nexus/jelly#@29i@qhhzuF5h2fEPGpakwjEjxq3WedYZz5qmJFUoQ/kuz1qmPlwx@JDO4Mf7mg2tDi0NcwWqMPeE6jgUeM@H8eKE@v/GxpaBB3aaq10uB2owf0/AA "Jelly – TIO Nexus")
### Background
With the exception of lanthanides and actinides, the output will consist of an integer expressed in bijective base 18. For example, hydrogen corresponds to **1910 = 11b18**, helium to **3610 = 1Ib18**, and eka-radon/ununoctium/oganesson to **11410 = 7Ib18**.
We start by mapping all atomic numbers we can to the corresponding integers, while mapping lanthanides and actinides to those that correspond to lanthanum (**11110 = 63b18**) and actinium (**12910 = 73b18**).
To do this, we record the forward differences of the integers that represent the atoms. For example, the first is **1Ib18 - 11b18 = Hb18 = 1710**, the second is **1** (as are all differences between consecutive elements of the unexpanded periodic table), the fourth (**B** to **Be**) is **2Db18 - 22b18 = Bb18 = 1110**, and so on. To map all lanthanides and all actinides, we'll consider all differences between two lanthanides or to actinides (e.g., **La** to **Ce**) to be **0**.
To get the desired integer for an atomic number **n**, all we have to do is prepend **19** (hydrogen) to the differences and compute the sum of the first **n** elements of the resulting vector. The output is then simply displayed in bijective base 18, unless this would display **6 3** (lanthanides) or **7 3** (actinides). In the latter case, we simply replace the computed result with **L** or **A**.
Wrapped for horizontal sanity, the vector we have to encode looks as follows.
```
19 17 1 1 11 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1
```
After run-length encoding, we get the following.
```
19 1 17 1 1 2 11 1 1 7 11 1 1 44 0 14 1 18 0 14 1 15
```
To reduce the space required to encode the vector even more, we strip rightmost **1**'s (lengths) and add **1** to the runs.
```
20 18 2 2 12 2 7 12 2 44 1 14 2 18 1 14 2 15
```
Now we can reversibly convert these digit arrays from base 45 to integers.
```
20 18 92 12 97 12 134 59 108 59 105
```
All of these are smaller than **250**, so we can represent them with characters from [Jelly's code page](https://github.com/DennisMitchell/jelly/wiki/Code-page). Surrounded with `“` (literal start) and `‘` (interpret as integer array), we get the Jelly literal
```
“ÞØ\€a€⁶;l;i‘
```
which appears verbatim in the code.
### How it works
```
45“…‘bx/€F’ḣ¹Sḃ18µV=“?I‘⁾LAxȯ Main link. Argument: n (atomic number)
45 Set the return value to 45.
“…‘ Yield [20,18,92,12,97,12,134,59,108,59,105].
b Convert the integers in the array to base 45.
x/€ Reduce each resulting digit array (length 1 or 2)
by repetition, mapping [z] -> [z] and
[y,z] -> [y,…,y] (z times).
F Flatten the result.
’ Decrement, yielding the vector of length 118 from
the previous section.
ḣ¹ Head; take the first n elements of the vector.
S Compute their sum.
ḃ18 Convert to bijective base 18, yielding [p, g].
µ Begin a new chain with argument [p,g].
V Eval. The atom casts to string first, so [6,3]
, e.g., is mapped to 63, [7,18] to 718, etc.
=“?I‘ Compare the result with [63,73], yielding
[1,0] for lanthanides, [0,1] for actinides, and
[0,0] otherwise.
⁾LAx Repeat 'L' and 'A' that many times, yielding "L" for
lanthanides, "A" for actinides, and "" otherwise.
ȯ Flat logical OR; replace "" with [p,g].
```
] |
[Question]
[
**Output** is a shape that encloses 1009 pixels.
* The shape must take the form of a single, closed, non-intersecting loop.
**Input** is a positive non-zero integer.
* Each input must yield output that is unique — that is, each output must be unique from those generated using a lower input.
**Victory** is decided by the largest input limit:
* Your submission's input limit is regarded as 1 less than the lowest input that gives non-unique or otherwise invalid output.
* For instance, if valid and unique output is produced for an input of 1, 2 or 3 but not 4, your input limit is 3.
There is a 1009 byte limit on source code. If there is a draw the entry with the fewest bytes wins.
---
**Restrictions and clarifications:**
* A shape's maximum size is 109 by 109 pixels. Size includes the line used to draw the shape.
* A line is constant width.
* The enclosed space must be entirely enclosed by the line - you can't use the boundary of the image file.
* The enclosed 1009 pixels refers only to enclosed space. It does not include the line.
* Output is an image.
* There are no further graphical restrictions - e.g. on colour, line thickness etc.
* An output's uniqueness refers only to the enclosed space. Changes to the line or other graphical changes are irrelevant if the enclosed space is not unique.
* A translation of shape isn't unique. Rotations, reflections and any other transformations count as unique.
* Output must be reproducible — the same input will always give the same output
* There needn't be a relation between outputs, consecutive or otherwise.
* Outside of a submission's 'input limit' there is no defined output.
* No other input or fetching of external data is permitted.
* A line must be continuous — i.e. pixels must touch (touching a corner counts).
* A pixel is the smallest unit of 'drawing' used by your method of drawing, and won't necessarily correspond to a screen pixel.
---
**Examples:**
* Here is an example of a valid shape:

* The following shapes are invalid:


EDIT: **Line touching:**
* Enclosed space must be continuous which is defined as pixels touching. Touching corners counts.
* A line cannot enclose any space on its outer side. This image posted by @Sparr illustrates this point - only the first shape on each row are valid:

* The outer sides of a line may touch, but not in a way that encloses space.
* Touching lines may not overlap - e.g. two touching 1 pixel thick lines would have a combined thickness of 2px, never 1px.
[Answer]
## Python + Pycairo, 2100 shapes
Let's start with the obvious.

```
from cairo import *
from sys import argv
n = int(argv[1]) - 1
s = ImageSurface(FORMAT_ARGB32, 109, 109); c = Context(s)
c.set_antialias(ANTIALIAS_NONE); c.set_line_width(1); c.translate(54, 54)
def pixel(x, y): c.rectangle(x, y, 1, 1); c.fill()
W, H, R = 100, 10, 9
X1, Y1 = -W / 2 - 1, -H / 2 - 1
X2, Y2 = X1 + W + 1, Y1 + H + 1
pixel(X2 - 1, Y1)
c.move_to(X1, Y1 + 1); c.line_to(X1, Y2 + 1)
c.move_to(X2 + 1, Y1); c.line_to(X2 + 1, Y1 + R + 1);
c.move_to(X2, Y1 + R + 1); c.line_to(X2, Y2 + 1)
c.stroke()
for i in xrange(W):
offset = (n >> i) & 1
for y in Y1, Y2: pixel(X1 + i, y + offset)
s.write_to_png("o.png")
```
Takes the number on the command line and writes `o.png`.
[Answer]
# BBC Basic, score 10^288 (minus 1 if zero not counted)
Download interepreter at <http://sourceforge.net/projects/napoleonbrandy/> (not my usual BBC basic interpreter, that one doesn't support long enough strings.)
To encode a lot of information, you need a lot of perimeter. That means a thin shape. I start with a vertical bar of 49 pixels at the left, and add ten tentacles of 96 pixels to it. Each tentacle can encode 96 bits in a similar manner to @ell's solution, a total of 960 bits.
As BBC Basic cannot handle numbers that large, a number of up to 288 decimal digits is input as a string, and each set of 3 decimal digits is converted to a 10-bit binary number. Each bit is then used to wiggle one of the tentacles up by one pixel if it is a `1` (but not if it is a `0`.) The program can handle up to 288/3=96 such sets of 3 digits
```
1MODE1:VDU19,0,7;0;19,15,0;0; :REM select an appropriate screen mode and change to black drawing on white background
10INPUT a$
20a$=STRING$(288-LEN(a$)," ")+a$ :REM pad input up to 288 characters with leading spaces
50RECTANGLE0,0,8,200 :REM draw a rectangle at the left, enclosing 49 pixels
60FOR n=0 TO 95
70 b=VAL(MID$(a$,n*3+1,3)) :REM extract 3 characters from a$ and convert to number
80 FOR m=0 TO 9 :REM plot the ten tentacles
90 PLOT71,n*4+8,m*20+8+(b/2^m AND 1)*4 :REM plot (absolute coordinates) a background colour pixel for tentacle m at horizontal distance n
100 POINT BY 0,-4 :REM offsetting vertically by 1 pixel according to the relevant bit of b
110 POINT BY 4,4
120 POINT BY -4,4 :REM then plot foreground colour pixels (relative coordinates) above, below and to the right.
130 NEXT
140NEXT
```
**Output**
A typical output for a 288-digit number. Note that 999 is 1111100111 in binary. You can see how the sets of 9 digits cause the tentacles to undulate.

**Technicalities**
A.The answer to Martin's point 3 "is the shape connected if its pixel's touch only along a corner?" was "yes" so I understand my answer complies. Nevertheless, if you alternate (for example) 999's and 000's in every row, it looks very busy.
B. If we view this as a rectangle with bites taken out of the side, you can see that I allowed three pixels between each pair of adjacent tentacles, to ensure that the black line round the outside never touches itself. There is no specific rule on this (I hope my reason for asking is clearer in the light of my answer.) If the line is allowed to touch itself on the OUTSIDE of the shape, I could move the tentacles together and use less pixels for the vertical bar (and so make the tentacles a bit longer.) It would, however become very confusing to determine by eye whether a pixel was inside or outside the shape, so I think my interpretation that the outside of the black line should never touch itself is best.
C. BBC basic in this screen mode treats a 2x2 square of screen pixels as a single pixel. I've left this as it is, because it helps viewing if the shape is not too tiny. Each one of these BBC basic pixels is considered as a box of 4x4 logical units. From the start, the developers of BBC basic had the foresight to realise that one day screen resolutions would increase, so they made the logical resolution higher than the physical resolution.
[Answer]
## Mathematica, 496 bytes, Score: large-ish (>1157)
The lower bound I've got there is ridiculously low, but I haven't found a better way than brute force to check yet.
```
SeedRandom@Input[];
g = 0 &~Array~{109, 109};
g[[2, 2]] = 1;
h = {{2, 2}};
For[n = 1, n < 1009,
c = RandomChoice@h;
d = RandomChoice[m = {{1, 0}, {0, 1}}];
If[FreeQ[e = c + d, 1 | 109] &&
Count[g[[2 ;; e[[1]], 2 ;; e[[2]]]], 0, 2] == 1,
++n;
h~AppendTo~e;
g[[## & @@ e]] = 1
];
];
(
c = #;
If[e = c + #; g[[## & @@ e]] < 1,
g[[## & @@ e]] = 2
] & /@ Join @@ {m, -m}) & /@ h;
ArrayPlot[g, ImageSize -> 109, PixelConstrained -> True,
Frame -> 0 > 1]
```
I haven't golfed this yet, because there was no need to. I'll do that once someone proves they are actually tying with me.
The algorithm is basically doing a flood-fill from the top-left corner of the 109x109 image (offset by one pixel to allow for the line) and when I've flooded 1009 cells, I stop and mark the border. You said colours are up to us, so the background is white, the line is black and the interior is grey (I can remove the gray for a handful of characters if necessary).
The flood fill is quite constrained, but that ensures that I don't have to worry about about holes. Relaxing these constraints will probably dramatically increase my (yet unknown) score.
I'll try to put some lower bounds on the score now.
[Answer]
# Python 2, Score > 10^395
It is extremely slow, and I haven't actually managed to get any result other than n=0, but if you want to test it lower `SIZE` (the number of pixels) and `BOUND` the maximum side length of the bounding square and you should be able to get plenty of results. It was very difficult to try and calculate how many it would produce; I am fairly confident that the lower bound I give is accurate, but I suspect the actual count to be significantly larger, and I may try to improve on it later.
```
import sys
import pygame
sys.setrecursionlimit(1100)
def low(s):
return min(sum(e[1] for e in s[:i+1]) for i in range(len(s)))
def high(s):
return max(sum(e[1] for e in s[:i+1])+s[i][0] for i in range(len(s)))
BOUND = 109
SIZE = 1009
def gen(n,t=0):
if n <= (BOUND-t)*BOUND:
for i in range(1,min(n,BOUND)):
for r in gen(n-i,t+1):
a,b=r[0]
for x in range(max(1-a,high(r)-low(r)-BOUND),i):
yield [(i,0),(a,x)]+r[1:]
yield [(n,0)]
def create(n):
g=gen(SIZE)
for i in range(n+1):shape=g.next()
s=pygame.Surface((BOUND+2,BOUND+2))
l=low(shape);x=0
for y,(t,o) in enumerate(shape):
x+=o;pygame.draw.line(s,(255,255,255),(x-l+1,y+1),(x-l+t,y+1))
out=[]
for x in range(BOUND+2):
for y in range(BOUND+2):
if all((0,0,0)==s.get_at((x+dx,y+dy))for dx,dy in[(-1,0),(1,0),(0,-1),(0,1)]if 0<=x+dx<BOUND+2 and 0<=y+dy<BOUND+2):
out.append((x,y))
for x,y in out:
s.set_at((x,y),(255,255,255))
pygame.image.save(s,"image.png")
```
] |
[Question]
[
The goal of this code golf is to convert integers to English words.
The program prompts for input. If this input isn't an integer, print `NaN`. If it is an integer, convert it to English words and print these words. Minimum input: 0 (zero). Maximum input: 9000 (nine thousand).
So, `5` returns `five` (case doesn't matter), and `500` returns `five hundred` or `five-hundred` (dashes don't matter).
Some other rules:
A `one` before `hundred` or `thousand` is optional: `one hundred` is correct, but `hundred` too (if the input is `100` of course).
The word `and` in for example `one hundred and forty five` is optional too.
Whitespace matters. So, for `500`, `five-hundred` or `five hundred` is correct, but `fivehundred` is not.
Good luck!
[Answer]
## JavaScript (375)
Probably a terrible attempt, but anyway, here goes...
```
alert(function N(s,z){return O="zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),(z?O[s]||O[s-10]||O[s-20]:s<13?N(s,1):s<20?N(s,1)+"teen":s<100?N(a=20+(s/10|0),1)+"ty"+(s%10?" "+N(s%10):""):s<1e3?N(s/100|0)+" hundred"+(s%100?" "+N(s%100):""):s<1e5?N(s/1e3|0)+" thousand"+(s%1e3?" "+N(s%1e3):""):0)||NaN}(prompt()))
```
Pretty-printed (as a function):
```
function N(s,z) {
return O = "zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),
(z? O[s] || O[s-10] || O[s-20]
: s < 13? N(s,1)
: s < 20? N(s,1) + "teen"
: s < 100? N(a=20+(s/10|0),1) + "ty" + (s%10?" "+N(s%10):"")
: s < 1e3? N(s/100|0) + " hundred" + (s%100?" "+N(s%100):"")
: s < 1e5? N(s/1e3|0) + " thousand" + (s%1e3?" "+N(s%1e3):"") : 0) || NaN
}
```
Sample conversion (note that it even outputs `NaN` when out of bounds, i.e. invalid input):
```
540: five hundred forty
4711: four thousand seven hundred eleven
7382: seven thousand three hundred eighty two
1992: one thousand nine hundred ninety two
hutenosa: NaN
1000000000: NaN
-3: NaN
```
[Answer]
# Mathematica ~~60~~ 57
```
f = ToString@#~WolframAlpha~{{"NumberName", 1}, "Plaintext"} &
```
**Usage:**
```
f[500]
```
>
> five hundred
>
>
>
**Edit:**
```
InputString[]~WolframAlpha~{{"NumberName", 1}, "Plaintext"}
```
[Answer]
# Lisp, 72 56 characters
I realize 1) that this is old, and 2) that it relies entirely on the standard library to function, but the fact that you can get the c-lisp printing system to do this kind of thing has always impressed me. Also, this does in fact take the input from a user, convert it, and print it.
```
(format t "~:[NaN~;~:*~r~]" (parse-integer (read-line) :junk-allowed t))
```
It totals 72 characters.
* `:junk-allowed` causes parse-integer to return nil on failure instead of raising an error.
* `~:[if-nil~;if-non-nill]` conditional predicated on nil, handles NaN where necessary
* `~:*` backs up the argument interpretation to re-consume the input
* `~r` prints the number as an english word string, as requested, except with full corrected punctuation
Sample:
```
17823658
seventeen million, eight hundred and twenty-three thousand, six hundred and fifty-eight
192hqfwoelkqhwef9812ho1289hg18hoif3h1o98g3hgq
NaN
```
Lisp info mainly from [Practical Common Lisp](http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun_parse-integer.html).
## Edit, golfed properly down to 56 characters
```
(format t "~:[NaN~;~:*~r~]"(ignore-errors(floor(read))))
```
This version works rather differently. Instead of reading a line and converting it, it invokes the lisp reader to interpret the input as a lisp s-expression, attempts to use it as a number, and if any errors are produced ignores them producing nil to feed the format string conditional. This may be the first instance I've seen of lisp producing a truly terse program... Fun!
* `(read)` Invokes the lisp reader/parser to read one expression from standard input and convert it into an appropriate object
* `(floor)` attempts to convert any numeric type into the nearest lower integer, non-numeric types cause it to raise an error
* `(ignore-errors ...)` does what it says on the tin, it catches and ignores any errors in the enclosed expression, returning nil to feed the NaN branch of the format string
[Answer]
## Perl 281 bytes
```
print+0eq($_=<>)?Zero:"@{[((@0=($z,One,Two,Three,Four,Five,@2=(Six,Seven),
Eight,Nine,Ten,Eleven,Twelve,map$_.teen,Thir,Four,@1=(Fif,@2,Eigh,Nine)))
[$_/1e3],Thousand)x($_>999),($0[($_%=1e3)/100],Hundred)x($_>99),
($_%=100)>19?((Twen,Thir,For,@1)[$_/10-2].ty,$0[$_%10]):$0[$_]]}"||NaN
```
Newlines added for horizontal sanity. The above may be used interactively, or by piping it a value via stdin.
Works correctly for all integer values on the range *[0, 19999]*, values outside this range exhibit undefined behavior. Non-integer values will be truncated towards zero, and as such, only values which are truly non-numeric will report `NaN`.
Sample usage:
```
for $n (14, 42, 762, 2000, 6012, 19791, 1e9, foobar, 17.2, -3) {
print "$n: ", `echo $n | perl spoken-numbers.pl`, $/;
}
```
Sample output:
```
14: Fourteen
42: Forty Two
762: Seven Hundred Sixty Two
2000: Two Thousand
6012: Six Thousand Twelve
19791: Nineteen Thousand Seven Hundred Ninety One
1000000000: Thousand
foobar: NaN
17.2: Seventeen
-3: Nine Hundred Ninety Seven
```
[Answer]
# PHP, ~~327~~ ~~310~~ 308 bytes
```
<?$a=['',one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,0,fif,0,0,eigh];echo($n=$argv[1])>999?$a[$n/1000].' thousand ':'',$n%1000>99?$a[$n/100%10].' hundred ':'',$n?($k=$n%100)<20?($a[$k]?:$a[$k%10]).[teen][$k<13]:[2=>twen,thir,'for',fif,six,seven,eigh,nine][$k/10].'ty '.$a[$k%10]:zero;
```
takes the number as parameter, works for 0<=n<=12999
**breakdown**
```
// define names
$a=['',one,two,three,four,five,six,seven,eight,nine,
ten,eleven,twelve,thir,0,fif,0,0,eigh];
// print ...
echo
($n=$argv[1])>999?$a[$n/1000].' thousand ':'', // thousands
$n%1000>99?$a[$n/100%10].' hundred ':'', // hundreds
$n?
// if remains <20:
($k=$n%100)<20?
($a[$k]?:$a[$k%10]) // no value at index (0,14,16,17,19)? value from index%10
.[teen][$k<13] // append "teen" for $k>12
// else:
:[2=>twen,thir,'for',fif,six,seven,eigh,nine][$k/10].'ty ' // tens
.$a[$k%10] // ones
// "zero" for $n==0
:zero
;
```
[Answer]
# SAS, 70 characters
```
data;window w n;display w;if n=. then put 'NaN';else put n words.;run;
```
The `window` and `display` statements open up the SAS command prompt. Input for `n` goes on line 1. This takes advantage of the SAS format `words.` which will print the number as a word or series of words with "and", " ", and "-" as appropriate.
[Answer]
**PHP**
777 characters
This is definitely a terrible attempt, but you can't accuse me of taking advantage of any loopholes, plus it's a very lucky number. Thanks to ProgramFOX for the tip.
```
<?php $i=9212;$b = array('zero','one','two','three','four','five','six','seven','eight','nine');$t='teen';$c = array('ten','eleven','tweleve','thir'.$t,$b[4].$t,'fif'.$t,$b[6].$t,$b[7].$t,$b[8].$t,$b[9].$t);$d = array('','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');$e='hundred';$f='thousand';$j=str_split($i);if (strlen($i)===1){$a=$b[$i];}elseif (strlen($i)===3){$k=1;$a=$b[$j[0]].' '.$e.' '.x($j,$k);}elseif (strlen($i)===4){$k=2;$a=$b[$j[0]].' '.$f.' '.$b[$j[1]].' '.$e.' '.x($j,$k);}elseif (substr($i, -2, 1)==='1'){$a=$c[$j[1]];}else{$a=$d[$j[0]].' '.$b[$j[1]];}$a = str_replace('zero hundred','',$a);echo $a;function x($j,$k){global $i, $b, $c, $d;if (substr($i, -2, 1)==='1'){return $c[$j[$k+1]];}else{return $d[$j[$k]].' '.$b[$j[$k+1]];}}
```
**Long hand**
```
<?php
// Input
$i=9212;
// 0-9
$b = array('zero','one','two','three','four','five','six','seven','eight','nine');
// 10-19 (Very tricky)
$t='teen';
$c = array('ten','eleven','tweleve','thir'.$t,$b[4].$t,'fif'.$t,$b[6].$t,$b[7].$t,$b[8].$t,$b[9].$t);
// Left digit of 20-99
$d = array('','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');
// Hundreds
$e='hundred';
// Thousands
$f='thousand';
// Split input
$j=str_split($i);
// 1 digit inputs
if (strlen($i)===1){$a=$b[$i];}
// 3 digit input
elseif (strlen($i)===3){$k=1;$a=$b[$j[0]].' '.$e.' '.x($j,$k);}
// 4 digit input
elseif (strlen($i)===4){$k=2;$a=$b[$j[0]].' '.$f.' '.$b[$j[1]].' '.$e.' '.x($j,$k);}
// 10-19
elseif (substr($i, -2, 1)==='1'){$a=$c[$j[1]];}
// 20-99
else{$a=$d[$j[0]].' '.$b[$j[1]];}
// Fix for thousand numbers
$a = str_replace('zero hundred','',$a);
// Result
echo $a;
// Abstracted function last 2 digits for 3 and 4 digit numbers
function x($j,$k){
global $i, $b, $c, $d;
// 10-19
if (substr($i, -2, 1)==='1'){return $c[$j[$k+1]];}
// 20-99
else{return $d[$j[$k]].' '.$b[$j[$k+1]];}
}
```
[Answer]
# Python 2.x - 378
Derivative of Fireflys answer, although by changing `P` to include million or trillions, etc.. it could recursively be used for any range of positive numbers. This also supports values up to 999,999
```
O=",one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,thir,for,fif,,,eigh,".split(",")
P=",thousand".split(',')
def N(s,p=0):
h,s=divmod(s,1000);x=N(h,p+1)if h>0 else" "
if s<20:x+=O[s]or O[s-10]+["","teen"][s>12]
elif s<100:x+=(O[s/10+20]or O[s/10])+"ty"+N(s%10)
else:x+=N(s/100)+"hundred"+N(s%100)
return x+" "+P[p]
print N(input())
```
Sample test (input is `<<<`, output is `>>>`):
```
<<< 1234
>>> one thousand two hundred thirty four
<<< 999999
>>> nine hundred ninety nine thousand nine hundred ninety nine
```
Although, if someone can explain this odd "buffer underflow" issue I have, that'd be swell...
```
<<< -1
>>> nine hundred ninety nine
<<< -2
>>> nine hundred ninety eight
```
[Answer]
# SmileBASIC, ~~365~~ Three Hundred Forty Seven bytes
```
DIM N$[22]D$="OneTwoThreeFourFiveSixSevenEightNineTenElevenTwelveThirFourFifSixSevenEighNineTwenFor
WHILE LEN(D$)INC I,D$[0]<"_
INC N$[I],SHIFT(D$)WEND
INPUT N
W=N MOD 100C%=N/100MOD 10M%=N/1E3T=W<20X=W/10>>0?(N$[M%]+" Thousand ")*!!M%+(N$[C%]+" Hundred ")*!!C%+(N$[X+10+(X==2)*8+(X==4)*7]+"ty "+N$[N MOD 10])*!T+N$[W*T]+"teen"*(T&&W>12)+"Zero"*!N
```
There's a trailing space if the last one or two digits are 0.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
⌈≠[`NaN`|∆ċ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIjiiaBbYE5hTmB84oiGxIsiLCIiLCJ0b3AgdGVuIGJydWggbW9tZW50cyJd)
Easy win when it's a built-in :p
[Answer]
# Wolfram Language ~~27~~ 40 bytes
Making use of the native function, `IntegerName`,
```
Check[Input[]~IntegerName~"Words","NaN"]
```
The above prompts for user input. The present implementation returns "NaN" if the user enters anything other than an integer.
---
**Some examples (with pre-set inputs)**:
```
Check[243~IntegerName~"Words","NaN"]
```
>
> two hundred forty-three
>
>
>
---
```
Check[1234567890~IntegerName~"Words","NaN"]
```
>
> one billion, two hundred thirty-four million, five hundred
> sixty-seven thousand, eight hundred ninety
>
>
>
---
```
Check["abc"~IntegerName~"Words","NaN"]
```
>
> NaN
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 333 bytes
```
def f(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';k=n/1000;n,m=n/100%10,n%100;e,d=m/10,m%10;return' '.join([k and f(k),'thousand']*(k>0)+[D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0)))
```
[Try it online!](https://tio.run/##XY8/b4MwEMX3fgovlXGgqQ39AyVkypYxI2Ko5KO4wIGMCU2/PDXQCtTF8rt37@537c0UDfrjKCEnuYPs7ZJ0Ru@7tlImPiUXh36TBoGYoSGm0AAkb3pNcnUF0qkv0sEVkID6KAxBhUBZfE6o9fN/9uLGZYKPgnMeo1cv33vBPbQPj8GTSW1LXm1lrMH0Gimh@89GoZOW5B2lZSyZRy1031lJs51THjlz01OKmUeLHqWGuYxT2UntAWYiqGYQM0BlwU2h9HwHdc8slZlrewDpzpFHn2UWPTrUB59D1cE8YJiiS2aJwIM/hW7TIvjdL7NsGsAZY2OrFRrLKsKA3f2JZ/GyiqfgdRW@CEXkbzqjjbd@Q7ERgdg2RSEbfwA "Python 2 – Try It Online")
This is good for 1 to 999,999, inclusive.
[Answer]
# Pyth, ~~239~~ 242 bytes
```
L:rjdb6" +"dAm+cd;"nine"," one two three four five six seven eight"" twen thir for fif six seven eigh"|y_.ey+Wk.e?Y?thZjd,?hZ+@HhZ"ty"""@GeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>H5eZ?hZ+@GhZ" hundred"""c.[03_b]1"thousand"c_jQT3"zero
```
Input is an integer in range [0-999,999]. Try it online [here](https://pyth.herokuapp.com/?code=L%3Arjdb6%22++%2B%22dAm%2Bcd%3B%22nine%22%2C%22+one+two+three+four+five+six+seven+eight%22%22++twen+thir+for+fif+six+seven+eigh%22%7Cy_.ey%2BWk.e%3FY%3FthZjd%2C%3FhZ%2B%40HhZ%22ty%22%22%22%40GeZ%40%2Bc%22ten+eleven+twelve%22d%2BR%22teen%22%2Bc%22thir+four%22d%3EH5eZ%3FhZ%2B%40GhZ%22+hundred%22%22%22c.%5B03_b%5D1%22thousand%22c_jQT3%22zero&input=90210&debug=0). Explanation pending.
Previous version, very similar operation, but doesn't support 0:
```
L:rjdb6" +"dJc" one two three four five six seven eight nine"dKc" twen thir for fif six seven eigh nine"dy_.ey+Wk.e?Y?thZjd,?hZ+@KhZ"ty"""@JeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>K5eZ?hZ+@JhZ" hundred"""c.[03_b]1"thousand"c_jQT3
```
Explanation of previous version:
```
Implicit: Q=eval(input()), d=" "
Step 1: output formatting helper function
L:rjdb6" +"d
L Define a function, y(b):
jdb Join b on spaces
r 6 Strip whitespace from beginning and end
: In the above, replace...
" +" ... strings of more than one space...
d ... with a single space
Step 2: Define number lookup lists
Jc"..."dKc"..."d
"..." Lookup string
c d Split the above on spaces
J Store in J - this is list of unit names
Kc"..."d As above, but storing in K - this is list of tens names, without "ty"
Step 3: Bringing it all together
y_.ey+Wk.e?Y?thZjd,?hZ+@KhZ"ty"""@JeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>K5eZ?hZ+@JhZ" hundred"""c.[03_b]1"thousand"c_jQT3
jQT Get digits of Q
_ Reverse
c 3 Split into groups of 3
.e Map the above, element as b, index as k, using:
_b Reverse the digits in the group
.[03 Pad the above on the left with 0 to length 3
c ]1 Chop at index 1 - [1,2,3] => [[1],[2,3]]
.e Map the above, element as Z, index as Y, using:
?Y If second element in the group (i.e. tens and units):
?thZ If (tens - 1) is non-zero (i.e. 0 or >=2):
?hZ If tens is non-zero:
@KhZ Lookup in tens names
+ "ty" Append "ty"
Else:
"" Empty string
, Create two-element list of the above with...
@JeZ ... lookup units name
jd Join the above on a space - this covers [0-9] and [20-99]
Else:
c"thir four"d ["thir", "four"]
+ >K5 Append last 5 element of tens names ("fif" onwards)
+R"teen" Append "teen" to each string in the above
+c"ten eleven twelve"d Prepend ["ten", "eleven", "twelve"]
@ eZ Take string at index of units column - this covers [10-19]
Else: (i.e. hundreds column)
?hZ If hundreds column is non-zero:
@JhZ Lookup units name
+ " hundred" Append " hundred"
"" Else: empty string
Result of map is two element list of [hundreds name, tens and units name]
Wk If k is nonzero (i.e. dealing with thousands group)...
+ "thousand" ... Append "thousand"
y Apply output formatting (join on spaces, strip, deduplicate spaces)
Result of map is [units group string, thousands group string]
_ Reverse group ordering to put thousands back in front
y Apply output formatting again, implicit print
```
[Answer]
# [MOO](https://en.wikipedia.org/wiki/MOO_(programming_language)) - ~~55~~ 83 bytes
```
x=$code_utils:toint(read(p=player));p:tell(x==E_TYPE?"NaN"|$string_utils:english_number(x))
```
Note: this code does not print any prompt to the standard output.
As a bonus, this code can handle any number withing the bounds of the moo language (`2147483647`-`-2147483648`).
] |
[Question]
[
Imagine you have a grid where some squares are walls, some are empty, and some are lights that shine for arbitrary distances in the four cardinal directions until they meet walls:
```
####.####
##..L....
####.##.#
####.##L.
##......L
```
In the above grid, the lights cover all the tiles. But in some cases, they may not be:
```
###
.#L
###
```
Your challenge is, given a grid like the one above, determine whether all empty tiles are lit up. You may take input as a matrix of characters or integers, a list of lines, newline-separated lines (as above) with any three distinct characters, etc.
An input may contain none of a type of cell.
You may output truthy and falsy with any of the following:
* Values your language considers truthy or falsy (if applicable), or inverted
* One truthy value and everything else is falsy, or vice versa
* Two consistent values representing truthy and falsy
# Testcases (Given in above format)
Truthy:
```
L
L.
.L
L....
..#L.
....L
.L...
#
L...L...L
#####.###
#L...L...
##.####L.
#.L..####
```
Falsey:
```
.
.#
L#.
.#.
.L.
.#.
L...
L...
L.#.
L...
L.
..
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~29~~ ~~27~~ ~~25~~ 23 bytes
```
2(⌈ƛƛ:×c[¶1V];Ṅ;∩vṅ)∑¶↔
```
Split on wall, check if any spilt contain light, replace it with 1, transpose, do it again, check sum.
outputs empty string for false, dots otherwise.
-2 by @lyxal (pog)
-2 by @lyxal again (1 minute after first one)
-2 by ... yep still @lyxal
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIyKOKMiMabxps6w5djW8K2MVZdO+G5hDviiKl24bmFKeKIkcK24oaUIiwiIiwiWycgICAgIFxcbiAgICcsICcgKlxcblxcblxcbipcXG5cXG5cXG4nLCAnICBcXG4gICAgKlxcbicsICcgXFxuKlxcblxcbiAgICAnXSJd)
[translate the input](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLilqHGm1xcI1xcIFZcXExcXCpWXFwuwrZWO2Z3XFwlJCUiLCIiLCIjIyMjIy4jIyNcbiNMLi4uTC4uLlxuIyMuIyMjI0wuXG4jLkwuLiMjIyMiXQ==)
[Answer]
# JavaScript (ES6), 112 bytes
Expects a matrix with \$0\$ for walls, \$3\$ for lights and \$4\$ for empty squares. Returns *false* if the lights cover all the tiles, or *true* otherwise.
```
f=m=>m<(m=m.map((r,y)=>r.map((v,x)=>v&&[1,2,1,2].map((b,d)=>v|=(m[y+--d%2]||0)[x+~-d%2]&b)|v)))?f(m):/4/.test(m)
```
[Try it online!](https://tio.run/##RY7BbsIwDIbveYqIaDQWxTDGqVvYaTv1xrFwKG3KOjUtS7IKRNmrd0krhCXH///FTvydtqnJdHmy87rJZd8XQomNeuNKKFTpiXMdXkBs9Gja8OxMO50mz@EqdLkf@SHMPe8EV8llNp/nT6t91y0hOc/@BjM9QNcCwHvBFUSL9QKtNNbpXsuf31JLHhQmANQyzT/LSm4vdcaXgLbZWl3WRw5oTlVp@WRX7@oJYNHojzT74oaKDb0SSitpqaKCmkeja/Pbad@SIKIet82859cAg2gd0iAOohdXWBAtb5Bke4BX91zW1KapJFbNkfudHbxBHxMSI8GhuCCIzHsXsaOeEDbeDemcD3RJ2J2SEfhB5oHXhLhJ9KNsEP4PHOrw2P1go/oH "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 89 bytes
```
f=(a,n=4)=>n?f(a[0].map((_,x)=>a.map(c=>(t=c.at(~x))>1?p=t:t|p>>2,p=0)),n-1):!/0/.test(a)
```
[Try it online!](https://tio.run/##VZHBbtswDEDP1Vew9cES6ipu0VMyudhhtwzbPSlW1ZESFw5tyHTXIMl@PaXsdFsJyCQfSVMiX@yr7cpQtXSDzcqdfjy/uJL0yvkK3c/QtC7QTn4Nwe50GxpqaNe6DK4sXWWwh1db924KvseSqgbBkkQFe3GBYOC7pY2mwLEIDwfIZ@Ki8iARvkCuAOHaAG2qTtcO17T5PxrTEYpPcQXBUR8Qehzvt@KKM4ppC3yciWMGv0NF9rnme3FzvqzDfuvCSLytO0Zlg75a9@FfGhzVTAhvTt5Im6G5V6bABy/tIn/UW9tK@St7Y2YHpzSFJFNqfu@fN6WK24fW0JQObVHcZa3Jlcrw5lZNLyf5RJPrSFp1irq0net4Nk9iLsRcCz0oFqF1En2WOdNIRDLGhsNeFM1HJB9UjCAWJhFEWwiu1LE0GYzYQw96@NnHJzlbT7yhaiuV7tq6IjlZ4hKvJ2p4JYEpgM6RdInpiEPECy4O42Qw@nIPqU6nkGeQzlnfs05Y38GR96JYeLx/J6B9E77ZcjO24G10Te103ayllxRzT@8 "JavaScript (Node.js) – Try It Online")
Input matrix where 0 = empty, 2 = wall, 4 = light. Output true vs. false.
Rotate the matrix 90deg 4 times, fill empty cell if there is a light on its left side. Finally test if there are any empty cell left.
This function use ES2022 feature `Array#at` which requires a newer version of NodeJs than current TIO available. A Polyfill for `Array#at` is included in the header of TIO code. So it may be tested on it. You may execute it on a more recent version NodeJs without the header.
```
f=
(a, // input matrix
n=4 // rotate 4 times
)=>n?
f(
a[0].map((_,x)=>a.map(c=>(t=c.at(~x)) // rotate
/* t */>1?p=t:t|p>>2,p=0) // fill empty cell if there is a light left side
),n-1):
!/0/.test(a) // no empty cells left
```
---
# [JavaScript (Node.js)](https://nodejs.org), 95 bytes
```
a=>w=>a.every((c,i)=>c|[-2,-1,1,2].some(s=>a.some(_=>t=a[j+=s%2?(j%w-~s)%-~w&&s:s*w/2],j=i)&t))
```
[Try it online!](https://tio.run/##PVDLboMwELz7KyyhBLsxS@CYyPTUG1I/gKDGIiYFJSbCVmjVNr9O107TlXZndvZluVdXZZuxu7jEDAc9t3JWsphkoUBf9fjJWCM6Lovmu0pykWQiE3kNdjhrZn1TYG@ycFJV/UraRf7M@sWU3CxfJLdpubQb@zSleS162fGl43x22rpGWW2ppHtSElICgQBoBCDyOVqJqldIdK8Fx8wboJPooZK74AcjL3hOCE6CH40C8TcgYFj2CNEf24MbuzPjYC@nzrF0Z3ZmlXI4qwtzVBa0cshd887SCl9Yp8d7zfga@6IxxBu6FjQuETPECDGnP5WpORfUQWcO@uO1ZfHOxLzmW0L@/wHaYXxRuDocagZjh5OG03BkLXPVuuYYM1zDt/Mv "JavaScript (Node.js) – Try It Online")
Input flatten matrix with 0 = empty, 1 = light, 2 = wall, and its width. Output true vs. false.
```
a=> // the matrix; 0 = empty, 1 = light, 2 = wall
w=> // width of matrix
a.every( // if every cell is
(c,i)=>c| // either cell is not empty
// or cell is lighted
[-2,-1,1,2] // four directions; up, left, right, down
.some(s=> // any direction that
a.some(_=> // repeat enough times (we use `a` only because it is long enough)
t=a[ // repeat move until current cell is non empty
j+=s%2? // -2, 2 are left / right, while -1, 1 are up / down
(j%w-~s)%-~w&&s: // if we reached end of current row, stop move
s*w/2 // move up or down (may out of bound but we don't care)
],
j=i // starting from cell `i`
)&t // if non-empty cell exists and the cell is light
)
)
```
[Answer]
# JavaScript (ES6), 254 bytes
```
d=>!(f=i=>i?f(i-1,d=d.replace(/(?<=a|b)[ c]|[ c](?=a|b)/g,x=>"ab"[+
(x<"!")]),d=(t=s=>[...s.split`
`[0]].map((_,i)=>s.split`
`.map(x=>x[i]).join``).join`
`)(t(d).replace(/(?<=a|c)[ b]|[ b](?=a|c)/g,x=>"ac"[+(x<"!")]))):d)
(d.length+d[0].length).includes` `
```
Uses for empty spaces, `a` for lights, and any non-alphabetical and non-space character for walls.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~274~~ \$\cdots\$ ~~195~~ 191 bytes
```
#define F for(y=0,i=r*c;i--;
#define J(A,B,C,D)for(y=A c;--y+B&&~-m[C*c+D];)m[C*c+D]|=m[i]*2&4;
i;y;f(m,r,c)int*m;{F){J(-i%,c,i/c,-y)J(i%,1,i/c,y)J(-i/,r,-y,i%c)J(i/,1,y,i%c)}F)y|=!m[i];i=y;}
```
[Try it online!](https://tio.run/##bZTdjtowEIXveYppViAn2CUE9gK5qbTLlgvUNwBUoYmzNS0BJalKyqaPXurEcf7YyBCPz2fPmUkUZK@It9tDIEIZCVhBeIpJ5rtU@rGDXDLGB0Zckyf6TJf0xdbQEyBnLBs/j0Z/2XGzdHD8suO2mb35x43cOd5ozgeSZzwkRxpTtGWUOkd@XdnXNWFySJHKCVKW2WuiomkZFQGTE8WzjMohFtpEaTrIV3b25n8ojufSz3h@U2fCcS8jYsN1AOoqFlKRpNPNDny4TinUw23Np7ReU8Mzk3K8u8dt9vQUr9nj3g0v5x1bXteWW51QxT14pmG3tzy/L61b3bRbkdcvrduIuoA22ui95N9inf2RwqwE5n0ANbAwwKIBnJJINFA@Jaq7om8zfWufKC5ngakIqk7UxVYInqIkBfy@jx31L/CHqOxZ28sXb3tZLNXv0aLQjmdWtVu9zUCKLDIKxEVtc3k1/QSJ/CNOITH57Um14NQrHMbjkjavXlOkOkoXWuo73pYhrlTVyfdkNDLeyY3fyqvyGZc22hY65EGTB0ViQR76pEkbFGk30kEYw6GV01znWFEhsYZYdPPjw1drE@zsLpd3ovOvNCGW1WLyTqGJyhiStPw0dFsglFI/@H4TjBFgn2EYwDDZRspRQuvnn/i@aDvTPvz6Mo7yQX77h@HP/WtyY7//Aw "C (gcc) – Try It Online")
*Saved a whopping ~~45~~ \$\cdots\$ ~~55~~ 59 bytes and got below 200 thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs a pointer to an array of integers along with the room dimensions (since pointers in C carry no length info).
These integers represent a room with \$0\$ -> `.`, \$1\$ -> `#`, and \$2\$ -> `L`.
Returns \$0\$ if the room is lit up or \$1\$ otherwise.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 19 bytes
```
,Z»×¥@\Ṛ$2¡€Z»¥/F’Ạ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCIsWsK7w5fCpUBcXOG5miQywqHigqxawrvCpS9G4oCZ4bqgIiwidOKAnMK24oCdxZPhuaPigJzCtsK24oCdwrXhu7RpQOKCrOKCrOKAnC5M4oCdw4fCteKCrCIsIiIsWyJcIlwiXCJcbkxcblxuTC5cbi5MXG5cbkwuLi4uXG4uLiNMLlxuLi4uLkxcbi5MLi4uXG5cbiNcblxuTC4uLkwuLi5MXG5cbiMjIyMjLiMjI1xuI0wuLi5MLi4uXG4jIy4jIyMjTC5cbiMuTC4uIyMjI1xuXG4uXG5cbi4jXG5cbkwjLlxuXG4uIy5cbi5MLlxuLiMuXG5cbkwuLi5cbkwuLi5cbkwuIy5cbkwuLi5cblwiXCJcIiJdXQ==)
"Borrowing" the multiplication idea from Unrelated String (i.e. stealing lol). 0 for `#`, 1 for `.`, 2 for `L`.
[Answer]
# [J](http://jsoftware.com/), 43 bytes
```
*-:g&.|:>.g=.**[:}:@;"1<@(#$2&e.);.2"1@,.&0
```
[Try it online!](https://tio.run/##fVDLCsIwELzvVyyNNKboUHtMrRQETzmJNw8i0vpAFHyBoN9eu1o9mS5MstmZzC67qwLokjPLmnscs63RB4@nblJFfbsO8bAjrDNE0dw@bZ4Gg2HeVZ0kLGBSJMEg7yGMK0O0Oh5uxemSgbWC0@EWKRYJUbHaHFnPTtfL5q6bZ8mNWlrGpBzI/KeclwChhayDADGW1NVaqZj/7X02SgI1ZEJ8LD4FMVZSkLxtijd@Aj1Z7s@@LXh3AH8H1fJJFoT33TLf91BNZqh6AQ "J – Try It Online")
Based on [okie's "split on walls and check if each section contains a light" idea](https://codegolf.stackexchange.com/a/239863/15469).
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3xŸvTyT+:yT*y∞:ζí}SßĀ
```
Input as a list of lines, where `.L#` are `012` respectively.
Uses the legacy version of 05AB1E where the `ζ` and `:` builtin works on list of strings, which would have been `€SζJ` and required a map over the lines in the new 05AB1E (ending up [6 bytes longer](https://tio.run/##yy9OTMpM/f/fuOLojrLK0HNbQyJCtK0iQrQiDu2yCq49t83r8Nra4MPzjzT8/x@tZGhgYKCkg6CM4LxYAA)).
[Try it online](https://tio.run/##MzBNTDJM/f/fuOLojrKQyhBtq8oQrcpHHfOszm07vLY2@PD8Iw3//0erGxoYGKjrKCDRRgh@LAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamAMXs688tO3QwnNbHzUs0/NRNjA0etSwsPbQjtNzbP8bVxzdURZSGaJtVRmiVfmoY57VuW2H19YGH55/pOG/kn9pCdQEnUPb7P9HKykDgR6IiMkDMvR89IAAxASL6inDmT56EAUg4KOkowTECkogQQgPok1PD6wOrAYkA6SBkspQBT5QrcowO4EmwsTBhoPEwfaAhEAckB0gE/TARihDmGA7QQSYD9EMI5WhbLBCcjwWCwA).
**Explanation:**
```
3 # Push a 3
x # Double it (without popping): 6
Ÿ # Pop both and push a list in this range: [3,4,5,6]
v # Loop over each of these digits `y`:
: # Replace all:
T # "10"
yT+ # with "1y", where `y` is the current digit
# (which use the implicit input-list in the first iteration)
: # Then infinitely replace all:
yT* # "y0"
y∞ # with "yy", where the `y` are again the current digit
ζí # Then rotate once clockwise:
ζ # Zip/transpose; swapping rows/columns
í # Reverse each row
} # After the loop, we want to check if any empty spots remain:
S # Convert the list of strings to a flattened list of characters
ß # Pop and push its minimum
Ā # Check if this is NOT 0
# (after which the result is output implicitly)
```
[Answer]
Brev, 159, no, 156 bytes:
```
(define (l row) (strse row "[g_]*L+[g_]*" (strse (m 0) "_" "g")))
(print (apply any (compose (strse? "_") l string) (map (o string->list l) (read-lines))))
```
Uses \_ instead of . (shaves four bytes) and prints #f for lit up, #t for dark.
Update: remove a redundant partial applicator
[Answer]
# [SnakeEx](http://www.brianmacintosh.com/snakeex/spec.html), 34 bytes
```
m:{d<>}{d<R>}{d<L>}{d<B>}
d:,+[#$]
```
Uses `,` instead of `.`; to take inputs formatted as in the question, replace `,` on the second line with `\.`. Outputs one or more matches (truthy) for a room that is not fully lit, no matches (falsey) for a room that is lit. [Try it here!](http://www.brianmacintosh.com/snakeex/)
### Explanation
Core idea: find a `,` which can't "see" an `L` in any of the four directions. If no such `,` exists, the room is fully lit; if such a `,` exists, it is not fully lit.
```
d: Define a helper snake d to match
,+ 1 or more commas
[#$] followed by a pound sign or the edge of the grid
m: Define the main snake m to match
{d<>} d in the default direction (left-to-right)
{d<R>} and also in the direction 90 degrees clockwise (top-to-bottom)
{d<L>} and the direction 90 degrees counterclockwise (bottom-to-top)
{d<B>} and the reverse direction (right-to-left)
```
[Answer]
## Txr Lisp, 109 bytes
```
(do let((l(op mapcar(op regsub #/[. ]*L[. ]*/(op regsub #/\./" ")))))(find #\.(cat-str[l(transpose[l @1])])))
```
## 103 bytes
```
(op find #\.(cat-str[#1=(op mapcar(op regsub #/[. ]*L[. ]*/(op regsub #/\./" ")))(transpose[#1# @1])]))
```
## 97 bytes
Drop `(cat-str X)`, use quasiliteral ``@x``.
```
(op find #\.`@[#1=(op mapcar(op regsub #/[. ]*L[. ]*/(op regsub #/\./" ")))(transpose[#1# @1])]`)
```
This is an expression that evaluate so to a function which operates on sequence of strings, those being the lines of the grid.
The function returns `#\.`, the dot character, to indicate that unlit areas remain. Otherwise it returns `nil`. A character is truthy, and `nil` is the only false value.
The logic is just regex. The `regsub` function matches regular expressions. If the replacement argument is a function, the matched text is passed to it and replaced with what the function returns. For the substitution we use another partially applied `regsub` which replaces dots with spaces.
So, in every string of dots or spaces that contains an `L`, we replace the dots with spaces, doing this in every string. Then we transpose the vector of strings and do it again.
Truthy example:
```
#####.### #####.### #### ####
#L...L... --> #L L --> #L# --> #L#
##.####L. ##.####L # .L # L
#.L..#### # L #### # # # #
# # # #
.L## L##
# ## # ##
# L# # L#
# # # #
```
No dots remain, so everything is lit.
This main list-of-string processing action for replacing the `L`s is a function. In the 109 byte version, it bound to the lexical variable `l`, which we then refer to twice separated by a `transpose` call.
In the 103 byte version, we get rid of the local variable and just repeat the code in two places using the Lisp circle notation. `#1=OBJ` means "`OBJ`, also associated with label 1". And `#1#` then means "reproduce the object from label 1, `OBJ` here". With this we can make a piece of data (i.e. piece of source code, of code is data) appear in two or more places.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes
```
»×¥@\Ṛ$⁺
Ç€»ÇF1e
```
[Try it online!](https://tio.run/##NY4xDsIwDEV3H6NmrCzKCTox5QisHUAdWdgKSwZGBiRUJsTWkSKVbok4SHKRYLvUiuP/X2Inu6quDym50V/ds9yE4baIxw94G08dQ7suqrSPTevesbl/L2F4qFHr@jC@tiXflNW0BhmG8bzKl3nhresZp5RlGRgAQ0BaOIAIxXMYpkIApzNNdhLECThTmIA0ogDRANxJ0ooq5A3SqsPmDf9KhgH/5wc "Jelly – Try It Online")
*Fixed by borrowing back from hyper-neutrino lmao*
*-1 replacing the double transpose with a map by replacing the map with implicit vectorization*
Takes a matrix of 0 for `#`, 1 for `.`, and 2 for `L`.
```
»×¥@\Ṛ$⁺ Monadic helper link: light up all columns or a row
\ Scan by
» @ (vectorizing) max of right and
×¥ (vectorizing) product,
Ṛ then reverse.
$⁺ Do it again.
Ç€»ÇF1e Monadic main link: is there anything unlit?
Ç Light up
€ each row,
Ç light up the columns,
» and take the maximum at each position.
F Flatten the result.
1e Does it contain 1?
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
WS⊞υιυFLυF⌕A§υιLF⁴«JκιM✳⊗λW﹪℅KK³⁵✳⊗λ_»≔№KA.θ⎚¬θ
```
[Try it online!](https://tio.run/##bU/BTgMhED2XryDby5CsXNSTp00bkxqqm@jdrAvukiLTslBNjN@Ow7b15DsMw7w3j0c/dqHHzuX8OVpnOGz8PsXnGKwfQAjepmmEVHMr7lhLwwiJuncMHJTxQySSVPP93nrdOAdN3Hhtvk5bNa9UdVHcCP7NFg/pY/@CsDuZLrZ4NLC2wfTRooc1pjdnNDghCntOtUWdHMJT0NZ3DlpjdpSu5te3JeOc618Lev61Ip8f1kyTHTysMJG27JeohZcV1QNpVs50Af7@@YgRDpQh5yVBlsLolEoS2Hkml5dOyZktUCxfHd0v "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings and outputs a Charcoal boolean, i.e. `-` if the room is fully lit, nothing if not. Explanation:
```
WS⊞υιυ
```
Input the map and print it to the canvas.
```
FLυF⌕A§υιLF⁴«
```
Loop over the lights in all directions.
```
JκιM✳⊗λ
```
Move to a tile adjacent to a light.
```
W﹪℅KK³⁵
```
While this tile is not wall, ...
```
✳⊗λ_
```
... mark it as lit and move to the next tile. (Note: If there are two lamps, they'll light each other, but the loop above checks the original lamps, so it doesn't matter that they get removed from the canvas.)
```
»≔№KA.θ
```
Count the number of remaining unlit tiles.
```
⎚¬θ
```
Clear the canvas and output the result.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~94~~ 91 bytes
```
(?!_+L|((?<=(.)*)_.*¶(?<-2>.)*(?(2)^))+L)_(?<!L_+|L((?<=(?<!.)(?(4)$)(?<-4>.)*.).*¶(.)*_)+)
```
[Try it online!](https://tio.run/##NUu5DcJAEMyvC8sOdnzyBJZD4BrYEhArAgISAkTouiiAxo45GybYnfd5e90f13pmimqli@yrWTkcjRgRHD9vqWk@SVqxGRcgO0Jm55FX38tShPIFA1p/aX1im4sFMmrtBbaT9OkU0s9j/2fOLW3wLw "Retina 0.8.2 – Try It Online") Takes input using `_` as a floor tile instead of `.` but header converts `.` to `_` for you for convenience. Outputs the number of unlit floor tiles, so a falsy value if the room is lit. Explanation:
```
(?!_+L|
```
Don't match a floor tile that is to the left of a light, or...
```
((?<=(.)*)_.*¶(?<-2>.)*(?(2)^))+L)
```
... that is above a light.
```
_
```
Match an unlit floor tile.
```
(?<!L_+|
```
Don't match a floor tile that is to the right of a light, or...
```
L((?<=(?<!.)(?(4)$)(?<-4>.)*.).*¶(.)*_)+)
```
... that is below a light.
.NET balancing groups are used to ensure that the light is in the same column as the tile.
[Answer]
# Python3, 205 bytes:
```
import re
m=lambda x:re.sub('(?:\.+)*L(?:\.+)*',lambda j:'L'*len(j.group()),x)
f=lambda x:all(all(n!=('.','.')for n in zip(m(i),j)if n!=('#','#'))for i,j in zip(x,[*zip(*[m(''.join(c))for c in zip(*x)])]))
```
[Try it online!](https://tio.run/##hZBdTsQgEMef5RS4PDBUnBh9MU02XqDxArvG7AddaSgQ2k2ql6/QbWNiVhwyMGF@M/wZ/9l/OPv07MM46ta70NOgSLs2u3Z/3NGhDAq78x44vJRbvBNFtQRczkxT8ooXRllo8BTc2YMQchCk/mmyMwaS29s1cOQyuqhdoJZqS7@0hxa0kI3QNZ0QFhHGxcRo2SzUIDdFOotNC5xj47SFw4U6LEwxiLe4xHhUNe3d@ynoI3SiJDdB9edgqdFdD7U2vQrw6qyStMPOG90D39r4piDEB20jA0v5arVi0TBtJJ5YYTQy3yFbogqnbLIq1qRe11sRZFUq@hvK1MdXMJtO2hCTmkkJmeRm9OR7Vf/@5jIZwhaazKNK40gX7PdP@T0vHh@utsvoxJxQli1ME4uegybh88Yu0QyP3w)
[Answer]
# [Perl 5](https://www.perl.org/), 103 bytes
```
sub{$_=pop;while(!$h{$_}++){s/(Ll*)\./$1l/;$r=@l=();map/\s/?$r=0:$l[$r++]=~s/^/$_/,/./gs;$_="@l"}!/\./}
```
[Try it online!](https://tio.run/##dZDBbsIwDIbvfgpozNKuKIHDLoQM7qvGZTdgiEktoAWoGtCEUPfqnVNaiQKz1MT5fruJ/zTOzEuBiS7s8euMC53uU/Wz3pjYb@OaQB6GwdlKPzLPwUxI7BupMNNjo/1AbZepnFk5ItAboJliFoZz/Wvlp8SF7EohV1bRT72x8fK2pP68UADJPvOhRTEdDjnXr/15FyK4IwLEI0oBQjAnU0RU5MhtHXvYWX4A13UUwi2UXXRRM8HqLBKlKhrdPeoWzRNrHCN2K7uJRLk36tyd1cKqDIJz@f7tycdNF@NAj3GhKoQr/YQJCcGFpNlmd0i8jm117GznUbnWuBrx/Tcf8PfJR2vyxgmO@CE7HtYngsnS2PjEFeRQ0ESV1f96y@DaPVZ7BqymUJnojHKgNNS54ywpfWgM/2DiPw "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~146~~ 141 bytes
```
#define F(d)for(i=r*c;i--;F&=m[i])for(j=i;m[i]>3&1u*j<r*c&m[j]<8&&j/c!=i/c^d*d;j+=d)m[j]|=1;
i;j;F;f(m,r,c)int*m;{F(1)F(-1)F(c)F=1;F(-c)i=F;}
```
[Try it online!](https://tio.run/##dVLbbuIwEH33VwxEBYfctX0omPQxT/wBTaWs7YDTJCAnEVp1@fVlxwl0gS0j2Z45c@Zij7m34fx0soTMVS0hocLOd5qqWM84U57HkklcrVXao0WsmDFef0yiblYskTOp1kW6fJlMioCPYhXwdzETrHBiYRvP7zhiRLGCJSynlatdbqu6nVXsM6GRnVDPbNxOkIYGOuOEHU9BACHIat/@Iqg@Q6k22xaaXae5NMgcDllZEkvVvOyEhGXTCrXzt68Ek0Mrm3Y9R0lZb1eZqqkNnwRQDKDj0AVltoL14GGrSgnY0Jl0IXKIYSNbvs00tV0Q7MvbHBTCgK1fhfCskeBFC9Cy7XQNIbt1TVfTxdCdcpwUcz8z@Kll9nHP8@944QOedcebP@C91dPFF2TEcTS7AcT1TW9dKgeK7hii8PqyFwmCvca3yun4ScCTeKvHOGV1l2MgDl8oZMUyCpnjFPZV5NjtL1KkNtt3bUPH429S/OObMjAa5dREuaBxnoG2H1bFYTM1VFXfVFXXVR@XP491@E@37iPIEl/6/@fpavOsVLhg/mh9H0ZutSM5nlaErHzi9wcK8X3L2CgrRA1CrMHXL7SM@LiIdUHJAJhAywBGJwQjfRNq9Yqp4fdnn@yyWWetbwKPPzwvs01z8g5/AQ "C (gcc) – Try It Online")
Thank ceilingcat for -3 bytes
Not quite sure what Noodle9 did, and not sure why I can't `F(1)(-1)...` here
] |
[Question]
[
>
> This is a overhaul of [this now deleted question](https://codegolf.stackexchange.com/q/152430/56656) by [ar kang](https://codegolf.stackexchange.com/users/77282/ar-kang). If the OP of that question would like to reclaim this question or has a problem with me posting this I'd be happy to accommodate
>
>
>
Given a list of integers as input find the maximum possible sum of a continuous sublist that starts and ends with the same value. The sublists must be of length at least 2. For example for the list
```
[1, 2, -2, 4, 1, 4]
```
There are 2 different continuous sublists start and end with the same value
```
[1,2,-2,4,1] -> 6
[4,1,4] -> 9
```
The bigger sum is 9 so you output 9.
You may assume every input contains at least 1 duplicate.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Test cases
```
[1,2,-2,4,1,4] -> 9
[1,2,1,2] -> 5
[-1,-2,-1,-2] -> -4
[1,1,1,8,-1,8] -> 15
[1,1,1,-1,6,-1] -> 4
[2,8,2,-3,2] -> 12
[1,1,80] -> 2
[2,8,2,3,2] -> 17
```
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
`f` takes a list of integers and returns an integer.
```
f l=maximum[x+sum m-sum n|x:m<-t l,y:n<-t m,x==y]
t=scanr(:)[]
```
[Try it online!](https://tio.run/##PYrBCoMwEETvfkUoPRiSSLVSRBp/xHoIVlG6mxYTaYT@e5oILcsM82ZnUuYxAHhUs5aztsOientcNcx6MBmqV3oD0QBjByIacmDMTM93OqbLoO4EKKXZvvQjAYnKzbhi65hZkaCIrj@uxquwBPhW6xiQOym3LrHS9EovaU3bzvs25wUXBS95zssu2TEoJJHHfve9j1dFrv4Y4BIscBFeYXzmv2116pIv "Haskell – Try It Online")
# How it works
* `t` is the standard "get all suffixes of a list without importing `Data.List.tails`" function.
* In `f l`, the list comprehension iterates through all the non-empty suffixes of the argument list `l`, with first element `x` and remainder `m`.
* For each, it does the same for all nonempty suffixes of `m`, selecting first element `y` and remainder `n`.
* If `x` and `y` are equal, the list comprehension includes the sum of the elements between them. This sublist is the same as `x:m` with its suffix `n` stripped off, so the sum can be calculated as `x+sum m-sum n`.
[Answer]
# JavaScript (ES6), ~~68~~ 62 bytes
```
a=>a.map(m=(x,i)=>a.map((y,j)=>m=j<=i||(x+=y)<m|y-a[i]?m:x))|m
```
### Test cases
```
let f =
a=>a.map(m=(x,i)=>a.map((y,j)=>m=j<=i||(x+=y)<m|y-a[i]?m:x))|m
console.log(f([1,2,-2,4,1,4] )) // -> 9
console.log(f([1,2,1,2] )) // -> 5
console.log(f([-1,-2,-1,-2] )) // -> -4
console.log(f([1,1,1,8,-1,8] )) // -> 15
console.log(f([1,1,1,-1,6,-1])) // -> 4
console.log(f([2,8,2,-3,2] )) // -> 12
console.log(f([1,1,80] )) // -> 2
```
### Commented
```
a => // a = input array
a.map(m = // initialize m to a function (gives NaN in arithmetic operations)
(x, i) => // for each entry x at position i in a:
a.map((y, j) => // for each entry y at position j in a:
m = // update m:
j <= i || // if j is not after i
(x += y) < m | // or the sum x, once updated, is less than m
y - a[i] ? // or the current entry is not equal to the reference entry:
m // let m unchanged
: // else:
x // update m to the current sum
) // end of inner map()
) | m // end of outer map(); return m
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ĠŒc€Ẏr/€ịḅ1Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///IgqOTkh81rXm4q69IH0Tv7n64o9Xw4c6G/4fbgfzI//@jow11jHR0jXRMdAx1TGJ1uBTAAkAMZusaguTAJFQOBC1AIhZIAkCuGZAAixgBpYFajHUQOiwMYmMB "Jelly – Try It Online")
### How it works
```
ĠŒc€Ẏr/€ịḅ1Ṁ Main link. Argument: A (array)
Ġ Group the indices of A by their corresponding values.
Œc€ Take all 2-combinations of grouped indices.
Ẏ Dumps all pairs into a single array.
r/€ Reduce each pair by range, mapping [i, j] to [i, ..., j].
ị Index into A.
ḅ1 Convert each resulting vector from base 1 to integer, effectively
summing its coordinates.
Ṁ Take the maximum.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
▲mΣfΓ~€;ṫQ
```
[Try it online!](https://tio.run/##yygtzv6vkKtR/KipsUjz0Lb/j6Ztyj23OO3c5LpHTWusH@5cHfj///9oQx0jHV0jHRMdQx2TWC4wF4iBLF1DkDiYBIuDoAWIbwHnAjlmQALINwJKARUb68DUWhjARUGCAA "Husk – Try It Online")
## Explanation
```
▲mΣfΓ~€;ṫQ Input is a list, say x=[1,2,-2,4,1,4]
Q Slices: [[1],[2],[1,2],..,[1,2,-2,4,1,4]]
f Keep those that satisfy this:
Γ Deconstruct into head and tail, for example h=2 and t=[-2,4,1]
; Wrap h: [2]
~€ Is it an element of
ṫ Tails of t: [[-2,4,1],[4,1],[1]]
Result: [[1,2,-2,4,1],[4,1,4]]
mΣ Map sum: [6,9]
▲ Maximum: 9
```
[Answer]
# [Haskell](https://www.haskell.org/), 66 bytes
```
maximum.f
f(x:y)=[sum$x:take a y|(a,b)<-zip[1..]y,b==x]++f y
f x=x
```
[Try it online!](https://tio.run/##HcyxDoMgEADQ3a@4wUEjkNjR9L4EGU4jlAiGFE2Opt9e2nR543tQ3rcQqsO5RmIfr6hsYzueSo86X7Hl6aR9A4Ly7kgs/V2@fNKjUqaIBZHNMFgojQVG/hX@AIT09McJLTjQchTyJv6a@lltIJerXFP6Ag "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~108~~ ~~103~~ ~~90~~ ~~88~~ 83 bytes
```
function(l)max(combn(seq(l),2,function(x)"if"(rev(p<-l[x[1]:x[2]])-p,-Inf,sum(p))))
```
[Try it online!](https://tio.run/##PYtBCoAgEEWvEq1GmFlkm4gu0BnERYkDQppphbc3V/3de4@fKncLVX6Cud0Z4BB@K2BOvwfI9mqMEv9aRO@4h2RfiAsdqqhBz0VJrQVFpDUw5sdDFG2VwYDEqf1pRNnEBw "R – Try It Online")
`combn` strikes again! Generates all sublists of length at least `2`, sets the sublist sum to `-Inf` if the first and last are not equal, and takes the max of all the sums.
The `"if"` will raise a bunch of warnings but they are safely ignorable -- that's probably the best golfing trick here, `rev(p)-p` is zero in the first element iff `p[1]==tail(p,1)`, and `"if"` uses the first element of its condition with a warning.
[Answer]
# [Python 3](https://docs.python.org/3/), 81 bytes
```
lambda x,e=enumerate:max(sum(x[i:j+1])for i,a in e(x)for j,b in e(x)if(a==b)*j>i)
```
[Try it online!](https://tio.run/##TY7NCoMwEITP5ilyTNoVGpUiQvoimkOkCY00UfyB9OnTRBFk2YFvZgd2@q2f0ZVBY4678JW2f0vsQXHlNqtmuarGSk@WzRLfmma4M0H1OGMDEhuHFfE7DtCfaDSRnPf0NrwMDSn0KepQ1rYMCsgLqIBBJQBleHfiHpCzlO56pmnqZNVXJ/IzymEV8SC2SriU6ocQDULZNBu3Eh3fouEP "Python 3 – Try It Online")
[Answer]
# [Python](https://docs.python.org/2/), 62 bytes
```
f=lambda l:l and max(f(l[1:]),[sum(l)]*(l.pop()in l[:1]),f(l))
```
[Try it online!](https://tio.run/##TY7bCsIwDECf7VfksZVMbJ0yB35JCVIvw0HXla0D/fqZOYcSkpCTQ0h8pUcbzDhWJ@@ay82BLz24cIPGPWUlvdUlKbT90EivaC39JrZRqjqAt6XmFTtKjenep/PV9fceTmDFylqNBjODOWrMCY@EC@Qk3M9zpifnUwmzfJGmKCZcEOr9P2V24EL4dQ17fGA33dTmZxZbYiRIiKrtoA5xSAjtkLjzBL93S7GKXR0SVPJjKZyt8Q0 "Python 2 – Try It Online")
Outputs a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/20260).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~, 12 bytes
```
=ṚṖḢ
ẆÇÐfS€Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8/9/24c5ZD3dOe7hjEdfDXW2H2w9PSAt@1LTm4c6G/4fbj056uHPG///RhjoKRjoKukBsoqMA5JjEAgA "Jelly – Try It Online")
One byte saved by Mr. Xcoder, who is currently competing with me. :D
Explanation:
```
# Helper link:
=Ṛ # Compare each element of the list to the element on the opposite side (comparing the first and last)
Ṗ # Pop the last element of the resulting list (so that single elements return falsy)
Ḣ # Return the first element of this list (1 if the first and last are equal, 0 otherwise)
# Main link:
Ẇ # Return every sublist
Ç # Where the helper link
Ðf # Returns true (1)
S€ # Sum each resulting list
Ṁ # Return the max
```
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 54 bytes
```
Max@SequenceCases[#,{a_,b___,a_}:>2a+b,Overlaps->All]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVei4KCloPHfN7HCITi1sDQ1LznVObE4tThaWac6MV4nKT4@XicxvtbKzihRO0nHvyy1KCexoFjXzjEnJ1btv6aCvoNCNZeCQrWhjoKRjoIuEJvoKAA5JrU6CGEQCeHrGkIUQWi4GgiygIhboAmDxMxAFETcCKwQZIYx3FiofoNartr/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Pyth, 15 bytes
```
eSsMf&qhTeTtT.:
```
[Try it online](http://pyth.herokuapp.com/?code=eSsMf%26qhTeTtT.%3A&input=%5B1%2C%202%2C%20-2%2C%204%2C%201%2C%204%5D&debug=0)
### Explanation
```
eSsMf&qhTeTtT.:
.:Q Take all sublists of the (implicit) input.
f qhTeT Take the ones that start and end with the same number...
& tT ... and have length at least 2.
sM Take the sum of each.
eS Get the largest.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ŒʒćsθQ}OZ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6KRTk460F5/bEVjrH/X/f7SuoY6ukQ6YjAUA "05AB1E – Try It Online")
**Explanation**
```
Œ # push sublists of input
ʒ } # filter, keep values where
ć # the head of the list, extracted
Q # is equal to
sθ # the last element of the rest of the list
O # sum the resulting sublists
Z # get the max
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~94~~ ~~90~~ 86 bytes
```
import StdEnv,StdLib
@l=last(sort[sum(l%(i,j))\\e<-l&i<-[0..],j<-elemIndices e l|j>i])
```
[Try it online!](https://tio.run/##JY2xCoMwFEX3fkWWFoVEdOsQi4MdBDdHzZDG1/LCSyxNLBT67U0Fp8vhwLmGQPvklnklYE6jT@ieyyuyIc5X/@bb9Hg7NFSTDjELmxrD6jI6Zshtnk8TSEEnlGIsi0JxKwUQuM7PaCAwYPS1F1R5GqLeqjVr2Fjxip9LlX7mTvoRkuj61H68dmh22E// "Clean – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 86 bytes
*[Outgolfed by Dennis](https://codegolf.stackexchange.com/a/152470/60919)*
```
lambda x:max(sum(x[i:j+1])for i,v in enumerate(x)for j in range(i+1,len(x))if v==x[j])
```
[Try it online!](https://tio.run/##TY/RisMgEEWf61fMo6ETWG26pIF8iTsUu2t2DYkJiSn261NNW7qIM3g8XGbGm/8bnFyb@mvtdH/50RCqXgc@Lz0PylbtXlDWDBNYvIJ1YNzSm0l7w8OG2wQn7X4Nt3uBnXHxI7MNXOs6qJay1ZvZn7/1bGaoQbGdUgIl5hILFFgQnghfMF7C4@Odi@RslTAvXlI6ZcIloTj@p5F9xkL4dGX0YsAhZQr5NssPiogRY9tablw8wrD42NMu73Erthsn6zw0fLMyfFjrHQ "Python 2 – Try It Online")
Generates all sublists larger than length 2, where the first element is equal to the last, then maps each to its sum and selects the largest value.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->l{w,*r=0;(z=l.index w)&&r<<w+l[z..-1].sum while w=l.pop;r.max}
```
[Try it online!](https://tio.run/##PY3bCoMwEETf/Yo8SS@bYKyUgNofCXloqVIhtiFWYr18e7oJtCw7zJkdWDvePr6tPb3oxcHB1lm5m2vNuue9mYjbp6mtKnfUcmaMcsWGsSfu0emGOGyZlykt66/T5qXkkAPNoQAOhYKIuOgoD3nUmIcRgcUfEc4oyDmesHyCX1dkSuELs6x6Tcz4HkgrtUo2/wU "Ruby – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 70 bytes
```
a->maximum(sum(a[i:k]) for b=[findin(a,x) for x=a] for i=b,k=b if k>i)
```
[Try it online!](https://tio.run/##XZDdCsIwDEbv9xTBqw06sXXqFCriM3g3dtFpK3Gugt1gbz/TFX8mJSHkcPJBb90d1XowIKHSV7SDSveN6rHpmthRqQJ3dZmAeTyhkoVBe0EbK9aHVS9VOQ4oK1bLCtBAvcdk0PYSdQ7tFY7K6flJuzY6tNSdbmHmBzgTcLMQGxiYuOBMsFSwjHGWUa6UsJ1CqrBfffcp987YA0uzX8m/3OM8UL76p8TW1AL@cQV5dHj5zgQupmq@CED8Ox@FbyL6jOEF "Julia 0.6 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
Uses some features that post-date the challenge.
```
Ẇµ.ịEȧḊµƇ§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///hrrZDW/Ue7u52PbH84Y6uQ1uPtR9a/nBnw//D7Y@a1kT@/x8dbahjpKNrpGOiY6hjEqvDpQAWAGIwW9cQJAcmoXIgaAESsUASAHLNgARYxAgoDdRirIPQYWEQGwsA "Jelly – Try It Online")
### How it works?
```
Ẇµ.ịEȧḊµƇ§Ṁ || Full program. Takes input from CLA, outputs to STDOUT.
Ẇ || Sublists.
µ µƇ || Filter-Keep those
ȧḊ || ... Which have length at least 2 and ...
.ị || ... The elements at floor(0.5) and ceil(0.5) (modular, 1-indexed) ...
E || ... Are equal.
§ || Sum each.
Ṁ || Maximum.
```
-1 with help from [caird](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing).
[Answer]
## Batch, 179 bytes
```
@set s=%*
@set/a"m=-1<<30
:l
@set/at=n=%s: =,%
@set s=%s:* =%
@for %%e in (%s%)do @set/at+=%%e&if %%e==%n% set/a"m+=(m-t)*(m-t>>31)
@if not "%s%"=="%s: =%" goto l
@echo %m%
```
Takes input as command-line parameters.
[Answer]
# C, 104 bytes
```
i,j,s,l;f(a,n)int*a;{for(i=0,l=1<<31;i<n;++i)for(s=a[j=i];++j<n;l=a[j]-a[i]?l:s>l?s:l)s+=a[j];return l;}
```
[Try it online!](https://tio.run/##fZDRasQgEEXf8xWyUNBmAqsx2bDG7oekeZB0UwzWlpg@hXx7qlnKtmxQcWAucw937LL3rltXDQM4MKLHCizRdnpWYu4/R6zlEYykdZ1ToWsr0lSToDupmkHq1guDl01o20w1ur2Ys3sxF3c2xKWbLMbr9D1aZMSyejT6UNpikswJ8icI09VNtGmRRDMFBhkDDhT4IraJr9HP9Pjw9PZqD4B6vI0DKgkRyT8GuzP8i9kZIP5gz2/2jIYEW40h8j0E/00QbhUgVYzB97Yo/jI8ofQlBin2IOUNwnwIv0se/40SUPFAON1jVMeY@wQoD@5l/QE)
# [C (gcc)](https://gcc.gnu.org/), 99 bytes
```
i,j,s,l;f(a,n)int*a;{for(i=0,l=1<<31;i<n;++i)for(s=a[j=i];++j<n;l=a[j]-a[i]?l:s>l?s:l)s+=a[j];l=l;}
```
[Try it online!](https://tio.run/##fZDRasQgEEXf8xWyUNBmAms02bDG7oekeZC0KQabljVvId@ejlnKtmxQccDr3MMdu@yj69bVwgAenOqpgZHZcXo2au6/rtTqIzjN61pwZetRpallQffaNIO2LQoDyi5c28w0tr24s39xF392zKebjK9OLStSyaexI2XJnBBcQZje/cSblmgyc8ghy0ECB7moreP7ij09PTy9vY4HID3d2oGUjKnkHyO/M/DE7DkQ@WAXN3vGQ4KtxhBiDyF/E4RdBUgVY8i9KYq/DCSUWGKQYg9S3iA5hsBZRPw3SiDFA@F0j1EdY@4TEBHcy/oD)
[Answer]
## Clojure, 92 bytes
```
#(apply max(for[i(range(count %))j(range i):when(=(% i)(% j))](apply +(subvec % j(inc i)))))
```
[Answer]
## Java 8, 129 byes
```
a->a.stream().map(b->a.subList(a.indexOf(b),a.lastIndexOf(b)+1).stream().mapToLong(Long::intValue).sum()).reduce(Long::max).get()
```
For each integer `X` in the list, the function finds the sum of the largest sublist with start and end `X`. Then, it finds the maximum sum as the OP specifies.
[Answer]
# Perl, ~~61~~ 59 bytes
Includes `+3` for `-p`:
`max_ident_run.pl`:
```
#!/usr/bin/perl -p
s:\S+:$%=$&;($%+=$_)<($\//$%)||$_-$&or$\=$%for<$' >:eg}{
```
Run as:
```
max_ident_run.pl <<< "1 2 -2 4 1 4 1"
```
] |
[Question]
[
Given a finite [arithmetic sequence](https://en.wikipedia.org/wiki/Arithmetic_progression) of positive integers with some terms removed from the middle, reconstruct the whole sequence.
## The task
Consider an arithmetic sequence: a list of positive integers in which the difference between any two successive elements is the same.
```
2 5 8 11 14 17
```
Now suppose one or more integers is removed from the sequence, subject to the following constraints:
* The integers removed will be consecutive terms of the sequence.
* The first and last integers in the sequence will not be removed.
* At least three integers will remain in the sequence.
For the above sequence, possible removals include:
```
2 5 8 14 17 (removed 11)
2 5 17 (removed 8 11 14)
2 14 17 (removed 5 8 11)
```
Your task: Given one of these partial sequences, reconstruct the original full sequence.
## Details
You may assume input is valid (has a solution) and is missing at least one term. All numbers in the sequence will be positive (> 0) integers. The sequence may have a positive or negative difference between terms (i.e. it may be increasing or decreasing). It will not be a constant sequence (e.g. `5 5 5`).
Your solution may be a [full program or a function](https://codegolf.meta.stackexchange.com/a/2422/16766). Any of the [default input and output methods](https://codegolf.meta.stackexchange.com/q/2447/16766) are acceptable.
Your input and output may be a string (with any reasonable delimiter), a list of strings, or a list of numbers. You may represent the numbers in whatever base is convenient for your language.
Please mention any unusual I/O methods/formats in your submission, so others will be able to test your code more easily.
## Test cases
```
In: 2 5 8 14 17
Out: 2 5 8 11 14 17
In: 2 5 17
Out: 2 5 8 11 14 17
In: 2 14 17
Out: 2 5 8 11 14 17
In: 21 9 6 3
Out: 21 18 15 12 9 6 3
In: 10 9 5
Out: 10 9 8 7 6 5
In: 1 10 91 100
Out: 1 10 19 28 37 46 55 64 73 82 91 100
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); the shortest answer in each language wins.
[Answer]
# [Haskell](https://www.haskell.org/), 63 bytes
```
f(a:b:c)|s<-[a,b..last c],all(`elem`s)c=s
f a=r$f$r a
r=reverse
```
[Try it online!](https://tio.run/##hYxBbsIwEEX3PsVfZAGSgzKOjZOIHKArDoCQMKkjUE2K7LSbwtmDA6FSu2g31vi9N3Mw4c06NwztzFT7qplfwirdGL5fLJwJPZotN87NdtbZ0y7MmzqwFqb2SZt4GOZrbz@tD3Y4mWOHGq/vYDj7Y9cjQYuN4CQ56e0PSBkvufrFeM7lCNlXyl66CgIKBUiCNFt/9N@AJvZs/tT/rBNKLJFPQVQxiBfFhMeGsvhRj@I@F9BRqoe8o/HNpmIEVEIUyDVk7BSWEjpHIZ5heh1u "Haskell – Try It Online")
Basically works by trying to build the result from the front and, if that fails, from the back. This uses the fact that the first and last members of the input will always be correct, the fact that deleted members have to be consecutive, and the fact that there will always be at least three items in the input. All I have to do is assume that the second or second-to-last members are accurate and check if it works. Luckily Haskell has really beautiful syntax for creating arithmetic series.
EDIT: thanks to @xnor for pointing out a bug and providing a solution!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes
```
Ÿs¥¿Äô€н
```
[Try it online!](https://tio.run/##AScA2P8wNWFiMWX//8W4c8Klwr/DhMO04oKs0L3//1syMSwgOSwgNiwgM10 "05AB1E – Try It Online")
**Explanation**
* Construct the range [first, ..., last] with a difference of +/-1
* Calculate deltas of the input
* Get the absolute value of the gcd of the deltas
* Split the full range in chunks of that size
* Get the first element of each chunk
Saved 1 byte using `gcd of deltas` instead of `min delta`, inspired by [user202729](https://codegolf.stackexchange.com/a/148815/47066)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) v2, 9 bytes
```
⊆.s₂ᵇ-ᵐ=∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FXm17xo6amh1vbdR9unWD7qGP5///RhhY6ljpmOsax/6MA "Brachylog – Try It Online")
This is a function submission. The Brachylog interpreter can be made to evaluate a function as though it were a full program by giving it `Z` as a command line argument; in this case, the input is specified in the format, e.g., `[1, 2, 4]` and the output is returned in a similar format, e.g. `Z = [1, 2, 3, 4]`. (Of course, for a function submission, the input and output aren't in any format at all; they're just lists.)
This actually solves a harder problem than the one the OP asked for: it works out the shortest arithmetic sequence of integers containing the specified values in the specified order, regardless of whether the deletions are consecutive or not. Because it uses brute force, it can be very slow if many values are deleted.
## Explanation
The program has three main parts.
`⊆` finds a supersequence of the input (i.e. a sequence that has the input as a subsequence). When there's more than one possible output from a Brachylog program, the output chosen is the first output in tiebreak order, and the tiebreak order is determined by the first command in the program that has an opinion on it; in this case, `⊆` specifies an order that favours short outputs over long ones. So the output we'll get will be the shortest supersequence of the input that obeys the restrictions in the rest of the program.
`.` … `∧` is used to output the value it sees as input (i.e. the supersequence in this case), but also assert that a specific condition holds on it. In other words, we're outputting the shortest supersequence that obeys a specific condition (and ignoring any intermediate results used to see if it obeys the condition).
Finally, we have `s₂ᵇ-ᵐ` `=`, i.e. "all the deltas of the sequence are equal", the condition we're applying to the output. (The return value from this is a list of deltas, rather than the supersequence itself, which is why we need the `.` … `∧` to ensure that the right thing is output.)
Brachylog is held back here by not having any builtins that can handle calculation of deltas, applying an operation to overlapping pairs from a list, or the like. Instead, we have to say what we mean explicitly: `s₂ᵇ` finds all (`ᵇ`) substrings (`s`) of length 2 (`₂`) (the use of `ᵇ` is required to keep a link between unknowns in the substrings and in the supersequence; the more commonly used `ᶠ` would break this link). Then `-ᵐ` does a subtraction on each of these pairs to produce a delta. It's annoying to have to write out five bytes `s₂ᵇ-ᵐ` for something that most modern golfing languages have a builtin for, but that's the way that codegolf goes sometimes, I guess.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṂrṀmIg/$
```
[Try it online!](https://tio.run/##7X1tdyNXkfBn61d0wg5S27LG9mwg6x1PdsgLBEgI5AWIIkRbatmdabU03S2PZQInEyDwEHafLDmHTHYXCCSEs0tgCS/JeAaSc@zJnGT/hfxHslV16761WrJkaUKe3ScHxuruulV1695bt27dunW7/XS7E5354IOP3Xa6l8SnN4PotB/tOF3xvlBItjtx6mw4xWLx/PnCefi/523j//1mYa@/1Yng37ZP/yT4b9AoPP744wBdSbphkJbcQiHsRFuMwWts@xGWDqKtwnkv3OzE9NdPelET3odBkBQe78ep3wBk6XavDU@9LS/q7MDz3l5/x5N/E4tG0O4in422l26XnUYnDP1GGnSiBB@6/bLTij35otWLGmmnE8LPIPVj/hl2GsBH2REYol4bS3W6fuylnbjsdL048eFv7EXNThv@AmjSJ6CkD8XToA1venEYBpuV2L/Y85O0UGh0mn696235jhDAwc8PfnHwysGrB788eO3g3w9eP/jtwZ8O/nLwztEzrx8@e/i9w@cP//nwxcMr7/7o8KeHPzt87fBXh7@78cZ7bx2@cfjW4dV3Xzh827nt9o/9zamPF0vu4lJ5uXJ6ZXXtzN/e8YlP3vl3639/duPcXf9w/lN333PvfZ/@zP2f/dznH3jwCw998UsPP/LoY1/@ylcfrz5R@1r9695mo@m3traDJy@E7ajTvRgnaW/n0m5/7xtPffNbB28CkwbXS4Lr3x3sH/z@4A9Hl/94dPlPR5ffPLr81tHlq0eX948uXzu6fP3o8p@PLv/l6PLbNy/f/N7NH9z855sv3Lxy9MZvb/7k5qs3X7/5@/deff@Fm99//8WbP3r/5fdfu/nS@2@8//ubv/yvl9//8389c/M3//Xce78cXHt5cPU7g6s/HFy7Orj66uD6DwZXfz@4@uZg/5nB/rOD6z8c7P/LYP8Xg/3XB9dfHey/Pbj2/cH1Pw6u/ei91wZXn7kB0D@48ePB1Z/eADS/uPG7G@8M9p8e7H/nvd8O9n882L8y2H95sP8fg2vPDq79YHDtn969Prj288HV7w6u/uPg2v7g6i8H158bXP3D4Opbg/1vD/a/N7j@j4P9fx3svzLY/83g@i8H@@8Mrv2fwfU/Da698N6vBle/fQOgn7vx4uDqz24AmlfeBVKXB/vffe8/B/svDvZfGuz/fLD/68G17w2uPTe49n/f/fPBrw@uHz195ejpl46e/rejp3@CMi58zHk06iV@0wn9FHph4rQ6sZPAuAh9B7pcO1l3LlzsKYmyPIU0UZKvmVIUMvw@CATrRlWC@mBNLO6JbeB5/7vAF4ztNK43g62AxrfuSUX6EHYu@TF@GN1jBGCv2xWAo7seVDeIWgDTCjteWirCQ9EtRF6kX8EDvIKhVEn8NPYbvTiB0RoGbRjfq87Zs86ZFRjmjdBLEhBPGjeDRlrCf9z1wgLw59TrQRSk9Xop8cNW2Vn04i0YlouLFy7hL4RaQPDKMXAAhh8ADKHrdeAQnwsFpOHFQRr4SSkMoguEMvbTXhw5VXxRwa99akZ8dIKI/iY1LpsC4aa/W6J/y4Ar9vqIg34AGdRF3mbol8SXwkLQcqJOKgCRfSa2UliAthHIoBjqqwoIsRMLzK6z7KwWFraDrW0bpuEHoQUC@A1EG44uYlAj6lUNdwr6a8Qs1rQAxoJxZasGT9Z3ltCml/j1pt/otLuxn2DzA7upv4Vql7opiVz8MuUl3qDmvuDXQT9v@RuPxD3f1dwJiGqwvFqj9gmwcdJOHSlqGsgR03ElSx2YK2SL6PYW1VlHdEvyAZ9EoYYXwzS47flhKYJCDvyHHR3owDM9Yss6Z51V8RH/U22LDw2AXqVfyGy37FBnotmmEqXbfifuV1ownXXiOv8VuCsgknZScjVaxBQ22qVG2VmDPu6ULkDTr7nIQBebfA24uOD4YeI7pS72CtdZhC8SctUV/DJ3Da5f7HupX4caBlGJ/i07ou9vOMurMKkm93ViGE1NeKaGMAQnRy50MFmE/pbhBaGCFwIlvvDCECvgtTebnoMd@cFOBLNsn3@tOztQ2AOENjOaAZisnRIMtr7rgCRLMFnvQpUWXKsiIfWksATKDNTvMdyuDDG2zsZS3d9RSMrOfR4I1SDViXbqzT7xyh2OtAj0OlA7aFbERDmNaagHBI@fuOPgT9RN/J0BYg0QM4DkHZGXNBoQiiqBYP5uw@@m60YBDVswvkp6EsigNIxixahruxPlVNaupcUqYMavrkl9GG8n3PFLod9KQWSgTUj7G4@mWhCvtVKQvbGsQahMHgx2gaQXIr7qSm2xhKoB8blL@EtQXl4FMNIm5V0cnz7YjGgtCso04eDXJ8t9@6vie4GJVIOlJ2toau0u9lXfE59kxbv9etopoVlQhj4fijGFj5VMV6SPCol4IhxNHyrdDmCaTUswHcTBLqIQv3COI@XyAD3K7zRDiN@VIKknF3te7BvNkoDRDZZ7WoeqbUITMyhQKrla@eZAbVeSi3Fa4gKgcbhkCm2QdDugk12X0fDwaQY7oJp3gqYfNXEy2AkSNMpp2gPuxWBbJ4b5I2q3FYNZWRqogfWRhYRX9gwLnwVyVBtpv@sr8q6AT0m3qC@Ax/qAE7cieUqScg0i2OEVxOnTCqQwxLH6Jluym27TeOIaExP07NwGPSFI0qG6IDsIYXxYVYRWYRJre9js3RIhLxOslr0HyzyQsNFvku2glfqo4KuoiGsgVRwYquPQsBB2Tty5ZPd/JCNHIK6jdsD49ZuyrEsyYvzVbxGSGuk4NBsWJb0lxKsHSyclRQ7jrrQXdGEsb20BSsbilk3maFqTNUvSANaC9SQALkrHWGSsJ5T9MaQoaqLepQBnGbvOCjWDVzwwmqMmWLbQOAF2HIKoCAsRStOUvOLmqoNmJ613406zBzPT5KpwSO@J8Y3WVuiTAsOGwb6E4mqlKGKlqSTGKoOXUrcC6vhJWJpD7VyyU1LEQYAgCOYPNUuvXeKJjxQ9rW2qxcMXi2AXWvy7giMuWgna3pYaxRqf/Axzd4gzJfd/fk1DQA5ChSlR05DQuxobjkJZVAmbX7C0@8MGhlxR6Lmb7JitRPQAaf4T9Lpg0lghnBVVWjBegSUmWoNMIORdLjXoTXVl/UyN9Et1DSw5@F@NRzKUNIXL0DVmMWtUVVfXoW38EPnxoVS0VYdWTFKcFAjA1WijIBzGOxJj4uuSwoa4tB3AStYUwfgqrdSo3vl8VdfWa3LKzK/zKvamfFGUoAxbWDAIcuq1VqO@l63aGayakFaW9TWD9dpYvjQD@TxTO@VRX5uI@sqk1HOqvVo7KeGVY6tNzZHfhVDnp8cQlsByeMD4mLCeMRuRuf10FPJVA7k0XDPYkefRWEX3X@j00m4vLUnYYwZSHi6l7m3tQ2WVCU1OzWiH5yBQ163QS6UZBKyajyPUlCwi/oLOQgth20twycOEiiEZA0XUiwwdj4GOFTSSq9OTSYDNFrF4iE2Q2Abh9QU0VEkVJlUZcgGhYURxVyzxYgswVoCajstKiASHZTLs4/uiu55ZQeEkt1MSv8DQtlZrhQwkfC9Zn7mNxlPU5hlVgVSgFs5Zs@amNTvULUpVLFbTA4DRxgptPIQ2ngCtqFEVC9dy0RqNpAks51AL5SeDtmkQV0dS77vCwqCFFHGSIzWjD4zg49zJ@diVciU@yFoKBR/jC0nO8ScWAuO0RB5HF01YRFGlBSXidtbJrJXvQn4n9IAPi6@wdLzP0FhcYH9Eh5CyLkHtCO8XvgzYiyWtfH83jf026HpYI9Y7cR0WBGIZYHgqd8vCXwOP8GCS383zvnETmd7Eak0azGhBV5X7xhRbqsVGJuUulNmEBSTqZsVbibEYTr5UFIFVYSpFjc3GcGhowweQBeJiqWKPSckPuQWWekS2Lqu6ak2vrdRn0j28vrIlKQBIfRCCpQ2FHIFcbSPha2n@K8SqFviVeYs7beGglP5NfKAln7Bl0Rkl7E3hww8i9pKSplMwWIoWveLFkgAyewq@N2jq9Z76hVTJzV@XC4FVaeAJpynDVU0gWGeBuXBOTK7mhyUqrgrhDGCs39T7smMUcnnNiTOKSRGXcwYYCke4vFckg1RMeP8ll2pRKVAai8osDEkSEQqemYflDWP1bKw3NVeGOP3dLiCP0qSkftmNuGotlyWQvX60iqqyixsZp/CWHxF8pRsHbb/ErJNXd1FhHtP07Ez2QrPjIclu6DX8x9CbJBge6oIR6I@HEOh@UQ3VJXUd2AlPjvIy8GTWBMQrSiw6mhQu@zRdqKxNZEw9sPq59dB88zIeZw5mDL35UBOuUHeiyiyvHVedMQ1EHJY0ITe/RlkHmvjDvh9vM@EX2MRrtPw1ng3VK94KrSwATomhqTQP7sMxcmsike@Imy0/rfP2dqkXh6QZ4pB2tytPdoKI3DtJGtNeOBoM4ivo60rbSxtg3t1ePb/8uLe8V@O/K8t/t1RZri2unz59uyiFahZHJLXO7dtp2sVv2Di33@5CfwYYmkagPyfYIe1d9wo8dkC9EnvoJmiW3KzLWRau4HZT0y8Ve2lr@c5invN5CBQ0dBAtrxalQOKgqSfmQPrnxBu1uGBkJCH2JhUdtv6yBdao3mLGR2mCwpOTMPUyOflXqyDnEozouC@mS/pJNlLnkpjq2flGJVCZXQqaZHILd99uiSyNURhozkQMwhk1hNC1eMF5UaCqxE/24DfRciflzBRQlf4FCCGkYXh4/0Q0QnpnhPsEjB@au2n2xfcgK8v60XN/jmBlZ/4ICjf80ISb12fpC/f7Tq97Qp8plSX38Te@ac1@snHyPKfCloXx2I25VaV9ptoYxSQEiq/Egk@iZJpkovHvKn6rSWNMz5bmkt4CxbZQYIbxL4Eu@H3RAPCDtmw7cQp2AX@Wm8r0WJ/Ioh8nv8TwOe@q5uNlLkPgUBA/cXrDBQBIaVdXjF5LAewOVzyR36q7Nd0jxCdRGdyiSIO0b9nQaptcvGJIXTPxmiuHu1vaeWHX13wpN@iUWwPm1Dq2P7yzzXRhuauvQ3siSBHUud/FH4Z1T9tdkiPqRqoGFsbbhDZB4RrsGgRkaIGu6eqKOx4H1c7aFE1wqxVelnBLXeyOMp9LtDFvxF6ID9y9qIPWO63SttdPUq8Ba6rI95shyWzsWFMtJEu60msi15ECkeklwc2jwDLHeLc2oD0@bax4zoayQTbRIvCEZXr6NPq@ha2@6Zx1PNLEuHCBvwqQTRYA9mQRc6nrSpr1rgfLyCYYgb7VI@Vve4RZ/XB4Y0fjV6U3VJcQhqwmLDb@LaLD68fh/TnqzXrEhDzli5CHdF0gSOUMVlbk5br9ST8M@yL0AM0TDWDGJ2XCJCiWsU7WDP7jkulLvrGmL/p9sWgiMin1IqKlZZd2ukacx4RjErpdiQxO6tqm98WkUsc9njHDmjejJipN@0U4dIo33ijCnzGQuPE0TAykbxAqYhgfBf8YCkK2nuoNZnPRtia9JcUtLQwOOhHRf/TbdCjUeOdkqFuoEM1KC7o7dpCzztodK2XHxpvwfqrB9r8h2/TXBhRvf1KkmuT3Z@bfMPaNtpmST653LndMRjHUDpqgdRwxdkrFMhO3OiRqKNkZxQzh5HloDL3JWLGZoZTo9lUkzx@AfK043PVFZ9F6TckEjXFWU9Yaiw0SvZAyYiOobCXEv91ScaXoGkWpmIBgLgxDbEvGgIwzG3hmZX0WeuRDExvN3U63RMQEAqKFxsSWWOIrdESnwDsZ0tqwHIhy32/JKCUMsiXi0tzTwLlC7UkDO6xZ8Gc9iHDrhNUmWs4YCwrNtoM@pDPG0LOirRimSqo4D4LRSkojdz2laZC/AYuVqYKSPMt7XxzvIL4xagwmaPVLfugLxdgM4rSfCU7hjzC@RACb7RmV8wVDqWWLcFIAtqx9IAFziqKGDZANVrOsK10d0JJHhVYsxvtVUzXzh3w@KWC@AhQ/8beZIJcxTKpyxKRVUrgjdHW07KwhNQlyrvrq2p2WDSgCGTQC20NQle0pFAuJ31YpXLKW4zOQkhIdo9EWWwG6l2EgSx/NmJI6llDZajR1pKKMUAk7nS7onTQI6/jT2gIUuOoi/ktu/Yl3CGv2PLUzqvb/Gr22HtPC@EI1gXUQn6Thz3uZHIqI@5JyXzPXeW9sgNEGmSgmIgKwibAoRkYQDRHJ2DJqQm9UExGQDYM1ywGqKqNXPIv9WnRBO7RDq0YNMkKSjWg@ogDtsfEcoa4BewfJjeUnuRJI9J6@w2pMxIoLvw51W1PboT7tRU2rHbAQvcW5komxGZ5HkLa@TbGLTQhEINtQBo9SJZZM5zWBCYGI8Kg6LF1ItehYLzkgqllH5CTOERnZ1yGkcgXc9nbrtPk@FEmPfhM7yl4sy2jms1@fc5ZZEZS@lVcMmFiW4wi@g1UXYvB50AAYOQuJGEj41muz40Z90RXv4UKFKtUrOzv5SybicgdbmdHJmvrNwIuGl/nsGchs22GYo9iqK@nweBGWjWseHW1ufKUPMCfJmqJVr8i1yCcaNQLqr8axKFj@trxemFJ4swwexTUqsI@FhGcf2II51Jj51fxlTP7KACLPjNanJvGqAKrJfRRNBWWeA4gWDIG4JyCMW305tEXj4BdpdELl5BgxiucyLuXBlgyUVPIOImg1YJjj7oOyUwcDTQXVitGSVALQ8DDhEKQZVR/AjNbG7kPRbtylVxT2XthLhmNfh6Ooh6NNcyamyIsk4rAJi78oJVMl2fa6tntA7LSj94FMMfounQE0zdIr3iWz9kUXclBLONO/xO48BiSDdIWkb5YQpmibgmUYUHrrxK6qNKSxjKxZlBuwJ7Z/6KwTznTSpjVi1eQEiOsfAGQ9mhPONyqgLxPSt8pT15hQu@NjhHIDjmRF2Hkgd9o1g5uwSLmQH3VnBI@tTho8lhMTxfPc/w9dm1/o2skj18z2R3gr3EiTKdJPjnJaMC26LE0gQT8EoIjYPbp8tVizzxs4fHRGjKN1@SiGiDnWjHE/WZjdhx1nZ7GjrOyyY0fWGVF3RqjIRCF0ZsCbHe@mwt1GBLupkvOJYBsVujZtzJrJ5TmbSWnLDcu0KmLUDCqGnZUDv2fDkhG2x/4caWGBFRMkflpvBq2WH/t4Xi8TFa9C9O2AeD6zl7UvMlHyLHUDQKAzDvBUYr/d2fENG8KK2jfPBipucYs/TvzhEP6h4H3zkJLt0Rk6epBXC3UYKVMJxGrWIccOIphjKpepFpg80A7DDSA6hITqRXi487iWK@e2LYuDquVmqAu8@cRtgaCb7xjkvE68O84iVEduCFH2NJAA49csd9Gm0kyQLUynLJYdDlyy4MhLQ9/PwQNFb9Knc45qTuOAjzAyBLBFAZdNRpUkMVedQ2ErRZ2JFSbf0Ak1mifoxyKztewEtPQoBXLH1O4V5ormoUAeQOFfig9AB6/49AfLm7W4Yb4hJ3ppzP44MpWPn@ZGTWvmjInCzsys56yzY7kmpXE4J@c7zjJlgypq2GwVlZ4zeqnWxxIYE0skpqOijD6PHkah7PjjnTywLvLTgNZ7c/JW2BhBLcRhx2uWhKdxs9MJyURSMHzESLGr3UviYCW0vwGdu/wwsckJ0MK3YHqAasqimchhleM9yTqtLDcTeoHhj9gs041AglKmRCduqigta72mXft4qgl7HUZvmacHVy3XaWvcecYVuYBZyS5fJGUYiUGTvPmAAhaSQyxJjxyBWcsG9uevDttJqsllZpSEUyjI1aN8jy2oYDInibHr8CeOhraPE3e9JDHNvSwTHB5X73oxd40SDMj7N1atyb5ajco1uWOhO9T9sKA4fXqN1JaM4@3SjJmDdRkW84GbM01WgzJ6Y7r506GB4qSHCq39FntIrJaN5AmqDklvU5AAuCx9MTjkESoJWQmixI/T0orMz7Cul@kLhgtYwgu@lAREtJA73Eey28voWA0i8kDFIOHdeou0HDpgUdERDIFcoJ3Rak3m0PA5h4af1KzIBfnJOHGNQFrhJ7RXiONbhfFi8UswNIUBh1wQpOICMQjxyCmjSittkZ3AymlAAPXEh3pS765s@WkJcZM2Ycda3YKCpnClOyHtXPAjzQY9KjYQjat8DApUJIQRPgbBt4wgp7UZwbG/gBaKquDFXtC4IEt2O10RdSWqtsCKAydCAceIcM3QpP5TEkX4lI09WybMp8RrdCfBotpjFOVIS4qS4pNr1AfVjc0DPZGmFujFaQTM2cSxskN13QbzK5Z13ZUNdSwbOVIVmJiTEh@ESFxJVK5k7UKZbBKidempAiOIgy74a1lwbToxkgye4fQaRi809pCJNXPgSQb4b522EMQglIt161NFRPKtyGUdfcLJORBhDkeX3y5a8bDdWOJGKwfWBxTCXCoevFnkCEFXHjLVyGD6ou19dRxWfKHIE6Bjpkj6SZH9iE1f81qlpdrCcCWqYhGnm4XLFYsYP44SaWpgThhGnLjsVQBuHEcUglIH14s8B3HJapIkMkojr66ZyA1RTnlsFF6oXBZxNRMcAW0dC3T4i@IH2fk8KYmXsiT0IZJ8YnJjI0OwjDEa42rGojaEJCIZppGPZB3Vj@hqV3JqoBzwMiqA42W0q5xxjyGD5cQLbWVpEuIH9NERnfbyX4gnBT@tTI2xwoLV2JYkeYxxWL1jRaz1lj@xducdZCB@8o4VfXJIcUCBDUWg86SzyLEwVTFn4z4IfVx0VlecRfW1uLxapKQ/XkxBbMXlosz6g2@WnOId6juMtHVR9QoD4VvaTyMCa3SayIiVNadmQmdNzbjRTudO5Nh77y1QEDWxr6c@yh19qdoNlBomM@VbI/rGG6R2FmquaZEAu7LhlzDcOWOe1b20hKsW34sSNoLKzgXf79Y3yYo3fH0SzLTg5Dt3zIG8xnaP7ZoaP8jDZdmDSuLFWcO2U5sR@oMiSR1FPrGZw@YLElSTCT656j3SNizCGg0rs8IqEEgPciqoT6zpwm7mdJQKoaEaw1KJfrHjq@u3e6nHQs/JhMYpnWwLXsTEsFmrQ2bUkoicF41OL@KFEEtSfj/rqGxmDMXbjwrDIjoWexjTskC5chIZZKYsbS4nIm6lTBTscWFX@bmF1FpIV0RkcZPHr2jTTRBxM2sjXUSlsQSt2@yB0pVrqgosTMv2WoFxUT3KNGpFwy3zaS5KybahNw6FHEUpU@KnT2@Y@ODLxV4nDWinT3ZoXm0G8uyUWmzaKyiBgkwwicMdsZryY9V3RMcx8rFpL9bIIQgMb4mz6Gpkjdrp3OKjwBc4cYnQ5MSq2nrWJwDWafiIr2ed7NCQjSxaNbeNt@gcMjcFHzzQTa0KTtHSBkZuaCkj6PoXQHMLpLlyfiiwz5aRO5Pf2P5MdmMoh6bhschmDMtUWp0vy0kfNmk1mbruyyapLa/d9koGCPchzGaZ@OmE6/GhZGDmcjy1N8c5DmNJB8uhrI3wMZFhFsPQNoPIM5blsApw89bPsd8KdqXLr9NL250krVurn3XFk8pRp3ad3ZoKodTePOlZks5IvYW3t56z8yIcY6lxCpum2TqztucaSV/ksSfpUZTuS@op4qPRUWZkIO6EIe6lg1RKe2VyoPFRqFrGYzQfQkhEEKjlNVSAxgh2hCQFm6LsYH4wMXjoBVh18CYbtSnCQozCFNghCtBEIzemjLQ6owtryjxLCdZyUhLKgFQVqx9nA0opflUXcWXco4wkcR7uR6m3e28cdygY3t/1GxLWCmUlHkSq5DqlWELX8Lpyu@PjUI4ykcYJAXOO7AhclcZ2J2gwVCHzDf8gLdAQ4jtzIXTJhzeaBMG6iJbD/iO7mWu1aH7/tAunRuFsB4Vx6Df1kZ09t5wdgXld1sbPWkjuQRyXVWJIQcvMnGWnv@6MzIAhD69aHGj3@YfVNOm6GEFaI3sN5sI4@oTbVGOrxXsGomrufNtUKp2pWzVsluJelFgbSVZVhTdpsVrt4abLjhXNiCVrUnHE4XC626o44EgVR2nTkyvcEvRbna@0TjVKNWAkd@AO14v4PP50NpuVfZdwiDzCCLlupOJ17G/Sd4Bgcn0jTtZjNgfBmNwb2ZSJAnLNH73LS3CGUWQdssd01QhQyLxeFEl46ZPBAO1/zpmDc@dsDnAfVlJQTOgEmsLOYZ56rVY4aTbEY9c6rJxtrHZTMl1aqFsR7hytKyOzeV@TPDX8SR/IxVBvtVbGTXPtUKBvS45OqmPZ/qpa9vYgE5AJ2mpSD40A12ybJzNRJaSc6xqDlagnivAM5p@47MnMNb2MiwO5lX2VFIQXY8C2bAF9rNN0LFwC3J1LPHQYZBp3g7nIWVeeHoG1ljkE2g/8sClW/JaPgYMU2Tcgyk7sU7CcCiYFUxDpeCGMihk2gmAmr0k@2zogZgSP/o4fhX3Jp3CLjFV6mN6IjM0y7bPC4Lyk19O6nRQuc2GCudV1OpbMylbTXhA4ERoeuBC@W3IUdfhdkr1D8sHmnd1kWG6dcOVtA5pmCstAWNITWBrVUZ2wieo8p4Yr5p6oNtmzjNC64YTM8O6ommYsptZPyNUFv0@x0jDzg7HtpR4ypI73Y3YE6Ygk/6F2dXGWAX2MG/NdDWFawEQEHCAPP3XKBHqwMibAGzE@sAj75AUjIuQS2ZDNj6WNHAKU9oDHivEqE6ptueC0j8/EYaROIHo1TlGL5YSmUhWznUn4ukpw67V8J5IQd0dl8zcVx1Rb81KRqhNHNjoK4By2WbgPrajOjNmxyraurVk9g5faE6d8s3op5adwRkTzc@CARU1anrd8oFrnWqS6Wc1l5kMerJNwloAVc4JG4fCLCRskSUryDgy/Ka430c@8s6kTWU27HaVRqd0oaRAQSiOPVZn3FrVLl1@fcY39OxmYpEs18kv93SdIaVi1WdrQR8SJf@D3zJo16bZCb6ueXPK6xoEHftn1GkTIxHgbb/2a/K1xRIXkBEuPqpZNkCBv410Dk@rX9LcVq/Lywqws8jVCjhkFcBUbdCIvxp5TwtuxuJRbpT81C9@QW924rcTGJoIJKMhlw7E/6TgYDjQXFRRi4RIcwVLBDw3sT9h36KU8dCJLogCsokWnyLB5DSzey4WI8ZH7O/mPpK9UZoXHC4B8w1ll5PrhA3fDuTTkN@UW0MCZ4LphmsI/Q4672E6GrpHIxP40aY6A4XMA8oWZMiKbIE0VQsL8W@@ly7PH9qFjCVcrjK6KvHyEMkyxIGVSJCEfIXehyz6KbmZm7a/nZtbG4i11MgvjeJyLOem32z60cKNuRnBue2GrbkSW8jFBlWEHlpy0TW/BGeHKAnrZycJgeLf8ei5TmthJg5O56zbWRHIl0d1G3ZRlxh1T/8IwPCophEi5qqioCE1WL2VXoHvAyGpDRsWC1toZljGyvGTjGEGh3VAZi2h2EF8Exna/QePRQFjIb/OxNxNRJ8DMlSVC6Crf4XBjY6h3HaTSxrCEIG0hj@Sox/c698q6iuo49ZkiuvMUsPNx52/R@UHpKoqnHhj6umZ8fXjo6yp9dW0fIhKvAPEW/igZrEiPId3aEvLNHl3OejOl74gOHlNhE1jhywEX7ckQdBq404sbfk5xPlqKmqLp44UftAU3HlDc46HzZI28zsPMMCc4kIfrtE@DLBRFuIqHMgQoX/dBBPj6MQ0nzn3X8lxlIP52Cf9p@9DnxI@Yj3joVBB8BkRngTdcQLH8TVaEwMTxf77IlssHLqQfgAuQ91GAV0OuHV6lJliQt1po74080zIZxlgvjbJYYzNeQWZZsxhZj9nGYRH1zc2v4e2u4Q2yvOSfclNMbqEZftKh6@PwCd23T@IRe/toRqBi1rNh/OIQRAlNBlVSNIR6RGhK4rxBMxFlgRYQ9DKDj@nULIjlVRHEwSvZ6ipdt7FI@LiAa54kF4l6OSuY5Fw5VcX3wkISbEV05ZsJdZbPKxFpVcRIGYxJi6GgxZ9pmlXxa01nrDZu/NM5MobXKtg1lMjMJYy84DJrP7McBXbsrlbpFpc7a69tjAAi/Los0msr2aqIeZTMokBhZnfQCZBVH2rYeQLlrZs8iM1lD94xm4a@fpQXb5ongFhK4tSOOGGPYW8js5UPpdDkNGd8OSSPPtP1h5AV@sQR3BQ0qVcTWVC9nNDQVJGxmJWjStXEzlOk6ieCVvkSUkodxjeXqjSgFfpmkqcX@eQNWNPOy7qyTPmKBAVDc3nHyPwtx9iQKljNZIDqekGcOBvH3vWoB60iYji@KTpg@MpIOzu4cD@sUaKNEtHVMSxBS@OgTyQHRUpKgz5VCdLO7TAEaRyWU9@UnDJZxw1hxWBB7TqcLn4CJYALx7aH80CcM@IJmzs0WFURcfYLKVrxjOawxeUd7j9J1jOJxg3WdVpvK2P6eA7RR6ArqiDzamzgZ500EYWx@eKNVOTjxTRSofWigNw5IBrKmTd8p6ZcBTe241Kev2ooAH449v6JCGPLD94sylMd7NdiZK5i5WJvbpe6jdhLwnl77Mnwob2iHNd0/iWm8lAd/pVRqa0gBO5LuMKo1OuRX6/rPUdei4vTnBmrIO9Q7XAJUkZ0eUrikf0ylPihMHkyCFzymgkh7KwPQzXlVA352JmjYY7XbinHeXj3c/DuH4d3NUcSI6@VO14KuZRj/T07FY3aqc5mtzjuGqncpDeTdk87NY5qxSzWER1XH5XOKbA6PucEN62obV75tbE3IAlJkWxYJqxgSCWbafnUqblpz2nnJOOz28zAbN5yNu489C3I3zf9UWix8e83wRSC/pFwNAL6rzi/NDAsf5uqWWeuztXOAo1ZQCIeA163QopUXMSILZmhDNjyxdBWl4W9NiJJdjY5thLM2GTd/ytEMyp/uBJR0tsMqfecNHRbrCoFFrIuhLc4/zy1cADygWrp6B@zR8qGD2ck0gs5PxJbdWXhH0OvnsgRLJz1Up92QH37eICYjw2LFyW3itn618@Ic1iPPnKfOIJGtr/Cp7MvS3IYfmycFyPwIZMsp7xCMASMGPHupX5SSdIm1LLSCnvJdskdkeTfuA0pG0UofSl2gui8OUPeVStCFxElbpLhjTOL9uXBvHGKnkiaEzFkorBQPPhDcX3iy9tXV1YKCy58gPn0j9OU@4Qq9qepyKlib05RjBbxXO6tacqBsawKXp2iIE5FXGx/imJrd0ixnB9RahVLyexWFg5vM@Gy7702rvDQhgutiHXIrHMOuFe3wMh7XvYoWJfQD669PDV@vk1P0lC4vBGY1oarGedV2oo1Fu7QvpTCr8bhPr784NrP58kcOgvROduXVf/U1C2sRSq9p3ti0Sv4vfqdiTDmN5KOg7BxPjMDl3vOKbxpgjBtzlOWsvq0E6RY/e5EJFYnI6HlYRP59q2qh@375umXiN49QxOsQo/bYzw3fjADIp2siM6JNfwgLBtHA8S1D2V1nw1MQXuS/8aMIovujmUNnpt2SOsrNvHG9R5oItWWN78/hWLmGTyIxI1oqxSpoJT8PfMZynTLDfezH85rLJtIfzCd3lb6Os82FGEthLg5zzFBS2H2u8mdXmb/H@dJB2elPiioXZFOCqzJXbH8EqtoSfXeCURGpzbUrHF1@skx6udOjjd@PBWqapUOwJWdXm1ERLxJRDaeP/WQAo7t0H/dRvdNwDBbFKpVfzo/rUTnMWy1hNeN5Kul1rQVl1fkWnXfdfWhBC2Pmqrdz@ZIBd2loyh9egLJ412Lsmu9PBF8p9flAlszjj3rpgapgV@YQgPn3koi8Lz/8hR41MligSNzrpMxfmaGPolnhWwb6tWZbKhFZUMNrv7ihArc5eAMJ2iZb2WydIn@lXGNPIFK1d21ut6XPfP@GWay6l41qKEJUw1EXEMmGx37Hgx1duN3MzbdqqEiBtdnMZlItYPVD3I@u0En7QnpZ6dqQzudhhmVibWWmTUIcTCBqpEOM1XB5yYf13KdyflHGMWTE1DFLSsG/9xUtae9rj152Sv30t9PLUCKQZEHn6zToYhYYv78dHgzTaHYe3OGLmO0NvYewxYI52n7ZKbNsAOWe0P@BKnYS563pl5Hc9EHJhBo5moRSXT/makaA4PCrHExVs/tPz0dcuNek2ORt@eoQkGHIq2@HX6MxsBSBpDyHXDlLk/bXHTjhMaXEy9YNiyOyU6uqt6z/@2pFQyuXOo60B2MBkb24Awja3lPcfSdqVqfXdN7yictbvdlXM9ObeyDEWeoi2jeS5pdDOxXg/cLs9jWcRN7t4wk2lMRRNQblTiv/3AGGhjGwIrOJHRbDqH3fjuBqEVjcYnOfH2LYHko1@D1WZeidD5P1uw/p3dUGsw8NFUXnDwJBW@TH75YrBm5KNCjkO0U@hSkHmQ/nqerwdBv3WllNZxJqBt3oObpsMqziOboPFvDaSXw4mw6fzSHi6XqeCYx0LOvWfniBEIXgT1c4EvzsVX4iuU92x4d7P/LbJ3A3m7NTHNXTqjFzf1E82JSyXU8d2eWtucwqRj5nXifFHNC5n1cRi/OsinJl6buYkbeEIXlX6cdPFLHPHxrdcxSVsWsTKJiXp6L40g7i0qpON6xjL/Owi/bk9ToRE/2ttCN5ppupMH@dItyvrrumM4usSezqZbcXEcj1J22@Pd/Pg@qQ9l4jqf7ykmV@/DibjdXrKY/@ZHpnKvjrjEUZtKOVk6vz@LzoCgFoma6@vZc4/yb0BqZhQlH12pfyGD/P2byF41f6aTTNhadu9k151VXnboR6wh56MZ0xQ32fz2/JVVf3WnKuH9z4g0l0uHVXYnq0RlafM@e2q6/ehKFMt5HVHZEKgut0AyQakrONSnxx2aoiphRRRLl7IHdPdSb1Zpu2LdP5Mix7i3XK6mdyXd/89p1HOO7xHhfcf7l6TTHnmrZa5MsF4cit7j0pQm66lBgnKL8vWlKi3hDLvuVCXjWuQoVwUn2GjmtFZfZna0FMYsbZnHBJ1Rc4nq4PmstaD6@dXzXjGR5bm66RRy50tvLXz2Zo9P0Llz/4zw9nXyzAFf8n6bTMb12yY4dMzWMOar7E/QzdeSVyzw@AS86Mo4L7c2@EBwTGofGeCsIQ5GdeMMwG97987SEjaC@Kr5RsrptagP2oYCLnp2/3@istsQ25o99w/BKnZs/@nMa@/o8seOOkIjOsXP9CVLlqTd3qf259N/PEMxieoBVzZdmdUrJhNFeU46y@rxQwmTGKA9fnBfOdk9GXRy@NSNOaGdGdWpGTJwAgrEtzquuXcwASCg/fmKU@irQOi/C5cG2vD4QNetM8WsfDsXdjvSIPvXhEOzEsobfmkITGyTkcZlhGnrq/JZ0WBz8frYwAB0HcPCX@YXMJBcx/XVD/TZdGwfT76UTHjwF6kVyCBy8PuMeOoa9KJ7oIqAZxLiEp0kY00szYVpWmA5@PavOUNvjeH/SbKi8XRV5/ueThXaZU/XR5esnQ2LuQh38dor4HOleONifwCqUcV1yGnj2/PxGhtfoJHJk4G9zZBw@e0wQ/JTRtJrSEKHpo3/HHVLuBgrxjVljWwQdcvZSYJe8oYFOdFdEKiV466Ve6EXGSv3w2cbUlBte3A4a256vZvxn75lRMDItAKdoSnTTXp14S9Ph/4YXTGNJoc/F8PgcPtucS1OMIFcXgc9mA4yOpZ28ipPT5ctZFO3JOp6pYJo@GLugJT3lYDh89t6pZWYmlTAG8tWp/V0UYD2M6r4ZWrEqlgbk4hUejEh69o7LZrHnVjCJRlLSnt/DZ/35aSeoqNRO8NPWTq0ZyKDDZvoqmh3ppx@KBmsFm2DnNRqBNYRuvPOhEA97DS@xCIfza9mhwC@jZdszeIFx1Ywuoz1XxWfqVhsZoDQac9tHg9JA8e3pUXSavkLw4FznVIU2mhdazHdno35oLp2NcKZ@klaCROQsMVumOz@p@Ds2@zPHGUyUimfPCj84fDaeoQtLbyGMQyAcdzopjEKxT2N15n@dgYby4NjEup2wT6Gf1rbQ4bOPzG/gp14kBz78zFi2@6/P0Yg2KHk5pP5jBlL5k0YqLsPjPdk9nURtRZF9eI7L50BVD35ma/eLOQrSoOQNkUpuqf2YBFttL6PEX/kQ7EdJFw8AaNo7s@gSvAL3WFtD05rJZ0PnqtGnglVA9w2urI2KnMCNQ@g0ghP6Z5r@Vuz72m697SSWtJ12TPP085NZ0yPQ3XUS1uy0Ypq1d07GWi66d39024k254wgP30vZ1IaHwCpN59@NL1Acq6OVdjGi0QhyFwgqop/aobJbxMWhw00QBS2Yw6wj8JwjOgM9JOcKQiSetfDlKjQ8rqtxzos4uPtlzFXWY5nH8@R6SqMPP88Ox/1S0G6XeckcZiQZCrG7pl@RR94W7CqChOjfX44NRYan3moJok@IISqzKen7stbfgoCu9gDe1ph2Zoei774TWEJZxhXMinqns6Gam5ZvvujSeLF5X2vWqITBXSrm8GNphgZHT2RicfBkmJ/pa7x09KSQ5r8CJM27vjGjQeKfHdWJS0jsXUgdpo3HHRo3l7NGBeTBGQ3kWjUSMHc8Xe0yplTaPYyJykWcRrGg7VWwna6ciJR0d1Iewai6RddcegbbLw0tRKIw6Yqn8xn5HDiYLsvTRIwauSgV@XS@fAk0xfbTM0SrGceqc6L1tNUevOpgky5bFXhhbumPiE2xqR5YaRJM3LDaviC9Gqfc8tT@I9r32K@q@J3Dl@rnCDljDX2O3hTFakYhXPWAATrzguFdbJAhAnD3qB3x8EupjkjTcNLqgfoLYXCLRoBU4evTRjxYRNfOzFxx3pjHI85fO38zLur7MdYUyi/NCNK7cJSKBsz9iqMTeiEOxrhjefmGRNlXJm1ileEiST8dBWCmZfJDO0/fO2YTBjz4aE0zATtPVmcBLMH@ATRjkI388HsRlvhmvXsEV1vqrB15yrwsOOlpeKpU5VTza3iqf6pXS3RmeMf9E3CGuf1ueCkEwVqbmjM@6Be/kpu5EEXPefdeO5WsjJmMTcBb@G8D3Zo1FOf3lQWP8Yzi0DMC77frW/Kez1FXmBF4JjDmNl1Sl2baS/Ec6l23hGWd194eGrcdG1QCFUtaUcwjcGyswntLZoMT/xoy2cuZ8X41t2JD22hyKc/LqavEzXQzHr6S1zufOwJMDNtla7Fxycg3u6FaQCrYor3g9VmQ3ee5WmKN4NWy499s/Zfm6Y82DeAQpV9apqyvUjnUzi8cn7KxEkldVmI0v5XPnUSHHxtTP7lIxr33dPiLn7q7nvu@/RnPvu5zz/w4ENf/NLDjzz25a989fHNRrO1tf3khbAddS/GSbpzabe/V9Rk7jlxFTSOz8wihuJ54Pve@wyWPjstOuMCB4njoSlwkGWro8OujHb4jOQAl46NbbopBD0PZ9bKzuraJw3z@8oXp8mgK9rzi1@@90uPfPXR@7/wUBEnFXp3/mFuY/3q8a/c/dinHnygqCNgrjw2dd8Z7EMhze2XTzw4rJt0xG/V0nWDwlfn0b3zerfZub2TVCMzDjdviSiWThtsNqaWxfl77//Co54fdHoGGn/aPq9WSVe2ZxrBHjSD3zI46U6BroR53FUMdukOmNpPq3DvwysXpx83F0Heab8XdLp6kHgJdxT9am@3sbMZtc1xs3OScbNjVLx/spb8KjVlnxAVvlkoXOwFjQsqJ/m/Z5CqOx3Ma0OiC8m6@IOkCAHdkGmD5F@@uW5cullY0FzLC0jFhRdluiLi2OsrMTtSPe3I/AYHv8UEB8M3RoiLNXilihdG6Gb42cT1paPTJ6luI/YxQ4S4Q8WC4ZsXFTcHv/jrc8NXvq9oEX3vI8PUqmbqVx8ZptY0U//8V2WqJC@0oKth0UVjfXdtAb7xUedVy/XgtcmVknXP89r81FPb263Tb4EeXWFS6ewXazU3T2GZmiqBtXDiD2mjsroo2lJLQ9Edt7TGpSo9c@5SyoWXwSpuM7Q0tEjnLM5811whj@Pl5k6o2CNcmCfyEmeVoNqQ0DsfiT4x/qLoCSubuaJJ9A/ZL3Jrf3q6WTqn@bJSEBmEGP0TT9wi/HV9B5PMTfzq3El1Y78VSHfN4fO3gIK4@F3W4KW54z95l1wboYdGX/e@JbbdtvQFQhf8/jTenfy8SjWzu978zQlERPUqZa9UJ61DEtSjGnPNbGwMXbSObrtcHJniqBRcN9sGaSC76MGrJ1E154CpEVpzfs29Mtzc65lrFAU7Zmv8zSzVwUOioQ/4o606FExSL0oN1T6faq3m9GJMEGtdy8iI9uxp4Zcf@cqNHqLWZYujp76P/W@3Dega1tHyueuE8jnz0bMMjlnKUja0HJA1A4RaIQ9ohGnx9b@WA2DEoM9edckC2KPIGZPxo8vXbj3rYnrSKQIOn/8fZarPpdPm2e6ZW0Z5187wwzz/v86gP14krY@uL86srXmprs57N1J1pRy0Mn7rM@Ome344ruWjLA0dLiDk0sLd81snnM//P@W0xXFR74GWCLNDJGc6Onz@xjv/o2qHMdR40WhdYMoZ9sNXW/wPqTF@HVHloXsoPqKj299NYx9ntzYeEzym5w5fgPGRr5W3O7ZW3ywUtvtdP5bbRbdD/Qwmy7CCinyFdrqUbcN3mpcwAzCn45XJgDHzpJGfzQ4zqWUu7LBStKIxvF6zE7rZELsEIZrv9uLt01ZNWw45dZzIuNcjhi@1F@l6Q@spNp7kZuA/zK8dcpqhT6lZmdQ35kdqyCOFdJjMN28pGZ136ZnXi3NtZ7OBq7ktLKb4vMvncm8ekNrkp7eOTz79s0snfTbGWSmKfbUL/fYcNcBxKmACaYkjBPbdfWPF@vxfoQfs4t3heT1gLKsHr2g@SfeX5dyRxyJBTKONcryG1ZLNPlM1I76dUyIYXHtiXXVsgwy3iRnGtddq2eTbPUa4Oe7AE3Js6J13n56G6eO06DxY07ez4vRLGOuJ3/UotyJNxMVDTK1UWilL53zxAO96R3HKF4d4hB1zd8gX77/AL0Rg7zcLTb/l9cK0bhEQlkppWWIqYCgOVj7wkbI8zJRlqgJ6BHMIETj8P4i2CPzo6X@rfu3g1wfXj56@cvT0S0dP/6S2WLWf7ypSIcAYh0EqCv2kIl/GXS@I6eXltyv8NohS/fYv8i3eR9r0G/i2dNf6ylPLdz3RXHyiAv/Qz6Wnll0NGPXwlhKjmKhWFYsWQVh3vfcW/XkK/3WLNVExvDgr9HeNkoAnW/LGGzklQxrxITN3KnGL0PTFp1iaVUNqZceQhnwgKfCD4EE8sCQ0EbrNA6/Sqi4WZYAYk14i0vC/J2qLZfju5gC4VKoIEEJUoBdDscejeMVYxNiv@EnD6/oc7ET74uhmoicRXqQehfmIE0gh9rf8XdHfaIMQQ@u7AahB5OxrT1UlR7K/ASs1F@XK7yU7S8iO5p4qje8cd6noMhWqlU3FqKyESjsX/GgYagwhWbKltjnNWmxUkN/cijw1eS0WD968CypS@JiznP9foQAm4Va9l7bulJH6Bb5ErVgo9BKPJpNisfgo/lwvUK4QSsTvtJyzLWD2HN6G0e2lNfzyJd9rJk667TufJZhu3NmKvTZw1on9Jk5Y8E3lG8n/L@n6jaAVADiiLzu9BHqzgROjaB2Moq0cg@iR7SBxOl3SRMl2pxc2nU0fT14lQdNHdhAn667yMbg2ezDdpo7Iug9WT@iHwsmXNDAlyZbT7cXdTgItFETHoCL@tzphC1nBTE9JxRJrb1iut1asjz5y3/Kdjh818NTUlsWM75xFdnPa2Muw4uEr6L9t9iEfx44Xb/Xw2Mu49qUWPAYPnu4PYpB74qepRORHO0HciRC/sETBQjoGz@fPP/hpp4R3tnV6sfOFh4sJ3hke7Hgwq6auk3YAaf3Rh3Ff@LjmbXdh9gOKtiR7w6K8dZLMNOlHUJAVYPHOY1ABkiFpnu92UT95kfP16OuIDdlEHSbun4IXHkPgHQYBXm/kRP4llCNDExoWNjAnrh0D7I8FCYzw7TTtrp8@vRWk271NVMin7/GjKEgeCNLGNrTTaR6lwFsbBh@MPXGUHJRM5YmoiFqTN1aSfgLG6NaO65x1zqwTVWAo8Z2H@0nqt@/dDdISKVjQz4gOZ2qKpOBy1dXaemEBkNGHDdDCrSK8WCCFjWOYrfzCgh@aUD0NxWo9D8ofwiWUfwYsIjB9rSbVTpWCb3iMDdN16/rSFmIx3iy62JUZbIFG9QY94oXvzZJLdVNsGjCGaRg7pmTwewVvHW3CFAmFlu8suhU@QldC7tB8fbNIe5tmGXnmArex8uhIELzIWt1ejW/dAhfhEkYVT8j9PLnF2z8Dd4jlAnCYOBv6wEcai1tzypr/M@uYAoO6nYim1BdWAYlPipSQiAesLeBBhiv@4ejyH48u/@no8ptHl986unz16PJ@kQORReSM6XiUdiqiYaB1@bpQ4Nv@jDt9kPuygF5fq7l0matb@OCDD/zeB4P9Z@LB/tPt@7dO/80Hq58s31Fe@28)
Notes:
* Only work on some old version of Jelly. ([this commit](https://github.com/DennisMitchell/jelly/tree/630c34e6e7b1952d0f593b5355fded47b8ecbdc1) for example) (where `g` use [`fractions.gcd`](https://docs.python.org/3/library/fractions.html#fractions.gcd), which have the result sign the same as input sign, instead of [`math.gcd`](https://docs.python.org/3/library/math.html#math.gcd), which always return positive value).
* The TIO link above is Python 3 TIO link, the Python code consists of Jelly source code from the commit I mentioned above, with the exception of everything (3 files) packed into the same file (for TIO to run) and `dictionary.py` has been reduced to only some lines. Nevertheless `dictionary.py` is unrelated to this answer, as it does not use compressed string. (the `“...»` construct)
Explanation:
First, because a continuous segment is deleted and at least 3 elements remains, there are two consecutive numbers in the old list remain, and the deltas will all be multiples of the step. Therefore the `gcd` of the differences (`I`, increments) list will be the absolute value of the step.
Fortunately the `gcd` is signed (see note above)
So the program does:
```
ṂrṀ
```
An increasing integer range from the `Ṃ`inimum to the `Ṁ`aximum.
```
m
```
Modular, pick every n'th element.
```
Ig/$
```
Monadic (`$`) chain combine `I` (increments, differences) and `g/` (reduce `gcd` over elements of the list). If the increments are positive then the `gcd` will be positive and the returning list will be left-to-right (increasing), and vice-versa.
[Answer]
# Python 2, ~~104~~ ~~97~~ ~~89~~ ~~83~~ ~~71~~ ~~67~~ 60 bytes
*Thanks to [Chas Brown](https://codegolf.stackexchange.com/users/69880/chas-brown) for saving 4 bytes.
Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) for saving 7 bytes.*
Input the list by arguments.
```
lambda a,b,*c:range(a,c[-1],min(b-a,c[0]-b,key=abs))+[c[-1]]
```
[Try it online!](https://tio.run/##Pck7DkBAFEbh3iqUM/yTuHQSK2GKe72DIWisfjwK5fnOdp3D6lLfFZWfeZGGQ4YgqvOdXd8qRl0aslhGp8S8lVgjmNqrYDm0jsvvW7/toztVp4iQgrQOfkAGesDf)
**Explanation:**
Since the removed are consecutive, it is enough to check the differences between two pairs of consecutive elements.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 11 bytes
```
%hS.+SQ}hQe
```
**[Try it here!](https://pyth.herokuapp.com/?code=%25hS.%2BSQ%7DhQe&input=%5B21%2C+9%2C+6%2C+3%5D&test_suite=1&test_suite_input=%5B2%2C+5%2C+8%2C+14%2C+17%5D%0A%5B2%2C+5%2C+17%5D%0A%5B2%2C+14%2C+17%5D%0A%5B21%2C+9%2C+6%2C3%5D%0A%5B10%2C+9%2C+5%5D%0A%5B1%2C+10%2C+91%2C+100%5D&debug=0)**
Thanks to [Steven H.](https://codegolf.stackexchange.com/users/55696/steven-h) for saving a byte!
### [Pyth](https://pyth.readthedocs.io), 12 bytes
```
%.aiF.+Q}hQe
```
**[Try it here!](https://pyth.herokuapp.com/?code=%25.aiF.%2BQ%7DhQe&input=%5B21%2C+9%2C+6%2C+3%5D&debug=0)**
### How it works
```
%.aiF.+Q}hQe ~ Full program.
.+Q ~ Get the deltas.
iF ~ Reduce by GCD.
.a ~ Absolute value.
% ~ Modular. Get every nth element of...
} ~ The inclusive numeric range between...
hQ ~ The first element, and...
e ~ The last element.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
1)0GdYkG0)3$:
```
[Try it online!](https://tio.run/##y00syfn/31DTwD0lMtvdQNNYxer//2gjBUMTBUPzWAA "MATL – Try It Online")
Explanation:
```
Consider the example input [2 14 17]:
# implicit input, STACK: [[2 14 17]]
1) # push 1, index, STACK: [2]
0G # push 0, duplicate input, STACK: [2, 0, [2 14 17]]
d # take differences, STACK: [2, 0, [12, 3]]
Yk # get value in [12, 3] nearest to 0, STACK: [2, 3]
G0) # get last element in input, STACK: [2, 3, 17]
3$: # 3-input :, computes 2:3:17, the range from 2 to 17 by 3
# STACK: [[2 5 8 11 14 17]], implicit output.
```
[Answer]
# JavaScript (ES6), ~~92~~ 90
**Edit** 2 bytes saved thx Arnauld
Easy, as it is enough to check the differences between the first two and the last two. But still unbelievably long.
```
s=>(e=(z=s.pop(a=s[0]))-s.pop(d=s[1]-a),[...Array((z-(a-=d=e*e>d*d?d:e))/d)].map(_=>a+=d))
```
*Less golfed*
```
s=>{
a =s[0]
b =s[1]
z = s.pop()
y = s.pop()
d = b-a
e = z-y
d = e*e>d*d?d:e
n = (z-a)/d+1
return [...Array(n)].map((_,i) => a + i*d)
}
```
**Test**
```
var F=
s=>(e=(z=s.pop(a=s[0]))-s.pop(d=s[1]-a),[...Array((z-(a-=d=e*e>d*d?d:e))/d)].map(_=>a+=d))
var test=`In: 2 5 8 14 17 Out: 2 5 8 11 14 17
In: 2 5 17 Out: 2 5 8 11 14 17
In: 2 14 17 Out: 2 5 8 11 14 17
In: 21 9 6 3 Out: 21 18 15 12 9 6 3
In: 10 9 5 Out: 10 9 8 7 6 5
In: 1 10 91 100 Out: 1 10 19 28 37 46 55 64 73 82 91 100`.split`\n`
.map(r=>r.split`Out`.map(x=>x.match(/\d+/g)))
test.forEach(([i,k])=>{
var o=F(i.slice(0))
var ok = o+''==k
console.log(ok?'OK':'KO',i+' => '+o)
})
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes
```
Range[#&@@#,#[[-1]],#&@@Differences@#~SortBy~Abs]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T8oMS89NVpZzcFBWUc5OlrXMDZWB8RzyUxLSy1KzUtOLXZQrgvOLypxqqxzTCqOVfuvac0VUJSZV@KQFl1tZKijYKmjYKajYFwb@x8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~65 62 55~~ 54 bytes
```
->l{a,*,b,c=l;[*a.step(c,[l[1]-a,c-b].min_by(&:abs))]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOlFHSydJJ9k2xzpaK1GvuCS1QCNZJzon2jBWN1EnWTcpVi83My8@qVJDzSoxqVhTM7b2f0FpSbFCWnS0oaGOkY5hbKyWvQ4XXEzHWMcQIvYfAA "Ruby – Try It Online")
-1 byte thanks to Justin Mariner
[Answer]
# [Haskell](https://www.haskell.org/), ~~73~~ 69 bytes
```
f(h:t)=do(#)<-[(-),(+)];[h,h#minimum(abs<$>zipWith(-)t(h:t))..last t]
```
[Try it online!](https://tio.run/##hYw9b4MwFEV3/4orJYOtmohncAz52jNl7IAYqNLIVoFExVlS9bcTQ0ilLu3y9N655z5bdR/vdd33J25XXmyPZz4Tm6jgkZD8RZTrwko7a1zrmmvDq7duM9/d3OXVeRsUP5bEYlFXnYcv@6ZyLbY4nsFw@XStxxwnFEpSKsmUvyDFMpe6ZOwrYvt2BQWNDJSCDDtc/Q@giT2dP@N/6oQcSySTEKIghI9qwoNDcTj0wxj3DCaE@hGOaJjxZAyAcqgMiUEaPI1lCpMgU08x@u7v "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 49, 47 46 bytes
```
(0-[:<./2|@-/\]){.@[&]\({.<.{:)+[:i.{:(+*)@-{.
```
Inspired by Emigna's solution.
How it works:
```
(0-[:<./2|@-/\]){.@[&]\({.<.{:)+[:i.{:(+*)@-{. - fork of 3 verbs
({.<.{:)+[:i.{:(+*)@-{. - generates a list in the entire range of values
{: -{. - last minus first element
(+*)@ - adds the signum of the difference
[:i. - makes a list
({.<.{:) - the smallest of first and last elements
+ - adds the offset to the list (translates all elements according to the first one)
(0-[:<./2|@-/\]) - finds the step
2|@-/\] - the absolute differences between all consecutive elements
[:<./ - the smallest one
0- - negate (for splitting)
{.@[&]\ - splits the list from the right verb into left verb's result sublists and takes their first elements
```
[Try it online!](https://tio.run/##Vck7DsIwEATQ3qcYURCb4M06ED6rRPI9nFQIC2goUhrObgISKDQzejO3HMeOwBBw1myDtFTVD2@rfjCJfFgOvU7UUhJTBrlOrcuV8TZRNmpBKGJHBdZ4CuKo1Pl0uSOiRoMD3BZuP5/m@j8djthh87Xjyc1PH7@TVX4B "J – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
m←C▼Ẋ≠⁰…⁰
```
[Try it online!](https://tio.run/##yygtzv7/P/dR2wTnR9P2PNzV9ahzwaPGDY8algHJ////RxsZ6ljqmOkYxwIA "Husk – Try It Online")
Thanks a lot to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) for halving the byte count, by pointing that applying `…` on a list rangifies it!...
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 167+13=180 145+13=158 bytes
```
a=>{int x=a[1]-a[0],y=a[2]-a[1],d=x*x<y*y?x:y,s=Math.Abs((a[a.Length-1]-a[0])/d),i=0,j=a[0];var r=new int[s+1];for(;i<=s;j+=d)r[i++]=j;return r;}
```
[Try it online!](https://tio.run/##rZNBb5swFMfP8CneblCcDEjTbHPcaaq0UytN6qEHxMEFp3FGzWabLijis6fPDJJ0O0WqBLL9/P6/92z9XZhJUWuxb4xUT3DfGiueqV9U3Bj4sfON5VYW8L1RxVIqm@UE@uEa7sXvRqhCAIM9Z9c7DMOW8SzJJzyLc9LiPHXzJCcl215sl@1F@3X7pSWG3XG7nn57NEHAMz69FerJrieDMPxYhkSymGyYW9IXrkEzJf70hU2U5HRV64DKJTN0E7Ey1JmMopxtqBa20Qo07fbUH1t/qWUJd1yqIPR3vndTK1NXYvqgpRW3UolgPMjNWhQ/AyyU5bBLCcwJfCKQXOK/6Aj8t5EcNsOQngl@Z@K7N4myzwSuCMxOoI7lmK7/9JhwDjiJe938SB0iyF30vPl5PGzFAfoxPqH@jSdIThE9Q/alg2PrV3gdixlWTA866Gt2B8s81nUFb@v1pkcHFvXzr0pYMTwDGNe9t5xVV3WjSnwTozw4aty55AqCPmVwPXxgB8YQCn3PG5y84pURqPI9tDy4JkAiO6Y4LOGUg5EoQiV2cayRyfyUj0vHdin/FvA6Hz9/DFvdCHch3f4V "C# (.NET Core) – Try It Online")
+13 for `using System;`
Surprisingly, this challenge had more nuance that I initially anticipated.
### Acknowledgements
-22 bytes saved due to some neat simplifications from @DLosc.
### DeGolfed
```
a=>{
int x = a[1]-a[0], // difference between first and second numbers
y = a[2]-a[1], // difference between second to last and last numbers
d = x*x < y*y? x : y, // smallest absolute value difference
s = Math.Abs((a[a.Length-1] - a[0]) / d), // number of steps in the reconstructed sequence (not the number of elements)
i = 0, // step position
j = a[0]; // next number in reconstructed sequence
var r = new int[s+1];
// reconstruct the sequence
for(; i <= s; j+=d)
r[i++]=j;
return r;
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÌõUÎUäa rm
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zPVVzlXkYSBybQ&input=WzIxLDksNiwzXQotUQ)
```
ÌõUÎUäa rm :Implicit input of array U
Ì :Last element
UÎ :First element
õ :Range [first,last] with step size
Uä : Consecutive pairs of U
a : Reduced by absolute difference
r : Reduce by
m : Minimum
```
[Answer]
# [R](https://www.r-project.org/), 62 bytes
```
function(x)seq(x[1],tail(x,1),min(abs(d<-diff(x)))*sign(d[1]))
```
[Try it online!](https://tio.run/##jc3BCoJAEAbgu0/xQ5fdmMBRV9eoZ@gBooNpGwtllAq@/TYa5LEOw8D/f8y8gtsHN7R17x@tGnV3earxyCfqK39TI7Gmu29Vde5Us9s03jlBWq87f21VI1Dr4FStEoIhWAJnMoXW0eow9FskMLBgllziaKE/zR@HmFASckK6MAHCDDhBiRzpLDmepfkyjqW1KESYj5BnE5p3vLhJconEIi2QiTbIMxQprNyf2ji8AQ "R – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 147 bytes
```
from fractions import*
a=input()
b=[j-i for i,j in zip(a[:-1],a[1:])]
l=min(gcd(i,j)for i in b for j in b)
print list(range(a[0],a[-1]+l/abs(l),l))
```
[Try it online!](https://tio.run/##HczLDoIwEEDRPV8xy1ZLBBNfJP2SpospCI7pK6Uu9OcrdH/Pjd/8Cv5cyMdPBgkWnZlwANV34iHu4iau4qLLnIKDOeGYKfgVyMWQ8qFBWR3jjZHq3RLMIQGJN5CHH0WGamh7LVD1g@a6sdKRZ8s4sa3htd1LU1lFhjcxkc9gac0soV@e26TbF9voaE9oVma5sJyX8gc "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
lambda a:range(a[0],a[-1],[min,max][a[0]>a[1]](a[1]-a[0],a[-1]-a[-2]))+[a[-1]]
```
[Try it online!](https://tio.run/##VYzNDoIwEITP8hR7o43bhIL4QyJHXqLuYQ2gJFIJ4aBPX0shUQ@7O/PNZIf3dH/a1LXni3twf60ZuBjZ3hrBJiFkozSh6TuLPb/IzLBko4nEvNW35KVKScqtCZZc3bRQCZZFtBnGzk7AGKsyxtazKKqE0Zih1iSDDoaWIEXIEY4IeufnsDQW@OP@Qo1wQtgjZOu/JIB8db45g3ATz9wH "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṂrṀmILÞṪ
```
[Try it online!](https://tio.run/##y0rNyan8///hzqaihzsbcj19Ds97uHPV////o410FEx1FCx0FAxNgNg8FgA "Jelly – Try It Online")
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 64 bytes
```
?dsx[ksE0_1]sg[scdlcr-d2^vdK>gK0=g+sqz1<l]dslx[pdlE+dlx!=Z]dsZxp
```
[Try it online!](https://tio.run/##S0n@/98@pbgiOrvY1SDeMLY4Pbo4OSUnuUg3xSiuLMXbLt3bwDZdu7iwytAmJzalOKciuiAlx1U7JadC0TYKKBBVUfD/v6GCoYGCJYg0AAA "dc – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ḣtṡ?¯ġḞ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuKN04bmhP8KvxKHhuJ4iLCIiLCJbMjEsIDksIDYsIDNdIl0=)
] |
[Question]
[
## The task
In this challenge, your task is to write a program in a programming language **L** that takes a positive integer **n**, and outputs the sum of the proper divisors of **n** ([sequence A001065](http://oeis.org/A001065) on OEIS).
It should return the correct output for any **1 ≤ n ≤ 10 000**.
Here are the first 10 outputs:
```
0, 1, 1, 3, 1, 6, 1, 7, 4, 8
```
Furthermore, your program must be a *fake polyglot*, which means the following.
It is a valid program in another programming language **L'**, and for each input **1 ≤ n ≤ 10** (the test cases above), it returns the sum of proper divisors of **n**, but there exists some **11 ≤ n ≤ 10 000** for which it doesn't return the correct result.
It may return something incorrect, loop forever, crash etc.
It can give a wrong result for all **n ≥ 11**, for some of them or just one.
## Rules and scoring
You can write a full program or a function, and you can have different means of input and output in the two languages.
The lowest byte count wins.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
In this challenge, different major versions or implementations of a language are considered distinct.
Note that if you use programming languages with non-ASCII encodings (as many do on this site), the same *sequence of bytes* must be used for both languages.
This means that you must either convert between potentially different code pages or suffer penalties for multi-byte Unicode characters.
## Additional test cases
```
20 -> 22
36 -> 55
180 -> 366
997 -> 1
2875 -> 869
10000 -> 14211
```
[Answer]
## JavaScript (ES6), [V8](https://en.wikipedia.org/wiki/Chrome_V8) / [SpiderMonkey](https://en.wikipedia.org/wiki/SpiderMonkey) vs [Chakra](https://en.wikipedia.org/wiki/Chakra_(JavaScript_engine)), ~~66~~ 63 bytes
```
n=>[...Array(n)].map((_,d)=>s+=n%d?0:d,[0,n>10].sort(x=>s=x))|s
```
### Demo
```
let f =
n=>[...Array(n)].map((_,d)=>s+=n%d?0:d,[0,n>10].sort(x=>s=x))|s
console.log(JSON.stringify(
[...Array(20)].map((_, n) => n + 1).map(f)
))
```
### Output
Output of the above snippet on Chrome and Firefox (all correct):
```
[0,1,1,3,1,6,1,7,4,8,1,16,1,10,9,15,1,21,1,22]
```
Output on Edge (off by 1, starting at n = 11):
```
[0,1,1,3,1,6,1,7,4,8,2,17,2,11,10,16,2,22,2,23]
```
### Why?
No algorithm is imposed by the specification for the `.sort()` method. It's not even required to be stable. Therefore, each JavaScript engine uses its very own implementation.
However, `[0,1].sort(x=>x)` gives `[0,1]` with all engines.
So what's the difference?
What's happening here is that Chakra is passing `1` as the first parameter of the first (and only) iteration to the callback function (asking for a comparison of `1` with `0`), while V8 and SpiderMonkey are passing `0` (asking for a comparison of `0` with `1`).
You can use the following snippet to check what your browser is doing.
```
[0, 1].sort((x, y) => console.log("Let's compare " + x + " with " + y + "!"))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) / [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
The byte-code (hexadecimal):
```
d1 a8 4f 71 0d ad 53 fa
```
Using [Jelly's code-page](https://github.com/DennisMitchell/jelly/wiki/Code-page) returns incorrect results for any [excessive](https://en.wikipedia.org/wiki/Abundant_number) number (e.g. an input of **12** returns `12` rather than `16`):
```
ẎƭOqÆḌS«
```
**[Try it online!](https://tio.run/##y0rNyan8///hrr5ja/0LD7c93NETfGj1////DY0A "Jelly – Try It Online")**
Using [05AB1E's code-page](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md) returns correct results:
```
ѨOqмλSú
```
**[Try it online!](https://tio.run/##MzBNTDJM/f//8MRDK/wLL@w5tzv48K7//w2NAA "05AB1E - Try It Online")**
### How?
05AB1E parses up to and including the `71` (`q`) which instructs to quit and then stops parsing:
```
ѨOq - Takes input from stdin
Ñ - get divisors
¨ - remove right-most (the input value itself - yielding proper divisors)
O - sum
q - quit (causing an implicit print of the top of the stack)
...мλSú is never parsed
```
Jelly parses the whole program up-front as three links due to the effect of the bytes without an assigned meaning, `ƭ` and `q` acting as delimiters. The entry point of a program is it's final link:
```
Ẏ - Link 1 (never used), tighten list
...ƭ delimits links 1 & 2)
O - Link 2 (never used), cast from characters to their ordinals
...q delimits link 2 and the main link
ÆḌS« - Main link: number, n
ÆḌ - proper divisors
S - sum
« - minimum of that and n
- as a full-program: implicit print
```
[Answer]
# Python 2 and Python 3, 58 bytes
[TIO for Python 2](https://tio.run/##Xck7DoAgDADQ3VN0MVDDICYuRm7AEVwg/ppoMRUHT4@7b33Xm/fEXfFuKkc44xyAh/s5NTWaR2uTKOVcVArXJEBADBJ4W7Q1jLQC1zRaLL/sWxwquIQ4AxnwmrB8)
[TIO for Python 3](https://tio.run/##Xck7DoAgDADQ3VN0MbTGQWJcDNyAI7hA/DWRYlAHT4@7b33ne@9J@uLsVA4fw@xBxuuJyA2K0TplpawNStGaMjCwQPayLahbIV5Bajaayi@HjsYKzsxyA3ILDpmofA)
```
lambda n:sum(i*(n<11or''==b'')for i in range(1,n)if n%i<1)
```
It works in python 2, but for every n > 10 it would output 0 in python 3.
All because of different approaches in comparing strings with bytes:
* in Python 2 `'' == b''`
* in Python 3 `'' != b''`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org) and [PHP](https://php.net/), ~~73~~ 70 bytes
```
function($n){for($d=$i=0;++$i<$n;)$d+=$i*!($n%$i);return"$n">10?0:$d;}
```
In both languages, this is an anonymous function. JavaScript gives the correct result, but PHP gives **0** for all **n >= 11**.
[Try it JS!](https://tio.run/##DctNCsIwEEDhq8QwQuKgpAs3nUbPUvIjI2VS0taNePaY7eN77/kzb6Hyul@lxNSy8i0fEnYuYkDsN5dqIHpg7wgReAIhCxF7uZy6OANbqmk/qmgQ/Rjc040Q6df6qQz7gXi6O2JEq0KRrSzptpSXYdSj0pgNW0vtDw "JavaScript (Node.js) – Try It Online")
[Try it PHP!](https://tio.run/##HYuxCsMgFEX3foV93EKsIGbokhebH@kWI7o8JSRT6Ldb6XKGwzk11TYvNdUbovItnrIeucgA0Vcs@4Dgkb1jY5BnCGsE083z3osHsuZ9O85dCELv0S1uQuBv4/@a/cj9erlOY7Ta1lQUsqVJkUXsgbb0EeL2Aw "PHP – Try It Online")
### How it works
Both languages do the same thing at first: iterate from 1 up to n-1, keeping a running sum of all numbers **i** for which **n % i = 0**.
What causes the difference in behaviour is the final part:
```
return"$n">10?0:$d;
```
In JavaScript, `"$n"` is just a string literal. The comparison `>` with `10` casts it to a number implicitly, but since it doesn't look like a number, it becomes NaN. NaN gives false when compared with a number in any way. As a result, `$d` is always returned.
However, in PHP, `"$n"` is a string containing the value of `$n`. When PHP casts this to a number, it simply becomes the value of `$n`. If it's greater than `10`, then `0` is returned instead of `$d`.
[Answer]
# [Python 3](https://docs.python.org/3/) / [Python 2](https://docs.python.org/2/), ~~64~~ ~~60~~ 58 bytes
*Thanks to @officialaimm for 2 bytes off*
```
lambda n:sum(d*(round((n>10)*.5)==n%d)for d in range(1,n))
```
In Python 3 this gives the correct results. In Python 2 the ouput is wrong for inputs exceeding `10`. The code exploits banker's rounding, which is done by Python 3 but not by Python 2.
Try it online! [Python 3](https://tio.run/##NckxDoQgEAXQq9CYzBhjcI2NCZ7Ehs3ISiIfglh4etzG1750lz1irM6s9bDhK1ZhPq9A0lKOF4QIy6C57Sc2Bo2wi1mJ8lDZ4rfR0IG5puxR6PBnoWATue7Nj@a/@gA) (correct), [Python 2](https://tio.run/##NclBCsMgEAXQq8ymMBMkJIFuCvYk2VgmtkL8ippFTm@6ydu@fLZfwtK9Xfvu4kcd4VWPyDpwSQeUGe95kmF8irV4qPhUSCmAisN349lApOcS0GgPtXF0mb25c5nk3xc) (wrong for `n > 10`).
[Answer]
# [Python 3](https://docs.python.org/3/) / [Python 2](https://docs.python.org/2/), 47 bytes
```
lambda n:sum(d*(n%d<1)for d in range(10/n>0,n))
```
An unnamed function, fake in Python 2.
Try it online for **[Python 3](https://tio.run/##VU67jsIwEKyTr9gmwgYDNoingAp@4u4oDN6ApWQTeQ2Crw8JR8MU08yzfsZrRdMm3/41hS1PzgKt@VYK1xeUuY2ReRXAgScIli4ojB7TTiuSsumUiBw7sfAcxcehwBgpYQC/E62mc2WWWq1WCzVZLmbK6BbHdZrE8Gw5Cci3IsIWctF1yTTBxxnrCD8Yqr2/e/YVHUJotywDfkVwVCKzvWCa1MFTFL1s5mC4g4x72btOwb@5fdu8AA "Python 3 – Try It Online")** or **[Python 2](https://tio.run/##VU7LUoMwFF3DV9wN06TGmuBQ2o5lZX@i6iKaC2YGLkxu2pGvR2jdeBZnc57DGL97yqf6@D61tvt0FujAl064taDMvRhZ9wEceIJgqUFh9BNVWpGU06JE5LiIreco/hwKjJESHuAt1@p5q8xOq/2@VPmuLJTRMz4OaRLDOHMSkC9thCPUYumSaYI/XzhEOGPoX/3Vs@/pFMK8ZRnwXwQ3HTLbBtNkCJ6iWGWFg8cKMl5ltzoFd/P8dvoF "Python 2 - Try It Online")**
In Python 2 `/` is integer division with integer arguments, whereas in Python 3 it is division.
When `n` exceeds **10** `10/n` evaluates to **0** in Python 2, but to a small positive number in Python 3 (this is certainly true up to the maximum required of **10,000** at least).
As such `10/n>0` evaluates to `True` for Python 3 and `range(10/n>0,n)` is equivalent to `range(1,n)` while in Python 2 `10/n>0` evaluates to `False` when `n` exceeds **10** whereupon `range(10/n>0,n)` becomes equivalent to `range(0,n)` causing `n%d` to attempt to perform modulo zero arithmetic, raising a `ZeroDivisionError`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) / [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
What Jelly sees:
```
11⁻iẎƭO}qÆḌS
```
[Try it online!](https://tio.run/##y0rNyan8/9/Q8FHj7syHu/qOrfWvLTzc9nBHT/B/oLABAA "Jelly – Try It Online")
Explanation:
`q` is unsupported in Jelly, so Jelly only "sees" what's after the `q`.
```
ÆḌS
ÆḌ Proper divisors
S Sum
```
What 05AB1E sees:
```
11‹iѨO}qмλS
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f0PBRw87MwxMPrfCvLbyw59zuYJAYAA "05AB1E – Try It Online")
Explanation:
```
11‹iѨO}qмλS Implicit input multiple times
11 Push 11
‹ Less than 11?
i } If equals 1, then
Ñ Divisors
¨ Remove last
O Sum
q Implicit print and quit
м Negative filter
λ Undefined, ignored error
S Split into chars
```
Of course everything after "quit" doesn't actually happen.
] |
[Question]
[
FizzBuzz is so simple, bet you can do it backwards. In this challenge, you will be given the length of the FizzBuzz string and must give the positive integer that produced that string.
## Description
To break this down, a FizzBuzz string for `n` is generated by the following algorithm.
Start with an empty string and, for every `i=1..n` (inclusive):
1. If `i` is divisible by `3` and by `5`, append `FizzBuzz` to the string.
2. If `i` is just divisible by `3` append `Fizz`.
3. If `i` is just divisible by `5` append `Buzz`.
4. If `i` is divisible by neither, append the decimal representation of `i`.
So for example `FizzBuzz(15)` is the following:
```
12Fizz4BuzzFizz78FizzBuzz11Fizz1314FizzBuzz
```
You will be given `Length(FizzBuzz(n))` and must determine `n`. You may assume that the input is positive and is always going to be the length of some FizzBuzz string.
## Rules
Your solution may a complete program or a function definition in any standardly acceptable language. Your program/function may take in arguments and return answers in any [standardly accepted way](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top). Standard loopholes are forbidden.
You may assume that the input is positive and valid (describes the length of some FizzBuzz string) and is smaller than the largest integer representable natively in your language.
This is code golf, so shortest byte-count wins.
## Examples
Here are some example cases
```
Length(FizzBuzz(n)) -> n
1 -> 1
6 -> 3
15 -> 6
313 -> 100
3677 -> 1001
```
## Edit
Fixed last test case. Thanks @SteadyBox.
[Answer]
# C, ~~81~~ 78 bytes
```
l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?snprintf(0,0,"%d",i):4:i%5?4:8);return i;}
```
**68 bytes** if you don't mind converting to `double` and back:
```
l,i;f(n){for(l=i=0;l<n;l+=++i%3?i%5?log10(i)+1:4:i%5?4:8);return i;}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
2 bytes saved using more recent language features `)` for `µ€` and `Ä` for `+\`
```
3,5ḍS×4oDL$)Äi
```
**[Try it online!](https://tio.run/##y0rNyan8/99Yx/Thjt7gw9NN8l18VDQPt2T@BwqamZsDAA)** or see the [test cases](https://tio.run/##ATUAyv9qZWxsef//Myw14biNU8OXNG9ETCQpw4Rp/8W8w4figqxH//9bMSw2LDE1LDMxMywzNjc3XQ).
### How?
Builds a list of the lengths of every item from `1` to the input, reduces by addition and then finds the one-based index of the input in the list. (This also means an invalid input results in `0`, "not in list").
```
3,5ḍS×4oDL$)Äi - Main link: theLength
) - perform the chain to the left for each (€) in
implicit range from 1 to the input and
pass the result into the monadic chain (µ) to the right
3,5 - 3 paired with 5: [3,5]
ḍ - divides? for a multiple of 15 [1,1]; sum = 2; times 4 = 8
S - sum for a multiple of 5 [0,1]; sum = 1; times 4 = 4
×4 - times 4 for a multiple of 3 [1,0]; sum = 1; times 4 = 4
for none of those [0,0]; sum = 0; times 4 = 0
$ - last two links as a monad
D - to decimal digit list
L - length - e.g. 313 -> [3,1,3] -> 3
o - logical or: replace a 0 with the decimal length, keep the 4s and 8s
Ä - reduce with addition: e.g. [1,1,4,1, 4, 4, 1, 1, 4, 4, 2, 4, 2 ,2, 8]
-> [1,2,6,7,11,15,16,17,21,25,27,31,33,35,43]
i - index of theLength in that list (e.g. 15 is at index 6)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~31~~ ~~28~~ 27 bytes
```
`@:tI5h!\XJA)VXznJ~z4*+G-}@
```
[Try it online!](https://tio.run/nexus/matl#@5/gYFXiaZqhGBPh5agZFlGV51VXZaKl7a5b6/D/v7GhMQA)
### Explanation
```
` % Do...while
@: % Push array [1 2 ...k], where k is iteration index
t % Duplicate
I5h! % Push column vector [3; 5]
\ % Modulo, with broadcast. Gives 2 × k matrix
XJ % Copy into clipboard J
A % Row vector that contains true for columns that contain two nonzeros
) % Index with that vector. This keeps numbers that are non-fizz/buzz
V % Convert to string. This inserts spaces between numbers
Xzn % Number of nonspace characters
J % Push 2 × k matrix resulting from modulo operation again
~z % Number of zeros
4* % Multiply by 4. Gives number of characters corresponding to fizz/buzz
+ % Add
G- % Subtract input. This is the loop condition: exit if 0
} % Finally (execute right before exiting loop)
@ % Push current iteration index
% End (implicit)
% Display (implicit)
```
[Answer]
## Mathematica, 67 bytes
```
(For[n=s=0,s<#,s+=Tr[4Boole[{3,5}∣++n]]/. 0:>IntegerLength@n];n)&
```
This is both faster and shorter than my initial solution:
```
1//.x_/;Sum[Tr[4Boole[{3,5}∣n]]/. 0:>IntegerLength@n,{n,x}]!=#:>x+1&
```
or my desperate attempt to shorten it:
```
(s=0;1)//.x_/;(s+=Tr[4Boole[{3,5}∣x]]/. 0:>IntegerLength@x)!=#:>x+1&
```
## Explanation
Standard `For` loop which increments `n` until `s := Length(FizzBuzz(n))` is at least equal to the input `#`. The only interesting bit is how I calculate the length of the `(n+1)`-th term of the FizzBuzz sequence
```
++n Preincrement n
{3,5}∣ Test for divisibility by 3 and 5 (returns a list)
Boole[ ] Convert True to 1 and False to 0
4 Multiply by 4
Tr[ ] Sum
/. Replace
0 0 (leading space is necessary or it thinks we are dividing by 0.0)
:> with
IntegerLength@n the number of digits in n
```
[Answer]
# Java 8, 100 97 bytes
Golfed:
```
l->{int i=0;for(String s="";s.length()<l;)s+=++i%15<1?"12345678":i%5<1||i%3<1?"1234":i;return i;}
```
Ungolfed:
```
import java.util.function.*;
public class HowDidIEndUpWithThisFizzBuzz {
public static void main(String[] args) {
for (final int[] data : new int[][] { { 1, 1 }, { 6, 3 }, { 15, 6 },
{ 313, 100 }, { 3677, 1001 } }) {
final int fizzBuzzLength = data[0];
final int expected = data[1];
final int actual = f(l -> {
int i = 0;
for (String s = ""; s.length() < l;) {
s += (++i % 15 < 1 ? "12345678" : (i % 5 < 1 || i % 3 < 1 ? "1234" : i));
}
return i;
} , fizzBuzzLength);
System.out.println("Length(FizzBuzz(n)) -> " + fizzBuzzLength);
System.out.println("Expected -> " + expected);
System.out.println("Actual -> " + actual);
System.out.println();
}
}
private static int f(IntFunction<Integer> function, int fizzBuzzLength) {
return function.apply(fizzBuzzLength);
}
}
```
Output:
```
Length(FizzBuzz(n)) -> 1
Expected -> 1
Actual -> 1
Length(FizzBuzz(n)) -> 6
Expected -> 3
Actual -> 3
Length(FizzBuzz(n)) -> 15
Expected -> 6
Actual -> 6
Length(FizzBuzz(n)) -> 313
Expected -> 100
Actual -> 100
Length(FizzBuzz(n)) -> 3677
Expected -> 1001
Actual -> 1001
```
[Answer]
# MATL, ~~31 30~~ 28 bytes
```
:tI5h!\~s4*t~b10&YlkQ*+YsG=f
```
Uses the same idea as Jonathan Allen's Jelly solution.
Try it on [matl.io](https://matl.io/?code=%3AtI5h%21%5C%7Es4%2At%7Eb10%26YlkQ%2A%2BYsG%3Df&inputs=15&version=19.8.0)!
[Answer]
## JavaScript (ES6), ~~62~~ 57 bytes
```
f=(n,k=0)=>n?f(n-(++k%3?k%5?`${k}`.length:4:k%5?4:8),k):k
```
### Test cases
```
f=(n,k=0)=>n?f(n-(++k%3?k%5?`${k}`.length:4:k%5?4:8),k):k
console.log(f(1 )); // -> 1
console.log(f(6 )); // -> 3
console.log(f(15 )); // -> 6
console.log(f(313 )); // -> 100
console.log(f(3677)); // -> 1001
```
[Answer]
# Javascript (ES6), 56 bytes
```
f=(x,s=i=0)=>s[x]?i:f(x,s+[++i%3?i%5?i:1e3:i%5?1e3:1e7])
```
```
<!-- snippet demo: -->
<input list=l oninput=console.log(f(this.value))>
<datalist id=l><option value=1><option value=6><option value=15><option value=313><option value=3677></datalist>
```
[Answer]
# Ruby, ~~69~~ 66 bytes
```
->n{i=0;(i+=1;n-=i%3>0?i%5>0?i.to_s.size: 4:i%5>0?4:8)while n>0;i}
```
Originally, I was avoiding the nested ternary operator *monstrosity* and got down to 69 bytes:
```
->n{i=0;(i+=1;n-=(x=[i%3,i%5].count 0)>0?4*x:i.to_s.size)while n>0;i}
```
[Answer]
# Python 3, 78 bytes
```
f=lambda i,n=1,s=0:~-n*(s==i)or f(i,n+1,s+(4*((n%3<1)+(n%5<1))or len(str(n))))
```
Recursive function. Will need the recursion limit increased for any result above 1000.
**Explanation:**
```
# i = length of final string
# n = current number in sequence, starting with 1
# s = length of current string, starting with 0
f=lambda i,n=1,s=0: \
# if s==1, this will evaluate to n+1, which is NOT 0, and will return
# else, it will evaluate to (n+1)*0, and trigger the second half of the OR clause
~-n*(s==i)or \
# recursively call the next iteration, with the next number in the sequence
f(i,n+1, \
# increase s by 4 if Fizz or Buzz, 8 if FizzBuzz, or len(n) if number
s+(4*((n%3<1)+(n%5<1))or len(str(n))))
```
[Answer]
# Python, 93 bytes
```
def g(n,c=0,a=[4,0]):
while n:c+=1;s=a[c%3>0]+a[c%5>0];s+=(s<1)*len(str(c));n-=s
return c
```
[Answer]
# k, 33 bytes
```
{1+&x=+\{(#$x;4;8)+/~3 5!'x}'1+!x}
```
Brief (python-ish) explanation:
```
{ } / function(x):
1+!x / array from 1 to x, inclusive
' / for y in array:
{ } / function(y):
(#$x;4;8) / yield [ len(str(y), 4, 8 ][
+/~3 5!'x / sum([not(y mod 3), not(y mod 5)])
/ ]
+\ / cumulative sum of result of for loop
1+&x= / get index of x in cumulative sum, add one
```
Example using kmac 2016.06.28:
```
f:{1+&x=+\{(#$x;4;8)+/~3 5!'x}'1+!x}
,/f'1 6 15 313 3677
1 3 6 100 1001
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~76~~ 70 bytes
```
?sa0dsbsc[lc4+sc]sh[lbZ+sc]so[lcdlb1+ddsb3%0=h5%0=hlc=olcla!=y]dsyxlbp
```
[Try it online!](https://tio.run/nexus/dc#@29fnGiQUpxUnBydk2yiXZwcW5wRnZMUBWblA8VScpIMtVOAKoxVDWwzTEFETrJtfk5yTqKibWVsSnFlRU5Swf//xmbm5l/z8nWTE5MzUgE "dc – TIO Nexus")
[Answer]
# Java 8, ~~95~~ 93 bytes
```
l->{int j=0,i=0;for(;j<l;)j+=++i%15<1?8:i%3<1||i%5<1?4:Math.floor(Math.log10(i)+1);return i;}
```
This is the optimized version of [@Snowman's answer](https://codegolf.stackexchange.com/a/110881/56341)
[Answer]
# Groovy, 76 bytes
`def f(n){i=0;for(s='';s.size()<n;)s+=++i%15<1?"1"*8:i%5<1||i%3<1?"1"*4:i;i;}`
Mostly the same as [@Snowman's answer](https://codegolf.stackexchange.com/a/110881/56341), but uses some Groovy magic/differences to cut down on the byte count.
[Answer]
# [Perl 6](https://perl6.org), ~~55~~ 52 bytes
```
{1+first $_,:k,[\+] map {4*($_%%3+$_%%5)||.chars},1..*}
```
```
{(0,{my \i=++$;$_+(4*(i%%3+i%%5)||i.chars)}...$_)-1}
```
[Try it online!](https://tio.run/nexus/perl6#Ky1OVSgzs@bKrVRQS1Ow/V@tYaBTDeTEZNpqa6tYq8Rra5hoaWSqqhprAwlTzZqaTL3kjMSiYs1aPT09lXhNXcPa/8WJlQppCobWXBCGGYxhaApjGRsaw5lm5ubW/wE "Perl 6 – TIO Nexus")
### How it works
```
{ } # A lambda.
0 # Start with 0.
,{ } # Use the iteration formula...
my \i=++$; # Fetch current index.
$_+( ) # Last element plus:
4*(i%%3+i%%5) # Fizz/Buzz/FizzBuzz length,
||i.chars # or number length.
...$_ # ...until the input is reached.
( )-1 # Sequence length minus 1.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 20 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
@µ35ìx_XvZÃ*4ªXìÊ}f1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QLUzNex4X1h2WsMqNKpY7Mp9ZjE&input=MzY3Nw)
```
@µ35ìx_XvZÃ*4ªXìÊ}f1 :Implicit input of integer U
@ :Function taking an integer X as argument
µ : Decrement U by
35ì : Digit array of 35
x : Reduce by addition
_ : After passing each Z through the following function
XvZ : Is X divisible by Z?
à : End reduce
*4 : Multiply by 4
ª : Logical OR with
Xì : Digit array of X
Ê : Length
} :End function
f1 :First integer >=1 that returns a falsey value (i.e, 0) when passed through that function
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 48 bytes
```
$\++;($_-=4*(!($\%3)+!($\%5))||length$\)&&redo}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRlvbWkMlXtfWREtDUUMlRtVYUxtMm2pq1tTkpOall2SoxGiqqRWlpuTXVv//b2xmbv4vv6AkMz@v@L@ur6megaHBf90CAA "Perl 5 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 68 bytes, `stdout`-spamming
* Thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) for this approach, saving six bytes.
```
f(n,j,r){for(r=j=0;!r;r=!n*j)n-=++j%3?j%5?printf("%d",j):4:j%5?4:8;}
```
[Try it online!](https://tio.run/##ZY3BasMwEETv@YqNikDrKMRCjlNshOkhLYHSQmhvuQTZChZ4W@T2FPLtruwSCukedmDe7oxdnqwdBidIehnw7D6CCMabtJyHMpg5JR5paRYLz3Xl@br6DC19OcF4zaTHIitGMyvuy8twVzeupQbeYpgjvF6uEtg9vbzut8BQdiZWobwySFYHcoJnNYKBKFD9iuA9HohJkl3Mim/GUcX6b2ubvmcFe3zYPb/vtwzLWXdsKTZ2eI7NAKAkjBtn8DcTyCeg/wG1nkB@C7TSEag0vQE632zk6CuEy/AD "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 74 bytes
```
f(n,j,r){for(r=j=0;!r;r=!n*j)n-=++j%3?j%5?snprintf(0,0,"%d",j):4:j%5?4:8;}
```
[Try it online!](https://tio.run/##XcyxasMwEAbgPU9xURHoEgUk5DjBRpgOLRQ6hWTLEmQrWJBLkdop5Nld2W2H9Ib74bufc6uzc8PgBckgI978NYpog1X1PNbRzmkRkFZ2uQzcNIGvm0QfsadPL5RUkvGWyYBVUY2notrW9@Gp7XxPHezzS0/422Ze8KJFsJADmp8QPOGRmMxFQZjbU1rrqWHpy7kuJVax1@e398PuhWE9u5x6yo1bfg4AWsK4cQZ/M3E5sfnHej1x@chGm8xaqQc25WYjR9UI9@Eb "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Lε35SÖ4*OygM}.¥sk
```
[Try it online](https://tio.run/##yy9OTMpM/f/f59xWY9Pgw9NMtPwr031r9Q4t9cz@/9/QFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/33ObTU2DT48zUTLvzLdt1bv0NLi7P86/6MNdAx1zHQMTXWMDY11jM3MzWMB).
**Explanation:**
```
L # Create a list in the range [1, (implicit) input]
# i.e. 15 → [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
ε # Map each value to:
35S # Push 35 as digit list: [3,5]
Ö # Check if the current value is divisible by these (1 if truthy; 0 if falsey)
4* # Multiply both by 4
O # And take the sum of that
# i.e. 2 → [0,0] → [0,0] → 0
# i.e. 9 → [1,0] → [4,0] → 4
# i.e. 10 → [0,1] → [0,4] → 4
# i.e. 15 → [1,1] → [4,4] → 8
yg # Push the current value again, and pop and push it's length
# i.e. 2 → 1
# i.e. 15 → 2
M # And then push the largest value on the stack
# i.e. 0 and 1 → 1
# i.e. 8 and 2 → 8
}.¥ # After the map: undelta the list (starting from 0)
# i.e. [1,1,4,1,4,4,1,1,4,4,2,4,2,2,8]
# → [0,1,2,6,7,11,15,16,17,21,25,27,31,33,35,43]
sk # Swap to get the (implicit) input, and get its 0-based index in the list
# i.e. 15 → 6
# (after which the result is output implicitly)
```
[Answer]
# Python 3.8 (86 bytes)
```
f=lambda s:len(s.rpartition("z")[2])/len(str(n:=max(s.count("F")*3,s.count("B")*5)))+n
```
This exploits the fact that after the last "Fizz" or "Buzz", all the following integers have the same number of digits.
[Try it Online](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRodgqJzVPo1ivqCCxqCSzJDM/T0OpSkkz2ihWUx8sU1KkkWdlm5tYAVSUnF@aV6Kh5KakqWWsA@c6Abmmmpqa2nn/C4oygSJpGkqGSpqaXAieERrXLbOqCouQCTYxp1LsakHiuMyByZnjlbTAL0vQcLAKQs5DqDI0JFYd8TZD1Boak6ba0IRU9aT6FF2foRlQ538A)
[Answer]
# Python 3 (79 bytes)
```
f=lambda s,n=0,l=0:l-len(s)and f(s,n+1,l+(4*(n%3//2+n%5//4)or len(str(n))))or n
```
# Python 2 (74 bytes)
```
f=lambda s,n=0,l=0:l-len(s)and f(s,n+1,l+(4*(n%3/2+n%5/4)or len(`n`)))or n
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 29 \log\_{256}(96) \approx \$ 23.87 bytes
```
Re1+Ax35d%.!S4*xdL~Ez(A$sAh1+
```
Port of Jonathan Allan's Jelly answer.
#### Explanation
```
# Implicit input
Re # Loop through range(0, input):
1+Ax # Add one and store in x without popping
35d # Pair [3, 5]
%.! # Check for divisibility
S4* # Multiply the sum by 4
xdL # Get the length of the digits of x
~ # Do a logical or
E # End the loop
z( # Get the running sums of the list
A$ # Push the input
sAh # Get the index of this in the running sums
1+ # And add one to account for Thunno's 0-indexing
# Implicit output
```
#### Screenshot
[](https://i.stack.imgur.com/wO2eb.png)
] |
[Question]
[
Write a program or function that takes in a 4×4 text grid consisting of exactly 4 `A`'s, 4 `B`'s, 4 `C`'s, and 4 `D`'s, such as:
```
ACDC
BBCA
BADD
ABCD
```
The `ABCD`'s may be in any arrangement but there will always be 4 of each. You can assume the input is valid. If desired you can also assume it has a trailing newline and/or that it comes as one line in reading order, e.g. `ACDCBBCABADDABCD`. You may also replace the characters `ABCD` with `0123` or `1234` respectively, if desired (but that's all).
Output a truthy value if the text grid has any form of reflective or rotational symmetry. Specifically:
* If there is a central horizontal line of symmetry. e.g.
```
BACD
BACD
BACD \___ bottom mirrors top
BACD /
```
* If there is a central vertical line of symmetry. e.g.
```
BCCB
DAAD
CAAC
BDDB
\/___ right mirrors left
```
* If there is a diagonal line of symmetry (in either direction). e.g.
```
___ diagonally mirrored
/
ABDC
BACD
DCAB
CDBA
\___ diagonally mirrored
```
* If there is 90° rotational symmetry. e.g.
```
BDAB
ACCD same if rotated 90 degrees (or 180 or 270)
DCCA
BADB
```
* If there is 180° rotational symmetry. e.g.
```
DBCA
BDCA same if rotated 180 degrees
ACDB
ACBD
```
(Note that translational symmetry doesn't come into play here.)
Output a falsy value if the grid doesn't have one of the symmetries mentioned above. e.g. the very first example grid.
**The shortest code in bytes wins.**
[Answer]
## CJam, 16 bytes
```
{{z_W%_}4*;])e=}
```
An unnamed block which expects the input as a list of four strings on top of the stack and leaves a `0` (falsy) for asymmetric inputs and a positive integer (truthy) for symmetric inputs.
[Test it here.](http://cjam.aditsu.net/#code=%5B%22ACDC%22%0A%20%22BBCA%22%0A%20%22BADD%22%0A%20%22ABCD%22%5D%0A%0A%7B%7Bz_W%25_%7D4*%3B%5D)e%3D%7D%0A%0A~) [Or run a full test suite.](http://cjam.aditsu.net/#code=%5B%22ACDCBBCABADDABCD%22%0A%20%22BACDBACDBACDBACD%22%0A%20%22BCCBDAADCAACBDDB%22%0A%20%22ABDCBACDDCABCDBA%22%0A%20%22BDABACCDDCCABADB%22%0A%20%22DBCABDCAACDBACBD%22%0A%20%22ABCDBABDCBACDDCA%22%0A%20%22DDCACBACBABDABCD%22%0A%20%22ABCDDACBDACBABCD%22%0A%20%22ADDABAABCCCCDBBD%22%5D%0A%7B4%2F%0A%0A%7B%7Bz_W%25_%7D4*%3B%5D)e%3D%7D%0A%0A~p%7D%2F)
### Explanation
The symmetries of the square are the elements of the [dihedral group of order 8](http://groupprops.subwiki.org/wiki/Dihedral_group:D8) (which are just the 4 rotations of the square and the same 4 rotations of some reflected version of the square). It's not possible to generate this group from repeated application of a single permutation. But two reflections always give some rotation. Hence, the entire group can be generated by alternating between two reflections four times. (We just need to make sure that the two reflections give the 90 degree or 270 degree rotation, not 0 or 180.)
The challenge asks whether the input square is equal to any of the other 7 symmetries. So this answer just generates all of them and then checks whether the input is among the others.
```
{ e# Run this block 4 times.
z_ e# Transpose the grid and duplicate it. (This is one type of reflection.)
W%_ e# Reverse the lines and duplicate it. (This is another type of
e# reflection. Together they rotate the grid by 90 degrees.)
}4* e# The last element will be the original grid again.
; e# Discard one copy of that original grid.
] e# Wrap all symmetries in a list.
) e# Pull off the original grid.
e= e# Count how many times it appears among the other symmetries.
```
To see how the repeated application of `z` and `W%` generates all symmetries, have a look at this "diagram":
```
0123
4567
89ab
cdef
original
z 048c W% 37bf
--> 159d -----------> 26ae
26ae 159d
37bf 048c
diag. refl. rot. 90 degrees ccw
z 3210 W% fedc
--> 7654 -----------> ba98
ba98 7654
fedc 3210
vert. refl. rot. 180 degrees
z fb73 W% c840
--> ea62 -----------> d951
d951 ea62
c840 fb73
antidiag. refl. rot. 270 degrees ccw
z cdef W% 0123
--> 89ab -----------> 4567
4567 89ab
0123 cdef
horiz. refl. original
```
[Answer]
# Pyth, 11 bytes
```
<7.u?%Y2CN_
```
[Test suite](https://pyth.herokuapp.com/?code=%3C7.u%3F%25Y2CN_&input=%0A&test_suite=1&test_suite_input=%5B%27ACDC%27%2C+%27BBCA%27%2C+%27BADD%27%2C+%27ABCD%27%5D%0A%5B%22BACD%22%2C+%22BACD%22%2C+%22BACD%22%2C+%22BADC%22%5D%0A%5B%22BCCB%22%2C+%22DAAD%22%2C+%22CAAC%22%2C+%22BDDB%22%5D%0A%5B%22BACD%22%2C+%22BACD%22%2C+%22BACD%22%2C+%22BACD%22%5D%0A%5B%27ABDC%27%2C+%27BACD%27%2C+%27DCAB%27%2C+%27CDBA%27%5D%0A%5B%27BDAB%27%2C+%27ACCD%27%2C+%27DCCA%27%2C+%27BADB%27%5D%0A%5B%27DBCA%27%2C+%27BDCA%27%2C+%27ACDB%27%2C+%27ACBD%27%5D&debug=0)
This uses Martin's transpose and reverse technique, but with a twist. While other solutions have explicitly generated all 8 symmetries, then counted the number of appearances of the original, this program uses Pyth's `.u` function.
The `.u` function is the "Apply until repeat is found". In this case, we alternately transpose and reverse until a repetition happens, then accumulate the results into a list. Then, I remove the last 7 values, so there will only be a value remaining if there were no symmetries, and the first repetition happened after all 8 reflections and repetitions were generated.
Explanation:
```
<7.u?%Y2CN_
<7.u?%Y2CN_NQ Implicit variables
Q = eval(input())
.u Q Starting with Q, apply the following until a repeat occurs,
then accumulate all values into a list.
?%Y2 If the iteration number is odd
CN Transpose
_N Else reverse
<7 Remove the last 7 results
```
[Answer]
## [05AB1E](https://github.com/Adriandmen/05AB1E/), 13 bytes
```
4Fø€JÂD}\\)¹å
```
**Explanation**
Uses the method expertly explained by [Martin in his CJam answer](https://codegolf.stackexchange.com/a/90218/47066).
```
4F } # 4 times do:
ø€J # zip and join each
ÂD # bifurcate, duplicate
\\ # delete the top 2 items on the stack
) # wrap stack in list
¹å # check if input is in that list
```
[Try it online](http://05ab1e.tryitonline.net/#code=NEbDuOKCrErDgkR9XFwpwrnDpQ&input=WydCREFCJywnQUNDRCcsJ0RDQ0EnLCdCQURCJ10)
[Answer]
# Perl, ~~61~~ 60 bytes
Includes +3 for `-p0a`
Give input square on STDIN, prints 0 for no symmetry, otherwise some positive number
```
./symmetry.pl
DBCA
BDCA
ACDB
ACBD
^D
```
`symmetry.pl`:
```
#!/usr/bin/perl -p0a
s,.,chop$F[$i++/($j-4?1:4)%4],eg;$\+=$$_++;++$j<8&&redo}{
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~37~~ ~~19~~ 17 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
@ngn reduced it by 20 bytes!
```
8>≢(∪⊢,⌽¨,⍉¨)⍣≡⊂⎕
```
[TryAPL online!](http://tryapl.org/?a=f%u2190%7B8%3E%u2262%28%u222A%u22A2%2C%u233D%A8%2C%u2349%A8%29%u2363%u2261%u2282%u2375%7D%20%u22C4%20%u22A2squares%u21904%204%u2218%u2374%A8%27ACDCBBCABADDABCD%27%20%27BACD%27%20%27BCCBDAADCAACBDD%27%20%27ABDCBACDDCABCDB%27%20%27BDABACCDDCCABAD%27%20%27DBCABDCAACDBACBD%27%20%u22C4%20f%A8squares&run)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~38~~ 36 bytes
```
@eL:1fbeL
(L;?:raL)(.;L$\.;L$/.;Lr.)
```
[Try it online!](http://brachylog.tryitonline.net/#code=QGVMOjFmYmVMCihMOz86cmFMKSguO0wkXC47TCQvLjtMci4p&input=WyJCREFCIjoiQUNDRCI6IkRDQ0EiOiJCQURCIl0)
This expects a list of strings as input. This prints either `true.` or `false.`.
### Explanation
* Main predicate:
```
@eL Split each line into a list of chars ; call that list of lists L
:1f Find all symmetries
b Remove the first one (the identity)
eL L is an element of that list of symmetries
```
* Predicate 1: Output is one of the 8 symmetries of the input.
```
(
L L = Input
; Or
?:raL L = reverse all lines of the input
)
(
. Output = L
; Or
L$\. Output = transpose of L
; Or
L$/. Output = antitranspose of L
; Or
Lr. Output = reverse of L
)
```
[Answer]
# TSQL, ~~229~~ 225 bytes
Be aware TSQL has no build-in for rotating, so this is part the code.
Returning -1 for true 0 for false
**Golfed:**
```
DECLARE @1 char(16)='BCCBDAADCAACBDDB'
DECLARE @i INT=0,@ char(16)=0WHILE @i<16SELECT
@=substring(@1,@i*4%16+@i/4+1,1)+@,@i+=1SELECT~count(*)/2FROM (SELECT
left(x,8)a,right(x,4)b,substring(x,9,4)c
FROM(values(@1),(@))x(x))x
WHERE a in(reverse(b+c),b+c,reverse(c+b))
```
**Ungolfed:**
```
DECLARE @1 char(16)='BCCBDAADCAACBDDB'
DECLARE @i INT=0,@ char(16)=0
WHILE @i<16
SELECT @=substring(@1,@i*4%16+@i/4+1,1)+@,@i+=1
SELECT~count(*)/2
FROM
(SELECT left(x,8)a,right(x,4)b,substring(x,9,4)c
FROM(values(@1),(@))x(x))x
WHERE a in(reverse(b+c),b+c,reverse(c+b))
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/1191884/is-this-square-symmetrical)**
[Answer]
# Python 2, ~~154~~ 146 bytes
Checks if any of the necessary transformations is equivalent to the original using numpy arrays. Input is taken as a list of four strings.
```
from numpy import*
A=array(map(list,input()))
R=rot90
T=transpose(A)
print any([all(A==Z)for Z in(A[:,::-1],A[::-1],R(A),R(A,2),R(A,3),T,R(T,2))])
```
[**Try it online**](http://ideone.com/bSIQ4D)
Taking input as a single string is one char longer, with `A=array(list(input())).reshape(4,4)`. `A[:,::-1]` is the same as `fliplr(A)`. `A[::-1]` is the same as `flipud(A)`.
[Answer]
# Python 3, 99 bytes
```
def f(x):
t=x;c=[]
for i in range(7):*t,=[map(''.join,zip(*t)),t[::-1]][i%2];c+=t,
return x in c
```
A function that takes input, via argument, of a list of strings and returns `True` or `False` as relevant.
This uses the same approach as @MartinEnder's [answer](https://codegolf.stackexchange.com/a/90218/55526).
**How it works**
```
def f(x) Function with input list of strings x
t=x;c=[] Initilaise temporary square t and combination list c
for i in range(7):... For i in range [0,6]:
[...][i%2] If i is even:
zip(*t) transpose(t)
*t,=map(''.join,...) t = t with each line concatenated (such that t is in the same
format as x)
Else:
*t,=t[::-1] t = reverse(t)
c+=t, Append t to c
return x in c Return True if x is in c else return False
```
[Try it on Ideone](http://ideone.com/5ZFFRg)
[Answer]
## JavaScript (ES6), 131 bytes
```
s=>[...`0101010`].map(c=>+c?``+b.reverse():`${b=b.map((s,i)=>s.replace(/./g,(_,j)=>b[j][i]))}`,b=a=s.match(/..../g)).includes(``+a)
```
17 bytes could be removed if you pass an array of 4 strings directly. I tried bit-twiddling (input in `"0123301223011230"` format) but that took me 199 bytes:
```
s=>[...'0101010'].map(c=>r=+c?r<<24&255<<24|r<<8&255<<16|r>>8&255<<8|r>>>24:r&0xc0300c03|r<<6&806093568|r<<12&3075<<16|r<<18&3<<24|r>>6&0xc0300c|r>>12&49200|r>>18&192,r=n=parseInt(s,4)|0).includes(n)
```
] |
[Question]
[
(This is [A065825](https://oeis.org/A065825).) The [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") defaults apply, so you can pick another format other than this one.
Given an input integer `n`, find the smallest number `k` so that there exists an n-item subset of `{1,...,k}` where no three items form an arithmetic progression.
## Procedure
Here, we calculate `A065825(9)`.
We assume you have already looped from 1 to 19, and `k`=20 (it's just an example).
### 1. Generate a range from 1 to k.
```
[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
```
### 2. Pick `n` items from that sequence, following the original order of the sequence.
```
[1 2 6 7 9 14 15 18 20]
```
### 3. No 3 items form an arithmetic progression.
If a sequence has arithmetic progression, it basically means the sequence has the same step between every two consecutive items.
For example, the sequence of positive even numbers (`[2 4 6 8 ...]`) has a consistent step (i.e. `4-2=2`, and `6-4=2`, etc.), so it has arithmetic progression.
The Fibonacci sequence (`[1 1 2 3 5 8 13 21 ...]`) does not have arithmetic progression, since it does not have a consistent step. (`3-2=1`, `5-3=2`, `8-5=3`, etc.)
As an example, let's pick 3 items from our generated sequence.
```
[1 2 6 [7 9 14] 15 18 20]
```
The picked 3-item sequence does not have arithmetic progression, since the differences are respectively `9-7=2` and `14-9=5`.
This has to apply to **every 3-item pair**:
```
[[1 2 6] 7 9 14 15 18 20] (2 -1 =1, 6 -2 =4)
[1 [2 6 7] 9 14 15 18 20] (6 -2 =4, 7 -6 =1)
[1 2 [6 7 9] 14 15 18 20] (7 -6 =1, 9 -7 =2)
[1 2 6 [7 9 14] 15 18 20] (9 -7 =2, 14-9 =5)
[1 2 6 7 [9 14 15] 18 20] (14-9 =5, 15-14=1)
[1 2 6 7 9 [14 15 18] 20] (15-14=1, 18-15=3)
[1 2 6 7 9 14 [15 18 20]] (18-15=3, 20-18=2)
```
Here are some examples of picking non-consecutive items from the output sequence:
```
[1 [2] 6 [7] 9 [14] 15 18 20] (7-2=5,14-7=7)
[[1] 2 6 [7] [9] 14 15 18 20] (7-1=6,9 -7=2)
```
If the above is satisfied for `k`, then `k` is a valid output for `A065825(9)`.
## Test cases
[Here](https://tio.run/##AS4A0f9vc2FiaWX//@KInsqSTMOmScO5ypLDpjPDuc61wqXDi33DoF99Z8SAfdC9//83) is a reference program I use to check my test cases.
```
n a(n)
1 1
2 2
3 4
4 5
5 9
6 11
7 13
8 14
9 20
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
ff!/#.OZ.cY3.cSTQ
```
[Try it online!](https://tio.run/##K6gsyfj/Py1NUV9Zzz9KLznSWC85OCTw/38zAA "Pyth – Try It Online")
`.cSTQ`: generate all list of numbers in the range [1,T] with length equal to the input.
`.cY3`: for each of those, generate all length 3 subsequences.
`/#.OZ`: filter for the subsequences where the average is a member of the list. These are the arithmetic progressions.
`f!`: filter for the original lists with no arithmetic progressions
`f`: find the lowest T where at least one list is found.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~123~~ ~~115~~ ~~96~~ 94 bytes
Another ~~-15~~ -17 bytes thanks to [Surcolose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!
```
f=lambda n,k=1:len(d:=f'{k:b}')*all(k>>i&k&k<<i<1for i in range(d.count('1')//n,k))or f(n,k+1)
```
[Try it online!](https://tio.run/##Vc7BasMwDAbge55C9NDYntvGK5QSksDYqXS7bL2PNHE2YccOsnMoo8/emY0NdhAI6dOPpkv88G67n@iG4@QpAungZ@q0hHAJWap10JF0N1NA7yyOGJkqhNjx7Jd@i5/N3@jl6fB8OL29nh4ejxLYvRDbQsJKcX4batuO574FJ02tSqsd68t6yD9Neb7mXLTWMtM0uDRLU1VYqcETIKADat27Zv2687OLLFc532xSCOcJDCx1dyrF/9dKqoKXGcBEmI5QwmLVLGTymH75Ag "Python 3.8 (pre-release) – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~147~~ ~~135~~ 124 bytes
-11 bytes thanks to [Surcolose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!
```
from itertools import*
f=lambda n,k=1,C=combinations:k*any(all(a+c-b*2for a,b,c in C(w,3))for w in C(range(k),n))or f(n,k+1)
```
[Try it online!](https://tio.run/##JcwxDoMwDIXhnVNkjMEdQjckJk7iUNJaJDYKkRCnT0GM79ent53lp9LXGrImw2XJRTXuhtOmubRNGCMl/yEjuI4Op3HW5FmosMo@rC3JaSlGS9388m0fNBtCj7NhMZM98A1wt@PZmeS72BVQAK4a7PXaOag34Zs8wKFzMDRmyyzFMF6Qof4B "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~96~~ 83 bytes
```
k=n=scan();C=combn;`[`=Map;try(while(!any(all[diff[C[C(1:k,n,,F),3],1,2]]))k=k+1);k
```
[Try it online!](https://tio.run/##K/r/P9s2z7Y4OTFPQ9Pa2TY5PzcpzzohOsHWN7HAuqSoUqM8IzMnVUMxMa9SIzEnJzolMy0t2jnaWcPQKlsnT0fHTVPHOFbHUMcoNlZTM9s2W9tQ0zr7v8V/AA "R – Try It Online")
Full program, returns 1-indexed member of the sequence. Very slow for `n > 8`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
∞.ΔLI.Æε3.Æε¥Ë≠}P}à
```
Outputs the \$n^{th}\$ value \$k\$.
[Try it online](https://tio.run/##yy9OTMpM/f//Ucc8vXNTfDz1Dred22oMJg8tPdz9qHNBbUDt4QX//5sDAA) or [verify the first 8 test cases](https://tio.run/##yy9OTMpM/W/h6ndopb2SwqO2SQpK9v8fdczTOzfF59A6vcNt57Yag8lDSw93P@pcUBtQe3jB/1qd/wA) (times out for \$\geq9\$).
**Explanation:**
```
∞.Δ # Find the first positive integer `k`
L # for which its list in the range [1,k]
I.Æ # with combinations of the input amount of elements
ε }à # contains any combination-list which is truthy for:
3.Æ # When taking all 3-element combinations of the current list
ε }P # they are all truthy for:
¥ # When taking the forward differences of both pairs in this triplet
Ë≠ # they are NOT the same
# (after which the resulting `k` is output implicitly)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~109...94~~ 91 bytes
*-8 bytes thanks to @GB*
```
->n{1.step.find{|k|[*1..k].combination(n).any?{|p|p.combination(3).all?{|a,b,c|b-a!=c-b}}}}
```
[Try it online!](https://tio.run/##VY0/D4IwFMR3P8VDB8A8Ggti/BN0MA4umhg3ZGhRIlEfRHAwbT871sTFG2643@Xu@ZLvrkhOXbAkxVnTXmpWlHRW@qbTIWfslrG8esiSRFtW5JHPBL1XSte6/gORBfe7BQIl5loGwknyQBqrTowm8TSMIYGUY4hjjHGGnCOPkI8xHGU9zz7NfHYR@RUUaNJQ2XaRUraA@tU20BfeQJHxbTpQlfmak/x2WXMtixZW4G53LszBdc16fzhs1kenD6b7AA "Ruby – Try It Online") Takes less than 1 s for \$n\le9\$. Times out for \$n\ge12\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œcœc3IEƇƊÐḟð1#
```
A monadic Link accepting a non-negative integer which yields a non-negative integer.
**[Try it online!](https://tio.run/##y0rNyan8///o5GQgMvZ0PdZ@rOvwhIc75h/eYKj8//9/cwA "Jelly – Try It Online")** (Too inefficient for n=9 within 60s.) Or see the [test-suite](https://tio.run/##y0rNyan8///o5GQgMvZ0PdZ@rOvwhIc75h/eYKj83@Jw@6OmNf8B "Jelly – Try It Online").
### How?
```
œcœc3IEƇƊÐḟð1# - Link: integer, n
1# - let k=n and count up to find the first k, for which this is truthy:
ð - dyadic chain - i.e. f(k, n):
œc - combinations of length (n) of (implicit [1..k])
Ðḟ - filter discard those n-tuples which are truthy under:
Ɗ - last three links as a monad:
œc3 - combinations of length three of (the n-tuple)
I - incremental differences - e.g. [3,6,8]->[6-3,8-6]->[3,2]
Ƈ - filter keep those diffence-pairs which are truthy under:
E - all equal?
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 94 bytes
```
(t=1;While[Select[Range@t++~(S=Subsets)~{#},!Or@@(Equal@@Differences@#&/@#~S~{3})&]=={}];t-1)&
```
[Try it online!](https://tio.run/##JcwxCsMgFADQq7QIEkmLhE4lCH9o55Y6dAgZrPwkghGqP5PEq9uh7wBvNbTgashZU2dVG1Jd/16cx0GjR0vDy4QZgdq2NFrp7ZOQkiiZ7afjIwI09@9mPMDNTRNGDBYTMC6BFV3yZRd8VCrvY0/nTvD6jC6QhFnC4f9ea/0B "Wolfram Language (Mathematica) – Try It Online") 1-9 takes 1 min
[Answer]
# JavaScript (ES6), ~~150~~ 145 bytes
This is quite inefficient for \$n>8\$.
```
n=>(g=a=>(P=a=>a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]))(a).some(a=>a[n-1]*P(a).every(([a,b,c,d])=>d|b-a!=c-b))?k:g([...a,++k]))([k=1])
```
[Try it online!](https://tio.run/##JYxBDoIwFET3nqImLP6X0oSdUatXYN804VMKUbQ1oASCnB1p2LxJJjPvQT11pr2/P4nzpV0quTh5hVrSyiyQRGvLr7EAxAeUVyWEIB4gXvSGcWtGPmjUXCmtEYFQdP5lIdyVS1J9yEJne9uOAIp4wQ0v9Worf0VCe2mSAvHWnGrY9HHcBI9qZKpxqXwLjkmWnpljF8mOa8YxTjvGjHedf1rx9DXkBNHkZlyX0VSBwznH3bz8AQ "JavaScript (Node.js) – Try It Online")
## Commented
### Helper function
Since we don't have any combinatorial function available as a built-in, we're going to define just one: \$P\$ is a helper function that computes the powerset of a given array.
```
P = a =>
a.reduce((a, x) =>
[...a, ...a.map(y => [...y, x])],
[[]]
)
```
### Main function
```
n => ( // n = input
g = a => // g is a recursive function taking a range a[]:
P(a).some(a => // for each array a[] in the powerset of a[]:
a[n - 1] * // make sure that the length of a[] is at least n
P(a) // compute the powerset of a[]
.every( // for each quad [a,b,c,d] in there,
([a, b, c, d]) => // the test is successful if either:
d | // - d is defined (meaning that this array has
// more than 3 entries)
b - a != c - b // - or a,b,c is not an arithmetic progression
) // end of every()
) // end of some()
? // if truthy:
k // success: return k
: // else:
g([...a, ++k]) // try again with k+1 appended to a[]
)([k = 1]) // initial call to g with k = 1 and a = [1]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
`@:GXN!"@IXN!ddA]va~}@
```
[Try it online!](https://tio.run/##y00syfn/P8HByj3CT1HJwRNIpqQ4xpYl1tU6/P9vAQA) Or [verify test cases `1`‒`8`](https://tio.run/##y00syfmf8D/Bwco9wk9RycETSKakOMaWJdbVOvyPdYmqCPlvyGXEZcxlwmXKZcZlzmUBAA) (test case `9` times out online).
### Explanation
```
` % Do...while
@: % Push range [1 2 ... k] where is the current iteration index
G % Push input, n
XN % Combinations of the elements [1 2 ... k] taken n at a time. This
% gives an n-column matrix where each row is a combination
! % Transpose. Each combination is now a column
" % For each column
@ % Push current column
I % Push 3
XN % Combinations of the elements of the current column taken n at
% a time. This gives a 3-column matrix
! % Transpose. Each combination is now a column
dd % Consecutive differences along each column, twice. This gives a
% row vector containing 0 for columns whose three elements form
% an arithmetic progression
A % All. This gives true if all entries of the vector are non-zero;
% that is, if there were no arithmetic progressions of length 3
] % End
v % Concatenate the stack into a column vector
a~ % Any, negate. Gives false if any entry from the above vector is
% non-zero. This will be used as loop condition; that is, if false
% the loop will end
} % Finally (execute on loop break)
@ % Push latest k
% End (implicit). The top of the stack is used as loop condiion
% Display (implicit)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~40~~ 37 bytes
```
≔⁰ηW∨⁻Σ⍘η²IθΦη&η&×ηX²⊕λ×ηX⁴⊕λ≦⊕ηIL↨η²
```
[Try it online!](https://tio.run/##ZY5BCsIwEEX3niLLCUSQoquuWkEQLBbqBUI7NANpqklqjx@b2IXUWc38/xheq6RtR6lDKJyj3sBBMMXz3axII4O7hYrM5KCZBiilw8ZbMj0owTLOBTtL5@EVtwtpjzYWJfmZHBam21wPGtDFrB7nBc0Eu5rW4oDGYweaxzcb5vjPpGGVfK7CP/1XvV4MPSSzG5reqyS@KnOeh3AK@7f@AA "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 3 byte by porting @SurculoseSputum's method. Now too slow for `n>6`. Explanation:
```
≔⁰η
```
Start with an empty bitmask.
```
W∨⁻Σ⍘η²Iθ
```
Repeat while the bitmask contains the wrong number of bits...
```
Φη&η&×ηX²⊕λ×ηX⁴⊕λ
```
... or it contains three terms in arithmetic progression...
```
≦⊕η
```
... increment the bitmask.
```
IL↨η²
```
Output the the length (in base 2) of the bitmask, which is necessarily equal to `k`.
At a cost of 2 bytes, I can replace `Φη` with `⊙↨η²`, which makes the code fast enough to compute up to `n=9`:
```
≔⁰ηW∨⁻Σ⍘η²Iθ⊙↨η²&η&×ηX²⊕λ×ηX⁴⊕λ≦⊕ηIL↨η²
```
[Try it online!](https://tio.run/##ZY/BCsIwEETvfkWOG4ggxYPQU@tJsFioPxDapQmkW01Si18fm9RD0TntzgzL21ZJ247ShFA4p3uCg2CK57tZaYMMbhYqTZODZhqglA4bbzX1oATLOBfsLJ2HZ5wKeqfCGglWaj9rhwV10dlsdz2gi149zmghE@xCrcUByWMHhsdjP53jfyeJVfLxxd7k6wP1wukh8V2Req82dIvyEE5h/zIf "Charcoal – Try It Online") Link is to verbose version of code. (Link only computes `n=8` to avoid unnecessarily overloading TIO.)
Looping over the odd numbers is slightly faster still, but not enough to be able to compute `n>9` on TIO. (It also gives the wrong answer for `n=0`, although that's not required by the question.)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 91 bytes
```
.+
*_¶
/^(_)*¶(?<-1>10*)*(?(1)$|1)|1(.)*1(?<-2>.)*(?(2)$)1/{`¶(1*)$
¶0$1
)T`10`d`01*$
r`.\G
```
[Try it online!](https://tio.run/##HcshDsJAEAVQP@cYMX8I2/1VCNJKLoBs6JCAwCAaHD3XHmAvtoXql7c8P6/3na2lg/hci3Q3m@G12Hg@cmB2uI1G6EqstATnn/oh7dBDwe4bv0CHSi1ZKbgGczwi01WWSNOltdMG "Retina – Try It Online") Uses @SurculoseSputum's method, but too slow for `n>8`. Explanation:
```
.+
*_¶
```
Convert `n` to unary, and add a working area for the bitmask.
```
/^(_)*¶(?<-1>10*)*(?(1)$|1)|1(.)*1(?<-2>.)*(?(2)$)1/{`
)`
```
Repeat while the number of bits in the bitmask is not `n`, or there are three bits in the bitmask with identical spacing...
```
¶(1*)$
¶0$1
```
If the bitmask contains no zeros then prefix one.
```
T`10`d`01*$
```
Increment the bitmask.
```
r`.\G
```
Output the length of the bitmask, which is necessarily equal to `k`.
The bitmask computations involve .NET balancing groups.
```
^(_)*¶
```
This captures the unary value of `n`. Since the `*` is outside of the `(_)`, the group is captured `n` times. .NET records each capture as a stack, so `$1` now has a depth of `n`.
```
(?<-1>10*)*
```
This attempts to match the regex `10*`. Each successful match pops one of the captures from the `$1` stack. This continues until the stack is empty or there are no matches.
```
(?(1)$|1)
```
A conditional expression now checks whether the stack is empty. If it is not, then we want this to be because we ran out of `1` bits to match, which will be at the end of the string. If the stack is empty, then we want this to be because there are too many `1` bits, so we should be able to match one.
Note that while Retina will try to backtrack if it fails to match, this necessarily means both that the stack is not empty and that the match is not at the end of the string, i.e. this condition will never succeed in the case where the number of bits is correct.
```
1(.)*1(?<-2>.)*(?(2)$)1
```
In a similar way, we capture a variable number of bits between two `1` bits, and then require that the same number of bits exists between the latter and another `1` bits. Here the condition for a non-empty stack is a logical impossibility (`$` before a `1`) thus requiring the stack to be empty at this point, indicating that the number of bits is the same.
] |
[Question]
[
My birthday is in a month, and this is a slice of tasty cake.
```
.-""-.
.-" "-.
|""--.. "-.
| ""--.. "-.
|""--.. ""--..\
| ""--.. |
| ""--..|
""--.. |
""--.. |
""--..|
```
In the fewest number of bytes, construct this slice of cake for me. You can print it to STDOUT or return it as a function result.
Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately.
### Rules and I/O
* No input
* Output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# Eggsembly - 203 bytes
```
push ' .-""-.\n .-" "-.\n|""--.. "-.\n| ""--.. "-.\n|""--.. ""--..|\n| ""--.. |\n| ""--..|\n ""--.. |\n ""--.. |\n ""--..|'
```
Here is a less golfed version.
```
push ' .-""-.\n'
push ' .-" "-.\n'
add
push '|""--.. "-.\n'
add
push '| ""--.. "-.\n'
add
push '|""--.. ""--..\\n'
add
push '| ""--.. |\n'
add
push '| ""--..|\n'
add
push ' ""--.. |\n'
add
push ' ""--.. |\n'
add
push ' ""--..|\n'
add
```
---
This one works a bit differently, but it's significantly shorter in Chicken at 57,878 bytes.
```
push " "
push 4
rooster
push '.-""-.\n'
add
push ' .-"'
push " "
push 6
rooster
add
push '"-.\n'
add
push '|""--..'
push " "
push 6
rooster
add
push '"-.\n|'
add
push " "
push 6
rooster
add
push '""--.. "-.\n'
add
push '|""--..'
push " "
push 6
rooster
add
push '""--..\\n'
add
push '|'
push " "
push 6
rooster
add
push '""--.. |\n'
add
push '|'
push " "
push 12
rooster
add
push '""--..|\n'
add
push ' ""--..'
push " "
push 12
rooster
add
push '|\n'
add
push " "
push 7
rooster
add
push '""--..'
push " "
push 6
rooster
add
push '|\n'
add
push " "
push 13
rooster
add
push '""--..|\n'
add
add
add
add
add
add
add
add
```
---
# Chicken - ~~57,878~~ 28,135 bytes
```
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken
chicken chicken
chicken chicken
```
So what was changed here is a little more understandable, here's the Eggsembly version.
```
push " "
push 4
rooster
push 4
peck
pick 4
axe
push '.-""-.\n'
add
push ' .-"'
pick 4
axe
push " "
push 2
rooster
add
push 6
peck
pick 6
axe
add
push '"-.\n'
add
push '|'
push '""--..'
push 2
peck
pick 2
axe
add
add
pick 6
axe
add
push '"-.\n'
add
push '|'
add
pick 6
axe
add
pick 2
axe
add
push " "
push 3
rooster
add
push '"-.\n'
add
push '|'
add
pick 2
axe
add
pick 6
axe
add
pick 2
axe
add
push '\\n'
add
push '|'
add
pick 6
axe
add
pick 2
axe
add
pick 6
axe
add
push '|\n'
add
push '|'
add
pick 6
axe
pick 6
axe
add
push 3
peck
pick 3
axe
add
pick 2
axe
add
push '|\n'
add
push " "
add
pick 2
axe
add
pick 3
axe
add
push '|\n'
add
pick 6
axe
push " "
add
add
pick 2
axe
add
pick 6
axe
add
push '|\n'
add
pick 3
axe
add
push " "
add
pick 2
axe
add
push '|\n'
add
add
```
[Answer]
# JavaScript (ES8), ~~115~~ 112 bytes
*Saved 3 bytes thanks to @ovs*
```
_=>`4.-""-.
1.-"6"-.
|06"-.
|603"-.
|060\\
|606|
|660|
1066|
706|
670|`.replace(/\d/g,n=>''.padEnd(n)||'""--..')
```
[Try it online!](https://tio.run/##LY1BCsMgFET3OUY2KtSfH1p@VmbXWwiNqAktopKUrry7NbSbefNmMy/zMYfdn/ktY3K@rqo@1LzcQPa9hG5spLMU/IHw@lfU@lQqLQlLNyK1Pp0DTVgW2H0Oxno@aDdsl6hmxiAbd4@OR1EKawcSgIlqUzxS8BDSxlcuRP0C "JavaScript (Node.js) – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~77~~ ~~65~~ ~~58~~ ~~54~~ ~~44~~ ~~43~~ ~~42~~ ~~40~~ 39 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
"-.*\\\
2⁸±4⁸+3⁸21*⌐∔13╋5|*×ω\;∔A«3╋03╋
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTIyLS4ldUZGMEEldUZGM0MldUZGM0MldUZGM0MlMEEldUZGMTIldTIwNzglQjEldUZGMTQldTIwNzgldUZGMEIldUZGMTMldTIwNzgldUZGMTIldUZGMTEldUZGMEEldTIzMTAldTIyMTQldUZGMTEldUZGMTMldTI1NEIldUZGMTUlN0MldUZGMEElRDcldTAzQzklNUMldUZGMUIldTIyMTQldUZGMjElQUIldUZGMTMldTI1NEIldUZGMTAldUZGMTMldTI1NEI_,v=8)
Explanation:
```
"-.*\\\ Helper function F taking an argument n
"-.* an array of n strings `"-.`
\\\ pad each line with 1 more space than the previous, 3 times
Main program:
2⁸ execute F with 2
± reverse that
4⁸+ and append F(4) - the top of the cake
3⁸ F(3)
21* extend horizontally 2x and vertically 1x - create one stripe
⌐ create extra 2 copies of that on the stack
∔ append 2 of those together
13╋ and insert it at (1; 3) in the last line
5|* array of 5 "|"
× prepend that to the left of the stripes
ω retrieve back the array of "|"
\;∔ prepend "\" to that
A«3╋ and insert that at ((10<<1); 3) in the object
03╋ and join the two parts together
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
F³«↑Fι⸿↑F³¶""--..»↑⁵←\F⁴←¶.-"F²«←"-.↓»↓⁵
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw1hToZqL0ze/LFXDKrRA05qLEyycqakQUJSZV6KhFFOkBBLFUGGMUJEXoxSjpKurpwdSWcsFEQaq1VEwBQpAuT6paSU6CkoxMSBFYBNMYCbA5fL0dGOU4PJGYKehKVHS1UNyj0t@eR6ynSA@2Nb////rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F³«
```
Loop over the three horizontal lines.
```
↑Fι⸿↑
```
The lines overlap by an amount depending on which line we're on. This calculates the correct amount of overlap but also moves the cursor to the left of the canvas again.
```
F³¶""--..»
```
Repeat three times, move the cursor down one line and then print a third of the horizontal line.
```
↑⁵←\
```
Print the vertical line on the right and the backslash on the corner.
```
F⁴←¶.-"
```
Repeat four times, move the cursor up one line and then print a quarter of the diagonal.
```
F²«←"-.↓»
```
Print the other diagonal. (I couldn't find a way of combining the printing with the movement but this is still 2 bytes shorter than the next best way I could find.)
```
↓⁵
```
Print the vertical line on the left.
[Answer]
# T-SQL, ~~125~~ 121 bytes
```
PRINT REPLACE(REPLACE(' .-""-.
.-"1"-.
|21"-.
|12 "-.
|212\
|121|
|112|
211|
121|
112|',2,'""--..'),1,' ')
```
Due to the overhead of the `REPLACE()` keyword, just two replacements gave me the best score. SQL allows line breaks inside of strings, so I don't have to replace those with `CHAR(13)` or whatever.
Hard to tell in the code above, but I had to add an extra space after the `\`, because normally that would be an escape character that would cause it to ignore the subsequent line break.
**EDIT**: Saved 4 bytes by changing my replacement characters to numerals instead of letters. This lets me eliminate the single quotes since `REPLACE` casts them to strings implicitly.
This generates:
```
.-""-.
.-" "-.
|""--.. "-.
| ""--.. "-.
|""--.. ""--..\
| ""--.. |
| ""--..|
""--.. |
""--.. |
""--..|
```
Happy birthday (next month)!
[Answer]
# Python 2, 99 bytes
```
00000000: 2363 6f64 696e 673a 4c31 0a70 7269 6e74 #coding:L1.print
00000010: 2278 da53 5050 50d0 d355 52d2 d5e3 02d1 "x.SPPP..UR.....
00000020: 5c6e 605c 30e2 d55c 30c5 74f5 f490 04a0 \n`\0..\0.t.....
00000030: 4c98 30a6 5c22 303b 0643 2110 d4c0 0491 L.0.\"0;.C!.....
00000040: a56a b850 d4c0 542a 60d3 ae80 453b 5c30 .j.P..T*`...E;\0
00000050: a94e 1d27 222e 6465 636f 6465 2827 7a69 .N.'".decode('zi
00000060: 7027 29 p')
```
[Try it online!](https://tio.run/##hZE/T8MwEMV3PsWjDAGkWhfbZydtN@hWVRV/tgx1Y4eWIa1Kh4L47uFCM7Bxkq2TfO93786b8LHtzueI8RGzWTZfPmb4xuHztN23GuOOhphAG2fgGmfhSpfgvAmwtclBwRO8diVc8ha4qfdx175NFrk6HHft6epCyHuG9gViYAMmJrkiIRpmsI4akZMB6ZgDo7N6Xq1WSr0@qT4GhhYG13134hqGUi/6zWqGtw2jsSWBbCCgatcVKSXn9JdhhGHrshBRcELTWjKzATlroPNcHNm6Z5TiY6FIVSOaqofrvwwrjMAuYFPwUM9WB7EVDUIqCJYFybURH@pdySAv92vRz6cVDQzuGaVNyKP2shktU1nHcMY1l0wX8uCDLBZqqbKRiklWm26zr93AcMLw1Mul5r84ZHed/G/3Aw "Bash – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 47+61=108 bytes
Once again stolen from @DigEmAll's nice answer previously, just compress to gzip and decompress in a 2 part answer.
```
cat(memDecompress(readBin('a','raw',61),'g',T))
```
[Try it online!](https://tio.run/##bU7BasMwDL37K4QpKA6OYTvsMOil2yf0mIvaqJuhcYLtUDry75mSNdDRCoOlp/eeXpxoiyDlKq0rp@YflpqnUbDKuTvg1q7wI2np6wei1LiC96tR/eOsTHgmhydyVOoSfeadD0XL7UfX9pFTKshYJDRKHSkXuixL2H/7BPIIXuHkzwxpOLQ@Jd8FJ0sGahqfZaIzHK6ZEzQDQ@7Ah37If5JALTcgxkCR4R20XXDnw6krNGmzSf6HLeDNQe6ixTrUAW3ifqu1meZAkvSTj2vWyNTM@cXXYqQL2rcXif@Fdm/MNP0C "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 58 bytes
```
”. -"|\
”S”""--..”ð6×)˜•I8Γ·³§€ΓÎíÈÜ7γ¿·U₃´îØ©G¹râî.
d•SèJ
```
[Try it online!](https://tio.run/##AWsAlP9vc2FiaWX//@KAnS4gLSJ8XArigJ1T4oCdIiItLS4u4oCdw7A2w5cpy5zigKJJOM6TwrfCs8Kn4oKszpPDjsOtw4jDnDfOs8K/wrdV4oKDwrTDrsOYwqlHwrlyw6LDri4KZOKAolPDqEr//w "05AB1E – Try It Online")
[Answer]
# Twig, 126 bytes
This is just a simple search/replace.
Nothing fancy
```
{{'012
10 2430 240 3 2430 3\\40 30 |40003|
3000|
0 30 |
000 3|'|replace([' ','.-"','"-.','""--..','
|'])|raw}}
```
Try this on <https://twigfiddle.com/8zxyxa>
Under "Result", click in "Show raw result", or else you will see this:
```
.-""-.
.-" "-.
|""--.. "-.
| ""--.. "-.
|""--.. ""--..\
| ""--.. |
| ""--..|
""--.. |
""--.. |
""--..|
```
Which looks closer to melting cheese than a cake slice...
---
Sadly, your cake has to be `|raw`, or you would get this:
```
.-""-.
.-" "-.
|""--.. "-.
| ""--.. "-.
|""--.. ""--..\
| ""--.. |
| ""--..|
""--.. |
""--.. |
""--..|
```
Which looks like .... I don't know :x
[Answer]
# [Python 3](https://docs.python.org/3/), 116 bytes
```
print(''' .-" .-"|| |\\
||
||
|
|
|'''.translate({1:'""--..',2:' '*6,3:'"-.\n'}))
```
[Try it online!](https://tio.run/##FYtNCoMwEIWZcecpQjajJRmwggvPkk0WBYWSimZTmp49vgy8vw/m@Obtk@Zaj3NPeRARg1Nvu2bcFYKYwFqlEHosLnCm0htidDaNMKLgX/MZ0/WO@TX8plWs9V5V3HMVI4/FzUBeQ5L/ONZ6Aw "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~158~~ 125 bytes
```
print""" .-""-.
.-"s"-.
|es"-.
|se "-.
|ese\\
|ses|
|sse|
ess|
ses|
sse|""".replace('e','""--..').replace('s',' '*6)
```
[Try it online!](https://tio.run/##RcwxCoAwDAXQ3VOELFGxGRw8jYtIQEFqaboIvXtNVTBD8nmBH660nX4sJcTdJ0QEG3aIjpt6tYYs71Gx5wcyzxU021bJDYhahkeginVxlHAsq7QkNJB1OmbqflVToH7qSrkB "Python 2 – Try It Online")
---
Basically a translation of the JS and T-SQL answers
[Answer]
# [///](https://esolangs.org/wiki////), 91 bytes
```
/d/"-.//D/""--..//s/ //S/ss/s .-"d
.-"Sd
|DSd
|SDsd
|DSD\\
|SDS|
|SSD|
DSS|
S DS|
SS D|
```
[Try it online!](https://tio.run/##HYihDcAwDAR5prDCnV/CGzwNqZRKBWWm3t21S@7v3t/Ln9szcTB1AYY5VVeZQ0QAwh0uS@cZTZ4R1qD5r7Z3B6NIiyHGcko/rInMDw "/// – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~84~~ ~~82~~ 81 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
“
"-.\|“•6ÅΩæÍ[ÕŽÇ4Δ¼µðв‹ìbÿ¹0mĆÛh6Ë\HvçÏ—ÜâE«εx±5Â\₅δćzÁ₅3¨Éj€¾ï737Æüí·?т¹•7вèJ
```
-3 bytes thanks to *@Emigna*.
[Try it online.](https://tio.run/##AZYAaf9vc2FiaWX//@KAnAogIi0uXHzigJzigKI2w4XOqcOmw41bw5XFvcOHNM6UwrzCtcOw0LLigLnDrGLDv8K5MG3EhsObaDbDi1xIdsOnw4/igJTDnMOiRcKrzrV4wrE1w4Jc4oKFzrTEh3rDgeKChTPCqMOJauKCrMK@w683MzfDhsO8w63Ctz/RgsK54oCiN9Cyw6hK//8)
**Explanation:**
```
“\n "-.\|“ "# Push string '\n "-.\|'
•6ÅΩæÍ[ÕŽÇ4Δ¼µðв‹ìbÿ¹0mĆÛh6Ë\HvçÏ—ÜâE«εx±5Â\₅δćzÁ₅3¨Éj€¾ï737Æüí·?т¹•
# Compressed integer 18017524448214263331172789946872235969387180564028761120954323919616255702509406136041325094115009009004153150633415914465807454405990069100373808902652333314
7в # Converted to Base 7 as list:
# [1,1,1,1,4,3,2,2,3,4,0,1,4,3,2,1,1,1,1,1,1,2,3,4,0,6,2,2,3,3,4,4,1,1,1,1,1,1,2,3,4,0,6,1,1,1,1,1,1,2,2,3,3,4,4,1,1,1,2,3,4,0,6,2,2,3,3,4,4,1,1,1,1,1,1,2,2,3,3,4,4,5,0,6,1,1,1,1,1,1,2,2,3,3,4,4,1,1,1,1,1,1,6,0,6,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,4,4,6,0,1,2,2,3,3,4,4,1,1,1,1,1,1,1,1,1,1,1,1,6,0,1,1,1,1,1,1,1,2,2,3,3,4,4,1,1,1,1,1,1,6,0,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,3,3,4,4,6]
è # Index each item in this list in the string
J # Join the indexed characters together (and output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•6ÅΩæÍ[ÕŽÇ4Δ¼µðв‹ìbÿ¹0mĆÛh6Ë\HvçÏ—ÜâE«εx±5Â\₅δćzÁ₅3¨Éj€¾ï737Æüí·?т¹•` is `18017524448214263331172789946872235969387180564028761120954323919616255702509406136041325094115009009004153150633415914465807454405990069100373808902652333314`.
Huge thanks to [*@MagicOctopusUrn*'s ASCII art compress generator](https://codegolf.stackexchange.com/a/120966/52210), after which ~~`žLR` has been golfed to `žh`, and the string has been fixed with the `…` and `«` because it contained a `"`~~ the transliterate has been golfed by reversing the string and number on the stack, using `в` instead of `B` to make it a list of characters instead, and index into it (thanks *@Emigna*).
[Answer]
# [Java (JDK)](http://jdk.java.net/), 139 bytes
```
v->" .-\"\"-.\n .-\"6\"-.\n|06\"-.\n|60 \"-.\n|060\\\n|606|\n|660|\n 066|\n 606|\n66 0|".replace("6"," ").replace("0","\"\"--..")
```
[Try it online!](https://tio.run/##RY6xbsMgEIZ3P8WJyUThxMSSNGO2TJG6lAzUsSMcjJEBS1GcZ3cxTtvp/@/jE3etGhVrr/dZd64fArRpxhi0wSbaKuje4mZXuPhtdAWVUd7DSWkLzwLgTX1QIcXY6yt06a08h0Hb29cF1HDzNKsAx/d3@8/kbVflAA18zCM7kMVAJokkDKXNVax94r9F8CT9QS5lZmJaQvAUwMUywQqFAD4RHGpnVFWXRJBtXgNA6D/liea1DJHQeZdvPT98qDvsY0CX7gzGlg0q58yjtNEYShftVbzmHw "Java (JDK) – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 88 bytes
```
/%/ //$/"-.
//#/""--..//!/%%/% .-"$ .-"!$|#!$|!#%$|#!#\\
|!#!|
|!!#|
#!!|
! #!|
!! #|
```
[Try it online!](https://tio.run/##FYghEsAwCAR9XsFBkOE@VFPRmYq6WP5Oibi9nd3fvd9nV9EpIuSkrhikUXWtCBJ0p0ssnQeYaT2YH7HrGu3IJiyHGNohp6Avq34 "/// – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 169 154 152 bytes
```
Console.Write(" .-\"\"-.\n .-\"2\"-.\n|12\"-.\n|21 \"-.\n|121\\\n|212|\n|221|\n 122|\n 212|\n 221|".Replace("1","\"\"--..").Replace("2"," "));
```
[Try it online!](https://tio.run/##RY1BCwIhEIX/yjCnFVLQ656ic5c6dPEiJiGYxo4Fsbu/3dSlepf3zcfAs8Rtmlx5ko83OL8pu/sINhgi2MMMlE32Fl7JX@FofBwYzOWQIqXgxGXy2Q0INYJr1MiFjh3Vxov8gpL16Sel1t2ppZWStUCqdsEmoUkUJ/cIxtYJiTvsA1wIZH@vqoceZGws61o@ "C# (.NET Core) – Try It Online")
*-15 bytes: Realized I could made use of C#'s Replace function and removed a variable.*
*-2 bytes: Left two unnecessary spaces in the Replace functions.*
---
Alternate way to do this using an anonymous function instead of writing directly to the console.
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 154 152 bytes
```
()=>{return(" .-\"\"-.\n .-\"2\"-.\n|12\"-.\n|21 \"-.\n|121\\\n|212|\n|221|\n 122|\n 212|\n 221|".Replace("1","\"\"--..").Replace("2"," "));};
```
[Try it online!](https://tio.run/##RY6xasMwEIb3PMXPTRLUAml1E2gK3bq0Q4eqg1CVIHDkoJMLxfGzu7JN23@57z7uuPPc@D6HeeCYznj95hIuLZK7BL46H/CAEb5zzDhW4uJK9Pjq4yeeXUyCS6577x9w@cwS4@5pSP5@swecsJ@F3B/GHMqQkyDUqMaSpUbZtKLZ@KZ/weg69Ce1taszt6UYXQu0WTpsEosk9RKuXf1XkKY7Wg80SpH896Z6rCEp26mdH/vEfRfUW44liJOodjdN0/wD "C# (.NET Core) – Try It Online")
*-2 bytes: Left two unnecessary spaces in the Replace functions.*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 79 bytes
```
•6ÂËhHyã¡0÷íÓ].‚ηƶãqÛ-#Œ‘-)ìMι"ΩÒý³!7₄βýiÑ¡1:l*;∊ëžZ~Ù¯ΩïŒ×.gιü#‡•“. -"|
\“Åв
```
[Try it online!](https://tio.run/##AY8AcP9vc2FiaWX//@KAojbDgsOLaEh5w6PCoTDDt8Otw5NdLuKAms63xrbDo3HDmy0jxZLigJgtKcOsTc65Is6pw5LDvcKzITfigoTOssO9acORwqExOmwqO@KIisOrxb5afsOZw4LCr8OOwqnDr8WSw5cuZ865w7wj4oCh4oCi4oCcLiAtInwKXOKAnMOF0LL//w "05AB1E – Try It Online")
```
•...•“...“Åв # trimmed program
Åв # characters in...
“...“ # literal...
Åв # with indices in digits of...
•...• # 17991054328044272488457460457310784314009191188977967735225363312688493035783656557746796791541044041617963464968803855853508169575617675885728820813516051270...
Åв # in base length of...
“...“ # literal
# implicit output
```
] |
[Question]
[
Some numbers such as: 6, 12, 20, 30, 42, 56, 60, 90, 120 and so on as can be expressed as a product of consecutive integer numbers as shown below.
```
6 = 2 * 3
12 = 3 * 4
30 = 5 * 6
60 = 3 * 4 * 5
90 = 9 * 10
120 = 4 * 5 * 6
```
Write a program or function that outputs a list of consecutive integers which product equals the specified number.
Examples of numbers that are not fit for this logic are:
```
99 = 9 * 11 (Product of non-consecutive numbers)
121 = 11 * 11 (Same numbers)
2 = 1 * 2 (Product of itself and 1)
13 = 13 (Product of only one number)
```
Please note that for the case of `2 = 2 * 1`, we do not consider it as a valid result, as a integer multiplied by 1 gives the same result. For this question, we would consider only integers >= 2 in the product.
**Input**
A valid 32-bit positive integer. Can be from standard input, a function argument, etc.
**Output**
A list of consecutive integer numbers >= 2 (in either ascending or descending order).
If there are several combinations of consecutive integers, just provide **one** instance will do. If you provide more, its fine.
**Restrictions**
The code should take a reasonable amount of time (< 5 minutes) to run on a [standard computer](http://www.clarku.edu/offices/its/purchasing/recommendations.cfm) for all valid inputs (positive 32-bit integers). If there is a consecutive integer product, the code should output one or more within the time limit. Else, the code should terminate with no output within the time limit.
This is code golf, so the shortest code in bytes wins.
[Answer]
# Java - 124
```
String f(int t){int s=2,h=3,p=s,i;String o="";for(;p!=t&&s*s<t;p=p<t?p*h++:p/s++);if(p==t)for(i=s;i<h;o+++=i+" ");return o;}
```
Starting at 2, this loops until the start number is > the square root of the target (or target is reached exactly). If the product is low, it multiplies by the high number and increments it. If high, it divides by the starting number and increments it.
For example, for 30, it would check:
```
2*3 = 6 (too low, multiply)
2*3*4 = 24 (too low, multiply)
2*3*4*5 = 120 (too high, divide)
3*4*5 = 60 (too high, divide)
4*5 = 20 (too low, multiply)
4*5*6 = 120 (too high, divide)
5*6 = 30 (bingo!)
```
Outputs a space-separated string of factors in ascending order.
With line breaks:
```
String p(int t){
int s=2,h=3,p=s,i;
String o="";
for(;p!=t&&s*s<t;p=p<t?p*h++:p/s++);
if(p==t)
for(i=s;i<h;o+=i+" ");
return o;
}
```
[Answer]
# Python - ~~104 97 95~~ 92 [try it](http://ideone.com/rCC7o4)
```
n=input()
s=i=2
c=1
while s<n:
s*=i+c;c+=1
if s==n:print range(i,i+c)
if s/n:i+=1;s,c=i,1
```
If `n` is, e.g., set to 120 beforehand, the program outputs the two solutions:
```
[2, 3, 4, 5]
[4, 5, 6]
```
[Answer]
## Clojure - ~~127~~ 109 bytes
```
(defn f[x](first(for[r[range]y(r 2 x)v[(take-while #(<=(apply * %(r y %))x)(r y x))]:when(=(apply * v)x)]v)))
```
Example:
```
(map f [6 12 30 60 90 120 1404816 99 121 2 13])
=> ((2 3) (3 4) (5 6) (3 4 5) (9 10) (2 3 4 5) (111 112 113) nil nil nil nil)
```
Explanation:
This is basic, quite unoptimized functional approach. I create a lazy list of all the possibilities using a simple loop over them (it does skip all combinations which would give too big numbers, preventing overflow) and take the first of them. If no possibilities exist, it returns nil.
Easiest to test in <http://tryclj.com/> .
---
I also now noticed that I can return all the possibilities: ~~**120 bytes**~~ **102 bytes**, but gives results in a nested list.
```
(defn f[x](for[r[range]y(r 2 x)v[(take-while #(<=(apply * %(r y %))x)(r y x))]:when(=(apply * v)x)]v))
```
Example:
```
(map f [6 12 30 60 90 120 1404816 99 121 2 13])
=> (((2 3)) ((3 4)) ((5 6)) ((3 4 5)) ((9 10)) ((2 3 4 5) (4 5 6)) ((111 112 113)) () () () ())
```
[Answer]
# [R](https://www.r-project.org/), ~~65~~ ~~63~~ ~~61~~ 58 bytes
*Edit: -2 bytes, and then -2 more bytes, thanks to Giuseppe*
*Edit: -3 bytes thanks to Robin Ryder*
```
x=scan();`[`=`for`;i[1:x,j[1:x-i,if(prod(i:j)==x)a=i:j]];a
```
[Try it online!](https://tio.run/##lY6xasNAEERr7VccpPAuyEJK4ULiqrQmXSrHoON8h88me2K1IgrB365IRUidZhh2mH0jyzLb0TtG6vpTb/uYpe/SqWnn8rbpPpUp4iD5gqm9kbUzObu687lzS/NcA3inuHvnHXXygY4AnoyE/ackDcaNJk7sNWU2mo2GUVuI9veGM31D8W8uPDaIvwZ/N3nSYVKz1k1TVdWhXv9nQTaJTdMe6g2g8vXi1F8RimKQxIoe2XLpeLQRmYjKNQkiWf6m@cwXen07HqEgeCw/ "R – Try It Online")
I really tried to find something cleverer and shorter, but couldn't.
Loops (unusually for R) through all combinations of consecutive integers from 1..x ~~2..x, printing any that whose product equals x. Breaking out of two loops is very awkward, so its shorter code to just print all the successes~~. (see explanation of Robin Ryder's improvement below).
Giuseppe's (second) 2-byte saving comes from redefining the array-index operator `[]` as the `for` command. This is a classic [R](https://www.r-project.org/) golf - since all operations and commands are functions that can be redefined (including indexing and `for`) - but has the side-effect of making the code almost unreadable afterwards... (and, if you ever used this in 'real' code, it would make all of [R](https://www.r-project.org/) almost unuseable afterwards, since indexing is now no longer possible!).
Robin's 3-byte saving skips my previous careful avoidance of non-valid ranges that don't include `1`, and instead sets-up the loops so that the *last* range found will always be valid. So, we just need to remember this (as the variable `a` here) and output it when we're finished. This has the effect that non-valid inputs leave `a` undefined, and so 'terminate' with no output by throwing an error.
[Answer]
# CJam, 31 bytes
```
q~:Qmq,A,m*{2f+~,f+_:*Q={p}*}%;
```
It's a brute-force approach, but execution time is only a couple of seconds using the [official Java interpreter](http://sourceforge.net/projects/cjam/files/ "CJam - Browse Files at SourceForge.net").
If you want to test the code using the [online interpreter](http://cjam.aditsu.net/ "CJam interpreter"), you should keep the input reasonably low. Anything less than 226 still works on my machine.
### Examples
```
$ TIME="%e s"
$ time cjam product.cjam <<< 2
0.12 s
$ time cjam product.cjam <<< 6
[2 3]
0.10 s
$ time cjam product.cjam <<< 120
[2 3 4 5]
[4 5 6]
0.12 s
$ time cjam product.cjam <<< 479001600
[2 3 4 5 6 7 8 9 10 11 12]
0.68 s
$ time cjam product.cjam <<< 4294901760
[65535 65536]
1.48 s
$ time cjam product.cjam <<< 4294967295
1.40 s
```
### How it works
```
q~:Q " Read from STDIN, interpret the input and save the result in variable “Q”. ";
mq, " Push the array [ 0 1 2 … (Q ** 0.5 - 1) ]. ";
A,m* " Push the array [ 0 1 2 … 9 ] and take the Cartesian product. ";
{ " For each pair in the Cartesian product: ";
2f+ " Add 2 to each component. ";
~ " Dump the array's elements on the stack. ";
, " Push the array [ 0 1 2 … n ], where “n” is the topmost integer on the stack. ";
f+ " Add “m” to each element, where “m” is the integer below the array. ";
_:* " Duplicate the resulting array and push the product of its elements. ";
Q={p}* " If the product is equal to “Q”, print. ";
}% " Collect the remaining results into an array. ";
; " Discard the array from the stack. ";
```
[Answer]
# Java, 162
returns an array of integers, or `null` if there are no consecutive numbers that exist.
```
int[] e(int n){for(int i=1;i<n;i++){int h=i+1,c=1,s=i;while(s<n){c++;s*=h++;}if(s==n){int[] o=new int[c];for(int j=0;j<c;j++){o[j]=h-j-1;}return o;}}return null;}
```
ungolfed:
```
int[] execute(int input){
for(int i=1; i<input; i++){
int highest = i+1, count = 1, sum = i;
while(sum < input){
count++;
sum *= highest++;
}
if(sum == input){
int[] numbers = new int[count];
for(int j=0; j<count; j++){
numbers[j] = highest-j-1;
}
return numbers;
}
}
return null;
}
```
[Answer]
# C 105 110 [try it](http://ideone.com/NW7Xad)
```
n,k,l;main(i){for(scanf("%d",&n);++i<n;)for(k=1,l=i;k<n;)if(k*=l++,k==n)for(l=n;l/=i;)printf("%d ",i++);}
```
**144** with bonus: this one iterates through every number and finds matching products
```
main(i,j,k,l,m){for(scanf("%d",&m);++i<13;)for(j=0;++j<46341-i;){for(l=k=1;k<=i;)l*=j+k++;if(l==m)for(puts(""),k=0;k<i;)printf("%d ",j+k+++1);}}
```
[Answer]
## PHP 258 chars, 201 not counting factorial function.
The simplest way to mathematically express "consecutive factors that equal a number" is `X!/Y!` Where `X` is the highest number and `Y` is the lowest minus one. Unfortunately I stopped taking calculus before I learned to solve `Z = X!/Y!`, so I had to bruteforce it a little.
**Messy, ungolfed version:**
```
<?php
// PHP does not define a factorial function, so I've kludged one in.
function fact($n) {
$r = 1;
for($i=$n; $i>1; $i--) {
$r *= $i;
}
return $r;
}
$input = intval($argv[1]);
if( $input < 2 ) { die('invalid input'); }
printf("input: %s\n", $input);
$max=min(ceil(sqrt($input)),170); // integer breakdown for > 170!
$grid = array();
for( $x=1;$x<$max;$x++ ) {
for( $y=$max;$y>=1;$y-- ) {
if( $y >= $x ) { continue; } // Skip results that would be < 1
$cur = fact($x)/fact($y);
if( $cur > $input ) { // too large!
echo "\n"; continue 2;
}
if( $cur == $input ) { //just right
printf("%7d\n\nFound %s == %s\n", $cur, implode(' * ', range($y+1, $x)), $cur);
break 2;
}
printf("%7d ", $cur);
}
echo "\n";
}
if($cur!=$input){printf("No consecutive factors produce %d\n", $input);}
```
Example output:
```
input: 518918400
2
3 6
4 12 24
5 20 60 120
6 30 120 360 720
7 42 210 840 2520 5040
8 56 336 1680 6720 20160 40320
9 72 504 3024 15120 60480 181440 362880
10 90 720 5040 30240 151200 604800 1814400 3628800
11 110 990 7920 55440 332640 1663200 6652800 19958400 39916800
12 132 1320 11880 95040 665280 3991680 19958400 79833600 239500800 479001600
13 156 1716 17160 154440 1235520 8648640 51891840 259459200
14 182 2184 24024 240240 2162160 17297280 121080960
15 210 2730 32760 360360 3603600 32432400 259459200
16 240 3360 43680 524160 5765760 57657600 518918400
Found 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 == 518918400
```
**Golfed:**
```
<? function f($n){$r=1;for($i=$n;$i>1;$i--)$r*=$i;return $r;}$i=$argv[1];$m=min(ceil(sqrt($i)),170);for($x=1;$x<$m;$x++){for($y=$m;$y>0;$y--){if($y>=$x)continue;$c=f($x)/f($y);if($c>$i)continue 2;if($c==$i){$y++;echo "$y $x";break 2;}}}if($c!=$i){echo 'No';}
```
Output:
```
[sammitch@vm ~/golf] time php consecutive_golf.php 518918400
9 16
real 0m0.019s
user 0m0.011s
sys 0m0.009s
[sammitch@vm ~/golf] time php consecutive_golf.php 518918401
No
real 0m0.027s
user 0m0.017s
sys 0m0.011s
```
I was not expecting the run time to be quite this quick!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 35
```
JvwKr2 4W-ZJ~@KgJZ1=YurGHK=Zu*NTY)Y
```
**Note:** My code actually finds the shortest representation of the input as a representation of consecutive integers >=2, so on invalid input it will print a 1 element list, possibly after a very long time. Since the problem statement says the input will be valid, I assume this is OK.
**Short explanation:**
Essentially, the program stores the upper and lower limits of a range, calculates the product of the numbers in the range using a reduce, adjusts the endpoints as necessary, and repeats until the product equals the input.
**Long explanation:**
For each snippet of code, I will give equivalent python, as well as a more detailed explanation and reasoning.
`Jvw` => `J=eval(input())`
Standard way to take input in Pyth.
`Kr2 4` => `K=range(2,4)` => `K=[2,3]`
Here's the first weird part: Instead of storing the endpoints as separate variables, I'm storing them as elements of a list. The reason will soon be clear. Also, instead of doing a simple assignment, which in Pyth would be `K[2 3)`, I'm using a range to save a character.
`W-ZJ` => `while Z-J` => `while Z!=J`
At this point, you might ask, "What is Z? You haven't defined it." In Pyth, all variables come predefined. Z happens to start as 0. However, Z will be set to the value of the product later, so this check will serve to end the while loop once the list is at the correct value.
`~@K>JZ1` => `K[J>Z] += 1`
Here's why I'm storing the values in a list, not in separate variables: I want to increment one of the two endpoints, depending on whether the product is currently too high or too low. That would be a rather long conditional if the endpoints were separate variables, but with the magic of list indexing, it becomes short. Also, the fact that this check comes before the product, and the fact that Z is initialized to 0, ensure that K will be `[2,4]` by the time we first take the product, which are the proper endpoints.
`=YurGHK` => `Y=reduce(lambda G,H: range(G,H),K)` => `Y=range(K[0],K[1])`
Now, I need the actual list that the product will be taken over, and that will be printed out if we succeed. Clearly, we will use a range function. The trickiness lies in obtaining the inputs to the range function. The obvious way to do this, by indexing the list, would be `=Yr'K@K1`. However, by using a reduce function on this two element list, we can shorten that by a character.
`=Zu*NTY` => `Z=reduce(lambda N,T: N*T,Y)`
And now, for the whole point of this affair, the reduce operation to find the product of the list.
`)` => End while
`Y` => `print(Y)`
On success, print the list.
**Example run:**
```
$ cat seq_prod
JvwKr2 4W-ZJ~@K>JZ1=YurGHK=Zu*NTY)Y
$ cat seq_prod | python3 pyth.py
<debug stuff>
==================================================
[9, 10, 11, 12, 13, 14, 15, 16]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
’ḊẆP=¥Ƈ
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//4oCZ4biK4bqGUD3CpcaH/yzDh8WS4bmY4bmEKcin4oG3//8xNTA "Jelly – Try It Online")
-1 byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)'s help!
## How it works
```
’ḊẆP=¥Ƈ - Main link. Takes an integer n on the left
’ - Decrement n
Ḋ - Generate the range [2, 3, ..., n-1]
Ẇ - Yield all contiguous sublists: [[2], [3], [4], [5], ..., [2, 3, 4, ... n-1]]
¥Ƈ - Keep those lists where the following is true:
P - The product of the list...
= - ...is equal to n
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
fo=¹ΠQ↓2ŀ
```
[Try it online!](https://tio.run/##yygtzv7/Py3f9tDOcwsCH7VNNjra8P//f0MjAwA "Husk – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `m`, ~~9~~ ~~7~~ 6 bytes
```
ḢÞSvΠc
```
*-2 bytes thanks to emanresu A*
*-1 byte thanks to Steffan*
[Try it online](https://vyxal.pythonanywhere.com/#WyJtIiwiIiwi4biiw55Tds6gYyIsIiIsIjYiXQ==), or [verify more test cases](https://vyxal.pythonanywhere.com/#WyJtQSIsIiIsIuG4osOeU3bOoGMiLCIiLCI2XG4xMlxuMzBcbjYwXG45MFxuMTIwXG45OVxuMlxuMTMiXQ==).
Explanation:
```
Ḣ # Range from 2 to n-1 (m flag makes it n-1)
ÞS # All sublists
vΠ # Calculate the product on each
c # Contains the input
```
[Answer]
## Java - 115
```
void f(int i){for(int j=2;j<i;j++)for(int k=1,x=j;(x*=j+k)<i;k++);if(x==i)for(i=j;i<j+k;i++)System.out.println(i);}
```
Slightly less golfed:
```
void f(int i) {
for(int j=2; j<i; j++)
for(int k=1, x=j; (x*=j+k) < i; k++);
if(x == i)
for(i=j; i<j+k; i++)
System.out.println(i);
}
```
[Answer]
# Matlab (88)
Code expects number to be stored in `x` and output in `l`.
```
for n=2:12
r=ceil(x^(1/n))
for s=-3*n:n
l=r-s+(1:n)
if prod(l)==x
return
end;end;l=x;end
```
Since `13! > 2^32` this code searches only for products of length 2 upto 12. This code has a constant runtime of around 0.001s.
[Answer]
# Scala - 86
```
def p(n:Int)=(2 to n).flatMap(i=>(i to n).map(i to _-1).find(_.product==n)).headOption
```
This code is very inefficient but optimizing it would only add a few more characters.
It uses a functional approach to check the products of all possible consecutive sequences. (a consecutive sequence of integers is represented as a Range object in Scala)
ungolfed:
```
def product(n: Int): Option[Range] = {
def productStartingAt(start: Int): Option[Range] =
(start to n-1).map(start to _).find(_.product == n)
(2 to n).flatMap(i => productStartingAt(i)).headOption
}
```
[Answer]
## CJam *does not currently work for large numbers due to long computation time*
This is my shortest CJam code. Test at <http://cjam.aditsu.net/>. It works by: defining input as A; creating an array of all numbers from 0 to A-1; Kicking 0; kicking the smallest numbers until multiplying all numbers in the array is not greater than A; checking if it is greater than A; if not, creating an array from 0 to A-2; and repeating until the answer is found. If none is found, an exception is thrown. I didn't consider that spaces between numbers were needed so they are inlcuded in the second code which is 32 characters long.
```
ri:A,{)\;,1{;(;_{*}*_A>}gA<}g
ri:A,{)\;,1{;(;_{*}*_A>}gA<}g" "*
```
[Answer]
## Dart - 102 chars
This is a slow implementation. It can be made faster but that requires more characters (like doing the loop only until `i*i<n`)
```
f(n,[i=2]){
t(j,p,a)=>p<n?t(++j,p*j,a..add(j)):p>n?f(n,i+1):a;
for(;i<n;i++)if(n%i<1)return t(i,i,[i]);
}
```
(The 102 chars is without line breaks and leading spaces).
To use it, do something like:
```
main() {
print(f(123456789*123456790));
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
⟦b₂s.×?∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/9H8ZUlAbrHe4en2jzqW//8fbaajYGiko2BsoKNgBsSWBiC@QSwA "Brachylog – Try It Online")
### How it works
```
⟦b₂s.×?∧
⟦b₂ in the range from 2 to input
s any consecutive sublist
(with longer list tried out first,
so [input] will be tried last)
. is the output, if …
× the product of the list
? is the input.
∧ return the output
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
o ã æÈ×¶U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=byDjIObI17ZV&input=MTI)
```
o ã æÈ×¶U :Implicit input of integer U
o :Range [0,U)
ã :Sub-arrays (in order of length)
æ :Get the first that returns true
È :When passed through the following function
× :Reduce by multiplication
¶U :Test for equality with U
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
L¦¨ŒʒPQ
```
Outputs a list of all possible results.
[Try it online](https://tio.run/##yy9OTMpM/f/f59CyQyuOTjo1KSDw/39DIwMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf99Di07tOLopFOTAg6tC/xfq/M/2kzH0EjH2EDHzEDH0gDIBlKWQMpQx0jH0DgWAA).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
¦¨ # Remove the first and last values to make the range [2, input)
Œ # Get all sublists of this list
ʒ # Filter this list of lists by:
P # Where the product of the sublist
Q # Is equal to the (implicit) input
# (after which the filtered list of lists is output implicitly as result)
```
[Answer]
# **Javascript, 88**
Golfed code:
```
function f(a){for(i=2;i<a;i++){b=[1];for(j=i;j>1;j--)if((b[0]*=b[i-j+1]=j)==a)alert(b)}}
```
Easier to read (nicely spaced) code:
```
function f(a){
for(i=2;i<a;i++){
b=[1];
for(j=i;j>1;j--)
if((b[0]*=b[i-j+1]=j)==a)
alert(b);
}
}
```
For each number from 2 to the input number, it finds the product of consecutive integers from the current number back down to 2. If this product equals the input number, then the series of consecutive numbers, along with the original input number, is output.
It outputs the input number followed by the consecutive integers whose product is the input number.
For example f(120) produces an alert with the text "120,5,4,3,2" and then a second alert with the text "120,6,5,4".
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 18 bytes
```
{⍵∊∊{⍵×/x}¨x←1↓⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHHV1ABGIdnq5fUXtoRcWjtgmGj9omP@rdDBSs/Z8G5D/q7XvU1fyod82j3i2H1hs/apv4qG9qcJAzkAzx8Az@n6ZgxpWmYGgEJIwNgIQZiLA0AIuBmZZgpiGQBKkxNAYA "APL (Dyalog Unicode) – Try It Online")
## Explanation
```
{⍵∊∊{⍵×/x}¨x←1↓⍳⍵}
x←1↓⍳⍵ assign range from 2 to n to x
¨ map over range using function
{⍵×/x} get products of subsets of size ⍵ in x
(this gets all reuquired products of consecutive numbers > 1)
∊ enlist/flatten the vector of vectors
⍵∊ is n present in the products?
```
] |
[Question]
[
Given a string whose length is divisible by 4, make a triangle as demonstrate below.
If the string is `abcdefghijkl`, then the triangle would be:
```
a
b l
c k
defghij
```
If the string is `iamastringwithalengthdivisiblebyfour`, then the triangle would be:
```
i
a r
m u
a o
s f
t y
r b
i e
n l
gwithalengthdivisib
```
If the string is `thisrepresentationisnotatriangle`, then the triangle would be:
```
t
h e
i l
s g
r n
e a
p i
r r
esentationisnotat
```
## Notes
* The string will only consist of characters from `a` to `z`.
* Leading/Trailing whitespaces and newlines are allowed as long as the shape is not broken.
* A list of strings as output is allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ ~~22~~ 21 bytes
```
≔÷Lθ⁴λ↙…θλ→✂θλ±λ↖✂θ±λ
```
[Try it online!](https://tio.run/##TczBCsIwEATQu1@RYwrpzZOepL0IRYriB4S4Jgth02aXil8fo4L1MDAwj3HBZpdsLOXAjJ70kaTHBW@gByAvQc@NUdua2Ow3Y0YSvevTgwa4i1Hd00XoQpr0/BYrOaMPdb9EdPDZjDqBtwK6qpVdp@/Pz/2jUiQgZ5gyMJBYwUTIlGrLaMlHKO1SWo4v "Charcoal – Try It Online") Link is to verbose version of code. Simply slices the string into three parts and prints them in the appropriate directions. Edit: Saved 3 bytes by using integer division and slicing. Saved a further byte by using `CycleChop` instead of `Slice` for the head of the string. Edit: Charcoal now supports drawing arbitrary text along the edge of a polygon, simplifying the code to 12 bytes:
```
GH↙→→↖⊕÷Lθ⁴θ
```
[Try it online!](https://tio.run/##TYoxCsMwDEWvktGGdOuUrhkayFAKPYBxVFugSoksEnJ619Cly38P3o85aJRAtT6EziR8FyI53DDKwTO8re@GJ6b8z9f6CxNHhQ@wweImthF3XMDNwMmy23zfXX2bzd9qtYxFYVUo7R4MhbGwNFMMnAjqZacv "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes
```
ćsIg4÷GćsÁćsŠN·<ú«s}».C
```
[Try it online!](https://tio.run/##MzBNTDJM/f//SHuxZ7rJ4e3uQMbhRiBxdIHfoe02h3cdWl1ce2i3nvP//5mJuYnFJUWZeenlmSUZiTmpeeklGSmZZZnFmUk5qUmVafmlRQA "05AB1E – Try It Online")
**Explanation**
```
ć # extract head of input
s # swap the remaining string to top of stack
Ig4÷G # for N in [1...len(input)/4-1] do:
ć # extract head
sÁ # swap remaining string to top of stack and rotate right
ć # extract head
sŠ # reorder stack as tail, head, remaining
N·<ú # prepend N-1 spaces to tail
«s # concatenate with head and swap remaining string to top
} # end loop
».C # join by newlines and center
```
[Answer]
## JavaScript (ES6), ~~119~~ ~~117~~ ~~108~~ 105 bytes
```
s=>(l=s.length/4,S=' ',g=([c,...s],p)=>S.repeat(l)+c+(l--?p+s.pop()+`
`+g(s,p?p+S+S:S):s.join``))(s+S,'')
```
### Formatted and commented
```
s => ( // given the input string s:
l = s.length / 4, // l = length of side edge - 1
S = ' ', // S = space (defining S costs 6 bytes but saves 7)
g = ( // g = recursive function which takes:
[c, // - c = next character
...s], // - s = array of remaining characters
p) => // - p = middle padding string
S.repeat(l) + c + ( // append left padding + left character
l-- ? // if side edges are not complete:
p + s.pop() + '\n' + // append middle padding + right character + Line Feed
g(s, p ? p + S + S : S) // and do a recursive call with updated middle padding
: // else:
s.join`` // append all remaining characters and stop recursion
) // (this is the bottom edge)
)(s + S, '') // initial call to g()
```
### Test cases
```
let f =
s=>(l=s.length/4,S=' ',g=([c,...s],p)=>S.repeat(l)+c+(l--?p+s.pop()+`
`+g(s,p?p+S+S:S):s.join``))(s+S,'')
console.log(f('abcdefghijkl'))
console.log(f('iamastringwithalengthdivisiblebyfour'))
console.log(f('thisrepresentationisnotatriangle'))
```
[Answer]
# C#, 260 bytes
```
namespace System{using static Console;class P{static void Main(){var d=ReadLine();int e=d.Length/4,x=e,y=0,g=0,i=0;Action<int,int>a=(p,q)=>{SetCursorPosition(p,q);Write(d[g++]);};for(;i<e;i++)a(x--,y++);for(i=0;i<e*2;i++)a(x++,y);for(i=0;i<e;i++)a(x--,y--);}}}
```
Really wanted to use `SetCursorPosition`.
Ungolfed:
```
namespace System {
using static Console;
class P {
static void Main() {
var d = ReadLine();
int e = d.Length / 4, x = e, y = 0, g = 0, i = 0;
Action<int, int> a = (p, q) => { SetCursorPosition(p, q); Write(d[g++]); };
for (; i < e; i++)
a(x--, y++);
for (i = 0; i < e * 2; i++)
a(x++, y);
for (i = 0; i < e; i++)
a(x--, y--);
}
}
}
```
[Answer]
# Mathematica, 164 bytes
```
(b=Length[c=Characters@#];k=Column[#,Alignment->Center]&;T=Table;k@{#&@@c,k@T[""<>{c[[i+2]],T[" ",2i+1],c[[-i-1]]},{i,0,(a=b/4)-2}],""<>T[c[[i]],{i,a+1,b/2+1+a}]})&
```
**input**
>
> ["iamastringwithalengthdivisiblebyfour"]
>
>
>
[Answer]
# [Python 3](https://docs.python.org/3/), 120 bytes
First golf, figured I might as well learn some Python along the way.
```
a=input()
l=len(a)//4
print(l*" "+a[0])
for i in range(1,l):print((l-i)*" "+a[i]+(2*i-1)*" "+a[4*l-i])
print(a[l:3*l+1])
```
[Try it online!](https://tio.run/##ZY7BDoIwEETvfEXTU7ctwQonkn6J4VClwOpmaZp68OsRo5y8zrw3mfQqy8rttgWPnJ5FQUWeIqsATdNVKSMXRVoKacLlNEA1rVmgQBY58ByVswT9l1JUI/xIHIw6a6zdEXR6b/91sq0m446Jj2gjj15K2C9db2Oc5gXvD3oD)
**Explanation:**
The first character is printed by itself after `len(a)//4` spaces, then the first and last `i`-th characters starting from the second are printed, separated by `2*i - 1` spaces.
Finally, the remaining substring is printed.
[Answer]
# [GNU sed](https://www.gnu.org/software/sed/), ~~178~~ ~~158~~ 132 + 1 = 133 bytes
+1 byte for `-r` flag.
```
s/(.)(.*)(.)/ \1\n\2;\3/
:
s/( *)(.\n.)(.*)(...);(.*)(.)/\1\2\1 \6\n\3;\4\5/m
t
:A
s/(.*\n)( *)(.*);/ \2;\1\2\3/m
tA
s/. (.)$/\1/gm
```
[Try it online!](https://tio.run/##NYyxDsIgEIZ3noLBAZoIaVGHMvkMrre0aaWXtGAANb68eMR0uOW/7/vSPJWStFBSqIZOag4teOgsGM16Ri9ed/A7oZS0O0toBy3ncCHFWDjBWW8ss/5aRdWAl3@9kZbCFK2CqUwlFBdwkwfKaLeVgsM2pBzRuzfmZVhn7/Iy4QsTjus8fu7hGb/hkTH4VI7xBw "sed 4.2.2 – Try It Online")
## Explanation
In [previous revisions](https://codegolf.stackexchange.com/posts/127784/revisions) I used a lot of bytes dealing with math, special cases, and cleanup, even though intuitively I was sure they could be avoided. I've since managed to do so, mostly.
Suppose we have the input `abcdEFGHIJKLMnop`. The letters `EFGHIJKLM` will be the bottom of the triangle, so I've capitalized them as a visual aid.
First we prepare the input by putting the first character on its own line (preceded by a space) and inserting a cursor (`;`) before the last character:
```
s/(.)(.*)(.)/ \1\n\2;\3/
```
Now we have:
```
a
bcdEFGHIJKLMno;p
```
Now, in a loop, we're going to do a few things to the last line: 1. Copy the spaces from the previous line and insert them after the first character, plus two; 2. Move the last character to right after the spaces, followed by a newline; and 3. Move the cursor three characters to the left.
```
:
s/( *)(.\n.)(.*)(...);(.*)(.)/\1\2\1 \6\n\3;\4\5/m
t
```
Here's the result of each iteration:
```
a
b p
cdEFGHIJKL;Mno
a
b p
c o
dEFGHI;JKLMn
a
b p
c o
d n
EF;GHIJKLM
```
You can see the pyramid begin to take shape. You can also see what the cursor was for: In each iteration it moved left three characters, and when there are no longer three characters to its left, it breaks the loop, which happens to be just when we've reached the "bottom" of the pyramid.
Now we're going to do a similar operation but in reverse. In a loop, we'll copy the spaces from the beginning of the line with the cursor to the beginning of the preceding line, plus one, in the process moving the cursor up to that line.
```
:A
s/(.*\n)( *)(.*);/ \2;\1\2\3/m
tA
```
Here are a couple iterations and the end result:
```
a
b p
c o
;d n
EFGHIJKLM
a
b p
;c o
d n
EFGHIJKLM
...
; a
b p
c o
d n
EFGHIJKLM
```
We're all done now, except for some extra characters: A `;` and extra space on the first line, and two spaces in the "middle" of the pyramid on the next three lines. A simple substitution gets rid of them:
```
s/. (.)$/\1/gm
```
All done!
```
a
b p
c o
d n
EFGHIJKLM
```
[Answer]
# [Haskell](https://www.haskell.org/), 136 bytes
```
i#x=x<$[1..i]
f s|let h=div l 4;l=length s=unlines$[(h-i)#' '++(s!!i):(2*i-1)#' '++[(s++" ")!!(l-i)]|i<-[0..h-1]]++[drop h$take(l-h+1)s]
```
[Try it online!](https://tio.run/##ZU9NT4QwFLzzKx4syRYRIsbT7nLyqiePpDFFHvRJKaSv6Jrsf8cmGqNxTpP5SGa04hGN2TbanevzKW2qsiQZ9cAXgx503dEbGLg7mtqgHbwGrldryCKnjdAFZbs97PNccBxTdhC3V1RU31ojOM8TSLI4FiYk5YVORXNTlrqopAx@5@YFdOrViCGg8ypjuXlkf68YGWpoIFHtS4f9oOl1NEkEv3ANidfEDheHjNYrT7MltnNgjpQdDP4rkJoUB9cO7@S1@roULhJTa7D96OfV/S3JKJoU2TBmUsvjM4hl9U/ePVgooc/gZ@32CQ "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 106 bytes
```
i=-1
s= ~/$/
sub /./,"#{' '*l=s/4}\\0
"
(l-1).times{sub /^(\w)(.*)(.)/,"#{' '*l-=1}\\1#{' '*i+=2}\\3
\\2"}
```
[Try it online!](https://tio.run/##RYvRCsIgGIXvfQpzwXSl5urWN5FgA6kfzA1/R8RYr25SF10czvngfGkZX6XZpVpUzgWsNAQtfeu9JriMVCt9ZM3a0rYLFvVlc@5EGOFBGqEyPDyu39uVu6fgqqsRf0NaUwXzIzjYvtKZONezrZR8B0x@Th59zEOGKQLGqa4EQ7wF/wE "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~100 97~~ 96 bytes
* [Jacoblaw](https://codegolf.stackexchange.com/users/70662/jacoblaw) saved 1 byte: integer division is unnecessary
```
a=input()+" "
k=j=len(a)/4
while j:print j*" "+a[0]+(2*(k-j)-1)*" "+a[-1];a=a[1:-1];j-=1
print a
```
[Try it online!](https://tio.run/##LYtBCsMgEADvvkI8aYK0hp5SfEnIYQ9S18gquqX09TalvQ3DTH1zLLSMAR6pPlmbWUklDp98DqTBXG7iFTEHmdbakFim6Qxm2K77rJdJHzYZ68xfWrffwcPm1i8l6534XTCG4oi9hdpCD8TAWAg7lZMaAj1yUB8 "Python 2 – Try It Online")
### Explanation:
One smart thing I've done here is padded the input with a space at the end,
such that the first character pairs with it and this can be pushed into the
loop (and since trailing whitespaces are allowed)
```
abcdefghijkl[space]
To print [0] [-1] Output=>[spaces]a[another_calculated_spaces(=0 here)][space]
Strip at both ends(a[1:-1])
bcdefghijkl
To print [0] [-1] Output=>[spaces]b[another_calculated_spaces]l
Strip at both ends(a[1:-1])
and so on.
```
The number of loops to follow is associated with `len(word)//4`. In the final step, the whole remaining string is printed(this forms the base of the triangle).
The spaces follow a simple pattern; the first set of spaces go-on decreasing by 1, while second set of spaces go on increasing by 2.
[Answer]
# C 225 bytes
```
p(c){putchar(c);}S(n){while(n--)p(' ');}main(int c,char**v){int i= strlen(v[1]),n=i/4,r;char*s=v[1],*e=&s[i-1];S(n);p(*s++);p('\n');for (r=1;r<n;r++){S(n-r);p(*s++);S(2*r-1);p(*e--);p('\n');}e++;while (s!=e)p(*s++);p('\n');}
```
**explained**
```
p(c){putchar(c);} // p is alias for putchar
S(n){while(n--)p(' ');} // S prints n spaces
main(int c,char**v){
int i= strlen(v[1]), // counter
n=i/4, // num rows in figure - 1
r; // current row
char*s=v[1], // start char
*e=&s[i-1]; // end char
S(n);p(*s++);p('\n');// print first row
for (r=1;r<n;r++){
S(n-r);p(*s++);S(2*r-1);p(*e--);p('\n'); // print middle rows
}
e++;while (s!=e)p(*s++);p('\n'); // print last row
}
```
[Answer]
# C#, 172 bytes
```
int i=0,n=s.Length;var p="";p=new string(' ',n/4)+s[i]+"\r\n";for(i=1;i<n/4;i++){p+=new string(' ',n/4-i)+s[i]+new string(' ',i*2-1)+s[n-i]+"\r\n";}p+=s.Substring(i,n/2+1);
```
[Try it online!](https://tio.run/##bY3BSsQwEIbv@xQhl23MttrFW8zJq4KwBw@uh1jH7kB3UmbiipQ@e0xlURD/wzDwzfdPJ3UXGXI3BBH1wLHncFypkul7LpEUEnbqFPFV3QekyvygaXUKrER5pdMBhWFkEKBFiIRCsWyMgfoBtMtISaG/2pCX5g6oTwe36KPX2o2e4KO8YqS@Wqv1hi6vjZUnfLZ6z3vS7i1yhb51eFOQQ2vNNNp/rBrP3h@EF9u6XRDVv6VzqZBm9/5yPsTSsLWtcXn3KQmOzW0kiQM0j4wJqtG4ec45fwE)
[Answer]
# Octave, 87 bytes
```
@(s,x=(n=nnz(s))/4)[[' ';flip(diag(s(1:x))')]' [' ';diag(s(n:-1:n-x+2))];s(x+1:n-x+1)];
```
\*In a windows machine the above code produces the correct result however in tio I added some code to correct it.
Explanation:
```
[' ';flip(diag(s(1:x))')]' %left side
[' ';diag(s(n:-1:n-x+2))] %right side
s(x+1:n-x+1) %bottom side
```
[Try it online!](https://tio.run/##LYzLDoIwEADvfgW37gaJKXoCmvgfhEOR1ya4GLZi7c9Xoh5nJpnl5uzWx3gFOXoDbJgDCOLpgnWtElUOMz2gIzuCgC48osJGJd/0t1xkuuDMpzliUwr49Id6pxiMZQFF9m7FrcTji9xk555HN3W0kVA79@17WJ6rwvIQIFTnHM2@jx8 "Octave – Try It Online")
[Answer]
# PHP>=7.1, 122 Bytes
```
for(;$i*2<$w=strlen($a=$argn)/2;$e=$a[-++$i])echo str_pad(str_pad($a[$i],$i*2).$e,$w+1," ",2),"
";echo substr($a,$i,$w+1);
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/e9f41a33cfebb849929bbf8d681fba21885a640f)
# PHP>=7.1, 124 Bytes
```
for(;$i*2<$w=strlen($a=$argn)/2;$e=$a[-++$i],$s.=$s?" ":" ")echo str_pad("",$w/2-$i)."$a[$i]$s$e
";echo substr($a,$i,$w+1);
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/109f5b7c2f1c202b2f5e9ca41e6224ce367030fa)
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 129 bytes
```
{n=split($0,a,"")
printf"%"(w=n/4+1)"s\n",a[++i]
for(;++i<w;)printf"%"(w-i+1)"s%"2*i-2"s\n",a[i],a[n-i+2]
$0=substr($0,i,i+w-1)}1
```
[Try it online!](https://tio.run/##TY3NCsIwHMPve4w/G6y2w214m3sS3aHFfQRnN9rOIuKz1yoIXkJIfiHSX0N46tauM1yelkIKIpasBtoNlFHuW70/8IqRPWsS8sQ5umRYTN5Ed/QN@0MLfMGM6h2K@rdAF0XHru6StGztpqwznysIcF9U7FWFAHmTMYYePdwk516PbrrgDgs19@oxLJt5Aw "AWK – Try It Online")
I should think this could be golfed a bit more, just not seeing it.
[Answer]
# [Retina](https://github.com/m-ender/retina), 99 bytes
```
^(.)(?=(....)+)
$#2$* $1¶$#2$*
( ( *).)(.*)(.)$
$1 $4¶$2$3
+`(( +).¶ ( *).)(.*)(.)$
$1$2 $5¶$3$4
```
[Try it online!](https://tio.run/##ZYxBCsMwDATvfoWgOkg2GOKkx5KflPogWkFxiu235QH5mCvIMQsLAztsla4lj/GkyLQ@KFo4sMNbQg@A07Gf6AgIPJsVvZXR4QS42JxwduFFBIHjsV8tTPZzN3HGZYz@0VblV6VJ6bnrVrSVzahqLu@v/AE "Retina – Try It Online") Explanation: The first two stages generate the first two lines, but after that no special-casing is necessary and each subsequent line can be generated automatically:
```
thisrepresentationisnotatriangle
t
hisrepresentationisnotatriangle
t
h e
isrepresentationisnotatriangl
t
h e
i l
srepresentationisnotatriang
...
t
h e
i l
s g
r n
e a
p i
r r
esentationisnotat
```
[Answer]
# Java 11, ~~213~~ ~~211~~ 178 bytes
```
s->{int n=s.length()/4,i=1;var r=" ".repeat(n)+s.charAt(0)+"\n";for(;i<n;r+=" ".repeat(n-i)+s.charAt(i)+" ".repeat(i*2-1)+s.charAt(n*4-i++)+"\n");return r+s.substring(i,n*2-~i);}
```
-2 bytes thanks to *@ceilingcat*.
**Explanation:**
[Try it online.](https://tio.run/##jZDBboMwDIbvfQqLU1IKW6feMibtAdbLjtsOBgKYgqmSQFVV7NVZKD10p01KFDv@bfn/ahwwqvPDlDVoLbwh8WUFQOy0KTDTsJ9TgHdniEvIxC2wUvn/0V9/9sCQwGSjl4tvBE5s3GguXSXkw25DyVYNaMAkAQSx0UeNTrAMbZxVaF6deJRh8MmBKjojFD2zMuEvaUR3Yh/f1Wj9FG3vqrzeRRSGy0CpjHa9YTBeYPvUXlcXtGHf9U1SjdNs4tinDWVgHTr/DB3l0HoMN6cfX4ByYTDDgdY7ZX26JuIKwcM5W6fbuOtdfPQ9rmHRxhxnIsA0y3VRVlQfmkD@KSdscdnyRK7CBWJOA1lKG52ei643/xjjKrIekNFW8@yqY7Lc@cgQctno24hxNU4/)
```
s->{ // Method with String parameter and String return-type
int n=s.length()/4, // The length of the input divided by 4
i=1; // And an index-integer, starting at 1
var r= // Result-String which starts as:
" ".repeat(n) // Leading spaces
+s.charAt(0) // + the first character
+"\n"; // + a new-line
for(;i<n; // Loop `i` in the range [1, `n`):
r+= // And append the result-String with:
" ".repeat(n-i) // Leading spaces
+s.charAt(i) // + the character of the left diagonal line
+" ".repeat(i*2-1) // + center spaces
+s.charAt(n*4-i++) // + the character of the right diagonal line
+"\n"); // + a new-line
return r // Return the result-String
+s.substring(i,n*2+i+1);} // + the bottom part of the triangle
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 29 bytes
```
4/÷ḣ‟+^ṘYṘ2ẇṘḣð£ƛ¥j¥ðd+£;J^JJ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=C&code=4%2F%C3%B7%E1%B8%A3%E2%80%9F%2B%5E%E1%B9%98Y%E1%B9%982%E1%BA%87%E1%B9%98%E1%B8%A3%C3%B0%C2%A3%C6%9B%C2%A5j%C2%A5%C3%B0d%2B%C2%A3%3BJ%5EJJ&inputs=iamastringwithalengthdivisiblebyfour&header=&footer=)
No canvas builtins! Because Vyxal doesn't have those. [feature-request](/questions/tagged/feature-request "show questions tagged 'feature-request'")?
-9 thanks to Aaron Miller.
[Answer]
# [Perl 5](https://www.perl.org/), 76 bytes
74 bytes of code +2 for `-F`
```
say$"x($l=@F/4),shift@F;say$"x$l,shift@F,$"x($#i+=2),pop@F while--$l;say@F
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFqUJDJcfWwU3fRFOnOCMzrcTBzRoirpIDE9ABq1LO1LY10tQpyC9wcFMoz8jMSdXVVckBKXZw@/8/MSk5JTUtPSMzKzvnX35BSWZ@XvF/XV9TPQNDg/@6bgA "Perl 5 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g4/>x<‚ĆI527SΛ
```
[Try it online](https://tio.run/##yy9OTMpM/f8/3UTfrsLmUcOsI22epkbmwedm//9fkpFZXJRaUJRanJpXkliSmZ@XWZyXD2QVZSbmpeekAgA) (no [test suite](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgZF/posOl5F9aAuHq/E830bersHnUMOtIW6WpkXmw3rnZ/3UObbP/n5iUnJKalp6RmZWdw5WZmJtYXFKUmZdenlmSkZiTmpdekpGSWZZZnJmUk5pUmZZfWsRVkpFZXJRaUJRanJpXkliSmZ@XWZyXD2QVZSbmpeekAgA) since there isn't a way to clean the Canvas).
**Explanation:**
```
g # Take the length of the (implicit) input
# i.e. "thisrepresentationisnotatriangle" → 32
4/ # Divide it by 4
# i.e. 32 → 8
> # Increase it by 1
# i.e. 8 → 9
x # Double it (without popping the value itself)
# i.e. 9 → 9 and 18
< # Decrease this doubled value by 1
# i.e. 18 → 17
‚ # Pair them together: [length/4+1, (length/4+1)/2-1]
# i.e. 9 and 17 → [9,17]
Ć # Enclose it, appending its head to itself: [l/4+1, (l/4+1)/2-1, l/4+1]
# i.e. [9,17] → [9,17,9]
I # Push the input-string again
527S # Push 527 as digit-list: [5,2,7]
Λ # Use the Canvas builtin with these three arguments
# (after which the result is output implicitly)
```
*Canvas explanation:*
The Canvas builtin takes three arguments:
1. The lengths of the lines to 'draw', which in this case is the list \$[\frac{l}{4}+1, \frac{\left(\frac{l}{4}+1\right)}{2}-1, \frac{l}{4}+1]\$.
2. The string to 'draw', which in this case is the input.
3. The directions, which in this case is `[5,2,7]`. These will be the directions `[↙,→,↖]`.
With these arguments, it will draw as follows (let's take the string `"thisrepresentationisnotatriangle"` as example again):
```
9 characters ("thisrepre") in direction 5 (↙)
t
h
i
s
r
e
p
r
e
17-1 characters ("sentationisnotat") in direction 2 (→):
t
h
i
s
r
e
p
r
esentationisnotatr
9-1 characters ("riangle") in direction 7 (↖):
(NOTE: "riangle" are only 7 characters instead of 8, since the string isn't any longer,
which won't cause problems and is actually convenient for our desired output)
t
h e
i l
s g
r n
e a
p i
r r
esentationisnotat
```
[See this 05AB1E tip of mine for a more in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210)
] |
[Question]
[
This challenge is a little tricky, but rather simple, given a string `s`:
```
meta.codegolf.stackexchange.com
```
Use the position of the character in the string as an `x` coordinate and the ascii value as a `y` coordinate. For the above string, the resultant set of coordinates would be:
```
0, 109
1, 101
2, 116
3, 97
4, 46
5, 99
6, 111
7, 100
8, 101
9, 103
10,111
11,108
12,102
13,46
14,115
15,116
16,97
17,99
18,107
19,101
20,120
21,99
22,104
23,97
24,110
25,103
26,101
27,46
28,99
29,111
30,109
```
---
Next, you must calculate both the slope and the y-intercept of the set you've garnered using [Linear Regression](https://en.wikipedia.org/wiki/Simple_linear_regression), here's the set above plotted:
[](https://i.stack.imgur.com/YCujs.png)
Which results in a best fit line of (0-indexed):
```
y = 0.014516129032258x + 99.266129032258
```
Here's the ***1-indexed*** best-fit line:
```
y = 0.014516129032258x + 99.251612903226
```
---
So your program would return:
```
f("meta.codegolf.stackexchange.com") = [0.014516129032258, 99.266129032258]
```
Or (Any other sensible format):
```
f("meta.codegolf.stackexchange.com") = "0.014516129032258x + 99.266129032258"
```
Or (Any other sensible format):
```
f("meta.codegolf.stackexchange.com") = "0.014516129032258\n99.266129032258"
```
Or (Any other sensible format):
```
f("meta.codegolf.stackexchange.com") = "0.014516129032258 99.266129032258"
```
Just explain why it is returning in that format if it isn't obvious.
---
Some clarifying rules:
```
- Strings are 0-indexed or 1 indexed both are acceptable.
- Output may be on new lines, as a tuple, as an array or any other format.
- Precision of the output is arbitrary but should be enough to verify validity (min 5).
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") lowest byte-count wins.
[Answer]
# Octave, ~~29~~ ~~26~~ ~~24~~ 20 bytes
```
@(s)s/[!!s;1:nnz(s)]
```
[Try it Online!](https://tio.run/#J806d)
We have the model
```
y= intercept *x^0 + slope * x
= intercept * 1 + slope * x
```
Here `y` is the ASCII value of string `s`
To find parameters intercept and slope we can form the following equation:
```
s = [intercept slope] * [1 X]
```
so
```
[intercept slope] = s/[1 x]
```
`!!s` converts a string to a vector of ones with the same length as the string.
The vector of ones is used for estimation of the intercept.
`1:nnz(s)` is range of values from 1 to number of elements of the string used as `x`.
Previous answer
```
@(s)ols(s'+0,[!!s;1:nnz(s)]')
```
For test paste the following code into [Octave Online](http://octave-online.net)
```
(@(s)ols(s'+0,[!!s;1:nnz(s)]'))('meta.codegolf.stackexchange.com')
```
A function that accepts a string as input and applies ordinary least squares estimation of model `y = x*b + e`
The first argument of ols is `y` that for it we transpose the string `s` and add with number 0 to get its ASCII code.
[Answer]
# TI-Basic, 51 (+ 141) bytes
Strings are 1-based in TI-Basic.
```
Input Str1
seq(I,I,1,length(Str1->L1
32+seq(inString(Str2,sub(Str1,I,1)),I,1,length(Str1->L2
LinReg(ax+b)
```
Like the other example, this outputs the equation of the best fit line, in terms of X. Also, in Str2 you need to have this string, which is 141 bytes in TI-Basic:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~
```
The reason this cannot be a part of the program is because two characters in TI-Basic cannot be automatically added to a string. One is the `STO->` arrow, but this is not a problem because it is not a part of ASCII. The other is the string literal (`"`), which can be stringified only by typing into a `Y=` equation and using `Equ>String(`.
[Answer]
## R, 46 45 bytes
```
x=1:nchar(y<-scan(,""));lm(utf8ToInt(y)~x)$co
```
Reads input from stdin and for the given test case returns (one-indexed):
```
(Intercept) x
99.25161290 0.01451613
```
[Answer]
# Python, ~~82~~ 80 bytes
-2 bytes thanks to @Mego
Using `scipy`:
```
import scipy
lambda s:scipy.stats.linregress(range(len(s)),list(map(ord,s)))[:2]
```
[Answer]
# Mathematica, 31 bytes
```
Fit[ToCharacterCode@#,{1,x},x]&
```
Unnamed function taking a string as input and returning the actual equation of the best-fit line in question. For example, `f=Fit[ToCharacterCode@#,{1,x},x]&; f["meta.codegolf.stackexchange.com"]` returns `99.2516 + 0.0145161 x`.
`ToCharacterCode` converts an ASCII string to a list of the corresponding ASCII values; indeed, it defaults to UTF-8 more generally. (Kinda sad, in this context, that one function name comprises over 48% of the code length....) And `Fit[...,{1,x},x]` is the built-in for computing linear regression.
[Answer]
# Node.js, 84 bytes
Using [`regression`](https://www.npmjs.com/package/regression):
```
s=>require('regression')('linear',s.split``.map((c,i)=>[i,c.charCodeAt()])).equation
```
## Demo
```
// polyfill, since this is clearly not Node.js
function require(module) {
return window[module];
}
// test
["meta.codegolf.stackexchange.com"].forEach(function test(string) {
console.log(string);
console.log(this(string));
},
// submission
s=>require('regression')('linear',s.split``.map((c,i)=>[i,c.charCodeAt()])).equation
);
```
```
<script src="https://cdn.rawgit.com/Tom-Alexander/regression-js/master/src/regression.js"></script>
```
[Answer]
## Sage, 76 bytes
```
var('m','c')
y(x)=m*x+c
f=lambda x:find_fit(zip(range(len(x)),map(ord,x)),y)
```
Hardly any golfing, probably longer than a golfed Python answer, but yeah...
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
n:G3$1ZQ
```
1-based string indexing is used.
[Try it online!](https://tio.run/nexus/matl#@59n5W6sYhgV@P@/em5qSaJecn5Kanp@TppecUlicnZqRXJGYl56KlA4Vx0A "MATL – TIO Nexus")
### Explanation
```
n: % Input string implicitly. Push [1 2 ... n] where n is string length.
% These are the x values
G % Push the input string. A string is an array of chars, which is
% equivalent to an array of ASCII codes. These are the y values
3$ % The next function will use 3 inputs
1 % Push 1
ZQ % Fit polynomial of degree 1 to those x, y data. The result is an
% array with the polynomial coefficients. Implicitly display
```
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
3&u:%.1,.#\
```
This uses one-based indexing.
[Try it online!](https://tio.run/nexus/j#@5@mYGulYKxWaqWqZ6ijpxzDlZqcka@QpqCem1qSqJecn5Kanp@TpldckpicnVqRnJGYl54KFM5V//8fAA "J – TIO Nexus")
## Explanation
```
3&u:%.1,.#\ Input: string S
#\ Get the length of each prefix of S
Forms the range [1, 2, ..., len(S)]
1,. Pair each with 1
3&u: Get the ASCII value of each char in S
%. Matrix divide
```
[Answer]
# JavaScript, ~~151~~ 148 bytes
```
s=>([a,b,c,d,e]=[].map.call(s,c=>c.charCodeAt()).reduce(([a,b,c,d,e],y,x)=>[a+1,b+x,c+x*x,d+y,e+x*y],[0,0,0,0,0]),[k=(e*a-b*d)/(c*a-b*b),(d-k*b)/a])
```
More readable:
```
function f(s) {
var [n, sx, sx2, sy, sxy] = [].map.call(s, c => c.charCodeAt(0))
.reduce(([n, sx, sx2, sy, sxy], y, x) => [
n + 1,
sx + x,
sx2 + x * x,
sy + y,
sxy + x * y
], [0, 0, 0, 0, 0]);
var k = (sxy * n - sx * sy) / (sx2 * n - sx * sx);
return [k, (sy - k * sx) / n];
}
$(() => $('#run').on('click', () => console.log(f($('#input').val()))));
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input" style="width: 100%">meta.codegolf.stackexchange.com</textarea>
<button id="run">Run</button>
```
[Answer]
# Javascript (ES6), 112 bytes
```
s=>[m=(a=b=c=d=0,([...s].map((u,x)=>{a+=n=x,b+=y=u.charCodeAt(),c+=x*x,d+=x*y}),++n)*d-a*b)/(n*c-a*a),b/n-m*a/n]
```
```
F=s=>[m=(a=b=c=d=0,([...s].map((u,x)=>{a+=n=x,b+=y=u.charCodeAt(),c+=x*x,d+=x*y}),++n)*d-a*b)/(n*c-a*a),b/n-m*a/n]
const update = () => {
console.clear();
console.log(F(input.value));
};
input.oninput = update;
update();
```
```
#input {
width: 100%;
box-sizing: border-box;
}
```
```
<input id="input" type="text" value="meta.codegolf.stackexchange.com" length=99/>
<div id="output"></div>
```
[Answer]
# Haskell, ~~154~~ 142 bytes
```
import Statistics.LinearRegression
import Data.Vector
g x=linearRegression(generate(Prelude.length x)i)$i.fromEnum<$>fromList x
i=fromIntegral
```
It is far too long for my likings because of the imports and long function names, but well. I couldn't think of any other Golfing method left, although I'm not expert on the area of golfing imports.
Stripped 12 bytes by replacing `ord` and the import of `Data.Char` by fromEnum thanks to nimi.
[Answer]
# SAS Macro Language, 180 bytes
Uses 1-based indexing.
The solution gets to be pretty wordy when the output is only the slope and intercept.
```
%macro t(a);data w;%do i=1 %to %length(&a);x=&i;y=%sysfunc(rank(%substr(&a,&i,1)));output;%end;run;proc reg outtest=m;model y=x/noprint;run;proc print data=m;var x intercept;%mend;
```
[Answer]
## Clojure, 160 bytes
No built-ins, uses the iterative algorithm described at [Perceptron article](https://en.wikipedia.org/wiki/Perceptron#Steps). Might not converge on other inputs, in that case lower the learning rate `2e-4` and maybe increase the iteration count `1e5`. Not sure if the non-iterative algorithm would have been shorter to implement.
```
#(nth(iterate(fn[p](let[A apply e(for[x(range(count %))](-(int(get % x))(*(p 1)x)(p 0)))](mapv(fn[p e](+(* e 2e-4)p))p[(A + e)(A +(map *(range)e))])))[0 0])1e5)
```
Example:
```
(def f #( ... ))
(f "meta.codegolf.stackexchange.com")
[99.26612903225386 0.014516129032464659]
```
[Answer]
## Maple, 65 bytes
```
Statistics:-LinearFit(b*x+a,[$(1..length(s))],convert(s,bytes),x)
```
Usage:
```
s := "meta.codegolf.stackexchange.com";
Statistics:-LinearFit(b*x+a,[$(1..length(s))],convert(s,bytes),x);
```
Returns:
```
99.2516129032259+0.0145161290322573*x
```
Notes: This uses the [Fit](http://www.maplesoft.com/support/help/Maple/view.aspx?path=Statistics/Fit) command to fit a polynomial of the form a\*x + b to the data. The ASCII values for the string are found by [convert](http://www.maplesoft.com/support/help/Maple/view.aspx?path=convert/bytes)ing to bytes.
] |
[Question]
[
In Windows, when you perform double-click in a text, the word around your cursor in the text will be selected.
(This feature has more complicated properties, but they will not be required to be implemented for this challenge.)
For example, let `|` be your cursor in `abc de|f ghi`.
Then, when you double click, the substring `def` will be selected.
# Input/Output
You will be given two inputs: a string and an integer.
Your task is to return the word-substring of the string around the index specified by the integer.
Your cursor can be right **before** or right **after** the character in the string at the index specified.
If you use right **before**, please specify in your answer.
# Specifications (Specs)
The index is **guaranteed** to be inside a word, so no edge cases like `abc |def ghi` or `abc def| ghi`.
The string will **only** contain printable ASCII characters (from U+0020 to U+007E).
The word "word" is defined by the regex `(?<!\w)\w+(?!\w)`, where `\w` is defined by `[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_]`, or "alphanumeric characters in ASCII including underscore".
The index can be 1-indexed **or** 0-indexed.
If you use 0-indexed, please specify it in your answer.
# Testcases
The testcases are 1-indexed, and the cursor is right **after** the index specified.
The cursor position is for demonstration purpose only, which will not be required to be outputted.
```
string index output cursor position
abc def 2 abc ab|c def
abc def 5 def abc d|ef
abc abc 2 abc ab|c abc
ab cd ef 4 cd ab c|d ef
ab cd 6 cd ab c|d
ab!cd 1 ab a|b!cd
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~10, 9~~ 7 bytes
```
À|diwVp
```
[Try it online!](http://v.tryitonline.net/#code=w4B8ZGl3VnA&input=YWJjIGRlZg&args=NQ)
This answer uses 1-based indexing.
This could be shorter if we do exactly what the title says: "*Select* the word around the given index in a string". We could do
```
À|viw
```
Which literally selects the word, but unfortunately doesn't change the output at all. So we need a little workaround to make it work by cutting it into a register, deleting the rest of the text, then pasting the register back in.
Explanation:
```
À| " Jump the position of argument 1
diw " (d)elete (i)nside this (w)ord.
V " Select this line
p " And replace it with the word we just deleted
```
[Answer]
# C, 104 bytes
```
p[99];i,d;main(l){for(scanf("%d",&i);scanf("%[^a-zA-Z0-9_]%[a-zA-Z0-9_]%n",&d,&p,&l),i>l;i-=l);puts(p);}
```
Expects the input on stdin to be the 0-based index followed by one space or newline, followed by the string. Maximal length for a word is 99 characters. E.g.:
```
2 abc def
```
[Answer]
# C (gcc), 94 bytes
```
f(n,p)char*p;{for(p+=n-1;isalnum(*p)|*p==95&&n--;--p);for(;isalnum(*++p)|*p==95;putchar(*p));}
```
Zero-indexed, defines a function taking the index, then the string.
[Answer]
## Retina, 22
```
(1)+¶(?<-1>.)*\b|\W.+
```
[Try it online!](http://retina.tryitonline.net/#code=KDEpK8K2KD88LTE-LikqXGJ8XFcuKwo&input=MTExMTEKYWJjIGRlZiBnaGk) or [verify all test cases](http://retina.tryitonline.net/#code=JShHYApTYFxcCl4uKwokKgooMSkrwrYoPzwtMT4uKSpcYnxcVy4rCg&input=MlxhYmMgZGVmCjVcYWJjIGRlZgoyXGFiYyBhYmMKNFxhYiBjZCBlZgo2XGFiICAgY2QKMVxhYiFjZA). The regular program takes the cursor position in unary followed by a newline and then the string. The test suite has additional code to run in per line mode, and uses a `\` as a delimiter, and it uses decimal, for convenience.
Uses balancing groups to find the cursor position, then backtracks up to a word boundary. Deletes the text up to the word, and then after the word.
[Answer]
# Pyth, 16 bytes
```
+e=:.<+QbE"\W"3h
Q first input (string)
+ b plus newline
.< E rotate left by second input (number)
: "\W"3 split on regex \W, non-word characters
= assign to Q
e last element
+ hQ plus first element
```
[Try it online](https://pyth.herokuapp.com/?code=%2Be%3D%3A.%3C%2BQbE%22%5CW%223h&input=3%0A%22foo+bar+baz%22&test_suite=1&test_suite_input=%22abc+def%22%0A2%0A%22abc+def%22%0A5%0A%22abc+abc%22%0A2%0A%22ab+cd+ef%22%0A4%0A%22ab+++cd%22%0A6%0A%22ab%21cd%22%0A1&input_size=2)
[Answer]
# [JavaScript (V8)](https://v8.dev/), 44 bytes
```
(i,x)=>RegExp(`\\w*(?<=.{${i}})`).exec(x)[0]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvtfI1OnQtPWLig13bWiQCMhJqZcS8PexlavWqU6s7ZWM0FTL7UiNVmjQjPaIPZ/QVFmXokGV5qGkY5SYlKyQkpqmpKmDpBvip0PxBC@CYivkJyiAFNgBhZQAApB@IYgviKIx6X5HwA "JavaScript (V8) – Try It Online")
This is longer than an existing JS solution, but I don't actually understand the approach it uses, and I wrote this prior to seeing that solution. Hopefully this is different enough to be interesting :P
Code explanation, so the same fate is not befallen upon ye
```
(i,x)=> take i (number) and x (string)
RegExp(`...${i}...`) construct a regex with i in it
.exec(x)[0] return the first result of that regex on the string
\w*(?<=.{i}) constructed regex
\w* match an entire word
(?<= ) if the end of the word comes after
.{i} at least i characters
```
[Answer]
# C, 115 bytes
Function `f()` requires the string and index (1-indexed) as parameters and prints the result to stdout. Cursor should be after the specified character.
```
f(char*p,int n){char*s=p+n;for(;s>=p&&isalnum(*s)+(*s==95);--s);for(p=s+1;*p&&isalnum(*p)+(*p==95);putchar(*p++));}
```
[Answer]
## JavaScript (ES6), 57 bytes
```
f=(s,n)=>s.slice(0,n).match(/\w*$/)+s.slice(n).match(/\w*/)
```
Simply slices the string at the cursor point (which is before the 0-indexed character, which works out the same as after the 1-indexed character), then extracts and concatenates the adjacent word fragments. Even returns a sensible result when the cursor is at the start, end, or nowhere near a word.
[Answer]
# Java 8, ~~86~~ 78 bytes
```
(s,p)->{for(String t:s.split("\\W"))if((p-=t.length()+1)<0)return t;return"";}
```
Ungolfed with test cases:
```
class Indexer {
public static String f(String s, int p) {
for(String t : s.split("\\W"))
if((p -= t.length()+1) < 0)
return t;
return "";
}
public static void main(String[] args) {
System.out.println(f("abc def",2));
System.out.println(f("abc def",5));
System.out.println(f("abc abc",2));
System.out.println(f("ab cd ef",4));
System.out.println(f("ab cd",6));
System.out.println(f("ab!cd",1));
}
}
```
Splits the string by non-alphanumeric characters, then keeps subtracting the length of each substring, plus 1, from the specified position, until it becomes negative. Since any repeating non-alphanumerics get represented as empty string, the subtraction logic is significantly easier.
This code isn't extensively tested, so I'd like to see if someone can break this. Also, considering that this is Java code, how is this not the longest answer here? :P
[Answer]
# Ruby, ~~41~~ 31 bytes
[Try it online!](https://repl.it/Cd3W/1)
*-10 bytes from @MartinEnder*
```
->s,i{s[/\w*(?<=^.{#{i}})\w*/]}
```
[Answer]
## Pyke, 19 bytes
```
#Q;cjmli<i+s)lttjR@
```
[Try it here!](http://pyke.catbus.co.uk/?code=%23Q%3Bcjmli%3Ci%2Bs%29lttjR%40&input=abc+def+a%0A9)
Uses `Q;` as a no-op to make sure the first input is placed correctly
```
# ) - first where
c - input.split()
ml - map(len, ^)
i< - ^[:i]
i+ - ^+[i]
s - sum(^)
lt - len(^)-2
```
[Answer]
# Python 2, ~~70~~ 66 bytes
```
import re
f=lambda x,y,r=re.split:r('\W',x[:y])[-1]+r('\W',x[y:])[0]
```
Splits the string by non-word separators, once on the original string up to the cursor index, then on the string beginning at the cursor index. Returns the last element of the left split plus the first element of the right split.
Thanks to Leaky Nun for saving 4 bytes!
[Answer]
# Clojure, 92 bytes
```
(fn[x k](let[[u i](map #(re-seq #"\w+"(apply str %))(split-at k x))](str(last u)(nth i 0))))
```
First, splits input string at position `k` into two strings. Then for these strings find occurrences of `"\w+"` and return them as list. Then concatenate the last element of first list and the first element of second list.
See it online: <https://ideone.com/Dk2FIs>
[Answer]
# JavaScript (ES6), 52 bytes
```
(s,n)=>RegExp(`^.{0,${n}}(\\W+|^)(\\w+)`).exec(s)[2]
```
```
const F = (s,n) => RegExp(`^.{0,${n}}(\\W+|^)(\\w+)`).exec(s)[2]
class Test extends React.Component {
constructor(props) {
super(props);
const input = props.input || '';
const index = props.index || 0;
this.state = {
input,
index,
valid: /\w/.test(input),
};
}
onInput = () => {
const input = this.refs.input.value;
const index = Math.min(+this.refs.index.value, input.length);
this.setState({
input,
index,
valid: /\w/.test(input),
});
}
render() {
const {input, index, valid} = this.state;
return (
<tr>
<td>{ this.props.children }</td>
<td>
<input ref="input" type="text" onInput={this.onInput} value={input} />
<input ref="index" type="number" onInput={this.onInput} min="1" max={input.length} value={index} />
</td>
{valid && [
<td>{F(input, index)}</td>,
<td><pre>{input.slice(0, index)}|{input.slice(index)}</pre></td>,
]}
</tr>
);
}
}
class TestList extends React.Component {
constructor(props) {
super(props);
this.tid = 0;
this.state = {
tests: (props.tests || []).map(test => Object.assign({
key: this.tid++
}, test)),
};
}
addTest = () => {
this.setState({
tests: [...this.state.tests, { key: this.tid++ }],
});
}
removeTest = key => {
this.setState({
tests: this.state.tests.filter(test => test.key !== key),
});
}
render() {
return (
<div>
<table>
<thead>
<th/>
<th>Test</th>
<th>Output</th>
<th>Diagram</th>
</thead>
<tbody>
{
this.state.tests.map(test => (
<Test key={test.key} input={test.input} index={test.index}>
<button onClick={() => this.removeTest(test.key)} style={{
verticalAlign: 'middle',
}}>-</button>
</Test>
))
}
</tbody>
<tfoot>
<td/>
<td>
<button onClick={this.addTest} style={{
width: '100%',
}}>Add test case</button>
</td>
</tfoot>
</table>
</div>
);
}
}
ReactDOM.render(<TestList tests={[
{ input: 'abc def', index: 2 },
{ input: 'abc def', index: 5 },
{ input: 'abc abc', index: 2 },
{ input: 'ab cd ef', index: 4 },
{ input: 'ab cd', index: 6 },
{ input: 'ab!cd', index: 1 },
]} />, document.body);
```
```
input[type="number"] {
width: 3em;
}
table {
border-spacing: 0.5em 0;
border-collapse: separate;
margin: 0 -0.5em ;
}
td, input {
font-family: monospace;
}
th {
text-align: left;
}
tbody {
padding: 1em 0;
}
pre {
margin: 0;
}
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
```
[Answer]
## Lua, ~~71~~ 67 Bytes
Woohoo, Lua isn't the longest solution! Still one byte behind python, but don't know how to golf this down. Indexes are 1-based.
**Thanks to @LeakyNun reminding me the existence of `string.match`, saved 4 bytes**
```
g,h=...print(g:sub(1,h):match"[%a_]*$"..g:sub(h+1):match("[%a_]+"))
```
### Old 71
**Note: the explanations are still based on this one, because it also applies to the new one, but contains some extra informations on `gmatch`**
```
g,h=...print(g:sub(1,h):gmatch"[%a_]*$"()..g:sub(h+1):gmatch"[%a_]*"())
```
### Explanation
First, we unpack the arguments into `g` and `h` because they are shorter than `arg[x]`
```
g,h=...
```
Then, we construct our output, which is the concatanation of the part before the cursor and after it.
The first part of the string is
```
g:sub(1,h)
```
We want to find the word at the end of this one, so we use the function `string.gmatch`
```
:gmatch"[%a_]*$"
```
This pattern match `0..n` times the character set of alphabet+underscore at the end of the string. `gmatch` returns an iterator on its list of match in the form of a function (using the principle of closure), so we execute it once to get the first part of our word
```
g:sub(1,h):gmatch"[%a_]*$"()
```
We get the second part of our word by the same way
```
g:sub(h+1):gmatch"[%a_]*"())
```
The only difference being we don't have to specify we want to match at the start of the string (using `[^%a_]*`), as it will be the match returned by the iterator when it's called the first time.
[Answer]
# JavaScript (ES 6), ~~43~~42 Bytes
```
s=>n=>s.replace(/\w*/g,(x,y)=>y<n?s=x:0)&&s
```
# JavaScript (ES 3), 65 Bytes
```
function(s,n){s.replace(/\w*/g,function(x,y){y<n?s=x:0});alert(s)}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ð«._DžjмS¡Á2£J
```
Port of [*@AndersKaseorg*'s Pyth answer](https://codegolf.stackexchange.com/a/85770/52210).
1-indexed like the challenge test cases.
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//8OwwqsuX0TFvmrQvFPCocOBMsKjSv//YWIhY2QKNA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVQwv/DGw6t1ot3Obov68Ke4EMLDzcaHVrs9V/nf3S0UmJSskJKapqSjlGsjgIS1xTOBWKErEJyigJI2gTGVwCKKOmYQbmKII4hMgei0NDIWMXUzFzL0kBJxzI2FgA).
**Explanation:**
```
ð« # Append a space to the (implicit) input-String
._ # Rotate this string the (implicit) input-integer amount of times
# towards the left
D # Duplicate this string
žjм # Remove [a-zA-Z0-9_] from the string
S¡ # Split the rotated string by each of the remaining characters
Á # Rotate the resulting list once towards the right
2£J # And only leave the first two items, joined together
# (which is output implicitly)
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 34 bytes
```
->\b{&{first *.to>b,m:g/<<\w+>>/}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mqVqtOi2zqLhEQUuvJN8uSSfXKl3fxiamXNvOTr@29n9xYqVCmoaRpoZSYlKyQkpqmpKmNRdE0BSbIEwlECMETcCCCskpCshKzSCiCkBxhKAhWFARLPQfAA "Perl 6 – Try It Online")
Anonymous codeblock that takes input curried, like `f(n)(string)`.
### Explanation:
```
->\b{ } # Anonymous code block that takes a number
&{ } # And returns another code block that
first ,m:g/<<\w+>>/ # Finds the first word in the input
*.to>b # Where the start is after the number
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 30 bytes
```
->s,n{s[/.{#{n}}\w+/][/\w+$/]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165YJ6@6OFpfr1q5Oq@2NqZcWz82Wh9IqejH1v4vUEiLVk9MUkhOUUhNU9dRMIn9DwA "Ruby – Try It Online")
A different approach, only 1 byte shorter and 3 years later. Why not?
[Answer]
# APL(NARS), 58 chars, 116 bytes
```
{m←⎕A,⎕a,⎕D,'_'⋄↑v⊂⍨m∊⍨v←⍵↓⍨¯1+⍵{⍵≤1:⍵⋄m∊⍨⍵⊃⍺:⍺∇⍵-1⋄⍵+1}⍺}
```
⍵{⍵≤1:⍵⋄m∊⍨⍵⊃⍺:⍺∇⍵-1⋄⍵+1}⍺ find where start the string...How to use and test:
```
f←{m←⎕A,⎕a,⎕D,'_'⋄↑v⊂⍨m∊⍨v←⍵↓⍨¯1+⍵{⍵≤1:⍵⋄m∊⍨⍵⊃⍺:⍺∇⍵-1⋄⍵+1}⍺}
2 f 'abc def'
abc
5 f 'abc def'
def
2 f 'abc abc'
abc
4 f 'ab cd ef'
cd
1 f 'ab!cd'
ab
6 f 'ab cd'
cd
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Żṙe€ØW¬œpƊ.ị
```
[Try it online!](https://tio.run/##y0rNyan8///o7oc7Z6Y@alpzeEb4oTVHJxcc69J7uLv7/@Hl@pqR//9HKyUmJSukpKYp6SgYxeooIPNN4XwgRpJXSE5RACswgQkoAIWAfDMoXxHMM4wFAA "Jelly – Try It Online")
Port of [Anders Kaseorg's Pyth answer](https://codegolf.stackexchange.com/a/85770/85334).
```
Ż Prepend a zero as a buffer between the first and last words,
ṙ then rotate left by the index.
œpƊ Partition that result around
€ ¬ elements which are not
e ØW word characters,
.ị then take the last and first slices
and smash-print them together.
```
Original:
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
xðe€ØW¬Ä÷Ɗ=ị@¥
```
[Try it online!](https://tio.run/##y0rNyan8/7/i8IbUR01rDs8IP7TmcMvh7ce6bB/u7nY4tPT/4eX6mpH//0crJSYlK6SkpinpKBjF6igg803hfCBGkldITlEAKzCBCSgAhYB8MyhfEcwzjAUA "Jelly – Try It Online")
```
eۯW For each element, is it a word character?
Ä Take the cumulative sum
¬ of the negations
÷Ɗ and divide by the original Booleans.
= For each value in the result, is it equal to
ị@¥ the one at the index?
xð Filter the string to truthy positions.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
'\w+'5B#XXi>)1)
```
Cursor is 1-indexed and after the character (as in the test cases).
[Try it online!](http://matl.tryitonline.net/#code=J1x3Kyc1QiNYWGk-KTEp&input=J2FiIGNkIGVmJwo0) Or [verify all test cases](http://matl.tryitonline.net/#code=YAonXHcrJzVCI1hYaT4pMSkKRFQ&input=J2FiYyBkZWYnCjIKJ2FiYyBkZWYnCjUKJ2FiYyBhYmMnCjIKJ2FiIGNkIGVmJwo0CidhYiAgIGNkJwo2CidhYiFjZCcKMQ).
```
'\w+' % Push string to be used as regex pattern
5B#XX % Take input string implicitly. Apply regex. Push matches and ending indices
i> % Take input number. Compare with obtained ending indices. Gives true for
% ending indices that exceed the input number
) % Use as logical index to select the corresponding matches
1) % Select the first match. Implicitly display
```
[Answer]
## PowerShell v3+, ~~103~~ 101 bytes
```
param($a,$n)for(;$n[++$a]-match'\w'){}$i=$a--;for(;$n[--$a]-match'\w'-and$a-ge0){}-join$n[++$a..--$i]
```
Kind of a goofy solution, but a different approach than others.
Takes input `$a` as the 0-based index of the string `$n`. Then, we find the boundaries of our word. While we've not reached the end of the string and/or we're still matching word-characters, we `++$a`. Then, because of fenceposting, we set `$i=$a--`. Next, we crawl backwards, decrementing `$a` until it's either `0` or we hit a non-word-character. We then slice the input string based on those two demarcations (with some increment/decrements to account for OBOE), and `-join` it together to produce the result.
### Examples
```
PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 2 'This!test'
This
PS C:\Tools\Scripts\golfing> .\select-the-word-around-the-index.ps1 5 'This!test'
test
```
[Answer]
# PHP, 98 bytes
```
function f($s,$p){foreach(preg_split('#\W+#',$s,-1,4)as$m)if($m[1]+strlen($m[0])>=$p)return$m[0];}
```
* splits the string by non-word-characters, remembering their position (`4` == `PREG_SPLIT_OFFSET_CAPTURE`), loops through the words until position is reached.
* PHP strings are 0-indexed, cursor before character, but may be before or after the word
[Answer]
## Python 3, ~~112~~ 140 bytes
```
from string import*
p='_'+printable[:62]
def f(s,h,r=''):
while s[h]in p and h>-1:h-=1
while h+1<len(s)and s[h]in p:h+=1;r+=s[h]
return r
```
0-indexed.
Seeks backward to the first alphanumeric character from the index, then goes forward to the last alphanumeric character after the index. There's probably a smarter way to do this.
[Try it](https://repl.it/CdJX/0)
[Answer]
## Javascript (using external library) (168 bytes)
```
(n,w)=> _.From(w).Select((x,i)=>({i:i,x:x})).Split((i,v)=>v.x==" ").Where(a=>a.Min(i=>i.i)<=n-1&&a.Max(i=>i.i)>=n-2).First().Select(i=>i.x).Write("").match(/^\w*^\w*/)[0]
```
Link to lib:<https://github.com/mvegh1/Enumerable/blob/master/linq.js>
Explanation of code: Library accepts a string, which gets parsed into a char array. It gets mapped to an object storing the index and the char. The sequence is split into subsequences at every occurrence of " ". The subsequences are filtered by checking if the cursor index is contained within the min and max index of the subsequence. Then we take the first subsequence. Then we transform back to just a char array. Then we concatenate all characters with "" as the delimiter. Then we validate against word regex. Then we take the first match.
[](https://i.stack.imgur.com/9WXAn.png)
] |
[Question]
[
Task is pretty simple. Your program should take a number `N` from `1` to `20` and draw the following ASCII art.
When `N=1`:
```
_____
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|_|_|
\ /
\-/
v
```
When `N=2`:
```
_______
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|__|__|
\ /
\---/
\ /
v
```
When `N=3`:
```
_________
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
|___|___|
\ /
\-----/
\ /
\ /
v
```
And etc. Trailing spaces are allowed.
This is a code-golf challenge so the shortest solution wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
Nθ×_θ↑×⁸θ←×_⊕θ↓_↓×⁸θ↘¹P⊕θ↘θv‖B
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0QjJDM3tVhDKV5JR6FQEy5qFVqgowCRskCV8ElNK4FJgXV55iUXpeam5pWkpgCNRVLpkl@ep6MAVIMuhNVckFRQZnoG0HBDoKhvaU5JZgFYCs0CbDoQ3lEqA1kXlJqWk5pc4lRaUpJalJZTqaFp/f@/8X/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
×_θ
```
Print the `n` `_`s near the bottom left of the pencil.
```
↑×⁸θ
```
Print the `3n` `|`s up the middle of the pencil.
```
←×_⊕θ↓_
```
Print the left half of the `_`s at the top of the pencil.
```
↓×⁸θ
```
Print the left `3n` `|`s of the pencil.
```
↘¹
```
Print the first `\` at the bottom left of the pencil.
```
P⊕θ
```
Print the left half of the `-`s near the bottom of the pencil without moving the cursor.
```
↘θ
```
Print the rest of the `\`s at the bottom left of the pencil.
```
v
```
Print the `v` at the bottom of the pencil.
```
‖B
```
Reflect to complete the pencil.
[Answer]
# [Zsh](https://www.zsh.org/), 175 bytes
```
x=\|${(l:n=$1:)}
x+=$x\|
<<<${x//?/_}
repeat n\*8-1 <<<$x
<<<${x// /_}
q=\\${(l:n*2+1:)}/
<<<$q
q=${q// /-}
repeat n q=${${q/?\///}/\\?/ \\}&&<<<$q&&q=${q//-/ }
<<<${q/\\*/ v}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY311fYxtSoVGvkWOXZqhhaadZyVWjbqlTE1HDZ2NioVFfo69vrx9dyFaUWpCaWKOTFaFnoGiqApCrgChRACgptY2IgxmgZaYPM0QfLFwIlVKoLQYp0EaYogARBwvYx-vr6tfoxMfb6CjExtWpqYD1qalBNuvoKtRBrCoFqtPQVymohzoa6fnG0USyUCQA)
30 bytes spent on the line on the tip :(
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwYKlpSVpuhY3J1bYxtSoVGvkWOXZqhhaadZyVWjbqlTE1HDZ2NioVFfo69vrx9dyFaUWpCaWKOTFaFnoGiqApCrgChRACgptY2IgxmgZaYPM0Yfr0YZoKFRTK7RVqVapLtS3j9HX16_Vj4mx11eIiamFmFQI5Gvpl9VCHAZ13-Joo1goEwA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ì'_×'|IúRĆI8*.Dð'_:'\I>úRηRεNið'-:]`\'v).º.c
```
[Try it online](https://tio.run/##yy9OTMpM/f//cI96/OHp6jWeh3cFHWnztNDSczm8QT3eSj3G0w4odG570LmtfplAIV2r2IQY9TJNvUO79JL//zcGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/iquSZV1BaYqWgZO@nw6XkX1oC4en4Kf0/3KMef3i6eo3f4V1BR9r8LLT0XA5vUI@3Uo/xswMKndsedG6rXyZQSNcqNiFGvUxT79AuveT/SnphOoe22f8HAA).
**Explanation:**
```
Ì # Increase the (implicit) input by 2
'_× '# Push a string with that many amount of "_"
'| '# Push "|"
Iú # Pad it with the input amount of leading spaces
R # Reverse the string, so the spaces are trailing
Ć # Enclose; append its own head "|"
I8* # Push the input, and multiply it by 8
.D # Duplicate the string that many times on the stack
ð'_: '# On the top copy, replace all spaces with "_"
'\ '# Push "\"
I>ú # Pad it with the input+1 amount of leading spaces
R # Reverse the string, so the spaces are trailing
η # Pop and push a list of its prefixes
R # Reverse this list of prefixes
ε # Map over each string:
Ni # If the 0-based map-index is 1 (so the second string):
ð'-: '# Replace all spaces with "-"
] # Close both the if-statement and map
` # Pop and push all values separated to the stack
\ # Discard the top copy (the loose "\")
'v '# Push a "v" instead
) # Wrap all strings on the stack into a list
.º # Mirror each line with overlapping center
.c # Pad leading spaces to centralize everything, and join by newlines
# (after which the result is output implicitly)
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 573 bytes
```
[>+<-]>[>+>+<<-]>>[<+<+>>-]>>>++++++++++[>++++++++++>+<<-]>-----...<<<<<[>>>>>.<<<<<-]>>>>>>.<<<++++++[->+++++>+++++<<]>++>-<<<<<<[>++++++++>+<<-]>>[<<+>>-]<-[-<[->>+>+>+<<<<]>>[<<+>>-]>>>>.<<[>.<-]>>.<<<[>>.<<-]>>>.>.<<<<<<]>>>>[<<+++<+>>>-]>.<<<-<<<[>+>>>+>+<<<<<-]>>>>[<.>-]>>.<[<<.>>-]>.>.<[>>+<<-](>>------<<)<++++[<++++>-]<-<---.<[>>+>>+<<<<-]<[<+<+>>-]<[>++>++<<-]>->+[>>>>.<<<<-]>>.>>>.<.<<--<.<<[>>>.<<<-]>>>++.>>>.<<<<<<<<[>+>+<<-]>[<+>-]>-[<<[>+>>+<<<-]>[<+>-]>[<+>>->>>++<<<<-]<[>+<-]>>+[>>>>.<<<<-]>.>>-[>.<-]<.>>>.<<<<<[<+>-]<-]<<+[>>>>>>>.<<<<<<<-]>>>>>>>>>.
```
[Try it online!](https://tio.run/##XZFRCgJRCEW3U4iuQO5GpI8Kggj6CFr/5FVnmvLjjb7n1aNzeZ3vz9v7@ljkx5aAuJ6Qn3ToIVxcALr4JsbOn0ylmZnTArT2SzrRqBWjpLmf0oH6KP/qJkEDuIZ6SsnGN@q2x2kQeTCwZrDpboPilRfFQR2FfNFuDKyVBzrc0OVSY53OAM12QE@d8mONFnUWq3MblYkumZfbLmtKyCwOEtu2qlsFZFe33qWtSCK2LXagu0rWJp7GTCK@v47qW/qVpf/0X2/O2Dv0b5@uwTvv7B3B@nN5tSwf "brainfuck – Try It Online")
Hi, this is my first doing code-golf challenge.
yeah, I think it can be shorter if It has a better variable position arrangement and better ways of creating "\_", "|", " ", "/", "", "-", "v", "\n", but I think I will try to figure it out later.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~127~~ 110 bytes
```
->n{puts ?_*(n*2+3),(-8*n..n).map{|i|a=i*i<2?" -_"[i]:S=" ";i<0?[?|]*3*a*=n:S*i+?\\+a*(n-i<<1|1)+?/},S*-~n+?v}
```
[Try it online!](https://tio.run/##DcxBDoIwEADAu68gPcGWVqEXg637CI6lIfXQZA9uiIqJofj16jxgHuvtU5Ir6srbsr6eFc5QM/TSNG2tzsBac6Pvcdky5egIyPYoKjULT2EYnajEhewJPeYABiI4HkYgidMk439SZG2Xu0bicW9HUF@W@N5L8l04JG9C@QE "Ruby – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 89 bytes
```
d3+\-*,λ\|?n*J\|Jʁ,;→8*‹(ð←†)\-←†\\?d›IJ\/J,ð\\J?d‹\-*J\/J,?‹(n›I\\J?nd-?‹+IJ\/J,)?›I\vJ,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJkMytcXC0qLM67XFx8P24qSlxcfErKgSw74oaSOCrigLkow7DihpDigKApXFwt4oaQ4oCgXFxcXD9k4oC6SUpcXC9KLMOwXFxcXEo/ZOKAuVxcLSpKXFwvSiw/4oC5KG7igLpJXFxcXEo/bmQtP+KAuStJSlxcL0osKT/igLpJXFx2SiwiLCIiLCIzIl0=)
## Explanation
```
d3+\-*, Print 2n + 3 dashes
λ Lambda to print:
\| Pipe joined with
?n*J; A string (arg) n times joined with
\|J Another pipe
ʁ,→ Palindromised (and set lambda to anon. var)
8*‹(ð←†) Loop 8*n - 1 times, call the lambda passing a space as arg
\-←† Call same lambda with dash as arg
\\?d›IJ\/J, Print \, n*2+1 spaces, and /
ð\\J?d‹\-*J\/J, Print space, \, n*2-1 dashes, and /
?‹(n›I\\J?nd-?‹+IJ\/J,) Loop through n-1 with loop index i
n›I\\J Pad n+1 spaces and /
?nd-?‹+IJ Append i-n*2+i-1 spaces
\/J, Append \/ and print
?›I\vJ, Print v padded with n+1 spaces
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~304 bytes~~ 296 bytes
```
x=n=>{p="repeat",u=1,h="\\",o=["|","|","|"],r=o.join(" "[p](n))+"\n",s=o.join("_"[p](n)),e=["-"[p](2*n+3)];for(e.push(r[p](8*n-1)+s),e.push([h,"/"].join(" "[p](2*n+1))),e.push(" "+h+"-"[p](2*n-1)+"/");u<n;)e.push(" "[p](1+u)+h+" "[p](2*n-2*u++-1)+"/");return e.push(" "[p](n+1)+"V"),e.join("\n")}
```
[Try it online!](https://tio.run/##VY9Bj8IgFIT/inknXh@tafdi0mV/hpe2MY3LWo15ECjGRP3tFdSt8cCBmflm4NCfer91ezvmbH71NJ0Vq5@LVeC01f0IMqhSDgraFqRRDVxBvk4nnTLFwexZwAIa2wlGJGgZpJ@Nzb8hdYTzx63KmL6wq/@ME7qwwQ/CJX2VcV4i@Zh9qs0gYQndx0aCS8Q5E2Ua6N2cGiKEdfjmGt@hZJcUMIXnprzKAtGMOD0Gx4tPKM0RrCEtPh8Sf4i3aWvYm6MujmYnzqJCnO4 "JavaScript (Node.js) – Try It Online")
This is my first try at code golfing so it's a very simplistic attempt. The long version would be:
```
var x=(n) => {
// Set some utility variables
let i = 1
let space = ' '
let backslash = '\\'
let repeat = 'repeat'
let pipes = ['|', '|', '|']
let segment = pipes.join(space[repeat](n)) + '\n'
let lastsegment = pipes.join("_"[repeat](n))
// Create the first line of dashes, the body with the last segment and the first line of the tip
let pencil = ["-"[repeat](n * 2 + 3), segment[repeat](8 * n - 1) + lastsegment, [backslash, "/"].join(space[repeat](n * 2 + 1))]
// Create the dashed tip line and the rest of the empty tip in a loop
for(pencil.push(space+backslash+"-"[repeat](2*n-1)+"/");i<n;){
pencil.push(space[repeat](1+i)+backslash+space[repeat](2*n-2*i++-1)+"/")
}
// Add the tip, join the array and return
pencil.push(space[repeat](n + 1) + "V")
return pencil.join("\n")
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 211 bytes
```
#define F(N,I)for(I=N;I>0;I--)
#define P(C)putchar(C);
i,j;main(c,v){F(2*c+3,i)P(95)P(10)F(8*c,i){F(2,v){P('|')F(c,j)P(i<2?95:32)}P('|')P(10)}F(c+1,i){P(92)F(2*i-1,j)P(i^c?32:45)P(47)P(10)F(c-i+2,j)P(32)}P('v')}
```
[Try it online!](https://tio.run/##VY/NbsIwEITvPMVKPWAXh58E1EJKOVRCygVx6LmScTaJUWJHtpNWann21Amlai@r1cx8s1oR5EJ03V2KmVQIe3JgCc20Icn2ECfP8zgJAjq62UfyQuvGiYIbv8Ujyc5xxaUigrX0c0/CezGJmKRHsl75sZjTPXm8F17pzT5zJOOvsVcFO/uAfAp369UmCunlagzMxduTRQ/5npD2tTJYXIE3sYvCzbJvXz7cTohATsLB/2lqx/TSzWawl8Y6cLJCEDpFyHXp/8in8FogqKY6oQGdATd5U6FyFqSFxmIK3ILzEan8t8yvusmLQWl52WDPeM3if1IagyW2XLkpJGqI4wev6hLhhKV@ZxACT1PppFa8/MNyg1Bz2x8mUv1mwOmhpDY6N7wCxf0f0lksMwpWQ4EGGahtNO26EKJv "C (gcc) – Try It Online")
This is my first time code golfing.
The number of arguments is used as the input, though the value of those arguments is irrelevant. In the example on Try it online, 2 additional arguments are passed (in addition to the program name itself) so here, n=3.
The main obfuscations used are
* define macros for printing characters and for loops
* replacing character literals with their decimal encoding (where it saved characters)
* the use of `main()`'s argument variables for temporary storage
* and, naturally, the removal of white-space.
I decided to have all `for` loops run backwards as it ends up using slightly fewer symbols overall due to the loop used for aligning the tip of the pencil.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 155 bytes
```
lambda n:'_'*(2*n+3)+f'\n|{(" "*n+"|")*2}'*(8*n-1)+f'\n|{("_"*n+"|")*2}\n'+'\n'.join(' '*i+('v'*(i>n)or f'\\{" -"[i==1]*(2*n-2*i+1)}/')for i in range(n+2))
```
[Try it online!](https://tio.run/##TY3BCsIwEETvfkXIZXcTqiS9iFB/xEipaDSi2xKKIG2/va6C6G1m3gzTPftLy@W6y3Oswnxr7odjo3gDNRj0hm1JNkLgcUCttHg9ajJ@Ero2XLgfrf9oYLASw/LaJkZQYJJFeMgobZnarGQUBq0KvUtV5fafq8JLy9G0AopSSSqxyg2fT8jWE81dTtxjREe0@Op3/gI "Python 3.8 (pre-release) – Try It Online")
Sorry... can't shorten no more.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 134 bytes
inspired by [Zaelin Goodman](https://codegolf.stackexchange.com/a/243232/80745).
```
param($n),'__'+,'| '*(8*$n-1)+'|_'|%{,$_[0]*3-join("$($_[1])"*$n)}
0..$n|%{' '*$_+"\$((' ','-')[$_-eq1]*(2*$n+1-2*$_))/"}
' '*++$n+'v'
```
[Try it online!](https://tio.run/##FctLDsIwDATQfU@BIiPb@ZSmbLhLiawuKgEq6QcJFrRnD2blmdHzPH2G9XUbxrGUuV/7J0FmjyLoPG4HtHSxkENkh5vgdvx6kK5J9hwe0z2TAdIeExtVvFdNXUNWhfoJ4swViDR7DMgdSBiWmCy1il0MeoT5ZPbqz53TEd9YSml/ "PowerShell – Try It Online")
[Answer]
# JavaScript (ES6), 143 bytes
```
n=>'_'[R='repeat'](w=n*2+3)+(g=x=>x<0?`
|${s=' _'[+!++x][R](n)}|${s}|`+g(x):`
`+' '[R](x)+(x>n?'v':`\\${' -'[+!~-x][R](w-++x*2)}/`+g(x)))(-8*n)
```
[Try it online!](https://tio.run/##ZcxNCoMwEIbhvaewIEzGkP7opkijd3Cr0kgbpUWiqGhA7dVTxVXp9v3mmXc@5N2jfTU9U/VTmoIbxUO4QxJzaGUj8x4yMnLletRHSkqueahv50hYszN1HOz1lB4o1VkSZ0ThsuVlFrQkGgNhCQo2bJNetQ5VBAMEIk2dCWy20Q/b6cjWJ66Hy2m3iIRdXYXmUauuruSxqktSkAui9Vu8v@Ijmi8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~252~~ ~~245~~ 241 bytes
```
#import<iostream>
#define g(i,n)for(int i=0;i<n;++i)
#define c std::cout<<
int f(int n){g(i,2*n+3)c'_';c'\n';g(i,8*n){g(j,2){c'|';g(k,n)c" _"[i==8*n-1];}c"|\n";}g(i,n+2){g(j,i)c' ';if(i+~n){c'\\';g(j,n-~n-i-i)c" -"[i==1];c"/\n";}else c'v';}}
```
[Try it online!](https://tio.run/##fY9BboMwEEX3nMJyFsYxVhuyqWLTi5QqiiYQTVIGBE42xLk6td2q3VT1ct6fN98wDPoEsCwr7IZ@dBb7yY3NoXvNVsemRWrYKceCZNuPOZJjWD0btGSUQvkTATa5424H/dVZm8VYm8Ik57hdrkltJYi9MCBqEiYOX9aJnotSziDucXgJd4CzPX/Dqgpcb96NB36viRufaqjyaweDjQmD4Yx6UBTUdTScC9IP0qgxinQSBQnwp@RoPqZQVtyE8X6JBbsDUi6zOWPhtflGmt@fMGtZavsNy//g9m/ol08 "C++ (gcc) – Try It Online")
* *7 bytes saved thanks to ceilingcat*
* *4 bytes saved thanks to ceilingcat*
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 205 bytes
```
n=>[(g=([[f,...d]])=>d.join((r=(n,c=' ')=>c.repeat(n+!~n))(n,f)))`____`,r(8*n-1,g` |||
`)+g`_|||`,g` \\ /`,(i=0,G=([[b,e,f]])=>r(++i)+b+r(2*(n-i)+1,f)+e)`\\/-`,...Array(n-1).fill`\\/`.map(G),G`v `].join`
`
```
[Try it online!](https://tio.run/##ZY/BboNADETvfIV7ip1dNqXqoRLdSD3xERDFBBZERL1ogyJVpf11uuRaXzx6I3nG1/pe35owTHMqvnVr4@U2wwR2FXsssbdYlp02xrSnE9lja65@EMRgUXRjd7CLsDHBTa6eUdTTrxBFqyMiPsdhHfBtL2mme4ZlWRIm1fM5Kt5IVcGBNQ72WRdb1EU73T2SAio1kLqogC97lDTqLJ5VjriqDilvnT5CqL@il5HphnHcDDaf9YQF6YLvwKdHXU54zZOk8wFwdDMIWMjyuN4tvOaglBB8JxBn@96Pzoy@R6H8H5sijfhn/QM "JavaScript (Node.js) – Try It Online")
The core of this solution lies in the ~~ab~~use of template parameters and tags in some internal functions:
* `r(n,c)` is just `c.repeat(n)`, except `n` changes to `0` if it's `-1`, and `c` defaults to a space.
* `g([[f,...d]])` joins `d` with `r(n,f)`.
* `G([[b,e,f]])` is similar to `g` but adds increasing padding on each iteration (for the pencil tip).
ES6 destructuring in function parameters allows for the use of template strings in place of comma separated character arguments, like this:
```
const f1 = (a,b,c) => [c,b+a];
const f2 = ([[a,b,c]]) => [c,b+a];
console.log(f1('a','b','c')) // -> ['c', 'ba']
console.log(f2`abc`) // -> ['c', 'ba']
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) (Version <=6), 139 bytes
```
param($n)'_'*(2*$n+3)
,($b=('|'+' '*$n)*2+'|')*(8*$n-1)
$b|% *ce ' '"_"
0..$n|%{' '*$_+"\$((' ','-')[$_-eq1]*(2*$n+1-2*$_))/"}
' '*++$n+'v'
```
[Try it online!](https://tio.run/##LYzBCsIwEETv@YoQtuxu0lQTL178EpXQSsBDjbWCHqzfHlfxNDOPx0zXZ57v5zyOtU793F8ICmNCS9FCcRtWLcGwI1zQoUZhbKOTxZa2snxgBcPSaHvKWgSTjFp3HZSlef385MwBiKS36JH3kHy@heP/P3iJxLwyb/XVnROID6y1xg8 "PowerShell – Try It Online")
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) (Version >=7), 140 bytes
```
param($n)'_'*(2*$n+3)
,($b=('|'+' '*$n)*2+'|')*(8*$n-1)
$b|% *ace ' '"_"
0..$n|%{' '*$_+"\$((' ','-')[$_-eq1]*(2*$n+1-2*$_))/"}
' '*++$n+'v'
```
[Try it online!](https://tio.run/##LY3BCsIwEETv@YoStuxutqkmXrz4JSqhlYCHWmsFPVi/Pa7iaWYeM8x0feb5fs7DUMrUzd2FYGRM6Cg6GGXDpiHod4QLClaojF0UTexoq8kHNtAvdeW6U660YZM167aFcalfv0ESewAi9Q165D0kn2/h@D8IXiUxr@zbfOsiCvGBpZT4AQ "PowerShell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0 -n`, 127 bytes
```
//;say for"_"x($'*2+3),($_=join$"x$_,qw(|)x3)x(8*$'-1),y/ /_/r,(map$"x$_.v92.($_-1?$":'-')x(2*($'-$_)+1)."/",0..$')
,$"x$'." v"
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiLy87c2F5IGZvclwiX1wieCgkJyoyKzMpLCgkXz1qb2luJFwieCRfLHF3KHwpeDMpeCg4KiQnLTEpLHkvIC9fL3IsKG1hcCRcIngkXy52OTIuKCRfLTE/JFwiOictJyl4KDIqKCQnLSRfKSsxKS5cIi9cIiwwLi4kJylcbiwkXCJ4JCcuXCIgdlwiIiwiYXJncyI6Ii1NNS4xMC4wXG4tbiIsImlucHV0IjoiMVxuMlxuM1xuMTAifQ==)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~40~~ 37 bytes
```
⇧\_*\|?꘍Ǐ?8*Ḋ\_Ḟ\\?›꘍¦Ṙ1‡\-Ḟ¨M÷_\vWøṗ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLih6dcXF8qXFx8P+qYjcePPzgq4biKXFxf4bieXFxcXD/igLrqmI3CpuG5mDHigKFcXC3huJ7CqE3Dt19cXHZXw7jhuZciLCIiLCIzIl0=)
## How?
```
⇧\_*\|?꘍Ǐ?8*Ḋ\_Ḟ\\?›꘍¦Ṙ1w‡\-Ḟ¨M÷_\vWøṗ
⇧ # Push input + 2
\_* # Push that many underscores
\| # Push "|"
?꘍ # Append the input amount of spaces
Ǐ # Append its own head, aka "|"
?8* # Push input * 8
Ḋ # Duplicate the string that many times
\_Ḟ # On the top string, replace all spaces with "_"
\\ # Push a backslash
?›꘍ # Append input+1 spaces
¦ # Pop and push its prefixes
Ṙ # Reverse
1‡\-Ḟ¨M # On the second string, replace all spaces with a hyphen
÷_ # Push each item of that to the stack, and discard the top one (a backslash)
\v # Push "v"
W # Wrap everything on the stack into a list
øṗ # Palindromise everything, center, and join by newlines
```
*-2 bytes thanks to emanresu A*
] |
[Question]
[
This challenge is inspired by [this](https://codegolf.stackexchange.com/a/112832/31516) very nice answer by TidB.
---
In TidB's answer, every eight character is in the correct order: `gnilwoB edoC` (`Code Bowling` backwards). The other strings however ~~are~~ were in a strange, random order.
Your challenge is to fix this.
Take a (non-empty) string and a positive integer `n` as input. The string will contain ASCII characters in the range: 32-126 (space to tilde).
You must sort the string in **ascending** order (seen from the left, based on the ASCII-code value), but skip every `n`th character, starting from the end of the string. As an example, let's take the string `abcdABC123` as input, and `n=4`, then we'll get:
```
abcdABC123 <- Input string. (n=4)
_b___B___3 <- These will not be sorted (every 4th starting from the end)
1_2AC_acd_ <- The remaining characters, sorted
1b2ACBacd3 <- The final string (the output)
```
Another example:
```
9876543210 <- Input string (n=2)
_8_6_4_2_0 <- These will not be sorted
1_3_5_7_9_ <- The remaining characters, sorted
1836547290 <- The final string (the output)
```
The input string can be taken on an optional format (string, list of characters, list of single character strings ...). The input integer can also be taken on an optional format.
**Test cases:**
The format will be `n=__`, followed by the input string on the next line. The output is on the line below.
```
n=1 (All elements will stay in place)
nafgaksa1252#"%#
nafgaksa1252#"%#
n=214 (The last character will stay in place. All other are sorted.
&/lpfAVD
&/AVflpD
n=8
g7L9T E^n I{><#ki XSj!uhl y= N+|wA}Y~Gm&o?'cZPD2Ba,RFJs% V5U.W;1e 0_zM/d$bH`@vKoQ 43Oq*C
g n !#$%&'i*+,./01l234579;w<=>?@ADoEFGHIJKBLMNOPQR STUVWXYeZ^_`abcdhjkmqsuovyz{|}~C
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ 14 bytes
```
ttfiX\qgP)S5M(
```
Inputs are a string enclosed in single quotes and a number. Single-quote symbols in the string should be escaped by duplicating (as in MATLAB and Octave).
[Try it online!](https://tio.run/##y00syfn/v6QkLTMipjA9QDPY1Ffj/3/1xKTkFEcnZ0MjY3UuEwA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/##y00syfmf8L@kJC0zIqYwPUAz2NRX479LyH/1vMS09MTs4kRDI1MjZSVVZXUuQy51Nf2cgjTHMBd1LiNDEy71dHMfyxAF17g8Bc9qOxvl7EyFiOAsxdKMHIVKWwU/7Zpyx9rIOvdctXx7dfXkqAAXI6dEnSA3r2JVhTDTUL1wa8NUBQWD@Cpf/RSVJI8EhzLv/EAFE2P/Qi1ndS4LAA).
### Explanation
Consider inputs `'abcdABC123'` and `4`.
```
tt % Implicitly input string. Duplicate twice
% STACK: 'abcdABC123', 'abcdABC123', 'abcdABC123'
f % Find: indices of nonzero elements: gives [1 2 ... n] where n is input length
% STACK: 'abcdABC123', 'abcdABC123', [1 2 3 4 5 6 7 8 9 10]
i % Input n
% STACK: 'abcdABC123', 'abcdABC123', [1 2 3 4 5 6 7 8 9 10], 4
X\ % 1-based modulo
% STACK: 'abcdABC123', 'abcdABC123', [1 2 3 4 1 2 3 4 1 2 3 4]
qg % Subtract 1, convert to logical: gives true (1) for 1, false (0) otherwise
% STACK: 'abcdABC123', 'abcdABC123', [0 1 1 1 0 1 1 1 0 1]
P % Flip
% STACK: 'abcdABC123', 'abcdABC123', [1 0 1 1 1 0 1 1 1 0]
) % Use as logical index into the string
% STACK: 'abcdABC123', 'acdAC12'
S % Sort
% STACK: 'abcdABC123', '12ACacd'
5M % Push logical index again
% STACK: 'abcdABC123', '12ACacd', [1 0 1 1 1 0 1 1 1 0]
( % Write into original string as specified by the index. Implicitly display
% STACK: 1b2ACBacd3
```
1-based modulo means that `mod([1 2 3 4 5], 3)` gives [`[1 2 3 1 2]`](https://tio.run/nexus/matl#@x8R8/9/tKGCkYKxgomCaSyXMQA) instead of the usual (0-based) [`[1 2 0 1 2]`](https://tio.run/nexus/matl#@x/z/3@0oYKRgrGCiYJpLJcxAA). This is needed here to handle the case `n=1` adequately.
[Answer]
# PHP, 101 bytes
negative string indexes (PHP 7.1) save 21 bytes - and possibly the day:
```
for([,$s,$n]=$argv;a&$c=$s[$i-=1];)$i%$n+1?$a[]=$c:0;for(sort($a);++$i;)echo$i%$n+1?$a[+$k++]:$s[$i];
```
Run with `php -nr '<code>' '<string>' <N>`.
**breakdown**
```
for([,$s,$n]=$argv; # import command line arguments to $s and $n
a&$c=$s[$i-=1];) # loop backward through string
$i%$n+1?$a[]=$c:0; # if index is not n-th, copy character to array
for(sort($a); # sort array
++$i;) # loop forward through string:
echo$i%$n+1 # if index is not n-th
?$a[+$k++] # print character from array
:$s[$i] # else print character from string
;
```
[Answer]
# Python 2, 191 bytes
Yeah, I'm sure this is a terrible solution.
```
n,s=input()
s=s[::-1]
R=range(len(s)/n+1)
J=''.join
k=s[::n]
t=J(sorted(J(s[i*n+1:i*n+n]for i in R)))
n-=1
print J(j[::-1]for i in zip(k,[t[::-1][i*n:i*n+n][::-1]for i in R])for j in i)[::-1]
```
[**Try it online**](https://tio.run/nexus/python2#XY49D4IwEIb3@xXEhVZBU3Bq0gGICyMrYeBLc2AO0tbE@OeRinFwuTy5e/Leu1BgFNL8sIyDUaaUMhQVFErXdOvZvSdm@IkOgkOufP84TEgwfjyqwKqcmUnbvmMrlLhfRekmVddJe@gheQXnHChUAmaNZL2cDduTn/HCmY1Babe1S/lm/HlFxR0PjpFvx2U5B7u6abskzUQU7wAuz7lv10YSQDRRkqV128Vv)
I'm not going to bother explaining it. It was alright until I realized that it needs to be indexed from the end. Now it's a monster. At this point, I'm just glad it works.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~65~~ 54 bytes
```
function s=f(s,n)
l=~~s;l(end:-n:1)=0;s(l)=sort(s(l));
```
[Try it online!](https://tio.run/nexus/octave#PY9ZU8IwHMTf@yn@iiWtVqAVRqVWLeKBcnhUPB6U0CYQCQk2KQ4efHUEH3zb@e3szu6CZiLWTApQAbWUI2yDB/O58rlFRFLdFlXXDkq@srgdKJlqa6Vsf7E0wYQ2iYlSOJ0BlSlEjY4DQmpgFPSQwH81U6C0TEkCTACGXmHcA8o4ASshFGdc/8VbYdQMa8VOrPGU2IZhQkSUhhgroqoGtZDAdIBHCrtexcutmznkuPaK54thl/JJHTmeW/4jg93mfgSnLwIaX4cHuRGDx7u3tWzIYRZAe@v7I/x5mp@P8/IIofj5uu7VsHN7dqlM6FbuCw@@SwBKr5@tYrLRv@gdT6/kDZR3Ou@bJ8jZs5fH6zLrL/cjBFoCUTGeEOBMkxRzQIXFLw "Octave – TIO Nexus")
Uses logical indexing to make an array of 'fixed' and 'sorted' characters. Explanation:
```
function s=f(s,n) % Create a function, taking a string `s` and the number `n`; the output is also named `s`.
l=~~s; % Create logical array with the same size of the input string
% [equivalent to much more verbose true(size(s))].
l(end:-n:1)=0; % Set the 'fixed' character positions. MATLAB/Octave automatically produces
% the correct result even if n is larger than the string length.
s(l)=sort(s(l)) % Select the elements from `s` where `l` is true. Sort, and store in the corresponding positions in `s`.
```
The way I created `l` requires that `s` is nonzero, which I think is a reasonable requirement, as many languages use `\0` as an end-of-string delimiter.
[Answer]
## JavaScript (ES6), ~~100~~ 93 bytes
Takes input in currying syntax `(s)(n)`.
```
s=>n=>s.replace(/./g,(c,i)=>(F=_=>(s.length-++i)%n)()?[...s].filter(F,i=0).sort()[j++]:c,j=0)
```
### Formatted and commented
```
s => n => s.replace( // given a string s and an integer n
/./g, // for each character c of s
(c, i) => ( // at position i:
F = _ => // F = function that tests whether the
(s.length - ++i) % n // character at position i is non-static
)() // call F() on the current position
? // if the current character is non-static:
[...s].filter(F, i = 0) // get the list of non-static characters
F, i = 0 // by filtering all characters in s with F()
) //
.sort()[j++] // sort them and pick the next occurrence
: // else:
c, // let c unchanged
j = 0 // initialize j = non-static character pointer
) //
```
### Test cases
```
let f =
s=>n=>s.replace(/./g,(c,i)=>(F=_=>(s.length-++i)%n)()?[...s].filter(F,i=0).sort()[j++]:c,j=0)
console.log(f("abcdABC123")(4))
console.log(f('nafgaksa1252#"%#')(1))
console.log(f('&/lpfAVD')(214))
console.log(f("g7L9T E^n I{><#ki XSj!uhl y= N+|wA}Y~Gm&o?'cZPD2Ba,RFJs% V5U.W;1e 0_zM/d$bH`@vKoQ 43Oq*C")(8))
```
[Answer]
# [Perl 5](https://www.perl.org/) `-lF`, 78+3 = 81 bytes
```
$i=<>;map{(@F-++$c)%$i&&((push@b,$_),$_='')}@F;say map/./?$_:(sort@b)[$g++],@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l09bGzjo3saBaw8FNV1tbJVlTVSVTTU1Do6C0OMMhSUclXhOIbdXVNWsd3KyLEysVgIr19fTtVeKtNIrzi0ockjSjVdK1tWN1HNz@/7e0MDczNTE2MjTgMvqXX1CSmZ9X/F/X11TPwNDgv26OGwA "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
FṢṁ
ṚsṚµḢ€ż@Ç
```
Full program that prints the string to STD out\*.
**[Try it online!](https://tio.run/nexus/jelly#@@/2cOeihzsbuR7unFUMxIe2Ptyx6FHTmqN7HA63////XykxKTnF0cnZ0MhY6b8JAA)**
### How?
```
ṚsṚµḢ€ż@Ç - Main link: string s, non-negative number n
·πö - reverse s
s - split into chunks of size n
·πö - reverse the resulting list
µ - monadic chain separation (call that list x)
Ḣ€ - head €ach - yield a list of the first entries of each of x and modify x
Ç - call the last link (1) as a monad - get the sorted and re-split list
ż@ - zip together (with reversed @rguments)
FṢṁ - link 1, sort and reshape like self: list of lists
F - flatten into a single list
·π¢ - sort
ṁ - mould the result like the input
```
*~~I can't help but think~~ there is a way to use the fact that `·∏¢` modifies its input*
\* for a function one would want to flatten the output into a single list with `F`.
For example an input of `"abcdABC123"`, `4` yields:
`[[['1'],['b']],[['2','A','C'],['B']],[['a','c',',d'],['3']]]`
rather than:
`['1','b','2','A','C','B','a','c',',d','3']`
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 100 bytes
```
n=>g=x=>x.some((c,i)=>(i-(L=x.length-1))%n&&x.some((d,j)=>(j-L)%n&&i<j&c>d&&[x[i]=d,x[j]=c]))?g(x):x
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY9ZUsJAFEX_XUUbpNOtSWMClKh0kEGccFYcUlE7IwmhWyugcdyIP5Sli3IbrkAU_dGvV_XOqfvefX7lwvWGL036Nuj7aund5dQIaEqNlCSi5yHkKCGmBgpV1KIpiT0e9DuqhnGWQ_jruEr05URq63sdliPoGC6EZmqGFnWV1Iws6lgYVwKU4oX059aHTxk1bGo0kY2RSQhhFiaRCDmSZTzhCJ6I2COxCJCPJGY7brVW1_S8hFEB_-UyZ37AugnT9KKekbIZGSPtvwVz8aVfbTdGVNf-p0jBXGv-ACyfcbB2b5Qz3RAc70eTg04MbinYmnm4qT6ePK30oKjIzulOQ68xZa-5nmRBu3hIjhY1D4DZ87vNnDtlr14sXW-IXVDIb19N10dPlzAeNx8Ox_MT)
Use no `sort`
[Answer]
# [Perl 5](https://www.perl.org/), 94 bytes
88 bytes of code + `-F -pl` flags.
```
$_=join"",(map{(--$i%$n?"":$F[$#F-$i--]),$_}sort grep$i++%$n,reverse@F),chop if($n=<>)>1
```
[Try it online!](https://tio.run/nexus/perl5#DcrbUoJAGADg@32KX1gMgk13hdQS1FQ6n8tOU0i2IIqwQdmU2auTl9/MJ5cEz2IgLhARF9izp2mUSJKhzn2xVAnBkYKTtiTtYPcJy@7ahDxrBvZWeZp9QJhxgSNdXycj4wue5bzjasZ4kgqIAhUndsvRHFoUiR@E/iz3KbOYLCkyoqjZqG9bZo3RKmKoXIlF0B32EaMmCusnzRsYvCRwuHRa8iyC@@tp6XMSw7cNZ/rvV3f18Lc/L6ftjfHjRZ/t@caVe5QrMLRut@52KQeoej@nlTf8ejDqLI7TSzBr5@@bPdT4Bw "Perl 5 – TIO Nexus")
It's quite too long in my opinion, but already not that ugly... I'm still trying to golf it further anyway.
[Answer]
# [Python](https://www.python.org/) + [NumPy](http://www.numpy.org/), ~~115~~ 114 bytes
```
from numpy import *
def f(x,n):l=len(x);x=array(x);m=[1<2]*l;m[-1::-n]=[1>2]*len(m[0::n]);x[m]=sort(x[m]);return x
```
Takes a regular Python list as input (wasn't sure whether taking an array would be considered kosher); returns a NumPy array containing the result.
Works by masking out the relevant indices and sorting the rest.
[Answer]
## Python 2, ~~119~~ 113 bytes
```
n,l=input()
i=range(len(l))
print"".join(sorted(l[~a]for a in i if a%n)[-a+a/n]if a%n else l[~a]for a in i)[::-1]
```
Builds a list of all characters to be sorted, sorts them and merges them for printing, while avoiding some of the reversing via negative indexing.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 36 bytes
```
pe<-jJ-.hdcoJ)-]j)[-++<>#acoz[\[\[<-
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/INVGN8tLVy8jJTnfS1M3NkszWldb28ZOOTE5vyo6BghtdP//N1KytDA3MzUxNjI0UAIA "Burlesque – Try It Online")
Takes input as `N "String"`
```
pe # Parse and push
<- # Reverse the string
j # Put N at the top of the stack
J-.hd # Store N-1 for later
co # Split string into chunks of N
J)-] # Duplicate and take the heads
j)[- # Take the tails of the other duplicate
++ # Reduce all the "useless" chars to string
<> # Reverse sort
#aco # Split into chunks of N-1
z[ # Zip the two lists
\[\[ # Flatten to string
<- # Reverse the string
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 53 bytes
```
{(my@a=$^a.comb)[grep (@a-*-1)%$^n,^@a].=sort;[~] @a}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ojt9Ih0VYlLlEvOT83STM6vSi1QEHDIVFXS9dQU1UlLk8nziExVs@2OL@oxDq6LlbBIbH2f3FipUKaglJiUnKKo5OzoZGxko6CyX8A "Perl 6 – Try It Online")
It feels like there should be a shorter way of doing this
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
DāR<IÖ≠©Ï{®ƶ<ǝ
```
I/O of the string as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f/f5UhjkI3n4WmPOhccWnm4vzr40Lpj22yOz/3/P1opUUlHKQmIk4E4BYgdgdgJiJ2B2BCIjYDYWCmWywQA) or [verify all test cases](https://tio.run/##yy9OTMpM/W/qpuSZV1BaUmyloGTv6WIfrKSQmJcCZofqcCn5l5YAJUFy/12ONAbZRBye9qhzwaGVh/urD607ts3m@Nz/Xjr/E5OSUxydnA2NjLlMuCwtzM1MTYyNDA24jLjyEtPSE7OLEw2NTI2UlVSVuQy51PRzCtIcw1y4jAxNuNLNfSxDFFzj8hQ8q@1slLMzFSKCsxRLM3IUKm0V/LRryh1rI@vcc9Xy7dWTowJcjJwSdYLcvIpVFcJMQ/XCrQ1TFRQM4qt89VNUkjwSHMq88wMVTIz9C7WcuSwA) (feel free to remove the `S` and `J` in the test suite to see the actual I/O with character lists).
And I agree with [*@mbomb007*'s comment](https://codegolf.stackexchange.com/questions/112935/sort-useless-characters#comment275399_112963), although it's still pretty short this way. :)
**Explanation:**
```
# Example inputs: s=["a","b","c","d","A","B","C","1","2","3"] and n=4
D # Duplicate the (implicit) character-list input
# STACK: [["a","b","c","d","A","B","C","1","2","3"],
# ["a","b","c","d","A","B","C","1","2","3"]]
ā # Push a list in the range [1,list-length] (without popping the list)
# STACK: [s, s, [1,2,3,4,5,6,7,8,9,10]]
R # Reverse it to range [length,1]
# STACK: [s, s, [10,9,8,7,6,5,4,3,2,1]]
< # Decrease each by 1 to range (length,0]
# STACK: [s, s, [9,8,7,6,5,4,3,2,1,0]]
IÖ # Check for each if it's divisible by the integer-input
# STACK: [s, s, [0,1,0,0,0,1,0,0,0,1]]
≠ # And invert those truthy/falsey values
# STACK: [s, s, [1,0,1,1,1,0,1,1,1,0]]
© # Store this list of truthy/falsey values in variable `®`
Ï # Only keep the characters in the list at the truthy indices
# STACK: [s, ["a","c","d","A","C","1","2"]]
{ # Sort those
# STACK: [s, ["1","2","A","C","a","c","d"]]
® # Push the truthy/falsey list again from variable `®`
# STACK: [s, ["1","2","A","C","a","c","d"], [1,0,1,1,1,0,1,1,1,0]]
∆∂ # Multiply each by their 1-based index
# STACK: [s, ["1","2","A","C","a","c","d"], [1,0,3,4,5,0,7,8,9,0]]
< # Decrease everything by 1 to make it 0-based indexing
# STACK: [s, ["1","2","A","C","a","c","d"], [0,-1,2,3,4,-1,6,7,8,-1]]
«ù # Insert the sorted characters at those indices in the list
# (NOTE: Unlike almost all other 05AB1E builtins that use indices, this
# insert builtin ignores negative and too large indices instead of using
# modular indexing, so the -1 are conveniently ignored here.)
# STACK: [["1","b","A","C","a","B","d","1","2","3"]]
# (after which this list is output implicitly as result)
```
[Answer]
# [Uiua](https://uiua.org), 16 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
⍜▽(⊏⍏.)¬⇌=0◿:⇡⧻,
```
[Try it!](https://uiua.org/pad?src=0_5_1__ZiDihpAg4o2c4pa9KOKKj-KNjy4pwqzih4w9MOKXvzrih6Hip7ssCgpmIDEgIm5hZmdha3NhMTI1MiNcIiUjIgpmIDIxNCAiJi9scGZBVkQiCmYgOCAiZzdMOVQgRV5uIEl7Pjwja2kgWFNqIXVobCB5PSBOK3x3QX1ZfkdtJm8_J2NaUEQyQmEsUkZKcyUgVjVVLlc7MWUgIDBfek0vZCRiSGBAdktvUSA0M09xKkMiCg==)
```
⍜▽(⊏⍏.)¬⇌=0◿:⇡⧻,
⇡⧻, # range of length
‚óø: # modulo input
=0 # where is it zero?
‚áå # reverse
¬ # not
⍜▽(⊏⍏.) # under-keep-sort (sort input where mask is 1)
```
[Answer]
# [J](http://jsoftware.com/), 28 bytes
```
]/:~@#~`(I.@])`[}0<(|i.@-@#)
```
[Try it online!](https://tio.run/##Zc7XjoJgEAXge59iFOW3gqDGFRvN3huWjQqi2FA0Ro2NV2dXt9w4yVzNd3JmZTkIpEGSAQR@CALzvQEChGY5aw1JxmQxU3YXCHbokT8fwYT7viTYAIt5LI@tyhPwTkzm39hm6sIARE1oTuAVdRpCEGAgDBogZaJOOV6g6BD6VTjJSZq@E1@Gpl4KJ/Wdxknin9kq2lxZHxSKjtCYw4W9LPWUb5ffxBx@Zgt2zOnCEVp6fX6CDFI6HQpHorH4OZFMpVlONDLZXL5QLPHlSrVWbzSh1e5I3V5/NhiN5ee3i9V6sz8cjdPlers/TOHV/fHsnkfLsTZkRlso3FIJbL2EXmtlPy50uCSh6rufuUffzG1wI42QOqiLNK/4m9niwQVSpEN049QMIDi@Vsipc5KX2VPJaEA4VNt7BWR9AQ "J – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ẏṘ~ḞFṘ⁽s?∇¢
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLhuo/huZh+4bieRuG5mOKBvXM/4oiHwqIiLCIiLCJhYmNkQUJDMTIzXG40Il0=)
Outputs as a list of characters
## Explained
```
ẏṘ~ḞFṘ⁽s?∇¢­⁡​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁢⁢‏‏​⁡⁠⁡‌⁢⁢​‎⁠‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁣⁣‏‏​⁡⁠⁡‌­
~Ḟ # ‎⁡Every nth item of
ẏṘ # ‎⁢The range [len(string), 0]
~ # ‎⁣without popping anything
F # ‎⁤Remove each item in that "every nth item" list from the range
Ṙ # ‎⁢⁡Reverse that so that the indices are in ascending order
¢ # ‎⁢⁢Apply
⁽s # ‎⁢⁣A function that sorts its argument
∇ # ‎⁢⁤to the items at indices in
? # ‎⁣⁡the string
¢ # ‎⁣⁢and insert the items in the result back at those indices
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# Ruby, 64 bytes
Uses regex to grab all irrelevant characters, both for replacement and for sorting.
```
->i,s,j=-1{s.gsub(r=/.(?!(?=.{#{i}})*$)/){s.scan(r).sort[j+=1]}}
```
[Try it online](https://repl.it/GgEN)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~111~~ 109 bytes
```
lambda n,s:(l:=len(s),r:=sorted(s[~i]for i in range(l)if i%n),[r.insert(i,s[i])for i in range(~-l%n,l,n)])[1]
```
[Try it online!](https://tio.run/##bc3ZUsIwGEDhe5/iFyxNNAJpQRatyuK@b7jUqoG2EAhpTaqOG69e8Zbh/ptz4s9kEEm7Gqs0BAceU8HGXZ@BJLqORN0RgUQaE1V3dKSSwEfanXAvjBRw4BIUk/0ACcxD4IbExFV5LnWgEsSJdrmHZ@RkVRiSCCKxh13qpbHiMkGmmR9GXKIQlQiYrNvzG80WtWwTY7wwS6wpqVUra@WSbdHiXEKnRLKwz0aaUatsZTNGdn6L/g9zBRGHjU57LqkSyPQrx7Vr2HmScPC9uZEdcbi7Gi6@DQR8OnC68vPR@L2f7I1z0ZbZezhvW01GLncPtQGd8k3@dp0GAMXnr5OCv9Tdf9l@P4ouoGSfvS63MtNj@gc "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
**EDIT**
It appears that there has been some confusion following my typo in the original post which used a lowercase o to define the plane and then an uppercase later. Unfortunately this bug did not get picked up in the Sandbox. Since many members have written answers with both and since the typo was my fault I will allow either uppercase or lowercase o in the definition of the plane. I have added a new rule for this.
**Background**
I like [ascii art animations](https://codegolf.stackexchange.com/questions/96541/make-an-ascii-bat-fly-around-an-ascii-moon%22ascii%20art%20animations%22) as I tend to call them so here is another one. I don't think this is too difficult to implement so will hopefully get some short and interesting answers.
**To all fellow community members**
If you improve on your answer please modify your byte count as
**~~old byte count~~ new byte count**
so we can see your progress. Thanks!
**Challenge**
Here is an ascii plane
```
--O--
```
Here is an ascii runway
```
____| |____
```
The plane starts at 5 newlines above the runway. To prevent any clashes between metric and imperial systems and make this a truly international challenge I won't mention meters or feet. Example:
```
--O--
____| |____
```
The Plane must land exactly in the middle of the runway as shown below:
```
____|--O--|____
```
**Input**
The initial horizontal position of the plane is defined by an integer input which is used to reference the tip of the left wing i.e. it is between 0 and 10 inclusive.
**Output**
Each stage of the planes flight must be shown. Example below (input=10):
```
--O--
____| |____
--O--
____| |____
--O--
____| |____
--O--
____| |____
--O--
____| |____
____|--O--|____
```
To keep things simple, we are ignoring the laws of perspective. The runway stays the same size as you get closer.
**Rules**
* **Update** The middle of the plane can be either an uppercase or lowercase o but whichever is chosen must be consistent throughout the code. If your language does not support the characters above feel free to use alternative ascii only characters.
* The plane descends 1 line per frame.
* The plane can only move 1 space to the left or right each time it descends one line. It does not have to move on each line of descent. As long as it finishes on the runway it is up to you when it moves right or left. You're the pilot!
* No error handling required. You may assume that the input will always be a valid integer from 0-10 inclusive.
* Output must consist of only the characters shown above (if your language does not support them the see edited first rule) and must be the same size i.e. must start 6 lines high by 15 characters wide. The height can decrease as it progresses as in the example above.
* Program or function is fine but must produce an output as shown
above.
* Leading/trailing spaces/newlines are fine by me.
* Please feel free to clear the screen between output frames if you wish. This is **not** a requirement.
* Standard loopholes prohibited as usual (although I don't think there are many that would help with this kind of challenge).
* This is code golf so shortest answer is obviously the winner and will probably get most votes but may not necessarily be accepted as the best answer if some really interesting solution comes along in some unexpected language, even if it is longer. Feel free to post anything that meets the rules as long as it works.
Ungolfed reference implementation in Python 2 available at [Try it online!](https://tio.run/nexus/python2#dVBLDoIwEN33FLMr0NRAohvjcAUPoIQQRamSQqDEmHB3bKdK0MRZvc77zEunti50mfem6Awq3Q4mCBntkEu5l5Kza9cM@owHntsZwc3oIM/YRWnVV@gZknuG9fenNcD3WMPJRhmMHZ97vGaPStUlzJsUY9gypzdN60J4tOgoCGfEt53SBvhR89WtUTqwehHYnGjOCoUvH4IgHdnUBRaBkMLmfY8yF4xESIgo6x/P7q9HfDx0X6B/zIV8pi/uP2@akvgF "Python 2 – TIO Nexus") so you can see how it looks for different input values.
[Answer]
# TI-BASIC, 62 bytes
```
:Input A
:A
:For(N,3,8
:ClrHome
:Output(8,1,"----I I----
:Output(N,Ans,"--O--
:Ans+(Ans<6)-(Ans>6
:End
```
Note that TI-BASIC does not support \_ or | and therefore I replaced with a capital I and -. This should not effect byte count.
[Answer]
## Python 2, 107 bytes
```
n=input();h=5
while h:print' '*n+'--O--'+'\n'*h+'____| |____\n';n-=cmp(n,5);h-=1
print'____|--O--|____'
```
[Try it online](https://tio.run/nexus/python2#@59nm5lXUFqioWmdYWvKVZ6RmZOqkGFVUJSZV6KuoK6Vp62uq@uvq6uurR6Tp66Voa0eDwQ1CiBQA2ICRa3zdG2Tcws08nRMgabo2hpyQbSDVYJ1g1Wq//9vaAAA)
Simply hardcodes the last line for the landing plane. It can likely be golfed by re-using parts from before or being integrated into the loop.
[Answer]
## Perl, 94 bytes
93 bytes of code + `-p` flag.
```
$\="____| |____
";$p="--O--";for$i(-5..-1){print$"x$_.$p.$/x-$i;$_+=5<=>$_}$\=~s/ +/$p/}{
```
[Try it online!](https://tio.run/nexus/perl#U1YsSC3KUdAt@K8SY6sUDwQ1CiBQA2JyKVmrFNgq6er66@oqWaflF6lkauia6unpGmpWFxRl5pWoKFWoxOupFOip6FfoqmRaq8Rr25ra2NqpxNcCjasr1lfQ1lcp0K@t/v/fEAA "Perl – TIO Nexus")
[Answer]
# TI-BASIC, 61 bytes
```
Input A
A
For(B,1,5
ClrHome
Output(5,1,"----/ /----
Output(B,Ans,"--O--
Ans+6-median({5,7,Ans
End
```
[Answer]
# JavaScript (ES6), 108 bytes
```
f=(a,b=5)=>b?" ".repeat(a)+`--O--${`
`.repeat(b)}____| |____
`+f(a<5?a+1:a-1,b-1):"____|--O--|____"
```
## Test it
```
f=
(a,b=5)=>b?" ".repeat(a)+`--O--${`
`.repeat(b)}____| |____
`+f(a<5?a+1:a-1,b-1):"____|--O--|____"
```
```
<input type=number min=0 max=10 oninput=o.textContent=f(+this.value)><pre id=o>
```
## Usage
Just call `f` with the index of the plane.
```
f(2)
```
## Output
```
--O--
____| |____
--O--
____| |____
--O--
____| |____
--O--
____| |____
--O--
____| |____
____|--O--|____
```
[Answer]
## Scala, ~~224~~ 181 bytes
**EDIT**: I had no idea you could do `"string"*n` to repeat it n times! Scala continues to blow my mind. Missing the `if(t>0)` instead of `if(t==0)` was a rookie mistake. Thanks for the tips, [Suma](https://codegolf.stackexchange.com/users/64633/suma)!
---
```
def?(x:Int,t:Int=5):Unit={var(p,o)=("--o--","")
o=s"____|${if(t>0)" "*5 else p}|____\n"
for(i<-0 to t)o=if(i!=0&&i==t)" "*x+p+o else "\n"+o
println(o)
if(t>0)?(x-(x-4).signum,t-1)}
```
---
Original remarks:
I figured a recursive solution would be fun to try. I'm relatively new to Scala, so I'm certain this is far from optimal.
[Answer]
## Batch, 230 bytes
```
@echo off
set/ax=10-%1
set s= --O--
for /l %%i in (0,1,4)do call:l %%i
echo ____^|--O--^|____
exit/b
:l
call echo %%s:~%x%%%
for /l %%j in (%1,1,3)do echo(
echo ____^| ^|____
echo(
set/a"x-=x-5>>3,x+=5-x>>3
```
`x` is the number of spaces to remove from the beginning of the string `s`, so I subtract the parameter from 10. The last line is the nearest Batch has to `x-=sgn(x-5)`.
[Answer]
# sed, 181 bytes + 2 for `-nr` flags
```
s/10/X/
:A
s/^/ /;y/0123456789X/-0123456789/;/[0-9]/bA;s/ -/P\n\n\n\n\n____|P|____/
:B
h;s/P([\n|])/--O--\1/;s/P/ /;s/^ *_/_/;p;/^_/q;x;s/\n//
/^ {5}$/bB;/ {6}/s/ //;s/^/ /;bB
```
## Ungolfed
```
# Add leading spaces
s/10/X/
:A
s/^/ /
y/0123456789X/-0123456789/
/[0-9]/bA
s/ -/P\n\n\n\n\n____|P|____/
:B
# Place plane in appropriate spot
h
s/P([\n|])/--O--\1/
s/P/ /
s/^ *_/_/
p
/^_/q
x
# Movement
s/\n//
/^ {5}$/bB
# move left one extra, since we'll move right next line
/ {6}/s/ //
s/^/ /
bB
```
Usage: `$ echo 2 | sed -nrf flightsim.sed`
[Answer]
# [Retina](https://github.com/m-ender/retina), 86 83 bytes
```
.+
$* --O--¶¶¶¶¶¶____| |____
{*`$
¶
2D`¶
( {5})
$1
}`^ {0,4}-
$&
+
--O--
G`_
```
[Try it online!](https://tio.run/nexus/retina#@6@nzaWipaCr66@re2gbAsYDQY0CCNSAmFzVWgkqXIe2cRm5JABJBQ2FatNaTS4VQ67ahDiFagMdk1pdLgUVNS4FbS6wWVzuCfH//xsAAA "Retina – TIO Nexus")
There is probably some sort of compression I could have used on the runway and the empty space over it, but anything I tried came up more expensive than plaintext (in Retina ¶ is a newline, so you can see the initial state in plaintext on the second line).
[Answer]
## [Scala](http://www.scala-lang.org/), 177, 163, 159 137 bytes
```
def p(x:Int,t:Int=5,a:String="\n"):String=a+(if(t>0)
" "*x+"--O--"+"\n"*t+"____| |____\n"+p(x-(x-4).signum,t-1)else"____|--O--|____")
```
Based on [another answer](https://codegolf.stackexchange.com/a/107290/64633), with significant reductions.
[Answer]
# [Perl 6](http://perl6.org/), ~~97~~ ~~90~~ 81 bytes
```
{say "{"{" "x 15}\n"x 5}____| |____"~|("\0"x$^h+$_*(17-$h/5)~"--O--") for ^6}
```
Contrary to what it looks like, it outputs the \*lower-case version of the plane (`--o--`), as allowed by the updated task description.
[Try it online!](https://tio.run/nexus/perl6#y61UUEtTsP1fXZxYqaBUDYQKShUKhqa1MXlA2rQ2HghqFECgBsRUqqvRUIoxUKpQicvQVonX0jA011XJ0DfVrFPS1fXX1VXSVEjLL1KIM6v9n6ZgYf0fAA "Perl 6 – TIO Nexus")
### How it works
Bitwise string operators FTW!
```
{ # Lambda accepting horizontal index $h.
say # Print the following:
"{ "{ " " x 15 }\n" x 5 }____| |____" # The 15x6 background string,
~| # bitwise-OR'd against:
(
"\0" # The NULL-byte,
x $^h + $_*(17 - $h/5) # repeated by the plane's offset,
~ "--O--" # followed by an OR mask for the plane.
)
for ^6 # Do this for all $_ from 0 to 5.
}
```
It works because bitwise string operators use the codepoint values of the characters at a given position in two strings, to calculate a new character at that position in the output string.
In this case:
```
space OR O = o
space OR - = -
any OR \0 = any
```
For an uppercase-`O` plane, we could have used `~^` (string bitwise XOR), with a plane mask of `\r\ro\r\r` (+4 bytes for backslashes):
```
space XOR o = O
space XOR \r = -
any XOR \0 = any
```
The formula for the plane's offset, `h + v*(17 - h/5)`, was simplified from:
```
v*16 # rows to the vertical current position
+ h # columns to the horizontal starting position
+ (5 - h)*v/5 # linearly interpolated delta between horizontal start and goal
```
[Answer]
# [Python 2](https://docs.python.org/2/), 160 bytes
```
i,s,p,l,r,c,x=input(),' ','--O--','____|','|____',0,4
while x>=0:print'\n'.join([s*i+p]+[s*15]*x+[l+s*5+r])+'\n';c+=1;x-=1;i=((i,i-1)[i>5],i+1)[i<5]
print l+p+r
```
[Try it online!](https://tio.run/nexus/python2#HYxBDsIgFET3PQU7aP/HlCgbK72CB0DiojHxG4IEamTRuyN1FvPeYjKVMGNEjwkXLIZC/KyiR844cimvUjbeW7bGbReOI56675P8g5XZjOeYKKz8Fvjh9aYgbB4IooNGpd1QwHrIg4bkethX0wJGTUW2IiMEIUnVW5q1Q4LdLtp1/0/mIUKq9fgD "Python 2 – TIO Nexus")
Here is the reference implementation golfed down to 160 from 384. Still a way to go I think. Just posted for fun and to encourage a better Python answer.
[Answer]
# Befunge-93, ~~136~~ 130 bytes
```
&5>00p10p55+v
:::00g>:1-\v>:"____| |_"
>:1-\v^\+55_$"--O--"10g
^\*84_$>:#,_10g::5v>:#,_@
<_v#!:-1g00+`\5\-`<^"____|--O--|____"
```
[Try it online!](http://befunge.tryitonline.net/#code=JjU+MDBwMTBwNTUrdgo6OjowMGc+OjEtXHY+OiJfX19ffCAgICAgfF8iCj46MS1cdl5cKzU1XyQiLS1PLS0iMTBnCl5cKjg0XyQ+OiMsXzEwZzo6NXY+OiMsX0AKPF92IyE6LTFnMDArYFw1XC1gPF4iX19fX3wtLU8tLXxfX19fIg&input=MTA)
**Explanation**
```
& Read the plane position.
5 Initialise the plane height.
> Begin the main loop.
00p Save the current height.
10p Save the current position.
55+: Push two linefeed characters.
"____| |_" Push most of the characters for the airport string.
::: Duplicate the last character three times to finish it off.
00g>:1-\v Retrieve the current height, and then push
^\+55_$ that many copies of the linefeed character.
"--O--" Push the characters for the plane.
>:1-\v 10g Retrieve the current position, and then push
^\*84_$ that many copies of the space character.
>:#,_ Output everything on the stack in reverse.
10g:: Retrieve the current position and make two copies to work with.
5v If it's greater than 5
-`< then subtract 1.
+`\5\ If it's less than 5 then add 1.
g00 Retrieve the current height.
-1 Subtract 1.
_v#!: If it's not zero, repeat the main loop.
^"____|--O--|____" Otherwise push the characters for the landed plane.
>:#,_@ Output the string and exit.
```
[Answer]
# Ruby, 94 bytes
```
->a{5.times{|i|puts" "*a+"--O--#{?\n*(5-i)}____| |____
";a+=5<=>a};puts"____|--O--|____"}
```
Prints the plane's position followed by newlines and then the airport.
Then it moves the plane by 1, -1, or 0, depending on its position relative to 5.
After looping the above 5 times, it prints the plane in the airport.
[Answer]
# [8th](http://8th-dev.com/), ~~177~~ 172 bytes
```
: f 5 >r 5 repeat over " " swap s:* . "--O--" . ' cr r> times "____| |____\n\n" . over 5 n:cmp rot swap n:- swap n:1- dup >r while "____|--O--|____\n" . 2drop r> drop ;
```
The word `f` expects an integer between 0 and 10.
**Usage**
```
4 f
```
**Explanation**
```
: f \ n --
5 >r \ Push vertical distance from airport to r-stack
5 repeat
\ Print plane
over " " swap s:* . "--O--" .
\ Print airport
' cr r> times "____| |____\n\n" .
\ Now on the stack we have:
\ distanceFromLeftSide distanceFromAirport
over \ Put distance from left side on TOS
5 n:cmp \ Compare left distance and 5. Return
\ -1 if a<b, 0 if a=b and 1 if a>b
rot \ Put distance from left side on TOS
swap n:- \ Compute new distance from left side
swap n:1- \ Decrement distance from airport
dup >r \ Push new airport-distance on the r-stack
while
"____|--O--|____\n" . \ Print final step
2drop r> drop \ Empty s-stack and r-stack
;
```
[Answer]
# Mathematica, 111 bytes
```
If[#<1,"____|--O--|____"," "~Table~#2<>"--O--"<>"
"~Table~#<>"____| |____
"<>#0[#-1,#2+#2~Order~5]]&[5,#]&
```
Anonymous function. Takes a number as input and returns a string as output. Could probably be golfed further.
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~93~~ ~~91~~ 84 bytes
```
:{X=space$(a)+@--O--`┘a=a-sgn(a-5)~t>-1|?X[t|?]t=t-1?@____|`+@ `+_fB|\_xB+A+_fB
```
*Dropped some bytes by replacing the declaration of X$; optimised the FOR loop that prints the distance above-ground. Explanation below is for the old version, but it basically works the same.*
For testing (and aesthetics) I had a slightly different version, at 103 bytes:
```
:{_z.5|_CX=Y[a|X=X+@ `]X=X+@--O--`
a=a-sgn(a-5)
~u>0|?X';`[u|?]u=u-1?@____|`+@ `+_fC|\_xC+_tB+_fC
```
These are functionally identical. The second one has the addition that the screen gets cleared between frames and that it halts for 0.5 seconds between frames.
# Sample output
Note that I've added two newlines between frames. The most golfed code above does not add empty lines between frames, the cooler one clears the screen.
```
Command line: 10
--O--
____| |____
--O--
____| |____
--O--
____| |____
--O--
____| |____
--O--
____| |____
____|--O--|____
```
# Explanation
Since I feel this touches upon many things I really like about QBIC, and gives a good insight in how some of its functions work under the hood, I've gone a bit overboard on the explanation. Note that QBIC is, at its core, an QBasic interpreter for Codegolf. QBIC code goes in - QBasic code comes out (and is subsequently executed).
```
:{ get the starting offset (called 'a') from the command line, and start a DO-loop
---- cool code only ----
_z.5|_C At the start of a DO-loop, pause for half a second and clear the screen
---- resume golf-mode ----
---- #1 - The tip of the left wing is anywhere between 0 and 10 positions to the right.
---- Create the plane with the spacing in X$
X=Y Clear X$
[a| For each point in the current offset
X=X+@ `] Add a space to X$
- Every capital letter in QBIC references that letter+$, a variable of type String
- @ and ` start and end a string literal, in this case a literal space.
- ] ends one language construct (an IF, DO or FOR). Here, it's NEXT
X=X+@--O--` Create the actual plane
- @ and `once again create a string literal. Every literal that is created in this
way is assigned its own capital letter. This is our second literal, so the body of
our plane is stored in B$ (A$ contains the space, remember?)
---- #2 Adjust the offset for the next iteration
a=a-sgn(a-5) The clever bit: We have an offset X in the range 0 - 10, and 5 attempts to
get this to be == 5. X - 5 is either positive (X = 6 - 10), negative
(X = 0 - 4) or 0 (X=5). sgn() returns the sign of that subtraction
as a 1, -1 or 0 resp. We then sub the sign from 'a', moving it closer to 5.
---- #3 Draw the plane, the empty airspace and the landing strip
~u>0| Are we there yet?
- ~ is the IF statement in QBIC
- It processes everything until the | as one true/false expression
- All the lower-case letters are (or better, could be) references to numeric
variables. Since QBasic does not need to post-fix those, they double as 'natural'
language: ignored by QBIC and passed as literal code to the QBasic beneath.
- The lower-case letters q-z are kinda special: at the start of QBIC, these
are set to 1 - 10. We haven't modified 'u' yet, so in the first DO-loop, u=5
?X';` If we're still air-borne, print X$ (our plane, incl. spacers)
- ? denotes PRINT, as it does in QBasic.
- ' is a code literal in QBIC: everything until the ` is not parsed, but
passed on to QBasic.
- In this case, we want a literal ; to appear after PRINT X$. This suppresses
QBasic's normal line-break after PRINT. This needs to be a code literal
because it is the command to read a String var from the command Line in QBIC.
[u|?] FOR EACH meter above the ground, print a newline
u=u-1 Descent 1 meter
?@____|` Print the LHS of the landing strip
+@ ` plus 5 spaces
+_fC| plus the LHS reversed.
\ ELSE - touchdown!
_x Terminate the program (effectively escape the infinite DO-loop)
- the _x command has an interesting property: ULX, or Upper/Lowercase Extensibility.
Writing this command with an uppercase _X does something similar, yet different.
The _x command terminates, and prints everything found between _x and | before
quitting. Uppercase _X does not look for |, but only prints something if it is
followed by a character in the ranges a-z and A-Z - it prints the contents of
that variable.
C+B+_fC But before we quit, print C$ (the LHS of the landing strip) and the plane,
and the LHS flipped.
---- #4 QBIC has left the building
- Did I say _x looks for a | ? Well, that gets added implicitly by QBIC at the end of
the program, or when one ( ']' ) or all ( '}' ) opened language constructs are closed.
- Also, all still opened language constructs are automatically closed at EOF.
- Had we stored anything in Z$, that would also be printed at this time.
```
[Answer]
# SmileBASIC, ~~109~~ 105 bytes
```
G$="_"*4INPUT X
FOR I=0TO 4?" "*X;"--O--";CHR$(10)*(4-I)?G$;"| |";G$X=X-SGN(X-5)?NEXT?G$;"|--O--|";G$
```
[Answer]
# PHP 7, 139 bytes
still awfully long
```
for($x=$argv[1],$d=6;$d--;$x+=5<=>$x)for($i=$p=-1;$i++<$d;print"$s
")for($s=$i<$d?" ":"____| |____
";!$i&++$p<5;)$s[$x+$p]="--O--"[$p];
```
takes input from command line argument; run with `-r`.
**breakdown**
```
for($x=$argv[1], // take input
$y=6;$y--; // loop height from 5 to 0
$x+=5<=>$x) // post increment/decrement horizontal position
for($i=$p=-1;$i++<$y; // loop $i from 0 to height
print"$s\n") // 3. print
for($s=$i<$y?" ":"____| |____\n"; // 1. template=empty or runway+newline
!$i&++$p<5;)$s[$x+$p]="--O--"[$p]; // 2. if $i=0, paint plane
```
] |
[Question]
[
Inspired by [this](http://www.bbc.co.uk/news/technology-31028787) recent article telling of a French programmer who wrote a 487 byte 2-player (human vs. human) chess program in Assembly, I wondered how small chess programs could be in other languages.
**Details**
* The program must only accept legal chess moves.
* Declaration of check/checkmate is not necessary (just desirable), although the first rule applies in cases of check.
* As per the article, castling is not a necessary implementation.
* Also, you do not have to implement en passant.
* You do however, have to permit pawn promotion upon reaching eighth rank (you may opt to simply force conversion to queen).
* It is up to you how the board is displayed - terminal ASCII, GUI, etc.
* You must display whose turn it is.
The rules of chess can be found [here](http://www.chess.com/learn-how-to-play-chess) - ignore specified tournament rules (e.g. timing, touching), and remember castling and en passant are not necessary implementations.
[Answer]
# C, ~~650~~ 600
```
n=8,t=65,s,f,x,y,p,e,u=10,w=32,z=95;char a[95],b[95]="RNBKQBNR";v(){p=a[s]&z;y=f/u-s/u;x=f-s-y*u;e=x*x+y*y;n=s%u/8|f%u/8|a[s]/w-t/w|a[f]/w==t/w|!(p==75&e<3|p>80&x*y==0|p%5==1&x*x==y*y|p==78&e==5|p==80&x*(z-t)>0&(a[f]-w?e==2:e==1|e==4&s%5==1));if(!n&&p-78)for(e=(f-s)/abs(x*x>y*y?x:y),x=s;(x+=e)-f;)n|=a[x]-w;}main(){for(a[93]=40;n--;a[92]=47)sprintf(a,"%s%cP p%c \n",a,b[n],b[n]+w);for(;1;){puts(a);for(n=1;n;){putchar(t);scanf("%d%d",&s,&f);v();memcpy(b,a,z);if(!n){a[f]=p-80|f%u%7?a[s]:t+16;a[s]=w;a[f]&z^75||(a[z-t/w]=f);f=a[z-t/w];t^=w;for(n=1,s=80;n&&s--;)v();if(n=!n)memcpy(a,b,z),t^=32;}}}}
```
To reduce the code for initializing the board, the display has White (uppercase) playing from left to right and Black (lowercase) playing from right to left. Input is in the form of two 2-digit decimal numbers (start position and finish position), giving file(0-7) and rank(0-7). For a bit of extra code (subtract 11 from each input), input could be made to comply with <http://en.wikipedia.org/wiki/ICCF_numeric_notation> (digits 1-8)
Here's a sample screenshot where Black has just advanced his Rook's Pawn. White tries various illegal moves with his queen, before finally capturing the pawn. Turn indicators are `a` for Black and `A` for White.

An interesting feature of my validation is the use of the square of the Euclidean distance. For the knight this is always 1^2+2^2=5, but I also use it for the King and the pawn.
Test for Check is done by backing up the board, carrying out the players move, and scanning all 64 possible opponent's moves.
The program has to be ended with Ctrl-C. I cant think of a more gracious way of doing it, other than putting in a special move to end the program. A game of chess actually ends when one player is unable to move on his turn (checkmate or stalemate) and that requires a lot of tests that arent required by the spec.
**Commented code**
```
n=8,t=65,s,f,x,y,p,e,u=10,w=32,z=95; // 8,10 height and width of board. w=ASCII space, also difference between ucase and lcase
// 95 is bitmask for conversion lowercase to uppercase, but also used as length of array, etc.
char a[95],b[95]="RNBKQBNR"; // a is main board, b is backup board (but used at start to hold 1st row data.)
v(){ // validate move in all aspects except check
p=a[s]&z; // p=uppercase(character on start square)
y=f/u-s/u; // signed distance in y direction
x=f-s-y*u; // and x direction
e=x*x+y*y; // square of Euclidean distance
n=s%u/8|f%u/8| // n=true if 2nd digit of input out of bounds OR
a[s]/w-t/w|a[f]/w==t/w| // start sq not friendly piece OR finish sq is friendly piece (also eliminates case where start=finish)
!( // OR NOT geometry valid
p==75&e<3| // 'K'(ASCII75) AND euclidean distance squared =1 or 2 OR
p>80&x*y==0| // 'Q'or'R' AND x or y = 0 OR
p%5==1&x*x==y*y| // 'Q'or'B' AND abs(x)=abs(y)
p==78&e==5| // 'N' AND euclidean distance squared = 5
p==80&x*(z-t)>0&(a[f]-w?e==2:e==1|e==4&s%5==1) // 'P'(ASCII80):x direction must correspond with case of player (z-t)
); // if capturing e=2. Otherwise e=1 (except on start rows 1 and 6, e can be 4)
if(!n&&p-78) // if not yet invalid and piece not 'N'(ASCII78)
for(e=(f-s)/abs(x*x>y*y?x:y),x=s;(x+=e)-f;) // Set e to the numeric difference to travel 1 square in right direction. Set x to start square
n|=a[x]-w; // and iterate x through all intervening squares, checking they are blank
}
main(){
for(a[93]=40;n--;a[92]=47) // iterate n through 8 rows of board. vacant spaces in bracket are use to assign start positions of kings to a[92&93]
sprintf(a,"%s%cP p%c \n",a,b[n],b[n]+w); // build up start position, each row 10 squares wide, including filler space the end and newline
for(;1;){ // loop forever
puts(a); // display board
for(n=1;n;){ // loop while move invalid
putchar(t); // display prompt 'A' for white 'a' for black
scanf("%d%d",&s,&f); // get input
v(); // validate move
memcpy(b,a,z); // backup board (and king position metadata)
if(!n){ // if move not yet invalid
a[f]=p-80|f%u%7?a[s]:t+16; // if not a pawn on last row, content of finish square = start square, ELSE queen of correct case (t+16)
a[s]=w; // start square becomes blank (ASCII32)
a[f]&z^75||(a[z-t/w]=f); // if finish square king, update king position metadata
f=a[z-t/w]; // to begin scanning to see if king in check, set f to current king position
t^=w; // and change colour
for(n=1,s=80;n&&s--;)v(); // for s=79..0 search for valid opponent move to capture king (stops with n=0)
if(n=!n)memcpy(a,b,z),t^=32; // valid opponent threat on king means invalid player move. Invert n, recover board from backup and change colour back.
}
}
}
}
```
[Answer]
# Python 3, 1166 1071 993 bytes
I only realized I needed to stop kings from moving into check after I had otherwise finished, but here's my submission anyways
```
h=abs
m=range
l=print
o=" "
a=o*8
j=[list(s)for s in["RNBKQBNR","P"*8,a,a,a,a,"p"*8,"rnbkqbnr"]]
u=False
v=lambda c:(c.lower()==c)==u
while 1:
l("b"if u else"w")
for b in j:l(*b)
q,r,s,t=[int(i)for i in input().split()];P=j[r][q];g=j[t][s];p=P.lower()
def w():
if g==o or not v(g):j[t][s]=P;j[r][q]=o;global u;u=not u
if not v(P):break
if p=="r"or p=="q":
for a,b,c,d in[(q,r,s,t),(r,q,t,s)]:
if a==c:
x=h(d-b)//(d-b)
for n in m(b+x,d,x):
if j[n if b else r][q if b else n]!=o:break
else:w()
if p=="b"or p=="q":
if h(q-s)==h(r-t):
for n in m(1, h(q-s)):
if j[r+(n if t>r else-n)][q+(n if s>q else-n)]!=o:break
else:w()
if p=="k"and h(q-s)<2 and h(r-t)<2 or(p=="n"and(h(q-s)==2 and h(r-t)==1 or h(r-t)==2 and h(q-s)==1)):w()
if p=="p":
f=t-r==(-1 if u else 1)
if(g!=o and not v(g)and h(q-s)==1 and f)or(g==o and q==s and f)or(g==o and q==s and t-r==(-2 if u else 2)and r==(6 if u else 1)):
w()
if t==(0 if u else 7):j[t][s]="q"if u else"Q"
```
To play, enter four space-delimited numbers, the first 2 being the coordinates of the piece you want to move, and the second 2 being where you want it to move to.
[Answer]
Sorry for the delay.
The program is called ChesSkelet. Currently it uses 352 bytes for both code and data. It's written in Z80 Assembly, and particularly for the ZX Xpectrum.
If you don't feel like compiling it and loading it in an emulator you can play online in ChesSkelet site (<http://chesskelet.x10host.com>).
The program is pretty simple, a big loop where:
- alternatively (1) white inputs its move or (2) black runs it's micro AI to move.
- board is updated in screen.
again, there is a huge guide describing the program and techniques in the website.
```
; ----------------------------------------------------------------------------- ; CHESSKELET /tseske'let/ ; Alex Garcia (reeagbo), Boria Labs 2018-2019 ; Thanks, @MstrBlinky and @johan_koelman, for your contribution ; Developed with ZXSpin, Notepad++ ; ----------------------------------------------------------------------------- ; Compilation with ZXSpin (all versions) and SpectNetIde (not all versions) ; Run with RANDOMIZE USR 30000 ; ----------------------------------------------------------------------------- ; debug mode: 0 = no, 1 = yes debmod equ 0 ; gramod: 0 = minimal interface, 1 = basic interface, 2 = full interface gramod equ 0 ; feamod: 0 = no features (if fails at legadd 'ret'), 1 = all features feamod equ 0 ; ROM memory addresses clescr equ 3503 laskey equ 23560 ; memory micro-pages (256B, typically H register) used for simple memory access auxsth equ $7D piearh equ $7E movlih equ $7F boasth equ $80 boaath equ $81 boaoph equ $82 canlih equ $83 org 30000 ; code is not directly portable ;------------------------------------------------------------------------------ ; Common code before turns ;------------------------------------------------------------------------------ ; legal moves generation (3B) ----------------------------------------- befmov call genlis ; candidate move list, used for both sides ; switch sides on every loop (6B+1B) ---------------------------------- whomov ld l, h ; (H)L: $7F7F = movlih + gamsta, ++ ld a, (hl) ; load state xor h ; (@johan_koelman) switch turn: bla=0, whi=1 ld (hl), a ; save state back in memory if feamod>0 jp z, blamov else jr z, blamov ; if 0, jump to black moves, jp maybe endif ; clear screen (3B) whimov call clescr ; ROM routine set screen mode ; print board ----------------------------------------------------------------- priboa ; A, B = 0 at this point ; initialization (4B) ld h, boasth ; H(L)= $80, L always 0, load board ++ ld d, piearh ; D(E): piece array pointer, E o/w later priloo ; print colored squares (8B) if gramod>0 ; opt: print colored squares ld a, 19 ; set bright ASCII code rst 16 ; print value ld a, c ; (@MstrBlinky) C is always $21 inc c ; change C parity and %00000001 ; keep Ab0, alternatively 0/1 rst 16 ; print value endif ; print piece (10B) ld a, (hl) ; load piece and %00100000 ; keep color, pih ld b, a ; Bb5: isolate piece color ld e, (hl) ; load piece res 5, e ; uncolor, pih ld a, (de) ; load piece character sub b ; capitalize (-32) only for white pieces rst 16 ; print piece ; next square, end of rank/board detection (15B+1B) inc l ; next square jp m, pricoo ; (@johan_koelman) end of 16x8 board, A=128? ld a, l ; (@MstrBlinky) and $08 ; 8 if end of rank, 0 other cases jr z, priski ; skip if not end of the rank add a, l ; ld l, a ; return result to L ld a, 13 ; A=
rst 16 ; print char
if gramod>0 ; opt: print colored squares, end of the rank
inc c ; change C parity
endif
priski jr priloo ; loop through all squares
; print coords (28B+6B)--------------------------------------------------------
pricoo ; (@MstrBlinky simplified it)
if gramod>0 ; opt: print board coords
ld bc, $0709 ; B: loop count, C: fixed rank/col
nextce ld a, $16 ; ASCII control code for AT
rst 16 ; print it
ld a, b ; set rank
rst 16 ; print it
ld a, c ; set column
rst 16 ; print it
ld a, '8' ; base rank
sub b ; decrease rank character (8..1)
rst 16 ; print rank value
ld a, $16 ; ASCII control code for AT
rst 16 ; print it
ld a, c ; set rank
rst 16 ; print it
ld a, b ; sets column
rst 16 ; print it
ld a, 'a' ; base column character
add a, b ; increase rank character (a..h)
rst 16 ; print rank value
dec b ; loop 8 times
jp p, nextce ;
endif
if gramod>0 ; opt: + "?" for input prompt
ld a, 13 ; A: set ASCII code
rst 16 ; prints it to go to the next line for input
ld a, '?' ; set "?" ASCII code
rst 16 ; print it
endif
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; WHITE MOVES
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; read chars from keyboard and stores them (16B(+4B+4B))-----------------------
; 4 times loop for coord input (3B)
ld b, 4 ; loop count
dec d ; D(E)= $7D =auxsth, E always 0 ++
; read key from keyboard loop (8B)
realoo ld hl, laskey ; LASTKEY system variable ++
xor a ; A=0
ld (hl), a ; reset LASTKEY, two birds with 1 stone
wailoo add a, (hl) ; load latest value of LASTKEY.
jr z, wailoo ; loop until a key is pressed.
; skip move/switch sides (4B)
if feamod>0 ; opt: special move, switch sides to play black
cp 's' ; if "s" pressed at any time
jp z, aftmov ; skip white's move, ### jr maybe
endif
; save pressed key and print it (5B)
inc de ; (@MstrBlinky) next char, E = 1 to 5
ld (de), a ; save char in string
rst 16 ; print it
djnz realoo ; loop for 4 input chars
; border reset (4B)
if gramod>1 ; opt: border reset after first white move
ld a, 7 ; set back to white
out (254), a ; set border back to white
endif
; translate coords to square (17B) --------------------------------------------
movchk ex de, hl ; (@MstrBlinky routine) DE=end of input string
movloo ld a, 56 ; rank calc = 8-(rank input-48) = 56-(HL)
sub (hl) ; A= 56 - (HL)
rla ; move it to high nibble (x16)
rla ;
rla ;
rla ;
dec hl ; (@MstrBlinky) run backwards through string
add a, (hl) ; rank + column (not 0-7 column)
sub 'a' ; make it a 0-7 column
ld c, b ; slide results through B and C
ld b, a ; at end of 2nd loop everything is in place
dec l ; (@MstrBlinky) beginning of input string?
jr nz, movloo ; if not, loop again
; search white move in legal move list (24B) ----------------------------------
if feamod>0 ; opt: validate white move
seamov ld hl, canlis ; canli pointer ++
ld a, (hl) ; number of candidates
;inc hl ; skip to first candidate (+2 bytes)
;inc hl ; removed v0.808, no move in those two bytes
sealoo ld d, (hl) ; origin candidate move
inc hl ; next byte
ld e, (hl) ; target candidate move
inc hl ; next byte, for next loop
ex de, hl ; candidate pair, DE: HL-canli pointer
or a ; reset carry
sbc hl, bc ; compare input move with cand. move (Z)
ex de, hl ; revert back, canli pointer
jr z, aftsid ; move match: jump out. ready to move
; B (origin sq), C (target sq) ready here
dec a ; count down
jr nz, sealoo ; loop until canli covered
jp whimov ; if not found, back to move input, jp maybe
else ; opt: skip validate white move
jr aftsid ; Outputs: B: origin square, C: target square
endif
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; BLACK MOVES
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
blamov
chomov ; preparations (7B)----------------------------------------------------
ld hl, canlis ; candidate list. No H reuse ++
ld b, (hl) ; number of candidates at position 0
ld c, l ; C=0, maximum valuation reset
inc hl ; skip 2 bytes to first candidate in list
inc hl ;
choloo ; loop through candidates (6B) ----------------------------------------
ld d, (hl) ; D: origin candidate square
inc hl ; next candidate byte
ld e, (hl) ; E: target candidate square
inc hl ; next candidate byte
push bc ; BC released
push hl ; HL is different from here
; pieces valuation ----------------------------------------------------
; pieces collection (8B)
evatap ld h, boasth ; board base ++
ld l, e ; target square
ld b, (hl) ; black piece value
ld l, d ; origin square
ld c, (hl) ; white piece value
res 5, c ; uncolor white piece; pih
; origin attacked square (7B)
evaato ld a, b ; target piece always counts
ld h, boaoph ; H(L): attacked board base, L: unchanged ++
bit 7, (hl) ; target square attacked?
jr z, evaatt ; not attacked, skip counting origin piece
if feamod=1 ; opt: rows 2 do not move even if attacked
ld a, d ; 0rrr0ccc, add origin square
and $70 ; filter ranks
cp $60 ; is rank 6?
ld a, b ; target piece always counts
jr z, evaexi ; skip this move
endif
; count origin piece (1B) if attacked, general case
evaatc add a, c ; A: 00pppppp, count white
; target attacked square (6B)
evaatt ld l, e ; H(L): point at target square
bit 7, (hl) ; target square attacked?
jr z, skiato ; if target not attacked, skip
sub c ; if target attacked, count white out
; compensate + prioritize piece valuation(6B)
skiato ld h, $20 ; prepare H for later rotation and use for A
add a, h ; A: 00pppppp, compensate=K+1, pih
rlca ; leave space for square weight
rlca ; A: pppppp00, piece addition is 5 bits
ld b, a ; B: piece addition value
evacol ld a, e ; A: 0rrr0ccc
; these two values below can be tuned for different opening schemes
if feamod>0
add a, 2 ; A: 0rrr0ccc
and 5 ; A: 00000ccc
else
inc a ; A: 0rrr0ccc
and 4 ; A: 00000cc0 (weight: 0,0,0,4,4,4,4,0)
endif
; ranks weight (ranks weight is 8..1, aiming for board's end)
evarnk add hl, hl ; HL: 00100000 0rrr0ccc (before)
add hl, hl ;
add hl, hl ; HL: 000000rr r0ccc000 (after)
sub h ; A: 00000cww (w=r+c)
add a, b ; total value: pieces + weight
; maximum value comparison (12B)
evaexi pop hl ; recover canli
pop bc ; recover previous maximum value
cp c ; compare with current maximum
jr c, chonoc ; if current eval (A) <= max eval (C), skip
ld c, a ; update best evaluation
pop af ; remove old maximum to avoid cascades in stack
; ### initial push to compensate?
push de ; push best candidates so far
chonoc dec b ; decrease loop counter 2 by 2.
djnz choloo ; loop through all candidates (canto)
pop bc ; recover saved values (B: origin, C: target)
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; AFTER SIDES
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; move piece (8B) -------------------------------------------------------------
; inputs here: B: origin square, C: target square
; write origin square and read piece in it (4B)
aftsid ld h, boasth ; point at board (canlih=$83 before) ++
ld l, b ; point at origin square
; castling, rook moves, v0.800 (26B)
; very innacurate as it may cause false moves
if feamod>0 ; opt: castling, rook move
casroo ld a, (hl) ; origin piece
add a, b ; + origin square
sub c ; - target square
caslon cp $38 ; $36(king) + $74(ori) - $72(tar)= $38, pih
jr nz, cassho ; no long castling
ld l, $70 ; long castling rook square (a1)
ld (hl), d ; erase rook (D=0 here)
ld l, $73 ; rook destination (d1)
ld (hl), $25 ; move rook, pih
cassho cp $34 ; $36(king) + $74(ori) - $76(tar)= $34, pih
jr nz, casend ; no short castling
ld l, $77 ; short castling rook square (h1)
ld (hl), d ; erase rook (D=0 here)
ld l, $75 ; rook destination (f1)
ld (hl), $25 ; move rook, pih
casend
endif
if feamod>0 ; opt: special move: prom, no under-prom (12B)
ld a, c ; A: 0rrr0ccc
and %01110000 ; A: 0rrr0000
add a, (hl) ; A: 0rrxpppp
cp $22 ; white pawn ($22) on rank 8 ($00), pih
ld l, b ; restore origin square
ld d, (hl) ; original piece
ld (hl), 0 ; write origin piece
jr nz, aftdes ; if not a pawn, skip
ld d, $27 ; make piece a queen, pih
else ; opt: write origin piece, no promotion (3B)
ld d, (hl) ; D: get origin piece
ld (hl), 0 ; write origin piece
endif
; write target square with origin piece (5B)
aftdes ld l, c ; (H)L: target square
; checkmate with exit (3B), board is not updated in screen
chkmat bit 4, (hl) ; captured piece is king ($16)?, pih
ret nz ; (@johan_koelman) return prompt at check mate
aftnok ld (hl), d ; write target square
call genlis ; update attacked matrix after move
aftmov
; reverse board (22B)----------------------------------------------------------
revboa ; push full board to stack (7B)
inc h ; H = $80 = boasth ++
ld l, h ; (H)L: end of board. trick: start from $8080
revlo1 dec l ; countdown squares
ld a, (hl) ; read piece
push af ; copy piece to to stack
jr nz, revlo1 ; loop down to beginning of the board
; collect board back ir reverse order + switch color (15B)
ld l, $78 ; (H)L: end of board again
revlo2 pop af ; collect piece from stack
or a ; is it an empty square?
jr z, revski ; if yes, skip
xor %00100000 ; otherwise, reverse color (b5), pih
revski dec l ; countdown squares
ld (hl), a ; piece back into board
jr nz, revlo2 ; loop until beginning of board
jp befmov ; back to white move, too far for jr
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; AUXILIARY ROUTINES
; -----------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; genlis: generates list of legal moves (92B + 9B) ----------------------------
; it was not possible to use it in two different places, only procedure in code
genlis
bacata ; backup attack board in reverse order, used in evaluation (13B)
ld l, $FF ; (H)L = $80FF (boaata-1), H always $80
ld de, boaopo + $78 ; DE: same thing, 1B passed end of board
bacloo inc hl ; HL: increase 16b counter to hop to next page
dec e ; E: decrease 8b counter to hit Z flag
ld a, (hl) ; load attack status
ld (hl), 0 ; clear attack status, no alternative!
ld (de), a ; backup attack status
jr nz, bacloo ; loop down to square $00
; exit values: DE=$8200, HL=$8177
; prepare environment (4B)
inc d ; D= $83= canlih
xor a ; reset
ld (de), a ; cantot= 0
ld b, l ; B= L = 77, SQUARE COUNT
; read piece from board (4B)
squloo ld h, boasth ; H: board base ++
ld l, b ; point at current loop square
ld a, (hl) ; read piece from board
; king castling, v0.800 (15B)
; only basic rule: no unmoved pieces or attacked squares check
if feamod>0
kincas ld l, a ; save A (can't use push AF, flags lost)
add a, b ; A: 0rrr0xxx + 000ppppp (uncolored white p.)
cp $AA ; king($36) at E1($74)= $AA, pih
ld a, l ; recover A
jr nz, kinend ; if no match, skip adding legal move
ld c, $72 ; E1-C1 move, rook's move missing
call legadd ; add king's move
ld c, $76 ; E1-G1 move, rook's move missing
call legadd ; add king's move and go on with king's moves
kinend
endif
; get move type and pointer to move list (6B)
squgon dec h ; H(L)= movlih, moves vector base ++
add a, a ; x4, each piece vector is 4B long
add a, a ;
ld l, a ; (H)L points at the move vector now
ld d, 2 ; 2 submoves per piece
subloo ; byte 1 - move type (5B)
ld a, (hl) ; move type loaded
or a ; =cp 0, 2nd move type not used case
; black/empty: move type=0 leads here
jr z, squexi ; ---v exit: square is done
ld e, a ; E: MOVE TYPE (B,C,D used here)
; pawn 2 squares forward - move type modified (8B)
if feamod>0 ; opt: special move, pawn 2 sq. forward
genpw2 add a, b ; piece square + move type
and %11111000 ; masked with relevant bits
cp $88 ; $28(str.pawn)+$60(rnk 6) ### univocal
jr nz, skppw2 ; if not, skip
inc e ; increase radius: 1 -> 2
skppw2
endif
; byte 2 - movlis delta (3B)
inc hl ; next piece sub-entry
push hl ; Save HL for 2nd loop
ld l, (hl) ; pointer to move delta
vecloo ; vector read (8B)
ld c, b ; TARGET SQUARE init
ld a, (hl) ; vector delta
or a ; =cp 0
jr z, vecexi ; ---v exit: vectors end with 0, next sq.
push hl ; save current delta
push de ; save move type + radius
; E: variable radius within loop
ld d, a ; D: store delta within loop
celloo ; prepare x88 check (7B)
ld a, d ; delta loaded
add a, c ; current target (sq. + delta)
ld c, a ; current target
and $88 ; 0x88, famous OOB trick
jr nz, vecnex ; ---v exit: OOB, next vector
; read target square (3B)
inc h ; H(L)= $80 = boasth ++
ld l, c ; point at target square
ld a, (hl) ; read target square content
; mark attacked ### str. pawn marked attacked
inc h ; H(L)= $81 = boaath ++
ld (hl), h ; mark attacked ($81)
dec h ; H(L)= $80 = boasth ++
dec h ; H(L)= $79= movlih ++
; target is white (4B)
bit 5, a ; is it white?, pih
jr nz, vecnex ; ---v exit: WHITE b4=1, next vector
; target not white (3B)
or a ; =cp 0, is it empty?, pih
jr z, taremp ; if not 0, it's black: legal, no go on
tarbla ; target is black (7B)
bit 5, e ; special move: pawn straight check
jr nz, vecnex ; ---v exit: no straight capture, next vector
ld e, a ; make radius=0 (=<8 in code, canonical: ld e, 0)
jr legadj ;
taremp ; target is empty (14B)
bit 4, e ; special move: pawn on capture check
jr nz, vecnex ; ---v exit: no diagonal without capture, next vector
dec e ; decrease radius
legadj
if feamod=0 ; opt: legadd for basic model
; add candidate (B: current square, C: target square) (9B)
push hl
ld hl, canlis ; HL: start of candidate list. No H reuse ++
inc (hl) ; +2 to candidate counter to move to next
inc (hl) ; first free position in list
ld l, (hl) ; point at free position
ld (hl), b ; 1) save origin square
inc hl ; move to next byte
ld (hl), c ; 2) save dest square
legend pop hl ; recover HL=pointer to vector list
else ; opt: legadd call for full model
call legadd
endif
bit 3, e ; if radius < 8 (Cb3=0), radius limit
jr nz, celloo ; ---^ cell loop
vecnex ; next vector preparation (5B)
pop de ; DE: recover move type + radius
pop hl ; HL: recover current vector
inc hl ; HL: next vector
jr vecloo ; ---^ vector loop
vecexi ; next square preparation (5B)
pop hl ; HL: recover pointer to sub-move list
inc hl ; HL: next byte, point at 2nd sub-move
dec d ; 2 sub-move iterations loop control
jr nz, subloo ; if not 2nd iteration, repeat loop
; end of loop (2B)
squexi djnz squloo ; ---^ squares loop
ret
; legadd: add legal move -------------------------------------------------------
if feamod>0 ; legadd for king castling
legadd ; (B: current square, C: target square)
push hl
ld hl, canlis ; HL: start of candidate list. No H reuse ++
inc (hl) ; +2 to candidate counter to move to next
inc (hl) ; first free position in list
ld l, (hl) ; point at free position
ld (hl), b ; 1) save origin square
inc hl ; move to next byte
ld (hl), c ; 2) save dest square
pop hl ; recover HL=pointer to vector list
;ret ; <===== not removed with feamod=0
endif
; -----------------------------------------------------------------------------
; DATA ------------------------------------------------------------------------
; -----------------------------------------------------------------------------
; Memory page: 7700h ----------------------------------------------------------
org $7700
auxstr ; input string stored here
; Memory page: 7E00h ----------------------------------------------------------
; used to convert values to pieces
org $7E00
if gramod=0 ; opt: space or dot depending on the size
piearr defb '.' ; $2B
else
piearr defb ' '
endif
org $7E02
defm "pnbr" ; change this array to any language, pih
org $7E07
defb 'q' ; change this array to any language, pih
org $7E16
defb 'k' ; change this array to any language, pih
; Memory page: 7F00h ----------------------------------------------------------
; sub-moves and vectors
org $7F00
; leave empty $00-$04-...-$24 for black pieces/empty square pointers
org $7F88 ; pawn: $22x4=$84
; piece, move type, vector list delta address (18B)
; move type / 0 / 0 / pawn straight / pawn diagonal / DDDD (real radius + 7)
movlis
pawgen defb $28, $E3 ; pawn straight
defb $18, $E7 ; pawn capture
org $7F8C
knigen defb $08, $EA ;
org $7F90
bisgen defb $0E, $E5 ; bishop
org $7F94
roogen defb $0E, $E0 ; rook
org $7F9C
quegen defb $0E, $E0 ; queen
defb $0E, $E5 ;
org $7FD8
kingen defb $08, $E0 ; king: $($16+$20)x4=$D8
defb $08, $E5 ;
org $7FE0 ; vectors start at: $7FE0 (arbitrary)
; (y, x) move delta pairs (16B)
veclis
strvec defb $FF, $01 ; +0, straight vectors
defb $10, $F0 ; +3, straight pawn, last half line
org $7FE5
diavec defb $0F, $11 ; +5, diagonal vectors
defb $EF, $F1 ; +7, diagonal pawn
org $7FEA
knivec defb $E1, $F2 ; +10, knight vectors
defb $12, $21 ; knight moves listed clockwise
defb $1F, $0E ;
defb $EE, $DF ;
; board status: 0000000 / turn (B=0, W=1)
org $7F7F
gamsta
; Memory page: 8000h ----------------------------------------------------------
; board squares format: 00cppppp
; pppp (value) : pawn=2, knight=3, bishop=4, rook=5, queen=7, king=$16
; c (color): white=1, black=0
; initial board setup
if debmod=1 ;opt: fill board for debugging
org $8000
boasta defb $00, $00, $00, $00, $00, $00, $00, $00 ; <--8
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $00, $02, $00, $00, $00 ; <--7
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $23, $00, $00, $00, $00 ; <--6
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $00, $00, $00, $00, $00 ; <--5
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $00, $00, $00, $00, $00 ; <--4
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $00, $00, $00, $00, $00 ; <--3
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $00, $00, $00, $00, $00 ; <--2
defb $00, $00, $00, $00, $00, $00, $00, $00
defb $00, $00, $00, $00, $00, $00, $00, $00 ; <--1
else ; opt: reduces board size for gameplay
org $8000
boasta defb $05, $03, $04, $07, $16, $04, $03, $05
org $8010
defb $02, $02, $02, $02, $02, $02, $02, $02
org $8060
defb $22, $22, $22, $22, $22, $22, $22, $22
org $8070
defb $25, $23, $24, $27, $36, $24, $23, $25
endif
; Memory page: 8100h ----------------------------------------------------------
org $8100
boaata ; attacked squares board
; Memory page: 8200h ----------------------------------------------------------
org $8200
boaopo ; reversed attacked squares board
; Memory page: 8300h ----------------------------------------------------------
; candidate move list at the very end of the program
org $8300
canlis equ $
````
```
[Answer]
## [><>](https://esolangs.org/wiki/Fish), 1467 bytes
Well, it doesn't quite break the 487-byte record…
```
> " :W"av
"RNBQKBNR"a/
"PPPPPPPP"a/
" "a/
" "a/
" "a/
" "a/
"pppppppp"a/
"rnbqkbnr"a/
l?!vo29.>
v?)b:i<~
\:8c*-:i:}4c*-:@g:o" "o{{oo" "o}i:o8c*-i:o4c*-
\{:"^")80g"^")-?X
\:"^")48**-
\&3[:}]$:@=3[:}]{:}=*?X&
\:"Q"=?v:"R"=?v
v > >&r:4[:}]$-r:4[:}]-{:?!v$:?!v~~&
["+-+10"]?$~137*.*731$~$?]"10+-+"[1)< >)1
\:"Q"=?v:"B"=?v
v > >&$:@$:@-r$:@$:@$-{-r4[r$:@$:@+r$:@$:@+{-}]{:?!v$:?!v~~&
)1["+-11"]?$137*. .*733]~~r?{"--11++"[1)< >
\>42b*p72b*p32b*p62b*p{{$:@$:@}}4[r
>$zz$zz$:@{:}=$:@5[:}]=*?v$:@$:@g" "-?X
.+9*a29$]~~<
\&$:@{:}-:*$:@5[:}]-:*+&
\:"N"=?v
X?-5&<v
\:"K"=?v
X?)3&<v
)-?vX >$:@$:@g:" "=?v"^")80g"^"
>049*.*942 ~<
\:"P"=?v
)?X:1=\&~$:@{:}-:*$:@5[:}]80g"^")?$-:2
X \?v2-?X?X$:@$:@80g"^"(2*1--g" "-?Xv
>~:?v?X >$:@$:@g" "-?Xv
@@?$~&049*.>1-?X$:@$:@g:" "=?X"^"(80g"^"(=?X >:880g"^")7*-=&"Q"
\>&80g"^"):&48**+@p" "@p0
>:8%1+$:8,:1%-1+$}$:@$:@g"Kk"&:&?$~=?v~~1+:88*=?X
v {{1030014103431434~{<
>l2=?v$:@$:@}}$@+2-a%@+2-a%$g"nN"&:&?$~=?X{{
\ >0010200121021222{{
>l2=?v$:@$:@}}$@+1-@+1-$g"kK"&:&?$~=?X{{
v >$:@1+$:@&:&2*1--g"pP"&:&?$~=?X$:@1-$:@&:&2*1--g"pP"&:&?$~=?X
\"10++r10-+r01++r01+-r11++b11+-b11-+b11--b"
>l2=?v48*4a*6+p44*4a*6+p74a*6+\
/} }@:$@:${{p+6*a46p+6*a4fp/
-?\$ zz:9%?!v$zz:9%?!v$:@$:@g:"y"&:&48**-=?X:"q"&:&48**-=?X" "
^~~< < <
v >~~"bW"&?$~80paaoo
```
Try it at [the fish playground](https://fishlanguage.com/playground)! (It makes use of a couple of bugs in that interpreter, so I can't promise it'll work anywhere else. You'll probably want to run it at maximum speed — it can take over a minute to do one move.)
When you run the code, it will print
```
rnbqkbnr
pppppppp
PPPPPPPP
RNBQKBNR
W:
```
Capital letters represent white, lowercase represent black. You can then give your move as input in the form `[a-h][1-8][a-h][1-8]`, e.g. `e2e4`, meaning "move the piece at `e2` to `e4`". The program will then print, for example,
```
W: P e2 e4
rnbqkbnr
pppppppp
P
PPPP PPP
RNBQKBNR
b:
```
The main form of memory in ><> is the stack; however, that's not very practical for storing a chess board. Instead, I used ><>'s self-modifying capability to store the chess board as part of the source code itself, accessing it with `g` and `p`.
The bulk of the code is to check whether your move is legal. There are several things to check here:
* Are you trying to move a piece that really exists, and is it yours (line 12, 0-indexed)?
* Are the start and end squares different (line 14)?
* Is the move in the right direction for the type of piece (orthogonal for rook and queen, lines 15–17; diagonal for bishop and queen, lines 18–20; L-shaped for knight, lines 24–26; 1 square for king, lines 27–28; or a pawn move, lines 31–35)?
* Are the squares between the start and end all empty (for rook, bishop, queen — lines 21–23)?
* Is the target square empty or occupied by an enemy (lines 29–30)?
* Are you in check after the move (lines 36–47)?
If any of those questions have the wrong answer, the program throws an error and halts; otherwise, it edits the chessboard in its source code, prints it again and waits for the next move.
For the king and knight moves, I borrowed Level River St's trick of checking the squared Euclidean distance: for a king, it's less than 3, and for a knight, it's exactly 5.
[Answer]
# C, 598 bytes
I shaved 2 characters from the best answer (598) by changing the `for(;1;)` to `for(;;)` and `t^=32` to `t^=w`
I win! :)
```
n=8,t=65,s,f,x,y,p,e,u=10,w=32,z=95;char a[95],b[95]="RNBKQBNR";v(){p=a[s]&z;y=f/u-s/u;x=f-s-y*u;e=x*x+y*y;n=s%u/8|f%u/8|a[s]/w-t/w|a[f]/w==t/w|!(p==75&e<3|p>80&x*y==0|p%5==1&x*x==y*y|p==78&e==5|p==80&x*(z-t)>0&(a[f]-w?e==2:e==1|e==4&s%5==1));if(!n&&p-78)for(e=(f-s)/abs(x*x>y*y?x:y),x=s;(x+=e)-f;)n|=a[x]-w;}main(){for(a[93]=40;n--;a[92]=47)sprintf(a,"%s%cP p%c \n",a,b[n],b[n]+w);for(;;){puts(a);for(n=1;n;){putchar(t);scanf("%d%d",&s,&f);v();memcpy(b,a,z);if(!n){a[f]=p-80|f%u%7?a[s]:t+16;a[s]=w;a[f]&z^75||(a[z-t/w]=f);f=a[z-t/w];t^=w;for(n=1,s=80;n&&s--;)v();if(n=!n)memcpy(a,b,z),t^=w;}}}}
```
Output
```
RP pr
NP pn
BP pb
QP pq
KP pk
BP pb
NP pn
RP pr
A31 32
RP pr
NP pn
BP pb
Q P pq
KP pk
BP pb
NP pn
RP pr
a36 35
RP pr
NP pn
BP pb
Q P p q
KP pk
BP pb
NP pn
RP pr
A
```
] |
[Question]
[
We consider two integers to be *similar* if, when written in decimal, have the same length, and if we compare characters in any two positions for both decimal strings, the comparison results (less, equal or greater) must be the same in both strings.
Formally, for two number that can be written as decimal strings \$a\_1a\_2\cdots a\_n\$, \$b\_1b\_2\cdots b\_m\$, they're *similar* if and only if \$n=m\$ and \$a\_i<a\_j\ \leftrightarrow b\_i<b\_j\$ (\$\leftrightarrow\$ means if and only if) for all \$ i,j \in [1,n]\$.
For example, 2131 and 8090 are *similar*. 1234 and 1111, 1234 and 4321 are **not** *similar*.
# The challenge
For a given positive integer, find a different non-negative integer *similar* to it. You can assume at least one such integer exists.
* Your implementation shouldn't be too inefficient. It must be at least able to pass the samples in around one hour on an average computer. (If it doesn't end in a few seconds, consider providing a screenshot running it)
* Your code can take the input and output as integers, strings or lists of digits. Standard loopholes are forbidden.
Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins!
# Examples
It's (quite) possible to have different outputs on these inputs as long as inputs and outputs are different and *similar*.
```
1 - 0
3 - 9
9 - 1
19 - 23
191 - 121
1111 - 2222 (0 is not considered valid)
2020 - 9393
2842 - 1321
97892 - 31230
113582 - 113452
444615491 - 666807690
87654321000 - 98765432111
98765432111 - 87654321000
526704219279 - 536714329379
99887766553210 - 88776655443210
```
Sample inputs as a list:
```
1,3,9,19,191,1111,2020,2842,97892,113582,444615491,87654321000,98765432111,526704219279,99887766553210
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~58~~ 52 bytes
```
lambda n:[9-(9in n)-sum(x>d for x in{*n})for d in n]
```
[Try it online!](https://tio.run/##ZVDJTsMwEL37K4ZycYCixM3mivTID8Ct9OA2DrjE08hxpKKq3148CYsQkaX4LTNvPN2Hfzvg4tJUL5dW2W2tAJdrOefSIGA07wfLj6samoODIxg83eA5IlADGTaXa9i96d07mAYQFNZgQTkNvbGmVQ62g4faNI126AEHu9VuyWrdTFUc72y0ZDBWV5WF0LjVyDG6qugfRHDaDw7hUbW9npxWHbm9xWglyW8Njugh/uelOQ3N6RS@aj51HvMmbf9Xs9/amMJxbTYPuN5vwjDcErAE/qV8wWc3aMaM7Q7OQ//RM0poDWoKCfi@97VBCsAn76AatUA60/GI2ED5oWs1N@j5Lhon3I1bDn5y2B9HQ@8gZuo0m93vD7QG1fHQMOyUxM5Ro2Z2ovozzFdwsuNtffpd/nkziy4JWzDJEjoJS8LHRCxiJspUMFmUUgRykZWCpWmaJ1kaXGWRZ@lCJHEcM/kNQmEm8iJORSJFIZmUZVkUeZ5l5PwE "Python 3 – Try It Online")
**Input**: The number `n`, as a list of digits.
**Output**: A similar number, as a list of digits.
*-6 bytes thanks to @xnor!*
**How**:
Reverses the list of unique digits, then maps them to `9,8,7,...` or `8,7,6,...` depending on whether `n` contains the digit 9 or not.
For example:
```
| n = 1827 | n = 7899
Reverse unique | 8721 | 987
Maps to | 9876 | 876
Results | m = 6978 | m = 6788
```
### Old solution
### [Python 3](https://docs.python.org/3/), 80 bytes
```
f=lambda n,i=9:(i in n)^(i-1in n)and[[d,d^i^~-i][i-2<d<=i]for d in n]or f(n,i-1)
```
[Try it online!](https://tio.run/##PYzBboMwEETv@xUWJ1uCyDY2tqPQH0Eg0bhRtgoGAZdc@ut0jdRaPuzMvJnlvT/nVB/Ho32N02ccWSqxDVeODBNLYuBYqfMaU@y6WMYBh58K@w4rfYu3FvvHvLJ40j1dD04DlRIHTsu87mx7b5CJF6avDJG@bHvEdAXGNtaeATkrLlyQlcjqMO38Llju3c9ST8mYMk774l8UxeV7xsSnceE0UZIrcrqseWEri@qjOM1DQQ0BVP4KFD3QUkvQ3mgIzgdNZm29BmNMo6whyrvGmlorKSWEP0FFqxsnjVZBuwAheO9c01ibyV8 "Python 3 – Try It Online")
**Input**: The number `n`, as a list of digits.
**Output**: A similar number, as a list of digits.
*-1 byte thanks to @KevinCruijssen!*
**How**
The solution tries to find a pair of consecutive digits \$(i-1,i)\$ such that one digit appears in \$n\$, and the other doesn't. It then replaces all occurrences of one digit with the other.
The pair of digits are searched from \$(8,9)\$ downward, in order to discourage replacing 1 with 0.
[Answer]
# JavaScript (ES6), 55 bytes
I/O format: list of digits.
```
a=>a.map(d=>d-=-!/9/.test(a)|!a.includes(d-=d>(a<'2')))
```
[Try it online!](https://tio.run/##NU/LbsMgELz3K5wTIMUEME@1@NZrfyDKgRqcOnJMZJye@u8uUHWl2dfM7mpv7tulYZ0eW7tEH/bR7s72Dt/dA3rb@9a2h5M54S2kDTr0c3B4Wob56UOCmfQ9dG@AAYTQ/noGFBxBl2Ey6J8rLZotB0YYKUFzVjRKG1bJTuiScM4lFbxOaCUF7xglpEyY/7KuEUwqwhk1TJUTxmitlJRCFD24vOAxru9u@IKpsX0zxCXFOeA5XmE6NiM8Y4zTpT748bx/hhUhfIvTAkH94hc "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array of digits
a.map(d => // for each digit d in a[]:
d -= // update d:
-!/9/.test(a) // if a[] doesn't include any 9, increment d
| // (this does d = d - (-1 | whatever) = d - (-1) = d + 1)
// otherwise, decrement d if:
!a.includes( // - a[] does not include d - 1
d -= d > // - and d is greater than 0 if the leading digit is not 1,
(a < '2') // or greater than 1 otherwise (so that it doesn't result
) // in a leading zero)
) // end of map()
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ ~~16~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
êRāTα:DIQ-
```
-6 bytes after being inspired by [*@SurculoseSputum* partially incorrect approach](https://codegolf.stackexchange.com/revisions/203194/2).
I/O as a list of digits.
[Try it online](https://tio.run/##yy9OTMpM/f//8KqgI40h5zZauXgG6v7/H22pY6FjrmOmY6pjomOsY6RjoGMQCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWwy6GV/w@vCjrSGHJuo5XLoXWBuv@9dP5HG@oY61jqGIKQoY4hEOgYGRgZ6BhZmBjpWJpbWBoBBY1NLYx0TExMzAxNTYCqLMzNTE2MjQwNDAx0LKEcJCbIDFMjM3MDEyNDSyNzSx1LSwsLc3MzM1NTkKZYAA).
**Explanation:**
```
ê # Sort and uniquify the digits in the (implicit) input-list
# i.e. [2,8,4,2] → [2,4,8]
R # And reverse it
# → [8,4,2]
ā # Push a list in the range [1, length] (without popping)
# → [1,2,3]
Tα # Take the absolute difference with 10
# → [9,8,7]
: # Replace in the (implicit) input-list the sorted unique digits with [9,8,...]
# → [7,9,8,7]
D # Duplicate it
IQ # Check whether it's equal to the input-list (1 if truthy; 0 if falsey)
# → 0 (falsey)
- # Subtract that from each digit
# → [7,9,8,7]
# (after which the resulting list is output implicitly)
```
---
**Original ~~20~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
∞IK.Δ‚εSæ2ùÆ.±}Ë
```
-4 bytes thanks to *@petStorm*.
I/O as regular integers.
[Try it online](https://tio.run/##ASkA1v9vc2FiaWX//@KInklLLs6U4oCazrVTw6Yyw7nDhi7CsX3Di///Mjg0Mg) or [verify the smaller test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXo/0cd8yq99c5NiXjUMOvc1uDDy4wO7zzcpndoY@3h7v@1Ov@jDXWMdSx1DEHIUMcQCHSMDIwMdIwsTIx0LM0tLI1iAQ) (larger ones time out).
**Explanation:**
```
∞ # Push an infinite list of positive integers: [1,2,3,...]
IK # Remove the input-integer itself from the list
.Δ # Then find the first value in this list which is truthy for:
‚ # Pair the current value with the (implicit) input-integer
# i.e. input=2842 and y=1321 → [2842,1321]
ε # Map both to:
S # Convert them to a list of digits
# → [[2,8,4,2],[1,3,2,1]]
æ # Take the powerset of this list of digits
2ù # Only leave the pairs
# → [[[2,8],[2,4],[2,2],[8,4],[8,2],[4,2]],
# [[1,3],[1,2],[1,1],[3,2],[3,1],[2,1]]]
Æ # Reduce each inner pair by subtracting
# → [[-6,-2,0,4,6,2],
# [-2,-1,0,1,2,1]]
.± # Take the signum of each (-1 if a<0; 0 if a==0; 1 if a>0)
# → [[-1,-1,0,1,1,1],
# [-1,-1,0,1,1,1]]
}Ë # After the inner map: check if the pair of lists are the same
# → 1 (truthy)
# (after we've found our value, it is output implicitly as result)
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 27 bytes
```
{((9-9=|/x)-!#?x)(?x@>x)?x}
```
[Try it online!](https://tio.run/##TUxBDsIwDPtKEJNoJcqaNG0TEJTX7LID10rb3l5aiQOWD7YTe3WftbXlvhmjTp/7XK07nUu1ptT3q9pSj7aZ@rhd52kxU7@y2OOCEEABBxGwA8iTBxIm0CxKPQxRCJg5YeT@JTlFDoTee9Cf@ZNjI1LKngmVsoKqSM4pxThK7Qs "K (oK) – Try It Online")
Takes the input as a list ot digits.
Inspired by [Kevin Cruijssen's 05AB1E](https://codegolf.stackexchange.com/a/203193/75681) and [Surculose Sputum's Python](https://codegolf.stackexchange.com/a/203194/75681) solutions - please don't forget to upvote them!
[Answer]
# [W](https://github.com/A-ee/w), 14 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
Port of the 10-byte 05AB1E answer.
```
♥f<~|J▄5sO#o═╥
```
Uncompressed:
```
oFU_:kkT-zrZ:a=-
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~24~~ 19 bytes
```
⭆θ⁻⁺⁸¬№θ9LΦγ∧›λι№θλ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaBTqKPhm5pUWawTkAAkLHQW//BIN5/xSoCKglJKlkqampo6CT2peekmGhltmTklqkUa6joJjXoqGe1FqIoibo6OQCVQD15SjCQHW//8bWhr@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Now based on @SurculoseSputum's newer answer. Explanation:
```
θ Input as a string
⭆ Map over characters and join
θ Input as a string
№ 9 Count `9`s
¬ Logical Not (i.e. does not contain `9`)
⁺⁸ Add `8`
Φγ Filter on printable ASCII
λ ASCII character
› Greater than
ι Input character
∧ Logical And
λ ASCII character
№θ Occurs in input
L Length of matches
⁻ Subtract from the `8` or `9`
Implicitly print
```
Previous 24-byte version based on @SurculoseSputum's older answer:
```
≔⌈Φχ¬№θIιη⪫⪪θ⎇⁼η⁹⌈θI⊕ηIη
```
[Try it online!](https://tio.run/##NYzNCgIhFIX3PYXLKxhku5hVDAUFRVAvICZ5Qa/5F/X0NiN1VodzPj5tVdJBuda2OeOD4KTe6KuHPbpiEsiVYOdQYAyVCkTBRpULIJ8jmOXD4pJweo4BCa5Phx26mUQqfWAXq3IZrGCbif6rI/9pDqST8YaKuYPtwj7PdWhNrmVbvtwX "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌈Φχ¬№θIιη
```
Find the highest digit not present in the input number.
```
⎇⁼η⁹⌈θI⊕η
```
If that digit is less than 9 then increment it (which will give a digit in the input number) otherwise take the highest digit of the input number.
```
⪫⪪θ...Iη
```
Replace the digit from the input number with the digit not in the input number.
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 143 bytes
Port of Surculose Sputum's Python answer.
```
u([])->[];u([H|T])->[H]++u([A||A<-T,A/=H]).
i(X)->case X of true->1;_->0end.
f(A)->[9-i(lists:member(9,A))-lists:sum([i(X>D)||X<-u(A)])||D<-A].
```
[Try it online!](https://tio.run/##bY7NCoMwEITvPkWOCWattb3400DAgw/gQZBQbBtLwJ@SKL3k3e3aXruwMLMfM6y2Qzc9Qbu7Na9lC7aVtoqBaFWOqvL111QqDNFK72UBNZeHS6VYFBjaIL13TpOGzD1Z7KpBHPMriFhPjyjoqdzjKRg6GLe4bNTjTVuacskY/E5uHWmLTaJk3jcFrJhRKMsCpIq2sTPT/hIBERAcM2dvaxZNe9omPOa4ijH@h534mSfIou0D "Erlang (escript) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 79 bytes
Port of @SurculoseSputum answer
```
#/.MapThread[Rule,{a=Union@#,Range[0,9][[-Tr[1^a]-(d=Boole[Max@a>8]);;-1-d]]}]&
```
[Try it online!](https://tio.run/##NY5tS8MwHMS/SllhKPzrkjSPjI4iIvhiIGO@ChGCDVlgTSVGEMY@e8xAj3tzx@/gZptPbrY5fNjih9JuHvb283hKzk768H12cLHDWwxLHFs42OidRqCM1t0xafxuTXc3DY/LcnZ6b39Gu5PmfrvtcDcZczXr8ppCzI1uYdV0u2YFz2mZn4IP@Wv0@iVm5136y60x6814wdCDAnwzBlwFBBEERFICSkhFatkzSYBSyjGjlZKCM9oTjFD99h/qkBEuECVYEaFAKSmF4JyxG3kt5Rc "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 29 24 16 bytes
```
9-9&e.+\:~@~.i.]
```
[Try it online!](https://tio.run/##jVJNT8MwDL3nV1gc9gUNzbquH2LSNCROiAMXLiC0dWlWtLVo7U5I/evFcemaAELUiuo82y/Oi9@aCz5UsIhhCFfgQozL4XD7eH/XRE40kPzyOa6XNc/4SzNm5fogX8tMLTg48WB0c12PGXtYccgL2Mv1NssVEgBkaQpJcXgvgb6sgmS3zpXcwkSnCpelSDFy69j9UGPKmcCoYweEcOvwpRNrX28EOFgGkiPQHvkkoZJlBZui2sE2O8qkyoq8ZEwmuwJS7KPzorMnzt4UPAOdWpHW@mqPVp/tWfke1XvGeYJyZuAbLHOyELMC/EdWdyFhPla0zMJg/x5zybqoj@gcM8RXXPcZGPcNqT6gs31i6XnYT1G8XyWzfWFdU1jCubT6fYjHmUIGiEQG0grlI9pjM7I5RnS70b@l@FtG/RRaKJc6EtSFKVRE9bZYvVB63FanzWYvj1CelMKxw1Fj5vzge/cqah0Eaz4B "J – Try It Online")
*-8 thanks to FrownyFrog!*
*Thanks to Bubbler for catching some bugs. All are now fixed.*
Inspired by Surculose's [sweet answer](https://codegolf.stackexchange.com/a/203194/15469), be sure to upvote him.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~77~~ 74 bytes
```
tee t|tr "`rs -T|sort -ur|xargs`" "`grep -q 9 t;seq $[8+$?] -1 0|xargs`"<t
```
[Try the test suite online!](https://tio.run/##XU9Na8MwDL3rVzxMbiVbPposoVl32k6FXXYbg3qJSQZt09ou6yH/3ZPCwmAIWdLTe3r4U7shtNpje7Zjb/URTaOeX19U8MbAT95C7a1D/Da50XrEVzvdtO3dXvGit@aM@IIafuPMBdF7tYqePhCnSBZa4wPfI2qH49jhurrh14noe/g6GFijO@wI6EZ@ANMOI@ITVLTD4xbqD2Rgwt39ohfFyYSUcqopxZxI@Z2DMiTg5FphjYxqPHBXcyf7HAVPGa0hUTJScBV9xbxynnLW808kWP0fF4@Cu5LxRBwg/hlPNbOFLwrRiKpYrlH4AQ "Bash – Try It Online")
Input is a list of integers on stdin (space-separated digits).
Output is in the same format, on stdout.
This is an implementation of [Surculose Sputum's nice method](https://codegolf.stackexchange.com/a/203194/59825): List the unique digits that appear in the input, sort them in decreasing order, and then replace them in the original input either with \$8, 7, 6, \dots\$ (if \$9\$ appears in the input) or with \$9, 8, 7, \dots\$ (if \$9\$ does not appear in the input).
[Answer]
This is a port of [@Surculose Sputum's solution](https://codegolf.stackexchange.com/a/203194/78264) in APL2.
```
U←((A⍳A)=⍳⍴A)/A←,A
((9∊A)⌽⌽⍳10)[U[⍒U]⍳A]
```
It presupposes that `A` is a vector of numbers and that `⎕IO=0`
] |
[Question]
[
In CSS, colours can be specified by a "hex triplet" - a three byte (six digit) hexadecimal number where each byte represents the red, green, or blue components of the colour. For instance, `#FF0000` is completely red, and is equivalent to `rgb(255, 0, 0)`.
Colours can also be represented by the shorthand notation which uses three hexadecimal digits. The shorthand expands to the six digit form by duplicating each digit. For instance, `#ABC` becomes `#AABBCC`.
Since there are fewer digits in the hex shorthand, fewer colours can be represented.
## The challenge
Write a program or function that takes a six digit hexadecimal colour code and outputs the closest three-digit colour code.
Here's an example:
>
> * Input hex code: #28a086
> * Red component
> + 0x28 = 40 (decimal)
> + 0x22 = 34
> + 0x33 = 51
> + 0x22 is closer, so the first digit of the shortened colour code is 2
> * Green component
> + 0xa0 = 160
> + 0x99 = 153
> + 0xaa = 170
> + 0x99 is closer, so the second digit is 9
> * Blue component
> + 0x86 = 134
> + 0x77 = 119
> + 0x88 = 136
> + 0x88 is closer, so the third digit is 8
> * The shortened colour code is #298 (which expands to #229988)
>
>
>
Your program or function must accept as input a six digit hexadecimal colour code prepended with `#` and output a three digit colour code prepended with `#`.
## Examples
* #FF0000 → #F00
* #00FF00 → #0F0
* #D913C4 → #D1C
* #C0DD39 → #BD3
* #28A086 → #298
* #C0CF6F → #BC7
## Scoring
This is a code-golf challenge, so shortest answer in your language wins! Standard rules apply.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ćs2ôH8+17÷hJ«
```
**[Try it online!](https://tio.run/##yy9OTMpM/f//SHux0eEtHhbahuaHt2d4HVr9/7@ys4Gzm5kbAA "05AB1E – Try It Online")**
### How?
```
ćs2ôH8+17÷hJ« | string, S e.g. stack: "#B23F08"
ć | decapitate "B23F08", "#"
s | swap "#", "B23F08"
2 | two "#", "B23F08", 2
ô | chuncks "#", ["B2", "3F", "08"]
H | from hexadecimal "#", [178, 63, 8]
8 | eight "#", [178, 63, 8], 8
+ | add "#", [186, 71, 16]
17 | seventeen "#", [186, 71, 16], 17
÷ | integer divide "#", [10, 4, 0]
h | to hexadecimal "#", ["A", "4", "0"]
J | join "#", "A40"
« | concatenate "#A40"
| print top of stack
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 16 bytes
```
r"%w"²_n16_r17Ãg
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIldyKyX24xNl9yMTfDZw&input=IiNmZjAwMDAi) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIldyKyX24xNl9yMTfDZw&input=WwoiI2ZmMDAwMCIKIiMwMGZmMDAiCiIjZDkxM2M0IgoiI2MwZGQzOSIKIiMyOGEwODYiCiIjYzBjZjZmIgpdLW1S)
```
r"%w"²_n16_r17Ãg :Implicit input of string
r :Replace
"%w" :RegEx /\w/g
² :Duplicate, giving /\w\w/g
_ :Pass each match through a function
n16 : Convert to decimal
_ : Pass through the following function, and convert back to hex
r17 : Round to the nearest multiple of 17
à : End function
g : Get first character
```
[Answer]
# 8088 Assembly, IBM PC DOS, ~~59~~ 58 bytes
**Unassembled listing:**
```
BE 0082 MOV SI, 82H ; SI to begining of input string
AC LODSB ; load first '#' char into AL
B4 0E MOV AH, 0EH ; BIOS display char function
CD 10 INT 10H ; call BIOS
B3 11 MOV BL, 17 ; set up for divide by 17
B9 0304 MOV CX, 0304H ; hex byte loop counter (CH=3), shift counter (CL=4)
LOOP_BYTE:
AD LODSW ; load next two ASCII hex chars into AX
B7 02 MOV BH, 2 ; hex chars loop counter
LOOP_ALPHA:
2C 30 SUB AL, '0' ; convert from ASCII
3C 0A CMP AL, 10 ; is digit > 10 (A-F)?
7C 02 JL NOT_ALPHA ; if not, jump to next char
2C 07 SUB AL, 7 ; ASCII adjust alpha char to binary
NOT_ALPHA:
86 E0 XCHG AH, AL ; swap first and second chars
FE CF DEC BH ; decrement loop counter
75 F2 JNZ LOOP_ALPHA ; loop to next hex char
D2 E0 SHL AL, CL ; shift low nibble to high nibble
02 C4 ADD AL, AH ; add first and second nibbles
32 E4 XOR AH, AH ; clear AH for add/division
05 0008 ADD AX, 8 ; add 0.5 (8/16) to round (with overflow)
F6 F3 DIV BL ; divide by 17
3C 0A CMP AL, 10 ; is digit > 10?
7C 02 JL DISP_CHAR ; if not, jump to display digit
04 07 ADD AL, 7 ; binary adjust alpha char to ASCII
DISP_CHAR:
04 30 ADD AL, '0' ; convert to ASCII
B4 0E MOV AH, 0EH ; BIOS display char function
CD 10 INT 10H ; call BIOS
FE CD DEC CH ; decrement loop counter
75 D4 JNZ LOOP_BYTE ; loop to next hex byte
C3 RET ; return to DOS
```
Standalone PC DOS executable. Input is via command line, output is to console.
Most of the code length is handling the conversion of required hex string I/O into bytes, since DOS/x86 machine code has no built-ins for that.
**I/O:**
[](https://i.stack.imgur.com/XWrel.png)
Download and test [HEXCLR.COM](https://stage.stonedrop.com/ppcg/HEXCLR.COM), or `xxd` hexdump:
```
0000000: be82 00ac b40e cd10 b311 b904 03ad b702 ................
0000010: 2c30 3c0a 7c02 2c07 86e0 fecf 75f2 d2e0 ,0<.|.,.....u...
0000020: 02c4 32e4 0508 00f6 f33c 0a7c 0204 0704 ..2......<.|....
0000030: 30b4 0ecd 10fe cd75 d4c3 0......u..
```
[Answer]
# JavaScript (ES6), 55 bytes
```
s=>s.replace(/\w./g,x=>(('0x'+x)/17+.5|0).toString(16))
```
[Try it online!](https://tio.run/##bcy9DoIwGIXh3asgYWgbtf0A5WeARNv0BlxdCBaCIZRQogzee8WhDuLZTvLkvZeP0lRjO0z7Xt@UrXNr8sLQUQ1dWSnMrk/Kmt2cFxgjmNF2JixItvT4AkInfZnGtm9wEBNiK90b3Sna6QbXGPlSwjJEiMeY5y9n8ysAPsYJkGshsiDiBydEwFeCgxBR5sRZRCsRpidIYyfCLP3T4DKW3wZP7Bs "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 88 bytes
```
(\w)(.)
$1,$2;
[A-F]
1$&
T`L`d
\d+
$*
+`1,
,16$*
,
8$*
(1{17})*1*;
$#1;
T`d`L`1\d
B\B|;
```
[Try it online!](https://tio.run/##FYuxDsIgGIT3ew2IKRQNf2uQhqmFMDm6iQkmOLg4GBMH9dmR3nD5vuTueXvdH9dau/QW3U6Ak@KDw3nexguIb3DKx1yQSg8u0WdSUGQaKtjWHX3o8BOSpANn5Nq8tAOlgiUtX4daWYy6BUzrlcDCRKPfg3kdwjiBDXbW1qzuo4l/ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(\w)(.)
$1,$2;
```
Pair up the hex digits.
```
[A-F]
1$&
T`L`d
```
Convert each digit separately to decimal.
```
\d+
$*
```
Convert each decimal digit to unary.
```
+`1,
,16$*
```
Finish the hexadecimal conversion of the pair of digits.
```
,
8$*
(1{17})*1*;
$#1;
```
Add 8 and divide by 17.
```
T`d`L`1\d
B\B|;
```
Convert back to hexadecimal.
[Answer]
# [PHP](https://php.net/), ~~75~~ 67 bytes
```
#<?php for($m=3;$m;)echo dechex((hexdec($argn)>>--$m*8&255)/17+.5);
```
[Try it online!](https://tio.run/##K8go@P9f2ca@IKNAIS2/SEMl19bYWiXXWjM1OSNfIQVIplZoaAAJIFNDJbEoPU/Tzk5XVyVXy0LNyNRUU9/QXFvPVNMaaIiRhaOBhZnCv/yCksz8vOL/um4A "PHP – Try It Online") or [verify all test cases](https://tio.run/##Pc/NDoIwDADg@56igUU3/xggAplAdAsvoR4IglwQIh5MjM@OG4g7NOuXtmnbqu33SVu1COFn0T07iOCEYG6mKVNvvgKwLDBVopExzROydEAZ2q7YTihtoVEwKd1wwqN0NTrBgQW7CZ0w0JgzUe7Kf6Xw0YUjVDaPIssrAr@tsg5w9rjdgcIbARR51YywAgOiGAyOkrg3h1NANRNcRy7HNadD6VXF4kWICupLhk4ax@s1rhfBzPE8atn@cuNR3o@zjfNdjfz0Xw).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~72~~ ~~70~~ 68 bytes
```
lambda x:'#'+''.join(f"{(int(x[i:i+2],16)+8)//17:X}"for i in(1,3,5))
```
[Try it online!](https://tio.run/##Rc/RboMgFAbge5/ixF4AkbWom1USLzaJz7Ck64WzsrG0aipLXAzP7kBnxg0nHz/kp//Rn10bzzJ/m6/V7f1SwcjRDgUI7b861WLpT1i1Go8nxVUQnWmYkCAlh0N45K/Gl90dFNhcSGP6RMhcV0MzQA6TB/6uLJldPnej3akzxpwuxso/E1kYF4@LibBYrWBCxNliLyJeLUqfWZosFmXplitkItdccXRmPM/Vck0oNGPf1Lq52I6LDHulm9uACfcAqlp/V1fbVmJ3Riz1d/db@2v0EKDTdjvP1@jZwOSShv8/PG2TofDRaZjWqPHJ/As "Python 3 – Try It Online")
This is a port of [Grzegorz Oledzkis](https://codegolf.stackexchange.com/users/1104/grzegorz-oledzki) original [answer](https://codegolf.stackexchange.com/a/187469/86751), which I helped him golfing down.
Two features of Python 3 help us save bytes:
* Floating point division by default
* Format string literals
*-2 bytes thanx to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 bytes
```
ḊØHiⱮs2ḅ⁴+8:17ịØHṭḢ
```
[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4biKw5hIaeKxrnMy4biF4oG0Kzg6MTfhu4vDmEjhua3huKL///8iI0MwQ0Y2RiI "Jelly – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 81 bytes
```
x=>"".Aggregate("#",(a,b)=>a+$"{(Convert.ToInt32(x[b]+""+x[b+1],16)+8)/17:X}")
```
[Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrgOh7NJs/1fY2ikxMrMq6TmmpxelpieWpGooKSvpaCTqJGna2iVqqyhVazjn55WlFpXoheR75pUYG2lURCfFaispaQNpbcNYHUMzTW0LTX1Dc6uIWiXN/9Zc4UWZJak@mXmpGmlAw9LSDIBASVMTXSLJyDjNwAKLhJFFooGFGUjiPwA "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~63~~ 48 bytes
```
"#"<>Round[15List@@RGBColor@#]~IntegerString~16&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19JWcnGLii/NC8l2tDUJ7O4xMEhyN3JOT8nv8hBObbOM68kNT21KLikKDMvvc7QTO1/AJBV4qCVpqDvoFCtpOzmZgAESjoKSsoGBiAOmOliaWjsbAJmOhu4uBhbgplGFo4GFmZQUWc3Mzel2v8A "Wolfram Language (Mathematica) – Try It Online")
-15 bytes thanks to [attinat](https://codegolf.stackexchange.com/users/81203/attinat)! Replacing `StringJoin` with `<>` and compressing the syntax.
1. `RGBColor@#` converts the input string to a color of the form `RGBColor[r, g, b]` with three floating-point arguments in the range 0..1.
2. `Round[15 List @@ %]` multiplies the list of three arguments by 15 and rounds them to the nearest integer. We now have a list of three integer values corresponding to the three desired hexadecimal digits.
3. `%~IntegerString~16` converts this list of three integers to a list of three hexadecimal strings of one character each.
4. `"#"<>%` prepends a `#` character and joins all these characters together.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~19~~ 12 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╞2/¢8+F/¢'#▌
```
Output as character-list. If this is not allowed, an additional trailing `y` has to be added to join the character-list to a string.
-7 bytes thanks to *@maxb*, since I looked past a builtin (`2ô_2<\1>]` to `2/`).
[Try it online.](https://tio.run/##y00syUjPz0n7///R1HlG@ocWWWi7AUl15UfTev7/V1d2czMAAnUudWUDAxAbxHKxNDR2NgGxnA1cXIwtQSwjC0cDCzOImLObmZs6AA)
**Explanation:**
```
╞ # Remove the first character from the (implicit) input-string
2/ # Split the string into parts of size 2
¢ # Convert each part from hexadecimal to integer
8+ # Add 8 to each integer
F/ # Integer-divide each integer by 17
¢ # Then convert back from integer to hexadecimal
'#▌ '# Prepend '#' in front of the list
# (which is output implicitly as result)
```
[Answer]
## Ruby (2.5.3), 45, 44, 42 bytes
```
->a{a.gsub(/\w./){|b|"%X"%((8+b.hex)/17)}}
```
EDIT: saved one byte because we don't need a character group for the second character in the regex (inspired by Neil's answer)
EDIT 2: saved 2 bytes because the dash rocket lambda syntax doesn't need brackets around the argument
[Answer]
## Python 2 (109 101 97 85 83 74 bytes)
```
lambda x:'#'+''.join(hex(int(int(x[i:i+2],16)/17.+.5))[2:]for i in[1,3,5])
```
The "nearest distance" is handled by division by 17 and rounding.
Improvements:
-8 bytes by using the `int(...+.5)` trick instead of `int(round(...))`
-4 bytes by using list comprehension instead of `map()`
-1 byte by hardcoding `#` in the output (thanks @movatica)
-10 bytes by not using `re.findall("..",...)` in favor of explicit String splicing
-2 bytes by not using list comprehension, but an inline generator expression in `join` (thanks @movatica)
-1 byte by not splicing the `:7` ending for blue part
-9 bytes by better iteration over colors - i.e. iterating over indices, not actual characters (thanks @movatica)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~35~~ 34 bytes
*@nwellnhof saved a byte*
```
s|\w.|sprintf'%X',.5+(hex$&)/17|ge
```
[Try it online!](https://tio.run/##Lcq7DoIwAIXhnadoUhVvlAJyi5O26ebu4EK0KEmlDW0CA7MP4CP6IFYInunky694I2KrfYDWvr@HhRCy1eBWNfxqgOHaAFkC3hVPJbi2ur@0qNeqqWpTuvOzu0XxZvng3Wyx8oO0v3NrIWN4GPi83gAO14EYjzQBZgPQPIjIbgIaEAcSTGmUT3CkkQPD7ICzZIIwz8aCsIT9C5J@pTKVrLX1TjHCAbaeEj8 "Perl 5 – Try It Online")
Reads from STDIN, replaces each pair of items that is not `#` with the appropriate single character using the division by 17 method for finding the nearest, then implicitly outputs (`-p`) the result.
[Answer]
# Python 3, 67 bytes
```
f=lambda x:(f(x[:-2])if x[3:]else"#")+f'{(int(x[-2:],16)+8)//17:X}'
```
[Answer]
# [Red](http://www.red-lang.org), 103 bytes
```
func[c][r: to 1 c to #1 rejoin reverse collect[loop 3[keep to-hex/size r % 256 + 8 / 17 1 r: r / 256]]]
```
[Try it online!](https://tio.run/##TYzBDoIwEETvfMUkxJMxtKAI3AykH@C16aksESWUFDTGn6/LRdzL7JuZjKc2XKnVJuoqhO45Wm2N9hUWBwm7Sizh6e76keVFfiZYNwxkFz04NyHTD6KJi4cbvZO5/xA8dkhPOfYokECeeYkXPf/sGmPC5PtxQYdYKcEX/ViI1dm4KWVWHzeuRdNk5cZpcRFF/p/XKlfhCw "Red – Try It Online")
It turned out that the current Linux version of [Red](http://www.red-lang.org) doesn't have an implementation of the `hex-to-rgb` function, that's why I make the base conversion "manually" :)
# This works fine in the [Red](http://www.red-lang.org) GUI console on Windows:
# [Red](http://www.red-lang.org), 94 bytes
```
f: func[c][r: hex-to-rgb c to #1 rejoin collect[repeat n 3[keep to-hex/size r/:n + 8 / 17 1]]]
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 35 bytes
```
{S:g[\w.]=fmt :16(~$/)/17+.5: '%X'}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtgqPTqmXC/WNi23RMHK0EyjTkVfU9/QXFvP1EpBXTVCvfZ/cWKlQpqGSrymQlp@kYINl7KbmwEQcCkbGIBYXMoulobGziZcys4GLi7GllzKRhaOBhZmIL6zm5kbl91/AA "Perl 6 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
#F⪪⮌…⮌S⁶¦²⍘÷⁺⁸⍘ι¹⁶¦¹⁷φ
```
[Try it online!](https://tio.run/##TYyxCsMgFEX3foUky3tgwWRIhWxJl2yh@QKxthFERY3Qr7dNW0qXM9zDuXIVQTphSpmDtgmqusL@cHOBwOKNTnBRWYWoYHxIo8bV@d8yWb@lJb2yOyBS0u1oEcnnaRBRfe1k01lnfVUwmy0Cp@RPakqad9qcdjDGELEvpW65YLwrx2ye "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
# Literal `#`
S Input string
⮌ Reversed
… ⁶ Truncated to length 6
⮌ Reversed
⪪ ² Split into pairs of characters
F Loop over each pair
ι Current pair
⍘ ¹⁶ Convert from base 16
⁺⁸ Add 8
÷ ¹⁷ Integer divide by 17
⍘ φ Convert to large base
Implicitly print
```
[Answer]
# [R](https://www.r-project.org/), 57 bytes
```
cat("#",sprintf("%x",(col2rgb(scan(,""))+8)%/%17),sep="")
```
[Try it online!](https://tio.run/##K/r/PzmxRENJWUmnuKAoM68kTUNJtUJJRyM5P8eoKD1Jozg5MU9DR0lJU1PbQlNVX9XQXFOnOLXAFijyX9nZwMnQxO0/AA "R – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
+\#sm.H/+8id16 17c3t
```
[Try it here.](http://pythtemp.herokuapp.com/?code=%2B%5C%23sm.H%2F%2B8id16+17c3t&input=%27%23c0dd39%27&debug=0)
NOTE: In case the link above raises an `ImportError`, go [here](http://pythtemp.herokuapp.com/?code=%2B%5C%23sm.H%2F%2B8id16+17c3t&input=%27%23c0dd39%27&debug=0) instead; there is currently a bug in the "official" page, and this is a temporary solution by [Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen). This link may stop working after the official one is fixed.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 87 bytes
```
: f d>s 1- hex ." #"3. do 2 + dup 2 s>number d>s 17 /mod swap 8 > - 1 .r loop decimal ;
```
[Try it online!](https://tio.run/##RY3RCoIwGIXve4rDuozZ1DBNGISy9zA3U9A2NqV6etsK6b85fJz/nNNpO/f03gVZ1ws6SO4QU/TqhYhgT9IIUiPBAXIxXh1/LNNN2d/jGcdJS7hnY5CDgyJGZDFqbSBVO0zNiNL3@mSIz2@jQi0oB/FjrUW5c35GCOaPwHyJscAb1UWcVqeNKlbXabFRkl9Znv29SmQi0PoB "Forth (gforth) – Try It Online")
### Explanation
1. Ignore/truncate first character of input (`#`)
2. Set interpreter to hexadecimal mode
3. Output `#`
4. Loop 3 times, in each loop:
1. Add 2 to string starting address
2. Convert next 2 characters in string to a hexadecimal number
3. Use division and module by 17 (`0x11`) to get closest value for shortened component
4. Output with no preceding space
5. Set interpreter back to Decimal mode
### Code Explanation
```
: f \ start a new word definition
d>s \ convert double-length int to single-length (cheaper drop)
1- hex \ subtract 1 from string address, set current base to 10
." #" \ output #
3. do \ start a loop from 0 to 2 (inclusive)
2 + dup \ add 2 to string starting address and duplicate
2 s>number \ parse the next 2 characters to a hexadecimal value
d>s \ convert result to single-length value
17 / mod \ get the quotient and remainder of dividing by 17
swap \ move the remainder to the top of the stack
8 > - \ if remainder is greater than 8, add 1 to quotient
1 .r \ output result (as hexadecimal) with no space
loop \ end the loop
decimal \ set interpreter back to base 10 (decimal)
; \ end the word definition
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç┤!usτ╓♪╩⌂^÷◙
```
[Run and debug it](https://staxlang.xyz/#p=80b4217573e7d60dca7f5ef60a&i=%23FF0000%0A%2300FF00%0A%23D913C4%0A%23C0DD39%0A%2328A086%0A%23C0CF6F&a=1&m=2)
[Answer]
# [K4](http://kx.com/download), 39 bytes
**Solution:**
```
"#",{x@_1%17%8+16/:x?y}[.Q.nA]@/:3 2#1_
```
**Explanation:**
Uses the same strategy as a lot of these answers (i.e. add 8, divide by 17):
```
"#",{x@_1%17%8+16/:x?y}[.Q.nA]@/:3 2#1_ / the solution
1_ / drop first character
3 2# / reshape as 3x2 (e.g. "FF", "00", "00")
@/: / apply each-right to left lambda
{ }[ ] / lambda with first argument populated
.Q.nA / "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
x?y / get index of hex character, e.g. "AA" => 10 10
16/: / convert from base-16
8+ / add 8
17% / 17 divided by...
1% / 1 divided by...
_ / floor
x@ / index into .Q.nA to get hex character
"#", / prepend "#"
```
**Extra:**
* `"#",{x@*16\:a?&/a:abs(17*!16)-16/:x?y}[.Q.nA]@/:3 2#1_` - my original idea for **54 bytes**
] |
[Question]
[
Define that the natural number **p** is a *+1 prime* of the natural number **n** if **p** is a prime number and the standard binary representation (i.e., without leading zeroes) of **p** can be obtained by adding (i.e., prepending, appending or inserting) a single **1** to the standard binary representation of **n**.
For example, the binary representation of **17** is **100012**. The distinct natural numbers that can be formed by adding a **1** to **100012** are **1100012** or **49**, **1010012** or **41**, **1001012** or **37**, and **1000112** or **35**.
Among these, **41** and **37** are prime numbers, so **17** has two *+1 primes*.
### Task
Write a program or function that accepts a strictly positive integer **n** as input and prints or returns the number of distinct *+1 primes* of **n**.
Input and output must either be an integer, or its decimal or unary string representation.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
### Test cases
```
Input: 4
Output: 0
Input: 1
Output: 1
Input: 17
Output: 2
Input: 33
Output: 3
Input: 553
Output: 4
Input: 3273
Output: 5
Input: 4145
Output: 6
Input: 4109
Output: 7
Input: 196869
Output: 8
```
[Answer]
# JavaScript ES6, 141 bytes ~~143~~ ~~147~~ ~~160~~
*Saves 13 bytes, thanks to @Naouak*
```
n=>[...t=n.toString(2)].map((l,i)=>t.slice(0,v=i+1)+1+t.slice(v)).filter((l,i,a)=>a.indexOf(l)==i&&(p=(n,c)=>n%c&&c>n-2||p(n,++c))('0b'+l,2))
```
Similar method to my TeaScript answer, uses RegExp (you heard me right) to check for primes.
### Ungolfed
```
n=>
[...t = n.toString(2)] // To binary
.map((l,i)=> // Make cycles
t.slice(0, v = i+1)
+ 1
+ t.slice(v)
).filter((l,i,a)=>
a.indexOf(l) == i && // Remove Duplicates
(p=(n,c)=> // Prime checking
n % c &&
c > n - 2 ||
p(n,++c)
)('0b'+l,2)
).length
```
[Answer]
# Pyth, 20 bytes
```
s/LPd{mij\1c.BQ]d2hQ
```
[Test Suite](https://pyth.herokuapp.com/?code=s%2FLPd%7Bmij%5C1c.BQ%5Dd2hQ&input=2&test_suite=1&test_suite_input=2%0A4%0A1%0A17%0A33%0A553%0A3273%0A4145%0A4109%0A196869&debug=0)
```
s/LPd{mij\1c.BQ]d2hQ
Q = eval(input())
m hQ For insertion position in [0 ... Q]
.BQ Convert Q to binary string
c ]d Chop at insertion position
j\1 Join on '1'
i 2 Convert to integer
{ Deduplicate
/LPd Map each number to the number of times it occurs in its
prime factorization, e.g. whether or not it is prime.
s Sum and print.
```
[Answer]
# [TeaScript](https://github.com/vihanb/TeaScript), 22 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859)
```
x÷¿®x÷E(i¬,1)¤©d¡F(¥)n
```
TeaScript is starting to look like APL... The special characters are converted to longer, commonly repeated sequences
[Online interpreter](http://vihanserver.tk/p/TeaScript/) be sure to check "Inputs are numbers."
### Explanation && Ungolfed
```
xT(2)s``m(#P(xT(2)E(i+1,1),2))d()F($P)n
xT(2) // Take input, convert to binary
s``m(# // Loop over input
P( // Convert to decimal...
xT(2) // Input to binary
E(i+1,1) // Inset 1 into (above) at current index in loop
,2)
)d() // Remove duplicates
F($P) // Filter items that aren't prime
n // Grab length.
```
[Answer]
# Julia, ~~55~~ 52 bytes
```
n->sum(isprime,∪(2n+(k=2.^(0:endof(bin(n))))-n%k))
```
`k=2.^(0:endof(bin(n)))` generates an array containing the powers of 2 from 1 to the highest power less than `n`. `2n+k-n%k` then uses array operations to determine all of the possible "+1 numbers". `∪` (equivalent to `union`, which does the same thing as `unique` in this situation) removes the repeat values. Then `sum(isprime,)` counts the number of primes on the list.
[Answer]
## CJam, 26 bytes
Not a winner, but it beats the existing CJam answers quite solidly and it's the first time I got to use the 0.6.5 command `e\`.
```
1ri2b+_,{_)e\_}%_&{2bmp},,
```
[Test it here.](http://cjam.aditsu.net/#code=1ri2b%2B_%2C%7B_)e%5C_%7D%25_%26%7B2bmp%7D%2C%2C&input=196869)
### Explanation
```
1 e# Push a 1 (this is the 1 we'll be inserting everywhere).
ri e# Read input and convert to integer.
2b e# Convert to base 2.
+ e# Prepend the 1.
_, e# Duplicate and get the number of bits N.
{ e# Map this block over i from 0 to N-1...
_) e# Create a copy and increment to i+1.
e\ e# Swap the bits at positions i and i+1, moving the 1 one step through the array.
_ e# Duplicate so we keep this version on the stack.
}%
_& e# Remove duplicates via set intersection with itself.
{ e# Filter the remaining digit lists based on this block...
2b e# Convert bits back to an integer.
mp e# Test for primality.
},
, e# Get the length of the remaining list.
```
One thing worth noting is that we swap the bits at `0` and `1` before making the first copy, so we lose the original array with the `1` prepended to the front. However, the input is always positive, so the leading digit will always be one. That means after prepending another one, the digit list will always start with `[1 1 ...]` so the first swap will be a no-op in any case.
[Answer]
## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), ~~54~~ 52 bytes
```
n1(2*d0c`,)(0c1c$%$r2*1c*1c++1g2:d1G)rxSI1-[0g2M+]N.
```
### Explanation
```
n Get integer from input (let's call it n)
1( ) Get the smallest power of 2 (say, k) greater than input (starting with 1)
2*d Multiply by 2 and duplicate
0c`, Copy n and see if it's greater (while loop breaks on 0)
(0c1c$% Copy n, copy k, and divmod (pushes n//k, n%k)
$r Swap top two elements
2* Multiply by 2
1c* Copy k and multiply
1c+ Copy k and add
+ Add
1g2: Get k and divide by 2
d1G) Duplicate and put one copy back in its former place
rx Reverse and dump (dumps n and top of stack is now 0)
S Remove duplicates
I1-[ ] Check each element for primality
0g Get potential prime from bottom of stack
2M 1 if prime, 0 otherwise
+ Add (this is why I didn't dump the left-over 0 earlier)
N. Output as integer and stop.
```
[Answer]
# Mathematica, 87 bytes
```
Union[#~FromDigits~2&/@StringReplaceList[#~IntegerString~2,a_:>a<>"1"]]~Count~_?PrimeQ&
```
[Answer]
# Julia, ~~110~~ ~~108~~ ~~104~~ 87 bytes
```
n->sum(i->isprime(parse(Int,i,2)),(b=bin(n);∪([b[[1:i;1;i+1:end]]for i=1:endof(b)])))
```
This creates an unnamed function that accepts and integer and returns an integer. To call it, give it a name, e.g. `f=n->...`.
Ungolfed:
```
function f(n::Integer)
# Get the binary representation of n as a string
b = bin(n)
# Construct an array consisting of binary strings with
# a one prepended, appended, and each insertion
x = [b[[1:i; 1; i+1:end]] for i = 1:endof(b)]
# Count the number of primes
c = sum(i -> isprime(parse(Int, i, 2)), unique(x))
return c
end
```
Saved 17 bytes thanks to Glen O!
[Answer]
# CJam, 58 bytes
```
L{:TQ\=A+Q\+TWe\-2<s:~2b}q~2b0+:Q,(%{:BLe=!{B+:L}&}%~:mp:+
```
This took me a day, and this was my 4th iteration.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~14~~ 11 bytes
```
ƤiX1Ãâ ®Íj
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=xqRpWDHD4iCuzWo&input=MTc) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=xqRpWDHD4iCuzWo&footer=eA&input=WzQsMSwxNywzMyw1NTMsMzI3Myw0MTQ1LDQxMDksMTk2ODY5XQotbQ)
```
ƤiX1Ãâ ®Íj :Implicit input of integer U
Æ :Map each X in the range [0,U)
¤ : Convert U to binary string
iX1 : Insert "1" at 0-based index X
à :End map
â :Deduplicate
® :Map
Í : Convert to decimal
j : Is prime?
:Implicit output of array sum
```
[Answer]
## PHP, 145 bytes
I've added a newline for readability:
```
function($n){for($b=base_convert;++$i<=strlen($s=$b($n,10,2));$r+=!$s[$i]&$k<=$j)
for($j=1;($k=$b(substr_replace($s,1,$i,0),2,10))%++$j;);echo$r;}
```
[Answer]
# CJam, 34 bytes
```
li2b_,),\f{_2$<@@>1\++}_&2fb{mp},,
```
[Try it online](http://cjam.aditsu.net/#code=li2b_%2C)%2C%5Cf%7B_2%24%3C%40%40%3E1%5C%2B%2B%7D_%262fb%7Bmp%7D%2C%2C&input=196869)
First version, will update if I come up with something better.
[Answer]
# APL, 55
```
{+/{2=+/0=⍵|⍨⍳⍵}¨∪⍵{2⊥(⍵↑X),1,⍵↓X←⍺⊤⍨N⍴2}¨-1-⍳N←1+⌊2⍟⍵}
```
2 bytes shorter Dyalog-specific version:
```
{+/2=+/¨0=|⍨∘⍳⍨¨∪⍵{2⊥⍵(↑,(1∘,↓))⍺⊤⍨N⍴2}¨-1-⍳N←1+⌊2⍟⍵}
```
[Answer]
## Matlab (120)
```
n=input('');a=dec2bin(n);g=arrayfun(@(x)bin2dec(cat(2,a(1:x),49,a(x+1:end))),1:log2(n));nnz(unique(g(find(isprime(g)))))
```
---
* More golfing in progress ...
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
{ḃ~c₂{,1}ʰc~ḃṗ}ᶜ¹
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/rhjua6ZKBAtY5h7akNyXVA/sOd02sfbptzaOf//9EmOoY6huY6xsY6pqbGOsZG5sY6JoYmpkDCwFLH0NLMwsxSx1THTMc8FgA "Brachylog – Try It Online")
Input through the input variable and output through the output variable.
```
{ }ᶜ¹ Count every unique
ṗ prime number
~ḃ the binary representation of which is
ḃ the binary representation of the input
~c₂ partitioned into two (possibly empty) lists
{ }ʰ with the first list
,1 having a 1 appended
c and the two lists then being concatenated back into one.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
BLṬkj1ʋ€$QḄẒS
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//QkzhuaxrajHKi@KCrCRR4biE4bqSU////zE5Njg2OQ "Jelly – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
←#ṗumȯḋJ1`Cḋ¹oSze↔ŀḋ
```
[Try it online!](https://tio.run/##yygtzv7//1HbBOWHO6eX5p5Y/3BHt5dhgjOQOrQzP7gq9VHblKMNQN7///8NzQE "Husk – Try It Online")
Barely got away with a single byte.
# [Husk](https://github.com/barbuz/Husk), 21 bytes
```
#oṗḋumJ1§z§e↑↓oΘŀo¢;ḋ
```
[Try it online!](https://tio.run/##yygtzv7/Xzn/4c7pD3d0l@Z6GR5aXnVoeeqjtomP2ibnn5txtCH/0CJroNz///8NzQE "Husk – Try It Online")
There's probably a much shorter way to do this.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~18~~ 17 bytes
```
#oṗḋużoJ1eḣḋ¹mtṫḋ
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8b9y/sOd0x/u6C49uiffyzD14Y7FQM6hnbklD3euBrL@//8fbaJjqGNormNsrGNqaqxjbGRurGNiaGIKJAwsYwE "Husk – Try It Online")
Different approach to [Razetime's Husk answer](https://codegolf.stackexchange.com/a/214572/95126), saving ~~2~~ 3 bytes.
**How?**
```
#oṗḋużoJ1eḣḋ¹mtṫḋ
#o # how many
ṗ # prime numbers
ḋ # among numbers formed by binary digits of
u # unique elements of
żo # zip together 2 lists of lists,
J1e # joining each pair with the digit '1'
ḣḋ¹ # list 1:
ḣ # all prefixes of
ḋ¹ # binary digits of input
mtṫḋ # list 2:
mt # remove first element from
ṫ # all suffixes of
ḋ # binary digits of input
```
[Answer]
# [Python 2](https://docs.python.org/2/), 103 bytes
```
lambda n:sum(all(i%j for j in range(2,i))for i in{n%2**i+((n>>i)*2+1<<i)for i in range(len(bin(n))-2)})
```
[Try it online!](https://tio.run/##PctBDoIwEEbhq8yGZKbogi6IGOQkbkqkOqT8NLUsjPHsVRPj9nt58ZFvK2zxp3MJbhkvjnC8bwu7EFirmfyaaCYFJYfrxHanIl/Tjz1RWWO0ZsYwqBhbN32v//xbwgQeFQyRvZWXlJgUmTwr4pZZpDRde2i7Nw "Python 2 – Try It Online")
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3) `s`, 11 bytes
```
bƛ?bm1ỊB}uṄ
```
[Try it Online! (link is to literate version)](https://vyxal.github.io/latest.html#WyJsc2IiLCIiLCJ0by1iaW5hcnkgbWFwPCBpbnB1dCB0by1iaW5hcnkgbSAxIGluc2VydCBmcm9tLWJpbmFyeX0gdW5pcXVpZnkgcHJpbWU/IiwiIiwiMzMiLCIzLjMuMCJd)
## Explained
```
'uniquify( to-binary map<
(input to-binary) 'insert (ctx-m 1)
from-binary}
)
prime?
```
] |
[Question]
[
## The Challenge
Build a N-Leveled [Cantor Set](http://en.wikipedia.org/wiki/Cantor_set).
>
> The Cantor ternary set is created by repeatedly deleting the open
> middle thirds of a set of line segments.
>
>
>
The program receives one parameter `N` (a integer number) and then prints (in console or similar way) a Cantor Set of N levels. The print can only contain undescore (`_`) and whithe spaces characters. The parameter can be positive or negative and the sign indicates the Cantor Set construction orientation: If `N > 0` the Cantor Set is constructed downwards and if `N < 0` the Cantor Set is constructed upwards. If `N = 0` then the program prints a single line (`_`).
For example:
N = 2
```
_________
___ ___
_ _ _ _
```
N = -2
```
_ _ _ _
___ ___
_________
```
N = 3
```
___________________________
_________ _________
___ ___ ___ ___
_ _ _ _ _ _ _ _
```
N = -3
```
_ _ _ _ _ _ _ _
___ ___ ___ ___
_________ _________
___________________________
```
## Winning criteria
As it is a code golf challenge, the shortest code wins.
Edited: Modify 0 input by ugoren's suggestion.
[Answer]
## GolfScript, 49 42 40 chars
```
~.abs.3\?'_'*\{.3%..,' '*\++}*](0>2*(%n*
```
With thanks to [hammar](https://codegolf.stackexchange.com/users/1811/hammar) for 42->40.
My best attempt yet at a more number-theoretic approach is sadly much longer:
```
~.abs:^3\?,{3^)?+3base(;1+1?.'_'*^@-)' '*+}%zip\0>2*(%n*
```
or
```
~.abs 3\?:^,{6^*+3base.1+1?.('_'*@,@-' '*+}%zip\0>2*(%n*
```
and I suspect that the length of `base` and `zip` will make it impossible to catch up.
[Answer]
## Python, 116 113 104 103 chars
```
n=input()
d=n>0 or-1
for i in range(n*d+1)[::d]:
s='_'*3**i
while i<n*d:s+=len(s)*' '+s;i+=1
print s
```
Older algorithm topped out at 113 characters
```
r=input()
u='_'
l=[u]
for _ in abs(r)*u:o=len(l[0]);l=[s+o*' '+s for s in l]+[u*o*3]
print'\n'.join(l[::r>0 or-1])
```
[Answer]
# Ruby (97)
Based on Steven Rumbalski's python version:
```
n,r=$*[0].to_i,[?_]
n.abs.times{z=r[0].size;r=r.map{|s|s+' '*z+s}+[?_*z*3]}
puts n<0?r:r.reverse
```
## Previous attempts, both same length (112)
Build lines from parts:
```
c=->x,n{n<1??_*x :(z=c[s=x/3,n-1])+' '*s+z}
r=(0..m=(n=$*[0].to_i).abs).map{|i|c[3**m,i]}
puts n<0?r.reverse: r
```
Start with one line, make holes in it:
```
r=[?_*3**a=(n=$*[0].to_i).abs]
a.times{|c|r<<r[-1].gsub((x=?_*o=3**(a-c-1))*3,x+' '*o+x)}
puts n<0?r.reverse: r
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~32~~ 31 bytesSBCS
```
{' _'[⊖⍣(0>⍵)∧⍀1⍪1≠3⊥⍣¯1⍳3*|⍵]}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6vVFeLVox91TXvUu1jDwO5R71bNRx3LH/U2GD7qXWX4qHOB8aOupUC5Q@uBApuNtWqAKmJr/6cBNT/q7XvU1XxovfGjtolAA4ODnIFkiIdn8P80BQMuIBuoRkFdQZ0rTcEQlQs0DFXACF0eTcAYXd4YAA "APL (Dyalog Unicode) – Try It Online")
Saved 1 byte thanks to Adám by changing the conditional flipping `⊖⍣(0>⍵)` to *inside* the indexing.
**How it works**:
This answer builds on the mathematical properties of the Cantor set itself. It is known that a number is in the Cantor set iff its ternary expansion contains no 1s. So what we do is discretize the interval [0, 1], compute the ternary expansion of the numbers in there, check which ones have a 1 in their ternary expansion and exclude them from the subsequent iterations of the drawing.
```
{' _'[⊖⍣(0>⍵)∧⍀1⍪1≠3⊥⍣¯1⍳3*|⍵]} ⍝ dfn expecting an integer as right argument (e.g. 2)
⍳3*|⍵ ⍝ discretize the interval (e.g. 0 1 2 3 4 5 6 7 8)
3⊥⍣¯1 ⍝ compute the ternary expansion in columns (e.g.
⍝ 0 0 0 1 1 1 2 2 2
⍝ 0 1 2 0 1 2 0 1 2 )
1⍪1≠ ⍝ find which numbers are ≠ from 1 and
⍝ append a row of 1s (e.g.
⍝ 1 1 1 1 1 1 1 1 1
⍝ 1 1 1 0 0 0 1 1 1
⍝ 1 0 1 1 0 1 1 0 1 )
∧⍀ ⍝ propagate the 0s downwards (e.g.
⍝ 1 1 1 1 1 1 1 1 1
⍝ 1 1 1 0 0 0 1 1 1
⍝ 1 0 1 0 0 0 1 0 1 )
⊖⍣(0>⍵) ⍝ mirror if the input number is negative
' _'[ ] ⍝ and index into ' _' to draw
```
[Answer]
## Perl, 93 chars
```
@x=($t=$x=_ x 3**($a=abs($n=<>)),map$x.=$"x($x=~s/(.)../$1/g).$x,1..$a);say for$n<0?sort@x:@x
```
I thought I'd try to see how well [Peter Taylor's GolfScript solution](https://codegolf.stackexchange.com/a/4795) would port to Perl. Notable features include the use of `sort` instead of `reverse` to save three chars, using the fact that a space sorts before `_`.
[Answer]
## Common Lisp, 217 210 characters
```
(defun m(x)(flet((c(n v)(if(= n 0)`((,v))(cons(substitute v nil(make-list(expt 3 n)))(mapcar #'append(c(1- n)v)(c(1- n)" ")(c(1- n)v))))))(format t "~{~{~a~}~%~}"(let((r(c(abs x)'_)))(if(< x 1)(reverse r)r)))))
```
**Expanded:**
```
(defun m(x)
(flet((c(n v)
(if(= n 0)
`((,v))
(cons(substitute v nil(make-list(expt 3 n)))
(mapcar #'append
(c(1- n)v)
(c(1- n)" ")
(c(1- n)v))))))
(format t "~{~{~a~}~%~}"(let((r(c(abs x)'_)))(if(< x 1)(reverse r)r)))))
```
I figure if the Lisp code manages to beat any initial count for another language (C, 219) I'm doing OK :)
[Answer]
## C (163 161 chars)
```
i,l,N;f(n,m,s){if(n){s=--n<l?m:s;f(n,m,s);f(n,s,s);f(n,m,s);}else
putchar(m);}main(n,v)int**v;{for(i=N=abs(n=atoi(1[v]));i+1;i--)l=n<N?N-i:i,f(N,95,32),f(0,10);}
```
Borrows a couple of tricks from [ugoren's answer](https://codegolf.stackexchange.com/a/4796/194), but the core logic is quite different. I couldn't follow his for loop, so it may be possible to hybridise and save a few more.
[Answer]
## C, 219 193 179 143 136 131 characters
Followed another of Petyer Taylor's ideas, plus an improvement of my own, saved 6 more.
Integrated some tips from @PeterTaylor, plus copied his main function, with slight changes, which save a character (is it fair to copy it? Since neither of us will win this one, I guess it isn't too bad).
I thought of a significant improvement in how my recursion works, and after seeing Peter Taylor's answer, I implemented it to regain the lead. When reading his answer again, I saw that I did almost exactly what he did. So this seems like the hybridization he suggested.
Also simplified the loop in `main`, keeping the same length.
And took Peter's trick to print newline, instead of `puts("")` - saves a character.
Removed `int` from variable declaration - a warning, but saves 4 chars.
New algorithm doesn't calculate 3^x in advance, but uses a single loop to print 3^x characters.
Can save one more by defining `int*v`, but then 64bit won't work.
Characters count excludes whitespace (which can be removed).
```
o,i,n;
p(c) {
n-- ?
p(c),p(o>n?c:32),p(c)
:
putchar(c);
n++;
}
main(c,v)int**v; {
for(n=abs(c=atoi(v[1]));i<=n;i++)o=c+n?n-i:i,p(95),puts("");
}
```
Older algorithm, 219 chars:
```
p(l,o,i,m,c,j) {
for(;i<(m=l);i++)
for(j=0,c=95;m/o||!putchar(c);j++)
i/m%3-1||(c=32),m/=3;
puts("");
}
main(c,v,n,i,l,o)int**v;{
(n=atoi(v[1]))<0?n=-n:(c=0);
for(i=n,l=1;i;i--)l*=3;
o=c?1:l;
for (;i<=n;i++)p(l,o,0),c?o*=3:(o/=3);
}
```
[Answer]
# J, ~~44~~ ~~39~~ ~~38~~ 37 bytes
```
' _'{~0&>_&(]|.)(,:1)1&(,],.0&*,.])~|
```
Uses iteration to build the next set starting with 1 (representing `_`) initially.
## Usage
```
f =: ' _'{~0&>_&(]|.)(,:1)1&(,],.0&*,.])~|
f 0
_
f 1
___
_ _
f _1
_ _
___
f 2
_________
___ ___
_ _ _ _
f _2
_ _ _ _
___ ___
_________
f 3
___________________________
_________ _________
___ ___ ___ ___
_ _ _ _ _ _ _ _
f _3
_ _ _ _ _ _ _ _
___ ___ ___ ___
_________ _________
___________________________
```
## Explanation
```
' _'{~0&>_&(]|.)(,:1)1&(,],.0&*,.])~| Input: integer n
| Absolute value of n
(,:1) The array [1]
1&( )~ Repeat abs(n) times starting with x = [1]
] Identity function, gets x
0&* Multiply x by 0
,. Join the rows together
] Identity function, gets x
,. Join the rows together
1 , Prepend a row of 1's and return
0&> Test if n is negative, 1 if true else 0
_&( ) If n is negative
|. Reverse the previous result
] Return that
Else pass the previous result unmodified
' _' The string ' _'
{~ Select from the string using the result
as indices and return
```
[Answer]
# [R](https://www.r-project.org/), ~~141 139~~ 137 bytes
```
m=abs(n<-scan());write("if"(n<m,rev,c)(c(" ","_")[Reduce(`%x%`,rep(list(matrix(c(1,1,1,1,0,1),3)),m),t(1))[,1+2^m-2^(m:0)]+1]),1,3^m,,"")
```
[Try it online!](https://tio.run/##JYrNCsIwEAZfRRYK@9ENNK0nf17Ca2ltjRECbpE0at8@BmRuMxNz1vN8W3k5mdXNCwPHbwzJM4UHFasS/Ucc2DHtSOhK6C/@/naep2qrppJf/AxrYp1TDFv5rPxpxEI6QBSS2AK92Lod1bQj66HBUNsB5etGFSFCNvv8Aw "R – Try It Online")
-15 bytes thanks too Giuseppe's use of `'('` as the identity function; `write` instead of `cat` to print output; clever use of`%x%`.
-2 bytes thanks to Kirill L. by using `c` instead of `'('` as the identity function.
[Answer]
## Python, 177 164 characters
```
N=input()
n=abs(N)
c=lambda x:0if x<1 else x%3==1or c(x/3)
r=["".join([["_"," "][c(x/3**i)]for x in range(3**n)])for i in range(n+1)]
print"\n".join(r[::N>0 or-1])
```
[Answer]
# Perl, 113 chars
```
$i=abs($I=<>);@w=$_='_'x3**$i;while($i--){$x=3**$i;s/(__){$x}/'_'x$x.' 'x$x/eg;push@w,$_}say for$I>0?reverse@w:@w
```
**Expanded:**
```
$i=abs($I=<>);
@w=$_='_'x3**$i;
while($i--){
$x=3**$i;
s/(__){$x}/'_'x$x.' 'x$x/eg;
push@w,$_
}
say for$I>0?reverse@w:@w
```
[Answer]
# JavaScript 121 bytes
Inner recursive function, then take care of backward output if needed
```
n=>(f=(n,t=n&&f(n-1),r=t[0])=>n?[r+r+r,...t.map(x=>x+t[n]+x)]:['_',' '],f=f(n<0?-n:n),f.pop(),n<0?f.reverse():f).join`\n`
```
*Less golfed*
```
n=>{
var f = n => { // recursive function
var t = n && f(n-1), r = t[0]
return n
? [r+r+r, ...t.map(x => x+t[n]+x)]
: ['_',' ']
};
f = f(n < 0 ? -n : n);
f.pop(); // last row is all blanks
if (n<0) f.reverse();
return f.join`\n`
}
```
**Test**
```
var F=
n=>(f=(n,t=n&&f(n-1),r=t[0])=>n?[r+r+r,...t.map(x=>x+t[n]+x)]:['_',' '],f=f(n<0?-n:n),f.pop(),n<0?f.reverse():f).join`\n`
function go()
{
var n=+I.value
O.textContent = F(n)
}
go()
```
```
<input id=I type=number value=3 oninput='go()'>
<pre id=O></pre>
```
[Answer]
## Batch, ~~265~~ ~~262~~ ~~242~~ ~~236~~ 235 bytes
```
@echo off
set/pn=
set c=%n%,-1,0
if %n% lss 0 set c=0,1,%n:-=%
for /l %%i in (%c%)do call:l %%i
exit/b
:l
set s=_
for /l %%j in (1,1,%n:-=%)do call:m %1 %%j
echo %s%
:m
set t=%s%
if %1 lss +%2 set t=%s:_= %
set s=%s%%t%%s%
```
Edit: Saved ~~12~~ 19 bytes thanks to @l4m2. Saved 8 bytes by removing the unnecessary `%a%` variable.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 111 bytes
```
filter f{if($s=[math]::Sign($_)){($x=$_-$s|f|%{$_+' '*($l=$_|% Le*)+$_})|?{$s-1};'_'*3*$l;$x|?{$s+1}}else{'_'}}
```
[Try it online!](https://tio.run/##HYzLCsMgFAX3@QoJN/iIQo1dJYT@QOmmy1KkC20C9kEMNKB@u5Wc1TAH5vv5mcVPxrmc7exWsyAbZkvAj7fXY53ufX@dn28CmtJAYBtBC/DRxiaAbjHCjIArMjbobBhtQScaTwG8kGnAGjPFwA2w7a6VKRnnTShHSvnAJReSd1x0XHGh@LFUK1RWX0qy3rGk7Q4YVyn/AQ "PowerShell – Try It Online")
Less golfed:
```
filter f{
if($sign=[math]::Sign($_)){
$x=$_-$sign|f|%{
$_+' '*($length=$_|% Length)+$_
}
$x|?{$sign-1} # output $x if $_ is negative
'_'*3*$length
$x|?{$sign+1} # output $x if $_ is positive
}
else{
'_'
}
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 31 bytes
```
*±¹↑→a¹¡oṁ§ṘȯJ' R2←o/3LgR'_`^3a
```
[Try it online!](https://tio.run/##AToAxf9odXNr//8qwrHCueKGkeKGkmHCucKhb@G5gcKn4bmYyK9KJyBSMuKGkG8vM0xnUidfYF4zYf///y00 "Husk – Try It Online")
Doesn't really use the cantor set, just uses a replacement method (and an infinite list).
Now, you may ask: why is an infinite list useful here? Here's an explanation:
## Explanation
```
¡oṁ§ṘȯJ' R2←o/3LgR'_`^3a
a take abs(n)
R'_`^3 repeat underscore n times(take n=3)
¡o iterate on this string, collecting results
g group the string into equal runs:
["_________"]
ṁ map each group to the following, and concatenate:
R2← repeat the first character twice
J' join with spaces
"_________" → "_ _"
o/3L take length /3 → 3
§Ṙ Repeat each character that many times
"___ ___"
Then:
↑→a¹ take n+1 elements from the list
*±¹ multiply by sign(n) (reverse if negative)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 148 bytes
```
n=>f=(L=n<0&&n,R=n>0&&n)=>[...Array(r=3**(n>0?n:-n))].map(_=>((j++).toString(3)+1).indexOf(1)>(L>0?L:-L)?'_':' ',j=r+r).join``+`
${L++<R?f(L,R):''}`
```
[Try it online!](https://tio.run/##JY3LCsIwEADvfkUPYnbNA6u36qZ48RQQ6lHEFm2lRTcSgyjit1fF28AwTFfdq9shtNeo2R/rfpVQ0jPZhsARLyajEauC2P4AyW6NMcsQqicEmo3H8BU5Z5oRd@ZSXWFPFqCTEk30mxhaPsEMZYqm5WP9WDeQogX3jVymHeZiLzKRCNVRkAFN51suS1kOhi8n5aLIG3CqwEyId9nPB1s9VTpVE5Wq6X8XyR483/y5Nmd/ghVEBETsPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 102 bytes
```
lambda n:'\n'.join(eval("[i+' '*len(i)+i for i in"*abs(n)+"'_'"+"]+['___'*len(i)]"*abs(n))[::n<1or-1])
```
[Try it online!](https://tio.run/##NcrBCgIhEADQXxm8jLNSsNFJ6ktcEZdWmrBRXAv6ejvt@b36688il5Huy8jxvT4iiMVF8PwqLHr7xqyVY4OAU95EMxmGVBowsKgprrsWMgoDKqO8cRhCOKY/nJy1cptLO82eRm0sHZJmqZ@uicb1Dw "Python 2 – Try It Online")
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~265~~ ~~232~~ 213 bytes
```
S-E-R:-between(S,E,R).
[]/R/R.
[H|T]/B/R:-T/[H,32,H|B]/R.
N+R:-(N>0->O is N-1,O+S,S/[]/R;R=`_`).
N*[H|T]:-1-N-_,writef("%n",[H]);N*T.
_*[]:-nl.
-N:-(0-N-J,K is N-J;N-0-I,J is -I,K is I-N),L is 3^K,J+R,L*R,1=0;1=1.
```
[Try it online!](https://tio.run/##JYxNC4JAEIbv/goJAldndt3spFggCGYxwepNzAgsBNGowEv/3Xbt9M77Mc/zNfbjA99TN88FpqhCvLWfqW0Hp4AUFONWVQsllNbsW9YiEXpSiiqDYAPZN6lNRZ4OHdr5uDvb3dsmlHD2CiiEeY5UfG2umkTuwghRImED06v7tHdntR5WUGU1i8gtudW4lV4MPbeQNNTX0xyOf2oeEfp4gNxYrUt8QGJwMldwOULuKTi5CmTsRzKWfN6jjc6WgW2Qi8GA8fkH "Prolog (SWI) – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org), 243 bytes
```
|i:i8|(0..i.abs() as usize).any(|j|print!("{}
",if i>0{f(j,3usize.pow(i as u32-1))}else{f(-i as usize-j-1,3usize.pow(-i as u32-1))})>());fn f(i:usize,j:usize)->String{if i<1{"_".repeat(j)}else{[f(i-1,j/3)," ".repeat(j/3),f(i-1,j/3)].concat()}}
```
Once again I win the prize for the longest answer
[Attempt This Online!](https://ato.pxeger.com/run?1=VY9BTsMwEEX3PYXxakaKTdNsqpbmEiwRQqayo7GKG8WOKnByEjZZwAFYcxLOwQVwkorC6mvmv5k_8_rWtD4MH8axJ0UOkMWDDqzavbfBiPXXd0cbWnewlJKkevQJUJ61nl40SuWeobNd3ZALV8Bjv-AZGUblMhqwWTFhsj6egKapYiVyxF4fvE6AoN9Vwor8Ly7-8VgC4jZdaIA2E5TZWVGUtyGlV3GMvckjf-Cy0bVWAew56C5Npe32usCMs4s91hfrXu6Pbp_62Pfz658VrHC7qEDMUszFKGdiGGb9AQ)
# [Rust](https://www.rust-lang.org), 247 bytes
```
|x:i32|->String{let r=(0..x.abs() as u32).map(|d|{(0..3_usize.pow(x.abs() as u32-1)).map(move|w|if(0..d).all(|v|w/3_usize.pow(x.abs() as u32-2-v)%3!=1){'_'}else{' '}).chain(['\n'])});if x<0{r.rev().flatten().collect()}else{r.flatten().collect()}};
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fY9NTsMwFIT3nMKthOwnEdMmm6ohXIJlQZVJnWDJ-ZHt_AjbJ2GTBRyA43AStiRNN4iI1ZNmvtG8eXtXjTbDZ1aigomSALKSG5QnH43Jgt3Xt-v3IgpdcP9glCjzs6sSsqG0p-xZjwGmUROFQAtWE3dydvKiY6PFK6d11ZHfXLCFGS2qlrvOiWziT0CZlMS1rrv9JxsGLVxHq2QLFh-x51JzixH2QNOX6fsDfizxE3iIRYb6u41VVPGWAM0kM4aP82haSclTQ2BOq0XLx5f5h3ocbWS5Imvr1zcoJyFAfPVHDZblaBk-y36uGIb5_gA)
] |
[Question]
[
A simple way to scramble a 2x2x2 Rubik's cube is to make a sequence random moves. This is not how official scrambles are done, but can get pretty close to a uniform distribution of all possible scramble states. Due to the way a 2x2 only has two layers, doing one turn on one face is equivalent (without considering the puzzle's orientation in space) to doing the same direction turn on the opposite face. For example, turning the top face clockwise moves all the pieces in relation to each other the same way turning the bottom face clockwise does. So scrambles only need to turn the top (U), right (R), and front (F) faces.
For this challenge, your program must generate a string that represents a sequence of 16 moves. A move is represented by a face, one of the letters `U`, `R`, `F`, followed by a direction: clockwise (empty string or space ), counterclockwise (apostrophe `'`), or 180 degrees (`2`). The turn and direction should be chosen uniformly at random, however two consecutive moves cannot turn the same face, For example a scramble cannot contain `R' R2`. So the first move should have a 1/3 chance for each face, but there should be a 50/50 chance for the chosen face *after the first move*. Moves are separated by a space.
Example scramble:
```
U F' R2 F' R' F R F2 U' F R2 F U2 F' U2 F2
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~84~~ ~~83~~ 82 bytes
-2 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!
```
import random as R
print(*[(R:=c([*{*"FUR"}-{R}]))+c(" '2")for c in[R.choice]*16])
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/PzO3IL@oRKEoMS8lP1chsVghiKugKDOvREMrWiPIyjZZI1qrWkvJLTRIqVa3Oqg2VlNTO1lDSUHdSEkzLb9IIVkhMy86SC85Iz8zOTVWy9AsVvP/fwA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
16Fн…FRUsK… '2âΩð«?
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0Mztwt5HDcvcgkKLvYG0grrR4UXnVh7ecGi1/f//AA "05AB1E – Try It Online")
```
16F # iterate 16 times:
н # get the first character from the value that was last on stack
…FRU # push string "FRU"
sK # remove the result from н
… '2 # push string " '2"
â # cartesian product of the strings
Ω # choose a random string from the list
ð« # append a space
? # print without a trailing newline
```
---
`Ô` - *Connected uniquified a* seems like a promising builtin for this challenge, but the best I could do with it is 22 bytes:
```
…FRU¸Þ€ΩÔ16£ε… '2Ω«}ðý
```
[Try it online!](https://tio.run/##ATAAz/9vc2FiaWX//@KApkZSVcK4w57igqzOqcOUMTbCo8614oCmICcyzqnCq33DsMO9//8 "05AB1E – Try It Online")
```
…FRU¸Þ # infinite list ["FRU", "FRU", ...
€Ω # select a random character from each string
Ô # remove consecutive duplicates
16£ # take the first 16 characters
ε } # for each of those:
… '2Ω« # append a random char from " '2"
ðý # join the resulting list by spaces
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~35~~ ~~29~~ ~~25~~ 19 bytes
```
16(h‛⊍Ṁ⇧$-` '2`Ẋ℅¨…
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=16%28h%E2%80%9B%E2%8A%8D%E1%B9%80%E2%87%A7%24-%60%20%272%60%E1%BA%8A%E2%84%85%C2%A8%E2%80%A6&inputs=&header=&footer=)
Thanks to Lyxal for -6 bytes.
```
16( # Repeat 16 times (Automatically closed)
h # Take first of previous
‛⊍Ṁ⇧ # Push `fru`, uppercased
$ # Swap top two elements on stack
- # Remove (So fru loses the first of previous iteration)
` '2` # Push ` '2`
Ẋ # Cartesian product
℅ # Random choice
¨… # No idea (Can't find any docs)
```
## My old version, 25 bytes
```
16(‛Ŀ¦⇧'¥≠;℅:£`'2 `℅+⅛)¾Ṅ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=16%28%E2%80%9B%C4%BF%C2%A6%E2%87%A7%27%C2%A5%E2%89%A0%3B%E2%84%85%3A%C2%A3%60%272%20%60%E2%84%85%2B%E2%85%9B%29%C2%BE%E1%B9%84&inputs=&header=&footer=)
```
16( ) # 16 times
‛Ŀ¦⇧ # Push compressed string `fur`, to uppercase
' ; # Filter by...
¥≠ # is not equal to register
℅ # Random choice
:£ # Duplicate and push to register
`'2 `℅ # Random of `'2 `
+ # Concatentated
⅛ # Push to global array
¾ # Push global array to stack
Ṅ # Join by space
```
I know this is a mess. Also this seems to be the only one that compresses even one of the strings.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 18 bytes
```
F¹⁶«≔‽⁻FRUωωω‽ 2'→
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw9BMU6Gai9OxuDgzPU8jKDEvJT9Xwzczr7RYQ8ktKFRJR6FcUxNEWHNxBhRl5pVoIDGhypUUjNSVNEHCvvllqRpWQZnpGSVAbu3///91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F¹⁶«
```
Repeat 16 times.
```
≔‽⁻FRUωω
```
Choose a random turn that wasn't just used.
```
ω
```
Output that turn.
```
‽ 2'
```
Output a random direction.
```
→
```
Except for the last move, leave a space for the next move.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 50 bytes
```
$
¶FRU¶ 2'
(([FRU])¶.¶.*)\2
$1
16}%@L`.
¶
|' L`..
```
[Try it online!](https://tio.run/##K0otycxLNPz/X4Xr0Da3oNBD2xSM1Lk0NKKB7FjNQ9v0gEhLM8aIS8WQy9CsVtXBJ0EPqJKLq0ZdAcjU@/8fAA "Retina – Try It Online") Explanation:
```
$
¶FRU¶ 2'
```
Append the possible turns and directions.
```
(([FRU])¶.¶.*)\2
$1
```
Remove the turn that was made the last time.
```
%@L`.
```
Pick a random turn and direction from those left.
```
16}`
```
Repeat the above 16 times.
```
¶
```
Join everything together.
```
|' L`..
```
Add spaces between the moves.
[Answer]
# [Factor](https://factorcode.org/), 83 bytes
```
[ [ "UFR"""16 [ over remove random dup , "2 '"random , 32 , ] times ] ""make 2nip ]
```
[Try it online!](https://tio.run/##NY0/C8IwFMS/yvEWl1KwgoPuiouD0ql0iOmThjZ/fElFP30MosvvjoO7uyudvOT2ejofd5hYHM@I/FjYaY4Q5QZvYdXEBWmE9vZmnCqdWPMriYoIwim9gxiXsM8dOlB7uBDRelu8f7JA2Bb9rw1LQAVqsKJfUmHTFPRIxpbXHkTfy8aZgD6nUYxm1BF6ZiX5Aw "Factor – Try It Online")
One of the odd times `make` is shorter than sequence words (or smart combinators like `append-outputs`). Mainly because turning code points into strings is verbose in Factor, but `make`, despite being verbose itself, can do that with ease. Plus, `,` is much shorter than `suffix` or `append`.
## Explanation:
It's a quotation (anonymous function) that takes no input and leaves a string on the data stack as output.
* `[ ... ] ""make` Make a string. Inside the quotation, `,` appends elements to a sequence. The `""` is an exemplar that tells `make` the result should be a string.
* `"UFR"""` Place two strings on the stack. The first, `"UFR"`, indicates which possible faces we can choose. The second, `""`, is the last face we chose, so we don't choose it twice in a row.
* `16 [ ... ] times` Call a quotation 16 times.
* `over remove random` Pick a random face that we didn't pick last time.
* `dup ,` Append it to our sequence without destroying it (since we need to know our last move again).
* `"2 '" random ,` Append a random direction/move to the face.
* `32 ,` Append a space.
* `2nip` Once `make` is done building the string, we still have some junk on the data stack to remove.
[Answer]
# JavaScript (ES6), ~~82 81~~ 79 bytes
```
f=i=>i>>10?"":"FRU"[(i=~~i-Math.random()*~-~!i)%3|0]+" '2"[i*3%3|0]+" "+f(i+64)
```
[Try it online!](https://tio.run/##NcexCsIwEADQXzkPxKQhJbbFQU3c3FwEp@IQ2kZPaiJpcZL8esTB6fEe9m2nLtJrlj70Q85OkzZkzFodELd4PF@wZaRTInmy872M1vfhyXiRZFoQX9YfdRUIqwpbKup/UThGYtPw7EJkHjSoHXjYQ/VTCA5d8FMYh3IMN@YY5/kL "JavaScript (Node.js) – Try It Online")
Or [run a consistency check](https://tio.run/##TY9fT8IwFMXf@RSXJoSWuW4DJMa5@SRvxsTEp7mHOjpWBitpb/yH7KvPzoDap3Nuz7n9dSNehS2M2qPf6JXsujJRSarSNApvCbkmy8cnklGVtK3y7wVW3IhmpXeUTVq/HSo2mn2FuUdgPCWZmszOlnglVd5izjqLAiGBwzEelNrQxukwhgZu4DLsj9Oex@AwADDSutuSstgZVVLn@VY2a6xgmMD8igFWRr8BsepTgjRGG3KKBpkDzTl/jgKO0mLfZb/5UhTSbd9LVKh086/aP7ETWFTnDcGaccd5J9zI0aTQ82c2d2B@e9KO7zh4eNnIAnktPyzt54xbbZD@teu@XejG6q3kW72m9QX8JLM6h@D0eyeiBUwgCkPGUS/Vu1zRKQMPxqMxY3H3DQ) on 500,000 calls
### How?
We start with \$i=0\$. [1]
At each iteration, we add to \$i\$ a random float in \$\left[0,3\right[\$ if \$i=0\$ (3 possible choices) or in \$\left[0,2\right[\$ if \$i\neq 0\$ (only 2 possible choices).
We use \$\lfloor i\bmod 3 \rfloor\$ as the index of the face character and \$\lfloor (3\times i)\bmod 3 \rfloor\$ as the index of the direction character.
After each iteration[1], we update \$i\$ to \$\lfloor i+64 \rfloor\$ in order to:
* get rid of the decimal part whose only purpose was to to choose a direction character
* make sure that we won't pick the same face character twice in a row (because \$64 \bmod3=1\$)
* be able to know that we've processed 16 iterations by testing if \$i\$ is greater than or equal to \$1024\$, because we add at least \$16\times64=1024\$ to \$i\$ (and at most \$16\times65+1=1041\$)
---
*[1] in order to save a few bytes, we actually start with \$i\$ undefined, coerce it to a number at the very beginning of an iteration, and add \$64\$ at the end.*
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/index.html), 41 bytes
```
16,{;'FRU'[a]-.,rand=:a" '2"3rand=32}%""+
```
[Try It Online!](https://tio.run/##S8/PSStOLsosKPn/39BMp9pa3S0oVD06MVZXT6coMS/F1ipRSUHdSMkYzDE2qlVVUtL@/x8A)
### Explanation
```
16,{;'FRU'[a]-.,rand=:a" 'r"3rand=32}%""+
16, // push the list [0..15]
{ // begin code block
; // remove the element already in the list
'FRU'[a]- // remove the previous value of a from the possible choices
(initially, [a] evaluates to an empty list as a is undefined)
.,rand= // push the length of the string, and index the string to a
random integer in this range
:a // set a to this value for the next iteration
" 'r" // push " 'r"
3rand= // index the string to a random position
32} // push the ASCII value for ' ', and end the block
% // map the block over the list [0..15]
""+ // convert the resulting list of ASCII values into a string
// the string is output implicitly
```
[Answer]
# [Haskell](https://www.haskell.org/), 114 bytes
```
(' '?16!!)<$>randomRIO(0,9*6^15-1)
_?0=[""]
c?n=[m:d:' ':r|m<-"RUL",m/=c,d<-" '2",r<-m?(n-1)]
import System.Random
```
[Try it online!](https://tio.run/##ZY1BC4IwGEDv@xU6AjW20iAhce4cBIHRySzG1JL85pi7BP32lnTt@B483kNMz3YYXA96NNY7vSbbwqoUqhkBdeziwsALeJL6fpQvCvPz5f4YxmS3TK/JliYRuvGYVRjXSHLFKsiabG4y84ac4vJ8wATWTJJmJi/YYGJyCjxUc1kjSv@3DkSvWFcUTJteWfeR3SDuk6NS6y8 "Haskell – Try It Online") (times out for obvious reasons, you can test it out [here](https://tio.run/##ZY1PC4IwHEDv@xQ6AjW2sg79EefOQRAsOqnFmFqSvzmml6DP3pKuHd@Dx3vI4Vl3nWvB9Hb0zq9hrGEhpK56QA0rXBh4Ad/5fpTOMvvT4nAKY7Kfb65buorQjccsx7hEimuWQ1IlU5HYN6QUi8sRE1gyRaqJvGCNiU0p8FBPZYko/Z86kK1mTZYxY1s9uo9qOnkfHFXGfAE "Haskell – Try It Online") with 8 moves).
The relevant "function" is `(' '?16!!)<$>randomRIO(0,9*6^15-1)`, an `IO String` object "containing" a random sequence of moves.
As always, solving [random](/questions/tagged/random "show questions tagged 'random'") challenges in Haskell is a great idea.
## How?
```
_?0=[""]
c?n=[m:d:' ':r|m<-"RUL",m/=c,d<-" '2",r<-m?(n-1)]
```
(?) is a pure function taking a character `c` and an integer `n` as input and returning the list of all valid sequences of moves of length `n` such that the first move is not `c`.
---
```
(' '?16!!)<$>randomRIO(0,9*6^15-1)
```
`randomRIO(0,9*6^15-1)` generates a random integer in the range `(0,9*6^15-1)`; incidentally, `9*6^15` is exactly the number of valid sequences of length 16. Then with `(' '?16!!)<$>` we use this random integer to index into `' '?16`, which is the list of valid sequences of length 16.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~20~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Would be [17](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=R8Y9IiAnMiLvYGaoYGtVKfY&footer=rtR1) if we could output the pairs reversed and in lowercase.
```
GÆ="RUF"kU ï" '2" ö
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=R8Y9IlJVRiJrVSDvIiAnMiIg9g) or [run it 100 times](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=R8Y9IlJVRiJrVSDvIiAnMiIg9g&footer=uA&input=MTAwCi1tUg)
or [verify that the same move isn't used twice in a row over 100 runs](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=R8Y9IlJVRiJrVSDvIiAnMiIg9g&footer=bc7lwCC4&input=MTAwCi1tUg)
```
GÆ="RUF"kU ï" '2" ö
G :16
Æ :Map the range [0,G)
= : Assign to variable U (initially 0)
"RUF" : String literal
kU : Remove characters in U
ï" '2" : Cartesian product with " '2"
ö : Random element of resulting array
:Implicit output joined with spaces
```
[Answer]
# JavaScript, ~~101~~ ~~99~~ 91 bytes
```
f=(i=s=17,m=Math.random)=>--i?'URF'[s=(s>3?m()*3:s+1+m()*2)%3|0]+" '2"[m()*3|0]+' '+f(i):''
```
[Try it online.](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYj07bY1tBcJ9fWN7EkQ68oMS8lP1fT1k5XN9NePTTITT262Faj2M7YPldDU8vYqljbUBvEMtJUNa4xiNVWUlA3UooGy4G46grq2mkamZpW6ur/k/PzivNzUvVy8tM10jQ0Nf8DAA)
## Explanation
We start with `i` and `s` both set to 17, then each iteration, if subtracting one from `i` yields a positive integer, we get the face character using a simple ternary and add a random direction character and then add a recursive call to `f` with the newly decremented `i`, and otherwise we simply return an empty string.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 63 61 bytes
```
"$(1..16|%{($l='R','U','F'-ne$l|random)+("'",' ',2|random)})"
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyflvqKdnaGBQo1r9X0lFA8QxA7I1VHJs1YPUddRDgdhNXTcvVSWnpigxLyU/V1NbQ0ldSUddQV3HCCZUq6n0v/Y/AA "PowerShell – Try It Online")
Technically, a 60-byte solution works by using an empty string rather than a space to the second random selection; however, an error is thrown each time the empty element is selected.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
“FUR“ '2”Wẋ⁴ŻṖḟ@"X€ɗ\ḊK
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//4oCcRlVS4oCcICcy4oCdV@G6i@KBtMW74bmW4bifQCJY4oKsyZdc4biKS/// "Jelly – Try It Online")
A full program that prints a 16-long scramble.
## Explanation
```
“FUR“ '2” | ["FUR"," '2"]
W | Wrap in a further list
ẋ⁴ | Repeat 16 times
Ż | Prepend a zero
ɗ\ | Reduce using the following as a dyad, keeping intermediate values:
Ṗ | - Remove last item
ḟ@" | - Filter out this from the next incoming copy of the list (but because of the Ṗ and ", this will only affect the FUR part)
X€ | - Randomly pick a value for each
Ḋ | Remove the first value (the zero)
K | Separate with spaces
| (Implicitly) print
```
[Answer]
# [J](http://jsoftware.com/), 46 bytes
```
3 :0
,'URF 2'''{~3(,3,~?@3-3:)@|+/\1+?3,15$2
)
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprv4/zdbKWMHKgEtHPTTITcFIXV29us5YQ8dYp87ewVjX2ErToUZbP8ZQ295Yx9BUxYhL87@fk55CSWJyZomCrq6uQrQVHp1ABlCzg46htqGpvYOKkRVXanJGvkKaAtBiAA "J – Try It Online")
Surprisingly verbose.
The only part of this I liked was the code to pick the random faces:
```
3|+/\1+?3,15$2
```
Here we create the 16 element list:
```
3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
```
Then "roll" `?` for each element (so pick randomly among `0 1 2` for the first element, and among `0 1` for the second), then scan sum the result `+/\`, then mod by 3 `3|`.
## tacit version, also 46
```
[:,'URF 2'''{~3(,3,~?@3-3:)@|?@3+/\@,1+15?@$2:
```
But I think the explicit version is easier to read, since if you discount the boilerplate `3 :0` and `)` it is effectively fewer bytes.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 54 bytes
```
(<F R U>.roll(*).squish Z~"2' ".comb.roll(*))[^16].put
```
[Try it online!](https://tio.run/##K0gtyjH7/1/Dxk0hSCHUTq8oPydHQ0tTr7iwNLM4QyGqTslIXUFJLzk/NwkmpxkdZ2gWq1dQWvL/PwA "Perl 6 – Try It Online")
* Uses [`squish`](https://docs.raku.org/routine/squish) to get rid of consecutive face repeats
* `Z~` metaoperator zips the two lists, then concatenates the resulting pairs
* `comb` makes light work of the literal space requirement
---
While golfing I found other interesting Raku features that are worth highlighting:
### Alternative, 86 bytes
```
((<F R U>.roll,{{:F<R U>,:R<F U>,:U<F R>}{$_}.roll}…*)Z~"2' ".comb.roll(*))[^16].put
```
[Try it online!](https://tio.run/##K0gtyjH7/19Dw8ZNIUgh1E6vKD8nR6e62srNBsTVsQoCSoDoUJACu9pqlfhasJraRw3LtDSj6pSM1BWU9JLzc5PAwhpamprRcYZmsXoFpSX//wMA "Perl 6 – Try It Online")
* Compact [pair literal](https://docs.raku.org/language/syntax#Pair_literals) syntax within sequence generator to determine valid next cube face
### Alternative, 94 bytes
```
my@m=<F R U>;((@m.roll,{%(@m.map:{$_=>(@m∖$_)}){$_}.roll}…*)Z~"2' ".comb.roll(*))[^16].put
```
[Try it online!](https://tio.run/##K0gtyjH7/z@30iHX1sZNIUgh1M5aQ8MhV68oPydHp1oVxMxNLLCqVom3tQNyHnVMU4nXrNUE8mvBamofNSzT0oyqUzJSV1DSS87PTQILa2hpakbHGZrF6hWUlvz/DwA "Perl 6 – Try It Online")
* Uses [set difference](https://docs.raku.org/language/setbagmix#infix_(-),_infix_%E2%88%96) operator to exclude key from `@m` when creating key-value pairs
[Answer]
# Java, ~~157~~ 151 bytes
```
$->{for(char i=16,c=0,j=3;i-->0;j=2)System.out.format("%c%c ",c="URF".replace(c+"","").charAt(j*=Math.random())," '2".charAt((int)(Math.random()*3)));}
```
*Saved 6 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210).*
[Try it online!](https://tio.run/##VY9BSwMxFITP3V8RgsWk7obagpc1CyJ468Wil@Lhmd1tE7NJSV4KsuxvX6Powbk8mPnewBi4QGXaj/mc3q1WRFmIkexAOzIWJOvXjwiYz8Xrlgw5ZXsM2h0PbwTCMfKxWJjcJBJqK/rkFGrvxKN3MQ1duH/Nb00v56uqGXsfmDpBIFre3pVKrksjt7WuqmZdG7nh@8@I3SB8QpHRAZDRpVoqQjNLX56fqAjd2YLqmLqhtKSUi@@6B2RmJXeAJxHAtX5gnJeUXG/oX8y0Q87@East57ye5rpY9AKU6s7IXLKW1z/bp2KavwA)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~107 106 116 108 105~~ 104 bytes
Basic randoms
-1 bytes to @qwr's space
-1 bytes to @razetime's space
+11 bytes to randomize starting n
-8 bytes by applying new loop method and skipping `' '.join()` and also defining `r` to `randint`
-3 bytes by spliting lines and removing some brackets and rearranging.
-1 byte by changing loop mathod to `exec`.
```
from random import*
r=randint;n=r(0,2)
exec("print('RFU'[(n:=n+r(1,2))%3]+choice('\\' 2'),end=' ');"*16)
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P60oP1ehKDEvBUhl5hbkF5VocRXZggQy80qs82yLNAx0jDS5UitSkzWUCoqAghrqQW6h6tEaeVa2edpFGoZAaU1V41jt5Iz8zORUDfWYGHUFI3VNndS8FFt1BXVNayUtQzPN//8B "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 83 bytes
```
f=(p='',g=s=>s[0][Math.random()*3|0],a=g`URF`)=>p[47]?p:f(p[0]==a?p:a+g` '2`+' '+p)
```
[Try it online!](https://tio.run/##Dcq9DsIgFEDhV2EDpDb4k5hUb93cXEycSBNu2oKYCgQaJ98dWU6@4bzxi3lMLq5bH6a5FAMsAqWNhQx9VnJQd1xfbUI/hQ/jm8NPDg2C1c/HTXPoozqehmvsDIt1BsBqFFYTuteCEioiLyYkwhzIs7vsaoTgZAw@h2Vul2CZYZyXPw "JavaScript (Node.js) – Try It Online")
* -4 bytes by [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
] |
[Question]
[
Recently I had a Maths test and noticed that a certain number on the test matched an interesting pattern. The number (`28384`) matched a generic digit sequence that looks like this
```
(n)(x)(n+1)(x)(n+2)(x)(n+3) etc...
```
where `n` and `x` are single digit integers. The sequence can begin with either `x` or `n` and end with either `x` or `n+y`.
Your task is, given a multi digit positive integer, output a truthy or falsey value, depending on whether the input matches the pattern. The input will be between 4 and 18 digits long. You may take input as a string representation of the integer. The input will not begin with a 0 but can contain or end with 0s.
`n+y` will always be a single digit number (hence why the length limit is 18).
# Test Cases
These should output a truthy value
```
182838485868788898
4344
85868
12223242526
```
And these should be falsey
```
12345
6724013635
36842478324836
1222232425
5859510511
```
As with all code golfs, shortest code wins! Good luck and may the odds, be ever in your favour!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~84~~ ~~81~~ ~~80~~ 79 bytes
*-1 byte thanks to ovs*
```
lambda x:g(x,1)|g(x,0)
g=lambda x,a:len(set(x[a::2]))==(x[a<1::2]in"123456789")
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKl2jQsdQswZEGWhypdvCJHQSrXJS8zSKU0s0KqITrayMYjU1bW1BbBtDEC8zT8nQyNjE1MzcwlJJ839BUWZeiUKahpKJhamFmQVQBAA "Python 2 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), ~~82~~ ~~79~~ ~~78~~ 77 bytes
```
lambda x:g(x,1)|g(x,0)
g=lambda x,a:len({*x[a::2]})==(x[a<1::2]in"123456789")
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKl2jQsdQswZEGWhypdvCJHQSrXJS8zSqtSqiE62sjGJrNW1tNYBsG0MQLzNPydDI2MTUzNzCUknzf0FRZl6JRpqGkomFqYWZhZKm5n8A "Python 3 – Try It Online")
Slightly shorter in Python 3, but I didn't think it deserved its own answer.
---
# Explanation
We set up a function `g` that takes string and an index (either 1 or 0). `g` then returns whether or not `len(set(x[a::2]))`, that is the number of unique digits in every other position, is equal to `(x[a==0::2]in"123456789")`, whether or not the other digits are in ascending order. If the digits are in ascending order this returns whether or not they are all the same, if not it will ask if the set is empty, which it cannot be, thus always returning false.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 11 bytes
```
Ds2ZI’M¦Ẏ¬Ạ
```
[Try it online!](https://tio.run/##AS8A0P9qZWxsef//RHMyWknigJlNwqbhuo7CrOG6oP///zE4MjgzODQ4NTg2ODc4ODg5OA "Jelly – Try It Online")
Explanation:
```
Ds2ZI’M¦Ẏ¬Ạ Accepts an integer
D Get individual digits
2 2
s Split into chunks of specific length
Z Zip
I Take deltas
’ Decrement
M Take maximal indices
¦ Apply at specific indices
Ẏ Reduce dimensionality
¬ Vectorized NOT
Ạ Check if all are truthy
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
TG9LNýN.øŒ})˜Iå
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/xN3Sx@/wXj@9wzuOTqrVPD3H8/DS//8NLYwsjC1MLEwtzCzMLSwsLC0A "05AB1E – Try It Online")
### Explanation
```
TG9LNýN.øŒ})˜Iå
TG } # For 1 to 9...
9L # Push [1 .. 9]
Ný # Join with current value
N.ø # surround with current value
Œ # Push substrings
) # Wrap stack to array
˜ # Deep flatten the array
I # Push input
å # Is the input in the array?
# Implicit print
```
It should work (test cases did) but if you find any flaws please let me know.
14 Bytes if no output counts as falsy:
```
TG9LNýN.øŒIåi1
```
[Answer]
## D, 117 bytes
```
int f(string n){int o=n[0]!=n[2],x=n[o];foreach(i,c;n){if(i%2!=o&&i>1&&c!=n[i-2]+1||i%2==o&&c!=x)return 0;}return 1;}
```
Definitely suboptimal, but it works fine
[Try It Online!](https://tio.run/##NVDtboMwDPzPU7iRQKCxCZIQ3EZsD4L4UfHRRaLJBGzr1PLsLIFiKfGdfU4uaZZFXb/MMME4NW92KSM9T@kJunCcBqUvoKO746bQZVId7E6r@GaTqWRnhvZcf4YqrqWTdaHy6aEwQaDe0yConVq90uolfTxsp3AdW7xFQzt9DxoSOT9RKmfP@zGqgetZ6TCCuwc2NgtlBT0UUJIUKTLkmKHAHBGPSGIgnHHu8lp2IKWUMsppRsVGGc8cEDnlScoEWxkTyCnP0SqRiX1uG1zZftlRkEqudp7vhVBL6HePLn4HNbVdr0PijyfwRzuvY/uFOoIPIH/tSOAERBsSbQfN3rws/w)
[Answer]
# Haskell, ~~108~~ ~~113~~ ~~97~~ 95 bytes
```
d(x:_:r)=x:d r
d r=r
c(x:n:r)=and$all(==x)(d r):zipWith(==)(d$n:r)[n..]
f s@(_:n:_)=c s||c(n:s)
```
Sample call: `f "182838485868788898"` yields `True`
Ungolfed version with explanations:
```
-- Take every other element from the string, starting with the first
d (x:_:r) = x : d r
d r = r
c (x:n:r) = and $ all (== x) (d r) -- Every other char is equal to the first
: zipWith (==) (d $ n:r) [n..] -- The remaining chars are a prefix of n(n+1)(n+2)...
f s@(_:n:_) = c s -- The case where s already starts with x
|| c (n:s) -- If not, prepend a dummy x and try again
```
[Answer]
## JavaScript (ES6), ~~66~~ ~~63~~ 60 bytes
Takes input as a string.
```
s=>[...s].every((d,i)=>d-s[j^(k=i+j&1)]==k*i>>1,j=s[2]-s[0])
```
### Test cases
```
let f =
s=>[...s].every((d,i)=>d-s[j^(k=i+j&1)]==k*i>>1,j=s[2]-s[0])
console.log('[Truthy]');
console.log(f("182838485868788898"))
console.log(f("4344"))
console.log(f("85868"))
console.log(f("12223242526"))
console.log('[Falsy]');
console.log(f("12345"))
console.log(f("6724013635"))
console.log(f("36842478324836"))
console.log(f("1222232425"))
```
[Answer]
# C (gcc), 123 bytes
```
#define X*s&&*s++-++n&&(r=0)
t,n,x,r;f(char*s){t=*s==s[2];for(r=1,n=s[t],x=s[!t],s+=2;*s;)t||X,*s&&*s++-x&&(r=0),t&&X;n=r;}
```
[Try it online!](https://tio.run/##fY5LbsMwDET3PoXqooL1CRBTssxC0D0MtFkETpx6USWQtDCQ5Oyu4H5WjbkZkvMwZL859f08Px@Ow@iPpOORUh6F2AjhKa2C27IiSS8nGexQ9R/7wCO7Jsejc/ENdnY4h0zV0ucx7eSU5SlrFA4sj5al262Tf6nTT6ZMlHbWu2Dv8@gT@dyPvmLFtSC5LiGvhqp8Obz7UpLc1QioUGODBltEfMWSMfsA1krrFXsJWfFrAFCgoQGzUA8xpZuVGNOC3tbKqDVIGdSgW8z3UJl/wIyR36e@v1qg@/wF)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~99 96~~ 89 bytes
* Saved 3 bytes: use of `all()` function
* @WheatWizard saved 7 bytes:shorthanding `&` `|` and replace extra variable by `k<1`
```
lambda x,g=lambda x,k:(x[k<1::2]in'123456789')&all(j==x[k]for j in x[k::2]):g(x,0)|g(x,1)
```
[Try it online!](https://tio.run/##ZY7LCoNADEX3/QpxUWfAhZPEMQ6dL2ldWIrWR1XEhYX@ux1bEGxXSc69HDI8p3vf4VLYy9Lmj@st9@awtNvaGDGfm5MyBrKqCxQgxTrhNJDHvG1Fba2Ls6IfvdqrOs8da1OaUsxhJF/rUHIZxqqbRCF8xcDIxDFrTpg5ZV/KwxYTEu3Ap7gjCgAQCGLQP9x9tiM6AYoUatxj1ExACTsJo/5zf@UOL28 "Python 3 – Try It Online")
Explanation:
First split the string into two lists: one with odd-indexed and other with even-indexed elements. The two lists A and B are supposed be such that either:
1. A contains same number and B contains consecutive numbers in ascending order.
OR just the opposite
2. B contains same number and A contains consecutive numbers in ascending order.
The consecutive condition is checked by: `a in '123456789'`
The same-number condition is checked by: `all(i=a[x] for i in a)`
[Answer]
# [PHP](https://php.net/), 68 bytes
```
for(;$v<10;)$s.=strstr(+$v.join(+$v,range(1,9)).+$v++,$argn);echo$s;
```
[Try it online!](https://tio.run/##HYxBDoMgFAX3HsP8BQRCpLb6zNd4FtOotAsg0Hh9qiazmNlMdLGMc3SxoiXtfqotHmjxxAsdegADai5bSILpGG3DkrKZ8i@dCEWH@YaPv0Snxe@rsHqQ0pytlL6Pkte3C5S5lD8 "PHP – Try It Online")
Output part of search string starting from and including the first occurrence of input to the end of search string as truthy value and nothing for falsy
for 2 Bytes more you can replace `echo$s;` with `!!echo$s;` to get `1` as truthy value
Find the occurrence of the input in one of the following strings in the array
```
Array
(
[0] => 0102030405060708090
[1] => 1112131415161718191
[2] => 2122232425262728292
[3] => 3132333435363738393
[4] => 4142434445464748494
[5] => 5152535455565758595
[6] => 6162636465666768696
[7] => 7172737475767778797
[8] => 8182838485868788898
[9] => 9192939495969798999
)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
2L&),duw]hSFTX=
```
[Try it online!](https://tio.run/##LYurDsJQEEQ9H8JNE0R39nGnoo6g6qioIYEEgQAH4fMvS0GdnMmcx@V5b@eGadvtrq/36XY8zMvYlv3cihBUGp3BSnJg2RRTs8Q6JgWAwuCI1dQ8GRXWi4Z@RYMGq8wbNf7NL0px@uDSu0j5AA "MATL – Try It Online")
With some help of @LuisMendo in chat. Note that, if empty output + error is also considered 'falsy', the `X` can be left out, bringing the score to **14 bytes**.
```
2L&) % Split the input into odd and even-indexed elements
, ] % Do twice (new feature since MATL v20.0), i.e., on both halves of the input
d % Pairwise differences of the array. Results in [0,0,...] for the 'constant' part,
% and [1,1,...] for the 'increasing' part.
u % Get unique elements. Results in [0] for the constant part, [1] for the increasing part.
w % Swap the stack to do the same for the other half of the input.
hS % Horizontal concatenation followed by sort. Results in [0,1] for the desired string.
FTX= % Check if the result is indeed [0,1]. Implicit display.
```
[Answer]
## JavaScript (ES6), 54 bytes
```
f=
s=>[...s].every((e,i)=>i<2|e-s[i-2]==(s[2]!=s[0]^i%2))
```
```
<input oninput=o.textContent=this.value[3]?f(this.value):``><pre id=o>
```
Takes input as a string.
[Answer]
# [Julia](https://julialang.org), ~~57~~ 56 bytes
```
~s=(!x=occursin(s,join(x*k for k='0':'9')x);!s[1]|!s[2])
```
* replace `||` by `|` by @MarcMush
[Attempt This Online!](https://ato.pxeger.com/run?1=VVBLTsMwFFzjU7hhkQYFKX7-PYMicQBuUGURlURNG2IpdqQgIS7Cppveid4GOwEkNp43o_HMsz8vx6nv6vP1y4-TP7yVO5IwBOQoUKJCjYgGk5wkggsRcZHjwACAgwAJKlJdaKZBcy201EonOb2lzr421LbUH5ow95Pv7OBoW3c9tUNQO0cq0ta9W3uBCxmjlAZRMK74wrhCAUJj6EKufpvX6sgkSiNZIRmLzDADhhthpFnWrC6Tb-_xih-u3G7m0u730-i6Yevyow0w351oa0d6KtMifUhNms3Z48btWPUeTqiyn_vP0eRoF9ZePorcPNXONaOnIbgMWkOa4YWQP9vyrP-uKC22NfN8XvEb)
* input: the number as decimal string
[Answer]
# Mathematica, 121 bytes
```
(m[x_]:=Take[s=IntegerDigits@#,{x,Length@s,2}];w[b_,n_]:=Union@Differences@m@b=={1}&&Length@Union@m@n==1;w[1,2]||w[2,1])&
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
```
ASm.+sMd.Tcz2&-GZ-H1
```
Output `[]` when the number matches the digit pattern, anything else otherwise.
[Try it online!](https://pyth.herokuapp.com/?code=ASm.%2BsMd.Tcz2%26-GZ-H1&input=12223242526&debug=0)
**Explanations** (example with input `85868`)
```
ASm.+sMd.Tcz2&-GZ-H1
cz2 # Chop the input in pairs: ['85', '86', '8']
.T # Transpose, ignore absences: ['888', '56']
sM # Convert to integers: [[8, 8, 8], [5, 6]]
m.+ d # Compute deltas: [[0, 0], [1]]
S # Sort: [[0, 0], [1]]
A # Assign first list to G and second list to H
-GZ # Filter 0 on G (on absence): [0, 0] -> []
-H1 # Filter 1 on H (on absence): [1] -> []
& # Check both lists are empty (logical and): [] & [] -> []
```
[Answer]
# Pyth, 17 bytes
```
qU2Ssm{.+d.TcjQT2
```
[Try it here](http://pyth.herokuapp.com/?code=qU2Ssm%7B.%2Bd.TcjQT2&test_suite=1&test_suite_input=182838485868788898%0A4344%0A85868%0A12223242526%0A12345%0A6724013635%0A36842478324836%0A1222232425%0A5859510511&debug=0)
Same algorithm as my Jelly answer.
Explanation:
```
qU2Ssm{.+d.TcjQT2 Accepts an integer
jQT Take digits of input
c 2 Split in pairs
.T Transpose
m Map the following on each of the two resulting lists:
.+d Take deltas
{ Deduplicate
s The list is now in [[a, b, ...], [A, B, ...]] format, convert it to [a, b, ..., A, B, ...]
S Sort
qU2 Check if equal to [0, 1]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~167 161 157 131~~ 106 bytes
*-55 bytes thanks to @WheatWizard's suggestions*
```
def g(t):k,c,f,j=t[::2],t[1::2],'123456789',''.join;return(len({*k})and j(c)in f)or(len({*c})and j(k)in f)
```
[Try it online!](https://tio.run/##NclBDsIgFEXRrXQGmB9TiqWIcSWNA0OhAubTEBwY49qxsTp6N@8sz3JLKGqdrGtmWpiOYMBBOJdR6@4CZeTfJbwTh14O6kiAkH1IHk/ZlkdGerdIX7v4ZlecmkAN89g4lvIPzB/iBnXJHgudKRFSDEIRBmvzlrdbqV7J9WT1Aw "Python 3 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~128~~ ~~119~~ ~~118~~ ~~108~~ ~~107~~ 104 bytes
```
s->{int i=3,a=s[2]-s[0],b=s[3]-s[1];for(;++i<s.length;)a+=b-(b=s[i]-s[i-2]==a?a:2);return(a|b)==1&a!=b;}
```
[Try it online!](https://tio.run/##VVFRb4IwEH73V9xIXCACkbZgFeuy7HnJEh8NDwVB67CQtpgY5293gE5dk/buvvt6ve@64wfuVXUud@vvi9jXlTKwazG/MaL0i0ZmRlTS/1L5WmTc5PGgbtJSZJCVXGv45ELCaQBwQ7XhpjWHSqxh3@bspVFCblYJcLXRTk8FuFebZ1uuVskCCmAX7S1OQhoQDLuc6RVKPL0aJ27a@rjzgyQuKmXHo5GYa7/M5cZsY4ePWOrZHUl0JOGhhDH@xmfIiVVuGiVt/pM6jAWv/IWl8fkC/Yr7Vu79mVwbDezWIYAVUEQxJTSkEZ1QSqfUcv9yBBPyiHrKIwwQQhgRFKLoGcQkfITRBJFxgCP8hOGIEkQmtL1LcfS/3rXgAwtpOA2DcRgEVg@dr2ra8cBt5L2g2VWWc1e1PGqT7/2qMX7dskxhW0MPjfUMhnooLbfnu1D4nbW7wzfVR/tJ70rxo@04zvWh86Db58sv "Java (OpenJDK 8) – Try It Online")
# Explanation:
```
s->{ // lambda
int i=3, // iterating index
a=s[2]-s[0], // diff of even-indexed characters
b=s[3]-s[1]; // diff of odd-indexed characters
for(;++i<s.length;) // iterate
a+=b-(b= // swap a and b
s[i]-s[i-2]==a?a:2 // or set b to 2 if the diffs don't match
)); //
return (a|b)==1 // return true if both a and b are in (0,1)
&a!=b; // but different
}
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 47 bytes
```
.
$*11;
(1+)(?<=\1;1+;\1)
^1+;1+
^;?(;1;)+;?$
```
[Try it online!](https://tio.run/##DcY7CoAwEAXAfs@RInFBfH6frJKLBMHCwsZCvP@aaua9vvs53VsJDWASoSnmbS8wqBUkkaMGWrUcDZbUcnBnR7DnwJETZy4k1x8 "Retina – Try It Online")
Outputs 1 if it matches the pattern, 0 if it does not
### Explanation
```
.
$*11;
```
Convert each digit n to n+1 in unary, separated by semicolons
```
(1+)(?<=\1;1+;\1)
```
(Trailing newline) converts each digit to the difference between itself and the one 2 spots before it
```
^1+;1+
```
(Trailing newline) removes the first 2 digits
```
^;?(;1;)+;?$
```
Counts the number of matches of this pattern, which checks for alternating 0s and 1s
[Answer]
# [Husk](https://github.com/barbuz/Husk), 19 bytes
```
S¤|o←Ẋ~&Λȯ¬→-E↔TC2d
```
[Try it online!](https://tio.run/##JcqtCgJBGEbhuzGNsN/vvJvFK9AmNoMgYhCbCBombBKxWY2C3bjJ5D04NzIuazscnuVuuyrrfDqWSXvfb3I6f1/NYfC5vZ/tI6fLcJzTdTriRSllRmAIFAZHBFAjqKiGfgRiZmFlY@9a1IJH1orExYI4lDWiAxDv7R8Hg9VGlRHNfw "Husk – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
y"v¯vUfsk≈⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwieVwidsKvdlVmc2viiYjigbwiLCIiLCIxODI4Mzg0ODU4Njg3ODg4OThcbjQzNDRcbjg1ODY4XG4xMjIyMzI0MjUyNlxuMTIzNDVcbjY3MjQwMTM2MzVcbjM2ODQyNDc4MzI0ODM2XG4xMjIyMjMyNDI1XG41ODU5NTEwNTExIl0=)
] |
[Question]
[
The *minimal power iteration* of a number \$n\$ is defined as follows:
$$\text{MPI}(n):=n^{\text{min}(\text{digits}(n))}$$
That is, \$n\$ raised to the lowest digit in \$n\$. For example, \$\text{MPI}(32)=32^2=1024\$ and \$\text{MPI}(1234)=1234^1=1234\$.
The *minimal power root* of a number \$n\$ is defined as the number obtained from repeatedly applying \$\text{MPI}\$ until a fixed point is found. Here is a table of the minimal power roots of numbers between 1 and 25:
```
n MPR(n)
--------------------------
1 1
2 1
3 531441
4 1
5 3125
6 4738381338321616896
7 1
8 16777216
9 1
10 1
11 11
12 12
13 13
14 14
15 15
16 16
17 17
18 18
19 19
20 1
21 21
22 1
23 279841
24 1
25 1
```
**Challenge:** Generate the numbers whose minimal power root is not equal to 1 or itself.
Here are the first 50 numbers in this sequence:
>
> 3, 5, 6, 8, 23, 26, 27, 29, 35, 36, 39, 42, 47, 53, 59, 64, 72, 76, 78, 82, 83, 84, 92, 222, 223, 227, 228, 229, 233, 237, 239, 254, 263, 267, 268, 269, 273, 276, 277, 278, 279, 285, 286, 287, 289, 296, 335, 338, 339, 342
>
>
>
## Rules
* You may generate the first `n` numbers of this sequence (0- or 1-indexed), generate the `n`th term, create a generator which calculates these terms, output infinitely many of them, etc.
* You may take input and give output in any base, but the calculations for MPR must be in base 10. E.g., you may take input `###` (in unary) and output `### ##### ######` (in unary)
* You **must** yield numbers. You may not (e.g.) output `"3", "5", "6"`, since those are strings. `3, 5, 6` and `3 5 6` are both valid, however. Outputting `2 3`, `"23"`, or `twenty-three` are all considered invalid representations of the number `23`. (Again, you may use any base to represent these numbers.)
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code (in bytes) wins.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes
```
{grep {($_,{$_**.comb.min}...*==*).tail>$_},1..*}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Or0otUChWkMlXqdaJV5LSy85PzdJLzczr1ZPT0/L1lZLU68kMTPHTiW@VscQKFL7vzixUiFNQzM6ztQg9j8A "Perl 6 – Try It Online")
Returns an infinite sequence. I suppose that the following 45 byte version works, too, but I can't prove that the fixed point is always found after n iterations.
```
{grep {($_,{$_**.comb.min}...*)[$_]>$_},3..*}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Generates the **nth** number **1**-indexed
```
µNÐΔWm}‹
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0Fa/wxPOTQnPrX3UsPP/f0MjAA "05AB1E – Try It Online")
**Explanation**
```
µ # run until counter equals input
NÐ # push 3 copies of the current iteration index (1-based)
Δ } # run this code until the result no longer changes
Wm # raise the number to the power of its minimum digit
‹ # check if greater than the index
```
Optionally as an infinite list at the same byte count:
```
∞ʒDΔWm}‹
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5Nczk0Jz6191LDz/39DIwA "05AB1E – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~41~~ ~~39~~ 37 bytes
```
(>:[echo^:(<(^0".@{/:~@":)^:_))^:_]1x
```
[Try it online!](https://tio.run/##y/r/X8POKjo1OSM/zkrDRiPOQEnPoVrfqs5ByUozzipeE0TEGlb8/w8A "J – Try It Online")
This one is a full program printing the infinite sequence. A very rare occasion where a full program beats a verb in J.
### How it works
```
(>:[echo^:(<mpi_fix))^:_]1x Using the mpi_fix below; it finds the MPI fixpoint
(<mpi_fix) Is mpi_fix greater than the input?
echo^: If so, apply echo; do nothing otherwise
echo returns an empty array
>:[ Discard the above and return input+1
( )^:_ Repeat the above infinitely (increment has no fixpoint)
]1x starting from arbitrary-precision number 1
```
---
# [J](http://jsoftware.com/), ~~41~~ 39 bytes
```
>:^:(>:(^0".@{/:~@":)^:_)^:_@>:@]^:[&0x
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WuoKNQa6VgoADE/@2s4qw07Kw04gyU9Byq9a3qHJSsNOOs4kHYwc7KITbOKlrNoOK/Jldqcka@QpqStoKdlUKmnpHBfwA "J – Try It Online")
A monadic verb. Given a 1-based index, returns the number at that index. The footer checks that first 20 terms are correct.
Reading the word "fixpoint", I immediately thought "Oh yeah, `^:_` will do the great job." Then I ended up with this abomination of angry and sad faces. And it's not even a train, it's a *single verb*.
### Ungolfed & How it works
```
nth_term =: >:^:(>:(^0".@{/:~@":)^:_)^:_@>:@]^:[&0x
mpi =: ^0".@{/:~@": Find the MPI
/:~@": Sort the string representation
0 { Take first item
".@ Convert back to number
^ Raise the input to the power of above
mpi_fix =: mpi^:_ Find the MPI fixpoint
next_term =: >:^:(>:mpi_fix)^:_@>: Given a number, find the next term
@>: Increment once, and then...
>:mpi_fix Is mpi_fix not greater than input?
>:^: ^:_ Increment while the above is true
nth_term =: next_term@]^:[&0x Given one-based index, find the nth term
next_term@] Apply next_term monadically
^:[ n times
&0x to the starting value of zero
```
The arbitrary-precision integer `0x` is needed to compute the fixpoint accurately, e.g. of the number 6.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
```
.f>u^GshS`
```
[Try it online!](https://tio.run/##K6gsyfj/Xy/NrjTOvTgjOOH/f1MDAA "Pyth – Try It Online")
This generates a list of the first \$ n \$ such numbers. The auto-filled program has `GZZQ` as a suffix. This simply finds (`.f`) the first `Q` numbers that have a minimal power root `u^GshS`G` greater than itself `Z`.
The minimal power root code works by finding a fixed point `u` of raising the current number `G` to the power of it's minimal digit, which is the same as the first digit (`h`) sorted lexicographically (`S`), then converted back to an integer (`s`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
*DṂƊƬḊCȦµ#
```
A monadic Link taking an integer, `I`, from STDIN which yields the first `I` entries.
**[Try it online!](https://tio.run/##AR0A4v9qZWxsef//KkThuYLGisas4biKQ8imwrUj//81MA "Jelly – Try It Online")**
(`*DṂƊƬṪ%@µ#` works for 10 too)
### How?
Counts up starting a `n=0` until `input` truthy results of a monadic function are encountered and yields those `n`s.
The function repeatedly applies another monadic function starting with `x=n` and collects the values of `x` until the results are no longer unique. (e.g.: `19` yields `[19]`; `23` yields `[23,529,279841]`; `24` yields `[24, 576, 63403380965376, 1]`; etc...) and then dequeues the result (removes the leftmost value), complements all the values (`1-x`) and uses `Ȧ` to yield `0` when there is a zero in the list or if it's empty.
The innermost function raises the current `x` to *all* the digits of `x` and then keeps the minimum (doing this is a byte save over finding the minimum digit first).
```
*DṂƊƬḊCȦµ# - Link (call the input number I)
# - count up from 0 and yield the first I for which this yields a truthy value:
µ - a monadic chain:
Ƭ - collect until results are not unique:
Ɗ - last three links as a monad:
D - convert to a list of decimal digits
* - exponentiate
Ṃ - minimum
Ḋ - dequeue
C - compliment
Ȧ - any-and-all?
```
[Answer]
# Mathematica, ~~59~~ 51 bytes
*-8 bytes thanks to [Misha Lavrov](https://codegolf.stackexchange.com/users/74672).*
```
Select[Range@#,#<(#//.x_:>x^Min@IntegerDigits@x)&]&
```
Pure function. Takes a number as input, and returns the list of terms up to that number as output. Nothing very complicated here.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~90~~ 88 bytes
-2 bytes by @mypetlion
```
def F(x):m=x**int(min(str(x)));return[int,F][m>x](m)
x=1
while 1:x<F(x)and print(x);x+=1
```
[Try it online!](https://tio.run/##FcuxCoAgEADQ3a9w9KxF2iwb@4loCDQU8hIzur7ean3w0lP8gV2t1m18EgQ6GpIyYBExoDhL/gygz65cGefP22mZ40iLiMDIKHb7sDuuNA1/X9HylP9O0FNjVK0v "Python 3 – Try It Online")
`print` as an expression saves two bytes over using `if` statement in Python 2. `F` computes the MPI fixpoint; the rest gives the infinite sequence to STDOUT.
[Answer]
## Haskell, ~~67~~ 62 bytes
```
filter((<)<*>until((==)=<<g)g)[1..]
g a=a^read[minimum$show a]
```
Returns an infinite list.
[Try it online!](https://tio.run/##DcbBDsIgDADQu1/Rww5g4qIHb9Qf2WbSTGDNChJg8e@tvtPbqO1eRAPOGli6r8Y4686PI3cWYxAtOhdttNNtHJdTBEJ6Vk@vKXHmdKShbe8P0KKJOANCqZw7DNBp93C//hf0uwah2PSylvID "Haskell – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 52 bytes
```
x=1;loop{b=x+=1;1while b<b**=b.digits.min;b>x&&p(x)}
```
[Try it online!](https://tio.run/##KypNqvz/v8LW0DonP7@gOsm2QhvINizPyMxJVUiySdLSsk3SS8lMzywp1svNzLNOsqtQUyvQqNCs/f8fAA "Ruby – Try It Online")
Prints infinite sequence
[Answer]
# Java 10, ~~178~~ 173 bytes
```
v->{for(int x=1,m;;){var b=new java.math.BigInteger(++x+"");for(m=9;m>1;)b=b.pow(m=(b+"").chars().min().orElse(0)-48);if(b.compareTo(b.valueOf(x))>0)System.out.println(x);}}
```
Port of [*@GB*'s Ruby answer](https://codegolf.stackexchange.com/a/174029/52210), so also prints indefinitely.
[Try it online.](https://tio.run/##LZA9T8MwEIb3/opTJ1slVisxgKxkQGJgoAxFLIjBdp3UwR@R47hBUX57uECX@35191wrsija8/eirOh7eBXGTxsA45OOtVAajmsKkIM5gyIfq8uUY23eoOmTSEbBETyUsOSimuoQCaphLA93jnM6ZRFBll5focVdzIl0YU@mecENjY5ktxt32y3lq86Vj9xVB05lKVkXrlggcu0ydRGxJ5Q549GG@Gx7Tfa0uH@g3NREMhVcJ6J@DxhnYQf9VpOR0mpPTz990o6FIbEu4mXWY4PP88JXgG6QFgFuHH@UDn9ATglnm88vEPT/AZ4p4gdrb@zz8gs)
**Explanation:**
```
v->{ // Method with empty unused parameter and no return-type
for(int x=1, // Start an integer `x` at 1
m; // Temp integer for the smallest digit, starting uninitialized
;){ // Loop indefinitely
var b=new java.math.BigInteger(++x
// Increase `x` by 1 first
+""); // And create a BigInteger `b` for the new `x`
for(m=9; // Reset `m` to 9
m>1;) // Loop as long as the smallest digit is not 0 nor 1
b=b.pow(m=(b+"").chars().min().orElse(0)-48
// Set `m` to the smallest digit in `b`
); // Set `b` to `b` to the power of digit `m`
if(b.compareTo(b.valueOf(x))>0)
// If `b` is larger than `x`:
System.out.println(x);}}
// Print `x` with a trailing newline
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 75 bytes
Returns the \$n\$th term, 1-indexed.
```
f=(i,x=n=1n)=>(N=x**BigInt(Math.min(...x+'')))>x?f(i,N):(i-=N>n)?f(i,++n):n
```
[Try it online!](https://tio.run/##HYvBCoJAEEB/ZQ6BM24ueehijUG3DvkNLqY2YbOhEgvRt29Lt/fgvYd7u6Wb5bUW6m99jAOjbAMrl0pcY8Mhz88yXnTFq1vv9imK1tpgsoyI6nAaUt9QhVJwUyv93RilSuPgZxRgKA8gcGTY7xIYQ9B5XfzU28mP2DrcfORLqWvBQNqJ4g8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~98~~ ~~90~~ ~~89~~ 86 bytes
-3 bytes thanks @Conor O'Brien
```
function*(){for(n=0n;;x>n&&(yield n))for(x=++n;(b=Math.min(...""+x))-1;)x**=BigInt(b)}
```
[Try it online!](https://tio.run/##FcuxDoIwEIDh3ae4MJA7GhocnGod3Bx8iAIFa@BqSiU1xmevMH3Dn/9pVrN0wb1izb632WjMw5u76DxXSN/BB2TdsFLpwmWJH2enHphoD0kLwQpbfTfxIWfHKKUsCpGI6qOiVFX66sYbR2zplwlJHbYNcDUBHGho1MYZTrtCEHSeFz9ZOfkRjWSbIhLlPw "JavaScript (Node.js) – Try It Online")
Using the fact that \$MPR(n)>n\$ if \$MPR(n)\notin \{1,n\}\$
Seems that a generator is shorter than returning an array of `n` numbers?
Or printing infinitely - 72 bytes
```
for(n=0n;;x>n&&alert(n))for(x=++n;(b=Math.min(...""+x))-1;)x**=BigInt(b)
```
[Try it online!](https://tio.run/##HcoxDsIwDAXQu3So7Ea1YI7MwMbAIdISSlD4RmmEcvsgWJ/eM3zCvpb0rjPsFnvIsVRdDbvlKNm2frdC0AO8byeM4z8QmH/e1Dl4WvQa6kNeCSQiw@Aa83z03KZJz2m7oNLCvX8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~171~~ ~~153~~ 138 bytes
```
__int128 m,a,t,h,s;r(){for(a=10,h=s;a=fmin(h%10,a),h/=10;);a=pow(s,a);a-s&&r(s=a);}f(n){for(;t-n;a-1&&a-m&&printf("%lu ",m,t++))r(s=++m);}
```
Outputs the first `n` terms whose MPRs are representable within the largest "integer" type.
Brute-forces the solution but still works surprisingly fast.
Some things may be able to be inlined (such as `r`, which is only called once), but it may require a decent amount of effort.
See previous revision for solution without `-lm`.
*-18 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
*-15 bytes and ultra-precision thanks to [rtpax](https://codegolf.stackexchange.com/users/85545/rtpax)!*
[Try it online!](https://tio.run/##JY3BCsMgEETv@QoJRBRXmhQKBfFbwmIxBmIS1LaHkF@v3dI57cxjdpyenKt1HOe1DNc7i4BQIEA2ScjDb0mgHXoINhu0Ps6rCB15lBAuBIykeN/eIlNkUGfOk8iW7tOL9f/AFL0SGjhHHTnfE0150XbLk7UQoSgl5a@kVKRaJcoi0tBrmx@yORpG8uLWS9Oc9eP8glOueolf "C (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
λfge;Ẋ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%CE%BBfge%3B%E1%BA%8A&inputs=9&header=&footer=)
```
λ ;Ẋ # While result changes...
f # Convert to digitlist
g # Take minimum
e # Number to power of that
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
3*DṂ$$ÐLḟ1,$Ɗ#
```
[Try it online!](https://tio.run/##y0rNyan8/99Yy@XhziYVlcMTfB7umG@oo3KsS/n///@mBgA "Jelly – Try It Online")
[Answer]
# JavaScript (Chrome), ~~78~~ 77 bytes
```
F=x=>(m=x**BigInt(Math.min(...''+x)))>x?F(m):m
for(x=0n;++x;)x<F(x)&&alert(x)
```
[Try it online!](https://tio.run/##HczBCsIwDADQux@yJSsGz85M8FDYwY8os85K20hXRv6@ird3em@3u20p4VOPWR6@uehL5UXyJtFTlLVZVp4gsQ7DLaxzrnB39UUpZCCivjeKiJNeLSQ8p8NTCiif8miMjqgXC4pd929/au0L "JavaScript (Node.js) – Try It Online")
Port of [my own Python 3 solution](https://codegolf.stackexchange.com/a/174023/78410). The latest version of Chrome supports `BigInt` (tested on my PC). Don't try this code as-is on your browser though.
[Answer]
# [Racket](https://racket-lang.org/), 270, 257 233 bytes
```
(define(f n)(local((define(m x)(expt x(-(first(sort(map char->integer(string->list(~v x)))<))48)))(define(g y)(if(= y(m y))y(g(m y))))(define(k x l)(if(=(length l)n)l(if(< x(g x))(k(+ x 1)(cons x l))(k(+ x 1)l)))))(reverse(k 1'()))))
```
[Try it online!](https://tio.run/##RY9BasNADEWvIuiiXxRDDV10keYugytPBitjoxmCZ5OrJ7JNyErS4@shWRgmqY8PDTmSHQP@ZUxZMFJm6DwExQtdaWXIulRa0WFMVirKbBXXsNBwCdadU64SxVCqpRy7sybP3G@@yHxi/vn1@tJFaow04o@aqxtzQzyad2ailfRIQSXHevExs27k5GfEzYwJX57rGcOcy77xZsq7z@QmVjZh/4kd@aepLBoa@a/9t4Mn "Racket – Try It Online")
This is my first [Racket](https://racket-lang.org/) submission, so it can definitely be golfed much further. Nevertheless I'm somewhat content, at least for managing to solve the task.
## More readable:
```
(define (f n)
(local ((define (m x)
(expt x
(- (first (sort (map char->integer (string->list (~v x)))
<))
48)))
(define (g y)
(if
(= y (m y))
y
(g (m y))))
(define (k x l)
(if (= (length l) n)
l
(if (< x (g x))
(k (+ x 1) (cons x l))
(k (+ x 1) l))))
(reverse (k 1 '()))))
```
[Answer]
# Axiom, 168 bytes
```
u(x)==(y:=x::String;x^reduce(min,[ord(y.i)-48 for i in 1..#y])::NNI)
q(a:PI):PI==(b:=a;repeat(c:=u(b);c=b=>break;b:=c);b)
z(x)==[i for i in 1..x|(m:=q(i))~=1 and m~=i]
```
The function to use it is z(); here it print numbers that has the corrispondence
one number not 1, not itself and are less than its argument.
```
(6) -> z 1000
(6)
[3, 5, 6, 8, 23, 26, 27, 29, 35, 36, 39, 42, 47, 53, 59, 64, 72, 76, 78, 82,
83, 84, 92, 222, 223, 227, 228, 229, 233, 237, 239, 254, 263, 267, 268,
269, 273, 276, 277, 278, 279, 285, 286, 287, 289, 296, 335, 338, 339, 342,
346, 347, 348, 354, 358, 363, 365, 372, 373, 374, 376, 382, 383, 386, 392,
394, 395, 399, 423, 424, 426, 427, 428, 432, 433, 435, 436, 442, 447, 459,
462, 464, 466, 467, 468, 469, 476, 477, 479, 483, 487, 488, 489, 493, 494,
523, 524, 527, 529, 533, 537, 542, 546, 553, 556, 557, 562, 563, 572, 573,
577, 582, 583, 584, 594, 595, 598, 623, 626, 627, 629, 632, 633, 642, 646,
647, 648, 663, 664, 669, 672, 676, 682, 683, 684, 693, 694, 695, 698, 722,
724, 729, 736, 759, 763, 773, 775, 782, 786, 823, 829, 835, 846, 847, 856,
873, 876, 885, 893, 894, 896, 923, 924, 928, 933, 953, 954, 962, 969, 973,
974, 984, 993, 994, 995]
Type: List PositiveInteger
```
[Answer]
# [Visual Basic .NET (.NET Core)](https://www.microsoft.com/net/core/platform), 290 bytes (includes imports)
```
Iterator Function A()As System.Collections.IEnumerable
Dim i=B.One,q=i,p=i
While 1=1
q=i-1
p=i
While q<>p
For j=0To 9
If p.ToString.Contains(j)Then
q=p
p=B.Pow(p,j)
Exit For
End If
Next
End While
If p>1And p<>i Then Yield i
i+=1
End While
End Function
```
[Try it online!](https://tio.run/##VVFNb8IwDL3nV/i2VkBFDztMokh0K1KlwSaBNO3YD0ON0qS06VZ@feeG8eVLnBf7@T3nJ51kusY@LitdmwZCCGBzagyW3rotsaas8ULax8rgHmt4AlKZbHMEU1ADkhQyAunJIGS6VUasdN5KhFUfG6wTo2tYtiozpBUsHHfRXNhftZRo8caLIzXMSlKJ4o1KoCD0PhSOjwGNq4DEV0FM6Qe@YGTiixt2nM0rseQhh2C61fAi4h1U3lZvTE1qz0OUSUg1zsHdFqi4veLm0PvUv041Prgi6sgA94tI5RDvxBo7Y3NLb9nm/oLv1WxOMHDAN6HMgQSNWM@tdMguTvtNm8KKBzuuEPAf1hhv178ig@4oyQroIObtXPEhWHmjJXpfNRl85zU7nftQwNIGtuepVfXwNMTV2AN4NnkPEYzuJVn/1gtbsOf5P/s/ "Visual Basic .NET (.NET Core) – Try It Online")
Requires the following import:
```
Imports B = System.Numerics.BigInteger
```
This uses an iterator function to return an infinite (lazy loaded) list of integers that meets the criteria. Uses `BigInteger` to avoid any size restrictions, particularly with intermediate calculations.
Un-golfed:
```
Iterator Function A() As System.Collections.IEnumerable
Dim i As B = 1
While True
Dim prevProduct As B = 0
Dim product As B = i
While prevProduct <> product
For j = 0 To 9
If product.ToString.Contains(j) Then
prevProduct = product
product = B.Pow(product, j)
Exit For
End If
Next
End While
If product <> 1 And product <> i Then
Yield i
End If
i += 1
End While
End Function
```
[Answer]
# [Common Lisp](http://www.clisp.org/), 238 bytes
```
(defun x(m n o p q)(setf i(sort(map 'list #'digit-char-p(prin1-to-string m))#'<))(setf j(expt m(first i)))(cond((= q p)nil)((and(= n j)(not(= n 1))(not(= n o)))(cons o(x(1+ o)0(1+ o)p(1+ q))))((= n j)(x(1+ o)0(1+ o)p q))(t(x j j o p q))))
```
[Try it online!](https://tio.run/##XU/LCoMwEPyVgR6cpQh66K39GPHViCbRbMG/t6u2FLph2WEem6QeXYrbxqbtXh4rJ3gERMzC1GoHxxQW5VRFZGZVXLLG9U7z@lkteWRcnC9zDXlSQz0mkUt2l096YLtGxcTOLZZ1YkIdfEM@MCOKd6OQlREPu3cQ@qAHLOWHwyeVELiyvBpRnCPuY5Zd/y74M@wqlSsGO@e/rLbj2QrjSxTWtwKF0W8 "Common Lisp – Try It Online")
[Answer]
# APL(NARS), 96 chars, 192 bytes
```
r←f w;k;i;a
r←⍬⋄k←1
A: i←k
B: →C×⍳i=a←i*⌊/⍎¨⍕i⋄i←a⋄→B
C: →D×⍳(a=k)∨a=1⋄r←r,k
D: k+←1⋄→A×⍳k≤w
```
test (partial result for argument 22 seems to much big so <21 arguments I don't know if can be ok)
```
f 21
3 5 6 8
```
[Answer]
# [Python 3](https://docs.python.org/3/), 102 bytes
```
x=int(input())
a=c=0
while x:
a+=1;b=a
while b-c:b,c=b**int(min(str(b))),b
x-=b!=1and b!=a
print(a)
```
[Try it online!](https://tio.run/##JYvLCoMwEADv@xXrLesDKsWLZT9mNwoG2jXYlMavj4qngWEm7mlZ7VlK5mDJBYu/5IhA2PMD/kt4z5hHQGm4fykL4O2086O2nrWur@8TzH3T5pSIWgXMHWvFvdiEJwXidlVCpQwH "Python 3 – Try It Online")
Decided to try a Python 3 solution that directly prints the nth term in the sequence.
[Answer]
# [C (clang)](http://clang.llvm.org/) + `-DL=long long` `-lm`, 213 bytes
```
q(char*a,char*b){return*a>*b;}L f(L a){char*c;asprintf(&c,"%lld",a);qsort(c,strlen(c),1,q);L b=pow(a,*c-48);return b>a?f(b):b;}i;g(j){for(i=0;j;i++){L x=f(i);x!=i&x!=1&x>0&&printf("%d\n",i)&&j--;}}
```
[Try it online!](https://tio.run/##LY3BboMwEER/xUWKtUtsCaQeqqwglx75hF4WJ6ZGjgmGqEiIX69L017eSDPSPKON59ClNIL55JizekaLa7zOjxhyrvOWtkZYaATj@lwN8XSPLswWpFHZwftLphhpnIY4g1HTHP01gEFVqhGpEW11H76AVW706xvS37Voaz5baPG0Cxx10ONqhwiuKqgndzzi2oilsuCQlpfKyR2lXOpCyn95drh8hEw5lLLXmrYt7bW4sQuAawdlgbSlb2M9d1PS703lh9CJXyTtbz8 "C (clang) – Try It Online")
Function `g(j)` prints the first `j` terms of the sequence.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~16~~ ~~12~~ 10 bytes
```
fS>ωṠ^o▼dN
```
Saved 6 bytes thanks to H.PWiz.
[Try it online!](https://tio.run/##yygtzv7/Py3Y7nznw50L4vIfTduT4vf/PwA "Husk – Try It Online")
### Explanation
```
fS>ωṠ^o▼dN
f N Filter the natural numbers where...
ω ... the fixed point...
Ṡ^o▼d ... of raising the number to its smallest digit...
S> ... is greater than the number.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 44 bytes
```
_ì ñ g
_gV ¥1?Z:ZpZgV)gW
@@[1X]øXgW}fXÄ}gUÄ
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=Cl/sIPEgZwpfZ1YgpTE/WjpacFpnVilnVwpAQFsxWF34WGdXfWZYxH1nVcQ=&input=NQ==)
Substantially different from the other Japt answer.
Explanation:
```
Empty line preserves the input
_ì ñ g Function V finds the smallest digit in a number Z
ì Get the digits of Z
ñ Sort the digits
g Get the first (smallest) digit
_gV ¥1?Z:ZpZgV)gW Function W finds the MPR of a number Z
gV ¥1?Z If V(Z) is 1, then it's stable; return it
:ZpZgV) Otherwise get MPI of Z...
gW And call W on it ( MPR(Z) == MPR(MPI(Z)) )
@@[1X]øXgW}fXÄ}gUÄ Main program
@ }gUÄ Get the nth number by repeatedly applying...
@ }fXÄ Find the next smallest number X which returns false to...
XgW MPR(X)
ø is either...
[1X] 1 or X
```
In terms of future golfing possibilities, I do a lot of manually calling a function on a number, which I suspect could be reduced but I'm not sure how.
[Answer]
# [Python 3](https://docs.python.org/3/), 54 bytes
```
lambda n,x=0:n!=x and f(n**min(map(int,str(n))),n)or n
```
[Try it online!](https://tio.run/##Dco9DsIwDAbQGU7hdrKrIPGzoErhJCxGJWCJfI3SDEVVz552edNL//IdcauBPD3rT@NrUIKb/blH42dSDBQYXRcNHDWxobipZIaIOMiYCTXsGhkoKz5vvrjrXfrjIeU9c2gXW@n0oCWwydpK3QA "Python 3 – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 35 bytes
```
r0f{J{J<]**}{J<]1!=}w!J1!=x/x/!=&&}
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/yCCt2qvayyZWS6sWRBkq2taWK3oBqQr9Cn1FWzW12v//DQ0A "Burlesque – Try It Online")
"Produces" the infinite list of MPRs (i.e. never finishes, never prints). For a finite list use:
# [Burlesque](https://github.com/FMNSSun/Burlesque), 36 bytes
```
ri{J{J<]**}{J<]1!=}w!J1!=x/x/!=&&}FO
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KLPaq9rLJlZLqxZEGSra1pYregGpCv0KfUVbNbVaN////w0NAA "Burlesque – Try It Online")
Takes an integer input `N` and tests the first `N` values
```
r0 # All integers starting from 0
f{ # Filter for
J # Duplicate original value (for later)
{
J # Duplicate current value
<] # Minimum digit
** # Raise current value to power of min digit
}
{
J<] # Find minimum digit (non-destructive)
1!= # Not equal to 1
}w! # While current value does not contain 0 or 1
J # Duplicate output
1!= # Not equal to 1
x/x/ # Reorganise stack
!= # Output is not equal to original
&& # AND not equal to 1
}
```
[Answer]
# [Dash](https://wiki.debian.org/Shell) (or other generic Bourne shell) + [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 190 bytes
```
a=0
while :
do
a=`echo $a+1|bc`
b=$a
while :
do
for m in `seq 0 9`
do
case "$b" in
*$m*)break;;
esac
done
case $m in
0)break;;
1)[ $a = $b ]||echo $a;break;;
esac
b=`echo $b^$m|bc`
done
done
```
[Try it online!](https://tio.run/##VY69DsIwDIR3P4VVeWlZ2hGiPAkCxU6NUkFb0QwsefeQlh/B4uHuO9/1HEPObFt4hOGmeIB@BrZOfZiReNcl8Q7EEv8Cl3nBEYcJXdQ7trh3q@o5KlYkVXGgobGpZVG@GgMa2Rdi0hdDaxbar93Vx9KFFknwlNK72/yl5bNJzjRuo7Z/68n5CQ "Dash Try It Online")
This implementation prints the infinite sequence -- as far as it is allowed.
I specifically did not use bash arithmetic because I didn't want the limit of bash's number system. If you change the line `a=0` to `a=$1`, you can start looking at any number (though subtract 1 if you want the first number considered). Passing in 9922289264447635429194, I found part of the sequence is:
>
> 9922289264447635429236
>
> 9922289264447635429254
>
> 9922289264447635429323
>
> 9922289264447635429328
>
> 9922289264447635429335
>
>
>
] |
[Question]
[
# Room Number Locator
I have come across an interesting problem solving technique at my job when given the wrong room number from a colleague for a meeting. Every now and then, while on the way to a meeting, a member on my team will send me the wrong room number, typically because they are in a rush at their desk and fat finger the wrong key.
Interestingly, upon arrival at the wrong room, I typically can guess which room they really meant by imagining a [Numeric Keypad](https://en.wikipedia.org/wiki/Numeric_keypad):

and by guessing an adjacent number they meant to press.
## Challenge
Your challenge is to write a function that takes a building office number (000-999) and outputs the possible typo solutions, **assuming your colleague only mistypes one digit.**
The following table shows which numbers are adjacent to each other on a Numeric Keypad:
```
0 -> 1,2
1 -> 0,2,4
2 -> 0,1,3,5
3 -> 2,6
4 -> 1,5,7
5 -> 2,4,6,8
6 -> 3,5,9
7 -> 4,8
8 -> 5,7,9
9 -> 6,8
```
## Input
A 3 digit number: `000-999`. Assume input of exactly 3 digits. If the number is less than 100 or less than 10, you will be given the leading zeros. (i.e. 004 & 028).
## Output
A list of possible rooms. This can be in any form you want, as long as there is a delimiter between room numbers. (i.e. space, comma, new line, etc..) If the number is less than 100 or less than 10, you can or cannot have the leading zeros as output, that is up to you. (i.e. 004 can be `004 04 4`, and 028 can be `028 28`)
Test Cases(leading zeros are optional):
```
008 -> 108, 208, 018, 028, 005, 007, 009
123 -> 023, 223, 423, 103, 113, 133, 153, 122, 126
585 -> 285, 485, 685, 885, 555, 575, 595, 582, 584, 586, 588
777 -> 477, 877, 747, 787, 774, 778
963 -> 663, 863, 933, 953, 993, 962, 966
555 -> 255, 455, 655, 855, 525, 545, 565, 585, 552, 554, 556, 558
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each language wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~112~~ 106 bytes
Recognizing that a numeric keypad is basically a 3x3 `GridGraph` with edges added for 0, we get the adjacent digits for each input digit with `AdjacencyList`.
This can be seen below:
`EdgeAdd[GridGraph[{3,3},VertexLabels->"Name",GraphLayout->"SpringEmbedding"],{0<->1,0<->2}]` yields:
[](https://i.stack.imgur.com/nxinX.png)
Then I use `Tuples` to figure out all the possible mistakes and pick out those with exactly one error with `Select` and `EditDistance`. By the way, this will work for longer room numbers and you can also increase the `EditDistance` parameter to allow for more than one error. Might be able to golf this down a little further but wanted to show my approach.
```
h@u_:=Select[Tuples[AdjacencyList[EdgeAdd[GridGraph[{3,3}],{0<->1,0<->2}],#]~Join~{#}&/@u],#~EditDistance~u==1&]
```
Slightly more golfed version hardcoded to length 3 room numbers (106 Bytes). This will output as a rank 3 list corresponding to each digit:
```
Thread/@ReplacePart[#~Table~3,{i_,i_}:>(AdjacencyList[GridGraph@{3,3}~EdgeAdd~{0<->1,0<->2},#]&/@#)[[i]]]&
```
[Try it online!](https://tio.run/##LYxNC4JAGITv/Q3B0xv5gWUfhkIiRIegbovEsru0G2qi6yGW9a9vbxADM8wwPC3VUrRUK0adk/n02GU30QimyX3qGzGSgr8oEx37XNSoScmfouCcVIPi1UB7SUwMsa3BBIflMYSfR1i9ej6/VTcbz/qrfMJhLrnSJ2TQjol5yrLQr911UJ0mMvdqfBkTQACpBRNChFAwCaSQYG4AhbmF9X9HWbtfuC8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
```
lambda r:[r[:i]+[c]+r[i+1:]for i,n in enumerate(r)for c in`ord(u'ÌЋ>তŧ0ɃD'[n])`]
```
[Try it online!](https://tio.run/##LYsxDoIwGEZ3dvc/cQDkJwEMik1k8ha1CQhUm0ghTRmcHfUKbkbvoXFw8wjeBEti3vCSl@9rD3rXyKgfgz/xoWhKIbcEOs39ZCgWX677fV5vyhwUoYoSwTxaME9R4YWE8UaBQAlCQiW7ulK5rhzlDrkwMWtU6XT26Hn@nNLH5Xu7vu7B@7iyqWRuxvphp4czpQEGmDCkIUY4NY4xwdh4jgbjBc7@3cAYsaBVQmrQaPupjdzRbv8D "Python 2 – Try It Online")
The 1st and 5th characters may not being displayed here (browser dependent), but the full string is equivalent to `[21, 204, 1035, 62, 157, 2468, 359, 48, 579, 68]`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
v•4TË\ªye-³—Ïʒ••Ćδn¼•S£yèʒNǝ,
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/7FHDIpOQw90xh1ZVpuoe2vyoYcrh/lOTgKJAdKTt3Ja8Q3uArOBDiysPrzg1ye/4XJ3//y3NjAE "05AB1E – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 190 bytes
```
function(x){l=list(c(1,2),c(0,2,4),c(0,1,3,5),c(2,6),c(1,5,7),c(2,4,6,8),c(3,5,9),c(4,8),c(5,7,9),c(6,8))
a=do.call(expand.grid, mapply(c,l[x+1],x))
a[apply(a,1,function(y){sum(x==y)==2}),]}
```
[Try it online!](https://tio.run/##PY7LCoMwFET3/Youb@hUTKp9QPMl4iLEWgJRgw@IiN@eGgJd3TNzB2bG0L6voV16PZuhJ882K62ZZtLEIRg05RAoEnDcUEYUuMfDUeKRdIE7nhGPBF4RiqSPRNLxz05KNkOmlbX08U71TfYdTYNzp5yzK2nYyl94DR@jVTLV0fsfuLJtWjryUq5MSrEz1Htwo@lnailuzGMNCz8 "R – Try It Online")
---
My second attempt at CodeGolf! Pretty long, 190 bytes, but the best I could manage with R. Curious to see if others have feedback or can do better!
[Answer]
## JavaScript (Firefox 30-57), ~~115~~ 109 bytes
```
f=([c,...a],p=``)=>c?[...(for(n of``+[12,240,1350,26,157,2468,359,48,579,68][c])p+n+a.join``),...f(a,p+c)]:[]
```
Edit: Saved 6 bytes thanks to @edc65 (although suggested `0`s now appear after other suggestions). ES6 version, ~~118~~ 112 bytes:
```
f=([c,...a],p=``)=>c?[...[...``+[12,240,1350,26,157,2468,359,48,579,68][c]].map(n=>p+n+a.join``),...f(a,p+c)]:[]
```
```
<input oninput=o.textContent=f(this.value).join`\n`><pre id=o>
```
[Answer]
# Java, 205 177 bytes
```
b->{for(int c=0;c<3;c++){char[]d=b.toCharArray();for(char e:"12,024,0135,26,157,2468,359,48,579,68".split(",")[new Byte(""+d[c])].toCharArray()){d[c]=e;System.out.println(d);}}}
```
I know it's long compared to the other answers. My excuse: it's in Java.
Oracle should rename `toCharArray` to something like `getCrs`.
## Credits
-28 characters by [**Kevin Cruijssen**](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Ruby](http://www.ruby-lang.org) 97 bytes
```
->i{c=0;i.map{|j|[12,204,1035,26,157,2468,359,48,579,68][j].digits.map{|k|f=*i;f[c]=k;p f};c+=1}}
```
[Try it online!](https://tio.run/##NY1NCoMwGET3PYXQXTuVJPrFSEgvkmbRWlKiCNKfRVDPnlqLzOrBm5nn5xZTNJd0OoexMUyHvL8O49ROlgsIVoKzgiAkOFUQpVQoqEapQFUNqZxtXX4Pj/B@/Yvd5M0haG8bZzo9ZH7WzdHweU77LFrLwKCc263AIVBsQFg2N6iwZIPlZ9VWiX5S@gI)
### Alternatively, 94 chars but 100 bytes
```
->i{c=0;i.map{|j|"\fÌЋ\u001A\u009Dতŧ0ɃD".unpack("U*")[j].digits.map{|k|f=*i;f[c]=k;p f};c+=1}}
```
[Try it online!](https://tio.run/##KypNqvxfaRvzX9cuszrZ1sA6Uy83saC6JqtGKSbtcM@F7phSAwNDRxBp6fJg2ZKjyw1ONrso6ZXmFSQmZ2sohWopaUZnxeqlZKZnlhRD9GbXpNlqZVqnRSfH2mZbFyik1Vona9sa1tb@V1aojI420DHQsYiN5QJzDHWMdIxhHFMdCx1TGMdcBwhhHEsdM7AysCJTkKL/AA)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 136 or 114 bytes
## ASCII version 136 bytes
```
m[]={12,240,1350,26,157,2468,359,48,579,68},p,i,X=10;f(n){for(i=100;i;i/=X)for(p=m[n/i%X];p;p/=X)printf("%d ",n/(i*X)*(i*X)+p%X*i+n%i);}
```
[Try it online!](https://tio.run/##PY3NioMwEMfPm6cIgpDYKSbamMjgPkeg9LBYlDmYhm73JD67m1R2LzP/j/kx43kex31frrdh1Q00FwW6NQqaDrSxyXcOWtPDxYGxPXRugwgEftAKJxHkOj2egpJTSEj14GUO4rBcQ02lv2HEmNP4pPCaRFHeeQGhFlR5Wb3nKZa@olMoSeK2zyLd8SDZyj7@GdXe@fkzgalAnt8ijz@vb1EUEtnGWGaWLwrizc3CpTgt3bSHMM4cwlp7iL77q0yutv0X "C (gcc) – Try It Online")
## Unicode ~~114~~ 108 bytes (TiO seems to count weirdly for this)
Thanks to @ceilingcat for this version.
```
p,i,X=10;f(n){for(i=1e3;i/=X;)for(p=L"\fðՆ\32\x9dতŧ0ɃD"[n/i%X];p;p/=X)printf("%d ",n/i/X*i*X+p%X*i+n%i);}
```
[Try it online!](https://tio.run/##S9ZNT07@/79AJ1MnwtbQwDpNI0@zOi2/SCPT1jDV2DpT3zbCWhPEL7D1UYpJO7zhaluMsVFMhWXKg2VLji43ONnsohSdp5@pGhFrXWBdAFSuWVCUmVeSpqGkmqKgpAOU0o/QytSK0C5QBdLaeaqZmta1/9M1gGoU8jS5qrk44eoNjFMUdO2AmoAS1gogl1grFJSWFGsoKWlac9VycYH05CZm5mmA9aVrWACFgZShkTGEYWphCmGYm5tDGJZmMClTkFTtfwA "C (gcc) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), ~~120~~ 85 + 2 (`-F`) = 87 bytes
```
map{@,=@F;$,[$i]=$_,say@,for(12,240,1350,26,157,2468,359,48,579,68)[$_]=~/./g;$i++}@F
```
[Try it online!](https://tio.run/##DcexDoIwFAXQn@mg4QJt4ZUS0qRTN7@AEMKgpgnaBlyM0U/36dlOPm8rMd@W/PJwPgwCo4iTEzP25elxSdtBaehWQjUkoQ0Udf8bi4Z6tBbU9TD2OIp5cp@6qq@DiEXx9oFZSvtN@RHTfefyRJVUksvwAw "Perl 5 – Try It Online")
Saved 35 bytes by borrowing an idea from @AsoneTuhid's ruby answer.
[Answer]
# [Python 2](https://docs.python.org/2/), 103 bytes
thanks to @Lynn for -4 bytes.
```
lambda n:{n[:i]+r+n[i+1:]for i,v in enumerate(n)for r in`0x134cd9a07d1e58feab643f7db24102`[int(v)::10]}
```
[Try it online!](https://tio.run/##JYzRCoMgGEbv9xT/nUVdqOUsYU/SgmwqE9ZfiIuNsWd3ya4OnI/vbO94X5End7mmh15mowHVBwflxypUOPiKqdGtAXy9g0ew@Fxs0NEWWGZ9DDjRF2vam@k1lYZZ0Tmr53PbOGlm3jLKp8FjLPZSKUbHb8q/mGOE0o7UQBhvMkQnMqSUGf35L4Ug6gSwhaMBsQZXxDL9AA "Python 2 – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 93 bytes
```
~r=[(R=copy(r);R[j]=i;R)for i=0:9,j=1:3 if(big(1)<<(i+10r[j]))&0x502A044228550A21102B05406>0]
```
[Try it online!](https://tio.run/##VY1LT8MwEITv/RVWDpUtVurajUP6MFIRd6RQTsaHvtko2JEJolz619O4Ug/sXD7tzszWPw1tir6/RGN5ZXah/eNRLCpbO0OLShxDZGRwPoPayPmU0ZFv6cSlWC45PUiMg1GIMZ41qhXmuVKl1rhSUqJ6Rp1j8YSuTy0xhC9GnlmLgFA6YFaCgmkCDSXoBI8wKMEMivtpkHMjNkwbyXeN56lK3Dbfn@GXv61fXt/XwLLucO4mbbMhnwG73B6Kf8Hsw2didPD7/go "Julia 0.6 – Try It Online")
* Takes a vector of digits and returns a list in the same format.
* `0x502A044228550A21102B05406` is a `UInt128` in which the `1+10j`th bit is set iff `i` is next to `j` on the numpad.
* `big(1)` is a `BigInt`. It is used to prevent overflow and uses less characters than `Int128(1)` or `UInt128(1)`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
ḷþị“-ⱮⱮVḟ|żṣ~ẋ³ɱgẆ’ḃ⁽¦ḳ¤$ṛ¦DŒp$¥"JẎ
```
[Try it online!](https://tio.run/##AV0Aov9qZWxsef//4bi3w77hu4vigJwt4rGu4rGuVuG4n3zFvOG5o37huovCs8mxZ@G6huKAmeG4g@KBvcKm4bizwqQk4bmbwqZExZJwJMKlIkrhuo7///9bMCwgMCwgOF0 "Jelly – Try It Online")
-1 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
*Explanation being updated...*
[Answer]
## SQL (SQLite), 533 bytes
```
with m as (select 0 as i, 1 as o union values (0,2),(1,0),(1,2),(1,4),(2,0),(2,1),(2,3),(2,5),(3,2),(3,6),(4,1),(4,5),(4,7),(5,2),(5,4),(5,6),(5,8),(6,3),(6,5),(6,9),(7,4),(7,8),(8,5),(8,7),(8,9),(9,6),(9,8))select o || substr('008', 2, 1) || substr('008', 3, 1)from m where substr('008', 1, 1) = cast(i as text)union select substr('008', 1, 1) || o || substr('008', 3, 1)from m where substr('008', 2, 1) = cast(i as text)union select substr('008', 1, 1) || substr('008', 2, 1) || o from m where substr('008', 3, 1) = cast(i as text)
```
### Ungolfed
```
with m as (
select 0 as i, 1 as o
union
values
/*(0,1),*/(0,2),
(1,0),(1,2),(1,4),
(2,0),(2,1),(2,3),(2,5),
(3,2),(3,6),
(4,1),(4,5),(4,7),
(5,2),(5,4),(5,6),(5,8),
(6,3),(6,5),(6,9),
(7,4),(7,8),
(8,5),(8,7),(8,9),
(9,6),(9,8)
)
select o || substr(s, 2, 1) || substr(s, 3, 1)
from m, t
where substr(s, 1, 1) = cast(i as text)
union
select substr(s, 1, 1) || o || substr(s, 3, 1)
from m, t
where substr(s, 2, 1) = cast(i as text)
union
select substr(s, 1, 1) || substr(s, 2, 1) || o
from m, t
where substr(s, 3, 1) = cast(i as text)
```
### Explanation
The input is a single text row on table `t` with column `s`. My understanding is that [according to this meta answer](https://codegolf.meta.stackexchange.com/a/5341/36915) this is an acceptable form of input. The input can be created as below.
```
drop table if exists t;
create table t (s text);
insert into t values('555'); -- Your input here
```
### Annotated solution
```
with m as ( -- Using this in the "with" allows us to only type is once
select 0 as i, 1 as o -- The first pair is here and it names the columns
union
values
/*(0,1),*/(0,2),
(1,0),(1,2),(1,4),
(2,0),(2,1),(2,3),(2,5),
(3,2),(3,6),
(4,1),(4,5),(4,7),
(5,2),(5,4),(5,6),(5,8),
(6,3),(6,5),(6,9),
(7,4),(7,8),
(8,5),(8,7),(8,9),
(9,6),(9,8)
)
select o || substr(s, 2, 1) || substr(s, 3, 1) -- concat the first wrong char with two correct chars
from m, t
where substr(s, 1, 1) = cast(i as text) -- when the first char is in the i (input) column from above
union
select substr(s, 1, 1) || o || substr(s, 3, 1)
from m, t
where substr(s, 2, 1) = cast(i as text)
union
select substr(s, 1, 1) || substr(s, 2, 1) || o
from m, t
where substr(s, 3, 1) = cast(i as text)
```
[Answer]
# [Kotlin](https://kotlinlang.org), 117 bytes
```
mapIndexed{i,c->"12,024,0135,26,157,2468,359,48,579,68".split(",")[c-'0'].map{replaceRange(i,i+1,it+"")}}.flatMap{it}
```
## Beautified
```
mapIndexed { i, c ->
"12,024,0135,26,157,2468,359,48,579,68"
.split(",")[c - '0']
.map { replaceRange(i, i + 1, it + "") }
}.flatMap { it }
```
## Test
```
fun String.f(): List<String> =
mapIndexed{i,c->"12,024,0135,26,157,2468,359,48,579,68".split(",")[c-'0'].map{replaceRange(i,i+1,it+"")}}.flatMap{it}
data class Test(val input:Int, val answers: List<Int>)
val tests = listOf(
Test(8, listOf(108, 208, 18, 28, 5, 7, 9)),
Test(123, listOf(23, 223, 423, 103, 113, 133, 153, 122, 126)),
Test(585, listOf(285, 485, 685, 885, 555, 575, 595, 582, 584, 586, 588)),
Test(777, listOf(477, 877, 747, 787, 774, 778)),
Test(963, listOf(663, 863, 933, 953, 993, 962, 966)),
Test(555, listOf(255, 455, 655, 855, 525, 545, 565, 585, 552, 554, 556, 558))
)
fun main(args: Array<String>) {
for (r in tests) {
val input = r.input.toString().padStart(3, '0')
val expected = r.answers.map { it.toString().padStart(3, '0') }.sorted()
val actual = input.f().sorted()
if (expected != actual) {
throw AssertionError("$input -> $actual | $expected")
}
}
}
```
## TIO
[TryItOnline](https://tio.run/##fZNNi9swEIbv/hWqCazMKiZWLFlemsAeelhoKXR7Kz0Ix05FvbaRle6W1L89q9fOx6aFCvJkPNbMvMOMf7auNs0hqHYNeXTWNNu4otEd+Wh6935yrMnq8KS7h2ZTvpSbvWHFfB0mnC14yhbJUjAuWSIyxlOp2FLkLFVMZDmTKoz7rjaOhiyMvhXzm8XN99hn2tuyq3VRftHNtqSGmduEGXcbhtEwxFWt3Sd/x7jhEGy006Sodd+Tr2Xv6C9dE9N0O3f30DhG8Kib/rm0/VGxd6+jIMAL5wN6siK193+uaED8GZModvIlC29zIIHhf4KRjJE8itjlfsKX5wiYHEiBZAEkwBIQAOeAvEohlLikgJ0CElCAEEAG5IDiQApIQF1ly7LsnC2FrYAsBRSQpcB1UC4vXUjYCsihO4fuPAckB/4SL96Ih50CElCjbg6kgBzFjw2hA4EOBDoQXkzgB4M1e9Kmodpu/czurdW/T2sWkf1YtGotodbPeRrhyY1znr+fq41HK3btFE+juNObR6eto74Vv2zRVVz50pWFKzdj6HFrsI1kT8x/s5Ah7lvrI+l1Ql24nf9bTYrw2fx7z1SEngu/Wx1j3raE437Y9pnc931pnWmbD9a2loazqdP5msyOpf6Q2SlZeKkxBBOHwys)
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 322 bytes
```
WITH m AS(SELECT LEFT(value,1)i,RIGHT(value,1)o FROM STRING_SPLIT('01,02,10,12,14,20,21,23,25,32,36,41,45,47,52,54,56,58,63,65,69,74,78,85,87,89,96,98',','))SELECT o+RIGHT(s,2)FROM t,m WHERE i=LEFT(s,1)UNION SELECT LEFT(s,1)+o+RIGHT(s,1)FROM t,m WHERE i=SUBSTRING(s,2,1)UNION SELECT LEFT(s,2)+o FROM t,m WHERE i=RIGHT(s,1)
```
The input is taken from the column `s` of a single-row table named `t`:
```
DROP TABLE IF EXISTS t
CREATE TABLE t (s CHAR(3))
INSERT INTO t VALUES('008')
```
Ungolfed:
```
WITH m AS (
SELECT LEFT(value,1) i, RIGHT(value,1) o
FROM STRING_SPLIT('01,02,10,12,14,20,21,23,25,32,36,41,45,47,52,54,56,58,63,65,69,74,78,85,87,89,96,98',',')
)
SELECT o+RIGHT(s,2) FROM t,m WHERE i=LEFT(s,1)
UNION
SELECT LEFT(s,1)+o+RIGHT(s,1) FROM t,m WHERE i=SUBSTRING(s,2,1)
UNION
SELECT LEFT(s,2)+o FROM t,m WHERE i=RIGHT(s,1)
```
[SQLFiddle](http://sqlfiddle.com/#!18/bfeb4/1)
] |
[Question]
[
## Background
The Collatz (or 3x+1) map ([A006370](https://oeis.org/A006370)) is defined as the following:
$$
a(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\
3n+1, & \text{if $n$ is odd}
\end{cases}
$$
Now, let's define the sequence \$s\_0\$ as the infinite sequence of positive integers \$1, 2, 3, 4, \cdots\$, and define \$s\_k\$ as the result of applying the process \$k\$ times to \$s\_0\$:
1. Apply Collatz map to each term of the input sequence.
2. Sort all the terms to get a non-decreasing sequence.
Here are first few terms of \$s\_0, \cdots, s\_3\$:
```
s0: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
s1: 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 16, 17, ...
s2: 1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8, 8, 9, 10, 10, 11, 11, 12, 13, 14, 14, ...
s3: 1, 1, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9, 10, 10, 10, 11, 11, 12, ...
```
## Challenge
Given \$k\$ as input, output the sequence \$s\_k\$.
Default [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O methods are allowed. For this challenge, this means you can use one of the following:
* Take \$k\$ as input, and output the terms of \$s\_k\$ forever.
* Take \$k, n\$ as input, and output the value of \$s\_k(n)\$ (0- or 1-indexed).
* Take \$k, n\$ as input, and output the first \$n\$ values of \$s\_k\$.
You can also use 0- or 1-indexing for \$k\$.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
```
f=lambda k,n:k and sorted([x/2,x*3+1][x%2]for x in f(k-1,n*2))[:n]or range(1,n+1)
```
[Try it online!](https://tio.run/##LcpBCsMgEEDRfU8xm4KTWBLNLpCTiAuLMRHbUawFe3rrIrvP46dfOSPJ1tz2Mu@nNRA4rQEMWfjEXHbLVJ0kr8MyCq3qXWoXM1TwBI6Fh@A0SES1ku6cDR076zYKbCl7Kn3ylL6FIYcrsC03Mc9/ "Python 2 – Try It Online")
-19 bytes thanks to Leo and Bubbler
-11 bytes thanks to dingledooper (-6 + -5 from Python 2)
-8 bytes by swapping over to the brute force solution
-2 bytes thanks to Noodle9
To get \$s\_k\$ up to \$n\$ elements, we only need to get \$s\_{k-1}\$ up to \$2n\$ elements.
[Answer]
# [Haskell](https://www.haskell.org/), 73 bytes
```
([1..]>>=).(#)
k#n|k<1=[n]|s<-k-1=n<$s#(2*n)++[n|_<-s#div n 3,mod n 6==4]
```
[Try it online!](https://tio.run/##DYpLDsIgFAD3nuIldNFaIa1aV7zewBMgMaQ/Ce2TSOOKs4ssJjOLeZngpnVNMz5SqVohdN9jJUpWHRyj6GSLinQMkjveIskisPJ8pKquFcWn5IGN9gsEl9P2HrNviFedNmMJN@Pv4D@WdihA7cZN0DU557zFjOSgGiE6rdNvmFezhMQH7/8 "Haskell – Try It Online")
`k#n` returns a list of the appropriate number of copies of `n`. The anonymous function `([1..]>>=).(#)` concatenates all of those together.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~27~~ ~~25~~ ~~23~~ 20 bytes
```
!¡ȯΞzme½o→*3Mfe¦2%2N
```
[Try it online!](https://tio.run/##ASUA2v9odXNr//8hwqHIr86eem1lwr1v4oaSKjNNZmXCpjIlMk7///80 "Husk – Try It Online")
The idea for this comes from [a message by rak1507 in the Husk chat](https://chat.stackexchange.com/transcript/message/57856414#57856414). Returns the full sequence corresponding to the given 1-based k.
### Explanation
We start from the list of natural numbers and then at each step produce one list with each even number halved and another list with each odd number multiplied by 3 and incremented, then we merge the two lists keeping them sorted.
```
!¡(Ξzme½(→*3)Mfe¦2%2)N
N Start from the infinite list of natural numbers
¡ Then iterate the following function
Mfe Build two lists by applying the following two filters
¦2 Numbers divisible by 2
%2 Numbers not divisible by 2
zme Apply the following two functions respectively
to the first and second list
½ Halve
→*3 Multiply by 3, then increase
Ξ Merge the two resulting lists
! Finally, return the result of the kth iteration
```
---
# Previous answer, 25 bytes
```
`ṘN!¡§z+oĊ2tȯ↓2ṁ:R5 0Ċ2∞1
```
[Try it online!](https://tio.run/##yygtzv7/P@Hhzhl@iocWHlpepZ1/pMuo5MT6R22TjR7ubLQKMlUwAIo86phn@P//fxMA "Husk – Try It Online")
A bit clunky, but here's what I have for now. Returns the full sequence corresponding to the given 1-based `k`.
-2 bytes thanks to Razetime.
### Explanation
Rather than building the sequence directly, we build a list containing at each position `n` the number of occurrences of `n` in the sequence, then we convert it to the final sequence.
```
`ṘN!¡§z+oĊ2tȯ↓2ṁ:R5 0Ċ2∞1
∞1 Start from an infinite list of ones
(in s0 each number appears once)
¡ Iterate the following function
§z+ Sum together
oĊ2t The even-positioned values
ȯ Ċ2 with the odd-positioned values
ṁ:R5 0 with 5 zeros added before each one
↓2 and the initial 2 zeros dropped
! Get the kth iteration
`ṘN Repeat each natural number as many times as indicated
```
The trick here is that at each step we build two infinite lists and sum them together: the first one is the even-position values, which will each move to position `n/2` simply because we remove the odd positions from the list; the second one starts from the odd positions (`n->(n+1)/2`), inserts 5 zeros before each value (`(n+1)/2->3n+3`), and removes the first two zeros (`3n+3->3n+1`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 or 17 bytes
```
×3‘
H
æ«ḂĿ€⁴¡Ṣḣ³
```
[Try it online!](https://tio.run/##ATAAz/9qZWxsef//w5cz4oCYCkgKw6bCq@G4gsS/4oKs4oG0wqHhuaLhuKPCs////zE1/zM "Jelly – Try It Online")
Takes *n* and *k* as arguments in that order, and outputs the first *n* elements of *s**k*. The 16-byte version above does not work for *k* = 0; if this invalidates the solution, you can add an `R` after `æ«` for a 17-byte solution.
## Algorithm
As is so often the case, producing terse code here was a matter of translating the problem directly using a brute-force algorithm rather than looking for a nice mathematical way to solve the problem. We simply start with a sufficiently long list, then Collatz and sort it the required number of times, and output the first *m* elements. (As an optimization, which saves runtime but more importantly a byte, we can in fact Collatz it the required number of times but sort it only once, because sorting+mapping+sorting a list is equivalent to just mapping+sorting it.)
The number of terms we start with is *n*×2*k*; this guarantees that all terms which are numerically at least *n* will be correct in the output (any term that started higher than this couldn't be reduced to *n* in only *k* iterations), and therefore the first *n* elements will necessarily be correct in the output (because no *s**k* can grow faster than the integers do, thus *s**k*(*n*) ≤ *n*).
## Explanation
```
Function 1Ŀ:
×3‘
×3 Multiply by 3
‘ Increment
Function 2Ŀ:
H
H Halve
Main program:
æ«ḂĿ€⁴¡Ṣḣ³
æ« Calculate {n} times 2 to the power of {k}
¡ Loop times:
⁴ k
€ On each {of the previous iteration's results, if any
or the numbers from 1 to the input, if not}
Ŀ Call the function whose index is
Ḃ determined by whether {that number} is odd or even
Ṣ Sort {the resulting list}
ḣ Take the first elements
³ n
```
I'm actually not sure why `ḂĿ` (which should call `1Ŀ` on odd numbers but a nonexistent "`0Ŀ`" on even numbers) decides to call `2Ŀ` on even numbers, but it's convenient here. (I assume it's some special case in Jelly that recognises that it doesn't make sense to do a recursive call here, but I'm not sure what triggers it; the special case isn't mentioned in the documentation for `Ŀ`, but the quicks aren't fully documented anyway.)
One interesting thing about this code is that it's a self-polyglot; the `€` does something different on the first loop iteration than it does on the other loop iterations (and the code wouldn't typecheck in a typical statically typed language as a consequence). I frequently do this sort of thing in horrifyingly low-level esolangs that are a nightmare to program in, but this is the first time I remember doing it in Jelly. As a consequence, the code doesn't work for *k* = 0 (it tries to sort the *digits* of *n*, due to a special case in Jelly that's more harmful than useful here). If this is a problem, it can be fixed at the cost of 1 additional byte by adding an `R` after the `æ«`.
[Answer]
# [J](http://jsoftware.com/), 39 bytes
```
]{.[:/:~[_&(]2&|`(-:,:1+3&*)})1+[:i.2&*
```
[Try it online!](https://tio.run/##fc67CsJAEIXhPk9xsNjcJmtmE28LVoKVlW0ICmJQGx/Ay6uvk23UJFoMDOzPN3txIx02WFqEIOSwMpnGartZu/qmKzu2z2qnotqo@z7KLFlOC5XEj5jTyp61UYmLg@B4OF0RMcEQCkJJmBCmhBlhTlgQOJeRd5aApWBJWBqWiKViyVg6k8fI2k80sg6wP@R/ur/gVe6rHfjTHuC7J0rPmpblN9uXO/ig/3XDu0XrmsC9AA "J – Try It Online")
Called like `k f n`, returns the first `n` elements.
I am using the same algorithm as ais523, though I stumbled upon it independently.
* `1+[:i.2&*` Generate `n*2^k` elements starting at 1.
* `_&(]2&|`(-:,:1+3&*)})` Apply collatz k times using Item Amend.
* `[:/:~` Sort.
* `]{.` Return first n.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 78 bytes
```
i=0;f=k=>f(k,c=(n,k)=>k--?c(2*n,k)|n%6==4&&c(~-n/3,k):console.log(i),c(++i,k))
```
[Try it online!](https://tio.run/##FchBDsIgEADAu/@QLALWqPXQZvEtZAWDkKWxTU9Nv454nPm41c30jdNiuLx8rREvY8CENkDShMA6SbTJmCfB9fTXxscH4l0Igt1wd2s1UOG5ZH/O5Q1RagKlYntZx0OAXtYf "JavaScript (Node.js) – Try It Online")
Quite [port](https://codegolf.stackexchange.com/a/224946/) but still some changes
# [JavaScript (Node.js)](https://nodejs.org), 98 bytes
```
i=>g=(n,a=[...Array(i<<n+1)])=>n?g(n-1,a.map((c,j)=>(c=c||j,c%2?c*3+1:c/2))):a.sort((a,b)=>a-b)[i]
```
[Try it online!](https://tio.run/##FYrLCoMwEAC/prDbxLTRmxql3yEe1vVBxCYSpVDw39P0MgzDrPShg4Pdz8z5cYqzidY0iwEnyXRKqVcI9AVb105o7NE0rl3AZVqSetMOwHJNEdjwda2Sb3nL90Lokh85IpakDh9OAJJD2igbsLN9nH0A60ajq8S6eFZCJEH27vDbpDa/wPwfEDRiFX8 "JavaScript (Node.js) – Try It Online")
Pure definition
`i<<n+1` for `n=1` case
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
o*L¹FεDÉi3*>ë2÷]{I£
```
[Try it online!](https://tio.run/##AScA2P9vc2FiaWX//28qTMK5Rs61RMOJaTMqPsOrMsO3XXtJwqP//zMKMTU "05AB1E – Try It Online")
A port of the jelly answer
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 34 bytes
Generates each sequence. Still a bit too verbose …
```
∧ℕ₁≜gT;?⟨×₂ᵐc{-₁/₃.%₂1∧}ˢ⟩ⁱ⁾l;Tj₍∋
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSu9qhtw6OmpofbFjxqm2Zs8HBXZ@3DrRP@P@pY/qhl6qOmxkedc9JDrO0fzV9xeDpI3dYJydW6QHH9R03NeqpAEUOg0trTix7NX/moceOjxn051iFZj5p6H3V0//8fbaBjqGOkY6xjomMaCwA "Brachylog – Try It Online")
```
∧ℕ₁≜gT;?⟨×₂ᵐc{-₁/₃.%₂1∧}ˢ⟩ⁱ⁾l;Tj₍∋
∧ℕ₁≜gT trying T = [1], then T = [2], then T = [3], …
;?⟨ ⟩ⁱ⁾ apply the predicade input times:
×₂ᵐ multiply each element by 2
{-₁/₃.%₂1∧}ˢ select outputs where
(element - 1)/3 must be odd
c join both lists together
l;Tj₍∋ get the length of the final result,
and output T so many times
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~67~~ 65 bytes
```
f=->k,n{k<1?[*1..n]:f[k-1,n*2].map{|x|x%2<1?x/2:x*3+1}.sort[0,n]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5bJ68628bQPlrLUE8vL9YqLTpb11AnT8soVi83saC6pqKmQtUIKF@hb2RVoWWsbVirV5xfVBJtoJMXW/vfRK8kMze1uLomuaZAIS06WcfIACgKAA "Ruby – Try It Online")
### Quickly explained:
If we know that the output is in the range (1..n), then we can start reducing the array (1..n\*2^k). The rest is standard Collatz for k steps.
(Thanks Kirill L. for -1 byte)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 84 bytes
```
~`(.+),(.+)
.+¶$1*$(2$*)$2$*$¶¶¶$$.`$*¶%$1+`(_+)\1$$|(_+)¶3$*$$2$$1$$#2$*¶O`¶,G$2`¶_
```
[Try it online!](https://tio.run/##FYo7CoAwEER7r@EI@RHM5hCWXkBILCxsLMRSPNYeYC8WNwy8GYZ3H8957am1r5robegYohdGcjAEZ6GAcA8QK5zwhOSrKd5uCXj7EM5qqQp9RurSWoXDAtIqreVA8w8 "Retina – Try It Online") Explanation: Uses the same `n2ᵏ` approach as other answers. Works by building up a Retina program with `k` and `n` hardcoded in and then evaluating it. For example, the link demonstrates `k=3` and `n=20`, and this results in the following Retina program:
```
.+
2*2*2*20*¶
```
Replace the input with `n2ᵏ` newlines.
```
$.`*
```
Generate all of the integers from `0` to `n2ᵏ` in unary.
```
%`
```
Separately for each line...
```
3+`
```
... repeat `k` times...
```
(_+)\1$|(_+)
3*$2$1$#2*
```
... if the current value is even, then halve it, otherwise treble it and add `1`. (The `3*` needs to be at the beginning to avoid conflicting with the `$1` while the `$#2*` needs to be at the end to allow for an implicit `_`.)
```
O`
```
Sort all of the lines into order. (This is not a numeric sort because the lines are still in unary at this point.)
```
,G20`
```
Select the `n`th line.
```
_
```
Convert it to decimal.
At a cost of 4 bytes, the first `n` terms can be output instead:
```
~`(.+),(.+)
.+¶$1*$(2$*)$2$*$¶¶¶$$.`$*¶%$1+`(_+)\1$$|(_+)¶3$*$$2$$1$$#2$*¶O`¶,G1,$2`¶%`_
```
[Try it online!](https://tio.run/##FYq7CYBAEAVz2/AJ9@NwzyIMbUBwDQxMDMRQLGsL2MbOPR4Mw2Pu4zmvnWr92OXoU0OXowoowBUEDwNU2oDMCCoDKLLbol8JeJuoTFZZCnv60qKFVdJMCcVk4K3WKZXxBw "Retina – Try It Online") Explanation: Only the last two lines change.
```
,G1,20`
```
Select the first to the `n`th line. (There is actually a zeroth line that we need to skip.)
```
%`_
```
Convert each line to decimal.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
²╒kÉm■sk<
```
Port of [*hyper-neutrino♦*'s Python 2 answer](https://codegolf.stackexchange.com/a/224946/52210), so will also output the first \$n\$ values (and will use the trick of only checking the range \$[1,n^2]\$).
[Try it online](https://tio.run/##y00syUjPz0n7///QpkdTJ2Uf7sx9NG1BcbbN//@GBgYKxgA) or [verify some more test cases](https://tio.run/##y00syUjPz0n7///QpkdTJ2Uf7sx9NG1BcbbN//@GBgYKBlwg0hBMGoFJYzBpAiZNAQ).
**Explanation:**
```
² # Square the (implicit) first input `n`
╒ # Pop and push a list in the range [1,n²]
k # Push the second input `k`
É # Pop and loop `k` amount of times using 3 characters as inner code-block:
m # Map each value in the list to:
■ # Pop and calculate its Collatz value
s # Then sort the list from lowest to highest
k # After the loop, push the first input `n` again
< # And only leave that many leading items from the list
# (after which the entire stack is output implicitly as result)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~183~~ \$\cdots\$ ~~148~~ 126 bytes
```
g;t;l;i;f(k,n){int a[g=l=n<<k];for(;g||k--;g=qsort(a,l,4,L"\x62b078bǃ"))for(i=l;i--;a[i]=g?i+1:t%2?3*t+1:t/2)t=a[i];i=a[n-1];}
```
[Try it online!](https://tio.run/##bZLNjpswFIX3eQrLEhWEiwab/I7jZlF11zdIUMV4gEGmTotZRJNh1YfrW5VeQ0PSURfA9fH5zgWuVVQq1felaEUtKlH4GkxwqUxLskMpa2l2O52K4tT4onx701EkSvnDnprWz6CGBXyhx/OKP8XrzdOvnzQInLOSGIXO7FClstxXIXtsPb5P5q2rHnjQSrclKnyYiKWi679llfGDy4y4zjY@pPLCgEOCHZawgjVsYAssBsaAcWAJsAWwJbAVsDWwDbAt8LgDy@7J9@x/cZeAIL@CN/QK/4vfJywQTEbwHr3B7/BbQgdz60Ab4ztjd8zpoB6U6jU/FfgPHsZq7ix/NTZpbNL4pPFJSyYNU7WMwYgZUS9ZM1cvudJ54xrh4D7z43n7Ca8lhftlQjsEhqHr3TV0yhRhqN2ohllldf31pCVD/wAYLM1O1gc8NWFoBt9gbOR4tiCXFjfHwbvNMeGDzKVsBuF7g/7Cp1p6z0AM3kn0kXjPnqWACdCAiVz@ngpCHymhgcO62Y0knj0aCtePHTukztbNuv63KuqstH30mp9zZdtM6T8 "C (gcc) – Try It Online")
*Saved a whopping 22 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs \$k\$ and \$1\$-based \$n\$ and returns the \$n^{\text{th}}\$ element of \$s\_k\$.
### Explanation
```
g;t;l;i; // declare all int vars needed
f(k,n){ // main function
int a[ ]; // array a to hold sequences
g= // init g to non-zero
l=n<<k // length is n * 2**k
for(; // main loop
g|| // g non-zero is an init loop for a
k--; // after that loop k times
g=qsort(a,l,4, // end of each loop sort
L"\x62b078bǃ") // using a -zexecstack
// comparator and set g
// to zero (return value
// of qsort for success)
for(i=l;i--; // loop over all elements in a
a[i]= // each loop set a[i] to...
g? // if it's the init loop
i+1 // set a[i] to i + 1
: // otherwise post-init loops
t%2? // apply Collatz map to a[i]
3*t+1
:
t/2)
t=a[i]; // temp for a[i] to save bytes
i=a[n-1]; // return the 1-based nth value
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 46 bytes
```
NθNη≔…·¹×ηX²θζFθUMζ⎇﹪κ²⊕׳κ⊘κW⁻ζυF№ζ⌊ι⊞υ⌊ιI…υη
```
[Try it online!](https://tio.run/##VY09bsMwDEZ3n4IjBahA64yZCi/N4MAocgHFZiMh@nEk00FyeZdql3YhyI@Pj6M1eUzGb9shzrwcOZwp403tm7@zlfm9FHeJeIij5@JW@jTxQvim4eQCFbQahnQXttVwU0ppeMrRV8ogNujN3KUQTJzwKReUo8kP7NPEPuFVQyu8mDMFigtN@OvcabhW04fxq4TSi/JunSfA3kUuVcZKwc@bLnFcaiIrFzigEx4GLhb5X7hvhuwE7UyR8hg9dTbNFbL1w7btmvZ1e1n9Nw "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` elements. Explanation:
```
NθNη
```
Input `k` and `n`.
```
≔…·¹×ηX²θζ
```
Create a range from `1` to `n2ᵏ`.
```
FθUMζ⎇﹪κ²⊕׳κ⊘κ
```
Apply the Collatz formula `k` times to the range.
```
W⁻ζυF№ζ⌊ι⊞υ⌊ι
```
Sort the range.
```
I…υη
```
Output the first `n` elements.
A port of @hyper-neutrino's algorithm takes 48 bytes:
```
NθNη≔⁰ζW‹Lυη«≦⊕ζ≔⟦ζ⟧εFθ≔⁺⊗ε÷Φε⁼⁴﹪λ⁶¦³εFε⊞υζ»I…υη
```
[Try it online!](https://tio.run/##TU7LSgNBEDxnv6KPPTBCMOIlJ0kiLBjZu3iY7LaZgc7MZh4RI3772EsW9FJQXdVV1VsT@2C41taPJb@W04EintW6@c@t8KeU3NHjUsNV2Kd1TIAvlJKAP2aLRWmwSsF3s9ibcba3vo90Ip9puD0uZuHt@q6BpsNHiCCNMAsdl4TbUA5MA5Jktj5v3cUNhM@Os6whDbtzMZzwQcM@DIUDsoZHpcS9muAvlxR0Jcm4W/tP00XnM25MEvjqmTY2jJMqy9W61lVzv6x3F/4F "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `k` and `n`.
```
≔⁰ζ
```
Start counting at `0`.
```
W‹Lυη«
```
Repeat until we have at least `n` elements.
```
≦⊕ζ
```
Get the next value we want to calculate the count for.
```
≔⟦ζ⟧ε
```
Start with a list of just that value.
```
Fθ
```
Repeat `k` times...
```
≔⁺⊗ε÷Φε⁼⁴﹪λ⁶¦³ε
```
Double the list and integer divide an appropriately filtered copy of the list by 3. This results in a list of all the values that result in the target value after `k` steps.
```
Fε⊞υζ
```
Add that many copies of the target value to the list of results.
```
»I…υη
```
Output the first `n` elements.
[Answer]
# [R](https://www.r-project.org/), 76 bytes
```
f=function(k,n,a=1:(n*2^k),b=a%%2)`if`(k,f(k-1,n,sort(a*b*3+b+a/2*!b)),a[n])
```
[Try it online!](https://tio.run/##jc3RCoMgGAXg@57CMQK1fyyVbgKfZGxloRQ6DXWM7eVbu@@i6/Odc@I6BudU/nYpxNxFvWiV5Wqkefkxz8FjCx6UZC32lD8sgUGqsuSkn02/ZQbbC9vEv40VHaiohkpdOT0NhIC6@TvZe8BWCvCS16QozihN4Y3ypJGZY8qIN0g7/dQ@J2RCRFbWwICDKJJaFvfBrOUN7KzCJskBxI4gfgQJsv4A "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 96 bytes
```
(x:w)#h|x<=h!!0=x:w#h
x#y=y#x
g x=[div i 2|i<-x,even i]#[3*i+1|i<-x,odd i]
f 0=[1..]
f n=g$f$n-1
```
[Try it online!](https://tio.run/##fczNToNAFIbh/VzF18AC9NBwoP6GuQ4XExZEoEyo2AipU8O946ltGsXq7vy8eZqib6vNZpoC9/gees3oMt0sFrGW1WuU8/Z67zm1htOmtDtYJKPNIkfVrupgc8@kV/aaj7fXspSTqhFrw8vlYer02q/9LuLppbAdNLZvthtgiq6Ejw@7fbJDg0DrEEGNNkSPEUFL6ENkEYaqH56Lvupzpc6zKEYBQUwwTEgIKWFFuCHcEu4I94QHAsuf5c8SsBQsCUvDErFULBlLl8R5SAePZ94f5H/sF33ikjM3E7@jF9y5vTp56dH7Tc7Ui/APPA9zNX0C "Haskell – Try It Online")
] |
[Question]
[
*With the US election going on right now, I noticed that there is one (completely meaningless, but still) thing which Trump can still achieve and which is out of reach for Biden: Having the won states being connected.*
**Task:** Given a list of strings of two-letter abbreviations (see below) for US states, determine whether they are connected. That is, is the graph whose edges are the states in this list and where two edges are connected whenever the corresponding states are neighbors to each other [connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory))? That is, for each two states, does there exist a path (in this graph) from one to another?
On Githhub, [ubikuity](https://github.com/ubikuity) has compiled a [list](https://github.com/ubikuity/List-of-neighboring-states-for-each-US-state/blob/master/neighbors-states.csv) of neighboring US states, which I copy here for convenience:
```
AK,WA
AL,FL
AL,GA
AL,MS
AL,TN
AR,LA
AR,MO
AR,MS
AR,OK
AR,TN
AR,TX
AZ,CA
AZ,CO
AZ,NM
AZ,NV
AZ,UT
CA,HI
CA,NV
CA,OR
CO,KS
CO,NE
CO,NM
CO,OK
CO,UT
CO,WY
CT,MA
CT,NY
CT,RI
DC,MD
DC,VA
DE,MD
DE,NJ
DE,PA
FL,GA
GA,NC
GA,SC
GA,TN
IA,IL
IA,MN
IA,MO
IA,NE
IA,SD
IA,WI
ID,MT
ID,NV
ID,OR
ID,UT
ID,WA
ID,WY
IL,IN
IL,KY
IL,MO
IL,WI
IN,KY
IN,MI
IN,OH
KS,MO
KS,NE
KS,OK
KY,MO
KY,OH
KY,TN
KY,VA
KY,WV
LA,MS
LA,TX
MA,NH
MA,NY
MA,RI
MA,VT
MD,PA
MD,VA
MD,WV
ME,NH
MI,OH
MI,WI
MN,ND
MN,SD
MN,WI
MO,NE
MO,OK
MO,TN
MS,TN
MT,ND
MT,SD
MT,WY
NC,SC
NC,TN
NC,VA
ND,SD
NE,SD
NE,WY
NH,VT
NJ,NY
NJ,PA
NM,OK
NM,TX
NM,UT
NV,OR
NV,UT
NY,PA
NY,VT
OH,PA
OH,WV
OK,TX
OR,WA
PA,WV
SD,WY
TN,VA
UT,WY
VA,WV
```
To be clear, “to be a neighbor of” is symmetric and hence the entry `AK,WA` means that AK neighbors WA *and* that WA neighbors AK. There might be some disagreement whether some of these states are indeed neighbors of each other but for the purpose of this question, let us go with the list above. (Although that would mean that Trump needs to lose Alaska in order to have his won states connected.)
**Input:** A list of two-letter strings or something equivalent such as a single string consisting of a series of two-letter pairs such as `"AK WA OR"` or `"AKWAOR"`. It may be assumed that each string is one of the two-letter abbreviations in the list above and that no string appears more than once in the list.
**Output:** Return/Ouput a truthy value if the states are connected and a falsey value if they are not.
(Very!) simple test cases:
* `[]` is connected.
* `["AK"]` is connected.
* `["AK", "WA", "OR"]` is connected.
* `["UT", "CO", "WY", "KS", "NM"]` is connected. (That is, they form a [connected graph](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)) although they do not form a “line” of neighboring states.)
* `["AK", "OR"]` is not connected.
* `["ID", "OR", "WA", "AL", "GA", "TN"]` is not connected.
[Standard I/O rules apply](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and [standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~169~~ 167 bytes
```
ConnectedGraphQ@Subgraph[Cases[#[v="StateAbbreviation"]&/@#@"BorderingStates"#@v&/@Interpreter["USState"]@#|"CA""HI"|"AK""WA"/."MI""MN"|"NY""RI"->0,a_ b_:>a<->b,3],#]&
```
[Try it online!](https://tio.run/##bVZdb@o4EH3Pr7CMVO1e0XalfataFG/CLbmQwJIUykZRFUpaooVQJSlXq8L9692xx4ltSh/cYM8cz5z58GzTep1t0zp/Tj9f7j6dXVFkz3W2ui/Tt/Xfdvi@fOVfsZNWWRV34v0dDeu0zthyWWb7HBR3BU0uru2OTf/alauszItXIVHRjr2HA6@os/KtzGCN6UMozmhidw7UYZQOPHqgbEjpnNHrK@p7lPoBbAULSqcevez90U2fyPLpppfeXvaW3T@Tbie5@PztGxFApKrTYlWRvCAvu5L/gr1@Uef1fxX59rsVZjWr6zJfvoNBsVDpklEOcstNlliW2ImLdJs9JfE5z8gd4aeWBTdG67wiaVXtnvGU/Ewr8poVWQlqK/Izr9fW7SFal1m6ioEPYUcORJDLHjnDD7mwLQJ/aK@zAeiYstU2L8BAwMz3mZvv84ob0iWUbTaSvmqyea9chyYJub4igFE9IQa56ZHKPuPHoWcJOgx3T@1JyM0doCGx1za5hciMhPEf9PuIm3DP@OqHfI0CeuRWDVECvoUzlP0jVRwh7Iz5GszE6vP1IaJKeCqFRxqyL1TGQ3kLXx@VCsCiyniqkOFSJTCWArAJR0OBGfSVAYgMZsA6X2iKkVT0hTGQgrBCEnI33X5z5oqzH3ydMKUM4UCBGXriCrXvDX/IHNDZKtwzg1o2Uu4GDl9DR0BAhZgEe25jSqQIQDKkT@zUM68xwxP4w4Wi2UNhTxMOGuGRJuyJWwaaGDPE/EBhItmhe4oMoZCpMT4VhpgosYWB7GnIYEDLEhI9nynFUWMSm2p5KnKH@k0AA80Hv6HS7ct4triuc4ruN@gO8j4wkoQraonty6hx/1u7pSeBJtZyzRTLgXuePr@hD3MFncTCiXTMscGCJJGpWsCItryfqjdV4LlfjNFSKugbsdTxMVRnVGZGYWJ/wFva9FXCgybLhZ1Yksgwrz4Zy4UKG4RQKfvmTXpDefxyU5Nus0jdJGP8Q@FPtUgEjlHWoWNk5RFpk@ZjzCNJSQsxbvybNGncRkamiXbfeGiEFP3RycbGprfJ8dRowzKYM9kfWrEJM6hEh7EasNOhYXrhTz2jDtpmeUQmdGICR6mFrpnqGi@yOX9JmCg4k/CILLuSToGj6JfqjwZrWCntE9CKPURnkkXnC1V0w2YnL8VAUSAFGlqlna6yENMEaXU1fubMqDuI3xHlvgJhN2m7lYLwzKTzVGV62sszX5htODrt2fiMgB3HQ09MC4mYf7bpvxnRxjnyChMKSeXAkBdVDYPPFZ8zHoq3clfDIBlr4onlbLK0NLfOT4cwdYkva3IOxoLtvKjjzmXvxYZp8Ff4nBa/Pix4Iq0PPpA0/9u3UJAJe@gYuj1faNOBr@s00nprmjP1SN@3Ldc6fv4P "Wolfram Language (Mathematica) – Try It Online")
TIO doesn't have [data sets](https://codegolf.meta.stackexchange.com/q/7314/81203) downloaded, so most of the footer is to ensure the code works as if they had been.
The `BorderingStates` properties differ from the given list of adjacencies in four ways: HI and AK do not border any other states, MI borders MN, and NY borders RI.
```
Interpreter["USStates"]@# (* get Entitys corresponding to abbreviations *)
#@"BorderingStates" (* for each state, get a list of bordering states, *)
#[v="StateAbbreviation"]&/@ % #@v& (* pair it (unordered) with each of those and convert back to abbreviations. *)
% /@ %%% |"CA""HI"|"AK""WA" (* append CA-HI and AK-WA, *)
% /."MI""MN"|"NY""RI"->0 (* discard MI-MN and NY-RI, *)
Cases[ % ,a_ b_:>a<->b,3] (* then get all pairs and convert them to edges. *)
ConnectedGraphQ@Subgraph[ % ,#]& (* is the subgraph consisting of input states connected? *)
```
[](https://i.stack.imgur.com/gIVib.png)
---
There's also [`GraphData["ContiguousUSAGraph"]`](https://mathworld.wolfram.com/ContiguousUSAGraph.html), which is missing AK-WA, AZ-CO, CA-HI, and NM-UT edges. Unfortunately, the vertices are numbered in what seems to be an arbitrary order.
[](https://i.stack.imgur.com/bxF5V.png)
[Answer]
# JavaScript (ES6), 360 bytes
Returns a Boolean value.
```
A=>!A.some(s=>s,(g=x=>A.map((s,j)=>'dx5d0w805045081o3klg165343501b328xi342010q4z45v3161r7k0q168i383xe40h3k0e0e3j7f090g6i190x120w621h0oax504lfbqd1b1n9g601l4rbb6o1c0p1v262h6vdy4lac1t561n1f06pnkm443q6jpq845x0u1a1c080y2z3a25112b1q9um81cgs1e041s530abh1k1zksin6d0w'.match(/../g).every(s=>t-=P(s,36),t=(P=parseInt)(x>s?s+x:x+s,36)%22958+1)||g(j),A[x=A[i=x],i]=0))(0))
```
[Try it online!](https://tio.run/##fVBda9tAEHzvr2gNJXdYUXbvK3LhVEQLJaRNQpJSivGDJEuyLFlfpyhnk//uSqb0oTR92GGZmZ1ldxsOoYm7vOnPq3qdHFN9DLT/LnBNvUuI0b5xSKat9gN3FzaEGGdLtX@2tnINzx5IEBI8rHlRZqgkF1wCRpx5NueCAUIrDkIOHBV2lwW0qLyce9wmAja8gAQSvr1MYQGZynEBFhk8K4YbqEM7Zpdp1K4xwmqRKcBSdFGkaoyhwYEptlHDei/KMMZeKqwwBdVUxU4I3qpt03pCWnjCcPR7sGcHHjKJyCJsF087D@PMYAICjeQQRhss8FCYvFLjXWfjrX28IReue5FRNxmSbj/9oj/Xd@MHuKJOr8mdbsLOJFdVT4n1zUcztx/s/CS/Z2whvTnSl5eMbKkTLK0Olrm2KydfaaCUjHWM68rUZeKWdUZSslxR@uYvahZcz16hnbezH8GEt/f/tHx/nMRPtyfjzwmvHya8@fafxFeyrj7/Fv8sDb5O@OXUP95MQ8df "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~207~~ ... ~~194~~ 187 bytes
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) for -1 byte!
+65 bytes because I had a bug in the generation program and forgot to include quite a few borders.
```
.•K0®Z"E=м7δþˆLäZΩcÉ!P0:n~Žæ₃ƒû‡âQƶºì`tu×^èÂā„∊\¦₁ôβ2Èœ÷бTBÀ7Õu2ôIkDδ‚εε•AмÎÝ≠ζó'#‚Ó¶–ºÇΘ¶7˜H»«âиÈ8ëf:ÝQº[EÍø’Δ₁#ÍÂ|Q₄T´ƶŽ#UΣMW„é!ʒHµßЏô7¬·ΔŠ¥Ò÷¾kå«ÛǝO₆ðÿ•51вηOs{R`38*+åyË+]DvDøδ*O}˜ĀP
```
[Try it online!](https://tio.run/##FY7bSgJRFIZfJceLoDKsCEPoolIwrMxSJM3QoiAMvbCCjkxTlBV1oUInLbOMpIiycRQPBftPg4SNz7BfZNrefPCvtVjfHwr755cXVbWbiWmrnry5BfNgs2KgMr4ah2N4dNPsAo41k3pjcLdWxROT9utRlJl4j7S9rpASXn2ra7iYwzOknz0m3rLIySzhd3uQaa4XkVoMhVqKfDiGIRqwzz1rvZBHAyYqM/Ga5mmej4aaFZwjyY5TVMFnu5ZvECMKE2PccEQviWJoJCykTF6QbhYRGcDLkhFJOyl5zDhDkYlXNM6dWh6kbTuTDhxEriu1qtZJH8ZdvBaymr@oheRxx8sUIRvIKynQOA8ZRFEgXwFk@Peb36SNSYd4xzev1d/TzNGCLbw15esb6OhEZgOnnV7TuglFKnfYdhqJH3FSVT2C0yF0tQkjthZdMy1ap1ucGBe8qk4XDOlW/Jsb/w "05AB1E – Try It Online")
This generates a adjacency matrix \$A\$ of the given states and checks if it represents a connected graph using a modified method from [this math.se answer](https://math.stackexchange.com/a/864636/612068). Instead of calculating \$A^k\$, we calculate \$A^{2k}\$, because it is shorter.
~~For some reason the matrix multiplication code `øδ*O` is really slow, this means that the test case with five states doesn't finish on TIO.~~
*Edit:* The lazy evaluation seems to cause problems here, resulting in extrememly long execution time.
**Commented**:
```
.•K...Õu2ôIkDδ‚ # convert from list of abbreviations to matrix of integer pairs
.•K...Õ # push compressed string "mirivaiascaldcoknjmoakmtcapacohidevtkywiinmemanmksilwaorgamnsdidohneflnctnnywywvmsndtxnhctarnvmdutlaaz"
# this is the concatenation of all state abbreviations
u # convert to uppercase
2ô # split into groups of 2
Ik # find the index of the each input in this state list
D # duplicate
δ‚ # and create a matrix of all pairs
εε•A...ÿ•51вηOs{R`38*+åyË+] # calculate adjacencies
ε # map over the rows:
ε # map over the pairs:
•A...ÿ•51в # push compressed integer list [19, 1, ..., 26, 50]
η # get all prefixes
O # sum every prefix
# this list now contains all adjacent states represented as
# a + b*38, where a>b
# it also contains some pairs (a, a), this reduces the maximum difference
# between integers, leading to shorter compression in a lower base
s # swap to current pair
{R # sort and reverse it => [a, b]
` # push both numbers on the stack
38* # multiply b by 38
+ # sum both values
# this maps a few different pairs of states to the same integers,
# but with the given permutations of states this is fine
å # is this contained in the list?
y # push the pair again
Ë # are all values equal? (is this the same state twice?)
+ # sum / boolean or
] # end both maps
# Now the adjacency matrix of the states is on the stack
# ex.: for input ["AK","WA","OR"] this is [[1,1,0],[1,1,1],[0,1,1]]
DgFDøδ*O}˜ĀP # check if adjacency matrix is connected
D # duplicate the matrix
v } # for each row square the current matrix M:
D # duplicate the matrix
ø # transpose it
δ # for every pair of rows in M and M^T
* # multiply element-wise
O # and sum each list
˜ # flatten the matrix
Ā # Check if every value is not 0
P # take the product / boolean all
```
[Try it with step by step output!](https://tio.run/##XZBbTxNRFIXf51ccTh9MoDVYQkqaEKKWBINYqiVEEMO0HWRomWlmptXiJUMxWDT60JJ4o4rVGgnEKE6nDeWSnE1rYpOT/obzR@oZ4QF52clOvrX3WkvVxYgsdTpYVpIpw49wX//CkJvYQ8JFZpZGe8n3KTw82N73UQsOW6vX4csU3YrCWtd4r1950jiAryy70sxDnZmfoBRq2mQPdmaNFLy@C98ge7zMzA8s9/wO4dwyWHTXC7lGAaqNTfIzfAVMH6zwPwKOqotJTdJ1KYZ0Q5OVe6dWBh0rKS9YAtaTCdlAsmKoHBENCYmRiCalZdGQVUU/y1@LOweVtKQ5PM91ItARl8pKTI5K/@EBajHznYAXRf75AVLnUFKUtVPEHSD1f33QCq1wq5fb@/AKimxtk9rw64KLK6FAbGYWePJn9A2xfa2NEVIn21Bq1yA3ANtzfiiGyN70MLyEGjPf0nXehYsv2Uchln0aJlbTbhy4JujnsUleF2x1/cmPkAp85CXVwPKRHVKl63wpQx6q5DAOZX79/e9ikGVX4QcccVv9l9q7tBrUH96c7Rvo7oFyBl70zAhYjC2IUUmJZtBJunOhAukA1KjVHXwsYF6OMS8hb9xjzKOkel/SzsGtjWNznJ9MJJCiKp4lSVPP1NjpTOOJMHYjfDXozMnbzhy95cwbY3im4/EoqichLmX@Ag)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~143~~ 139 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
,OṢ*/V%⁽]Ƙ%⁽9ḃ%⁽ðṭe“`€LE<⁼,#g>Q#&68-s¦Ø¬Yḟ¢>ȷ*I¬Þ!Ƈ?øẇ@Þ²m>Ṡ3+@O*c÷©%"*Þ¢Ð⁾ẠþÑẈÐẈ"æ×ḳw³l¢qṠ©|4°€£Ð%½^©Ñ³©Ṇ-N¿ð!ƊẉœK)½ƇØX#²4÷+‘Ĥȯ⁼ðþ`æ*L$PẸ
```
A monadic Link accepting a list of lists of characters (valid state abbreviations) which yields `1` if the states are connected or `0` if not.
**[Try it online!](https://tio.run/##FY49S8NgFIX/ik2MYJriYBEFiQ3iIBajDn5SKUgRJA7iIIJDo2LUKcXBDFJLlEAgYmiGfGAi3Iuhf@O@fyQmy/PAgcM5Zz1Nuy4KSaXYFud2BaanndyqtETRXWX0Kf7qsf5bl9167bVlpv9I/Km8zc8sLDYuwUELvAOK3sGWJ6G4Dh4Oa7mxghElRguHMD6XKR7N11uqeIIhuAInlqmNJtMzSkaY4YCSRzRLcOjgK0XBFQQa2BdlDdybJvjlMHygKUB6DC4OIACX4ofGJvyiX8ufKXn6e9mYhTQ30NrnYdzEsM76Ft7D5@S7/Is@Zl10xPb0FiVRURRHnHLISVPcqlJR3am4p3Cdfw "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##TY5dS8JgFMe/is4MmpMukiiI5agI0Vwv9iJjIYQEYRfRRQRdaEWrrpQu2kWYrBgMjIZeuI224Bwafo1nX2TtsYxufv/z9j/nHFVrtfMw5ERia@z0TjJouLKvUpkn1hVVNIn9Vg3qT5XgsltYWQgaH1zikN9ITM7OpU9BRxW6ZWI9g8YPB2wOutiO@8oiWsRRstiG3jFP7M5MKiuyBzgAI8mwUVXDZtDwiNNBD1vEucVmBAZ1fCRW/wz6NdBOIhsYFxkwo8Pwgs0kuPtgYAv6YBD7Jl2ETzTj/j1x7r4e8lPg@gqqewnoZXCQCuoqXsPr8D36F030KqizhYl14lghKtHCMJQkmYtJjJBnxsrFmF2BUtz8qW2XaLYkjjplyvwWZXHtv2c8nVv@zf72CAXK1VFcKjKy/A0 "Jelly – Try It Online").
### How?
```
,OṢ*/V%⁽]Ƙ%⁽9ḃ%⁽ðṭe“...‘Ĥȯ⁼ðþ`æ*L$PẸ - Link: states
` - use states as both arguments of:
þ - table using: (makes an adjacency matrix)
ð - the dyadic chain, f(A, B):
, - pair -> [A, B] e.g. ["HI", "CA"]
O - ordinals [[72, 73], [67, 65]]
Ṣ - sorted [[67, 65], [72, 73]]
/ - reduce using:
* - exponentiation [300182793244778239701651745925447642838407176218846116477308730441782375736846470235643437821593799141277880459172066217016359091361, 2201278718441498733883192946340630358395332861266884669706285143644864868806820973839329645162232740318586365901865065097808837890625]
V - evaluate 3001827932447782397016517459254476428384071762188461164773087304417823757368464702356434378215937991412778804591720662170163590913612201278718441498733883192946340630358395332861266884669706285143644864868806820973839329645162232740318586365901865065097808837890625
⁽]Ƙ - 24399
% - modulo 12108
⁽9ḃ - 15482
% - modulo 12108
⁽ðṭ - 7225
% - modulo 4883
¤ - nilad followed by link(s) as a nilad:
“...‘ - code-page-indices = [96, 12, 76, 69, 60, 140, 44, 35, 103, 62, 81, 35, 38, 54, 56, 45, 115, 5, 18, 7, 89, 235, 1, 62, 26, 42, 73, 7, 20, 33, 144, 63, 29, 246, 64, 20, 130, 109, 62, 205, 51, 43, 64, 79, 42, 99, 28, 6, 37, 34, 42, 20, 1, 15, 142, 171, 31, 16, 187, 15, 187, 34, 22, 17, 217, 119, 131, 108, 1, 113, 205, 6, 124, 52, 128, 12, 2, 15, 37, 10, 94, 6, 16, 131, 6, 180, 45, 78, 11, 24, 33, 145, 227, 30, 75, 41, 10, 144, 18, 88, 35, 130, 52, 28, 43]
Ä - cumulative sums = [96, 108, 184, 253, 313, 453, 497, 532, 635, 697, 778, 813, 851, 905, 961, 1006, 1121, 1126, 1144, 1151, 1240, 1475, 1476, 1538, 1564, 1606, 1679, 1686, 1706, 1739, 1883, 1946, 1975, 2221, 2285, 2305, 2435, 2544, 2606, 2811, 2862, 2905, 2969, 3048, 3090, 3189, 3217, 3223, 3260, 3294, 3336, 3356, 3357, 3372, 3514, 3685, 3716, 3732, 3919, 3934, 4121, 4155, 4177, 4194, 4411, 4530, 4661, 4769, 4770, 4883, 5088, 5094, 5218, 5270, 5398, 5410, 5412, 5427, 5464, 5474, 5568, 5574, 5590, 5721, 5727, 5907, 5952, 6030, 6041, 6065, 6098, 6243, 6470, 6500, 6575, 6616, 6626, 6770, 6788, 6876, 6911, 7041, 7093, 7121, 7164]
e - exists in? 1
⁼ - (A) equals (B)? 0
ȯ - logical OR 1
$ - last two links as a monad:
L - length
æ* - matrix power -> Adj^n_states
P - product -> products of columns
Ẹ - any?
```
All this could be shorter if one manages to find a suitable salt and domain for Jelly's built-in hash atom, `ḥ`, but I don't really know how to find that needle.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 266 bytes
```
≔E⪪S²⟦ι⟧θF⪪”}∨ⅉ\`⁸)ιfP≦?OX↙“a:;τ,πC_Dβ⁶k4_4÷‽ΦI¹#μO⪪ς¶⎇≦↙xh\8BNnkGMïTü)﹪▷;⮌Uχγx◧i◧⌊÷iXιh↧υηΠ�E~*>←ρ↧D!q⟦⦃№➙U&sU+]I⁹π‹¿ê⁸¤&º⌈ü{³⟦f‽?}O/QZ7·J&MDLnueÞW≕*"eε§ºR0q&RGTwbDLFS⁸~,*➙J↨a…⁷{¤[ε↖=DC⊞SS⌈BφW¦ï?ⅉIêEχ⌊±±3 ·ι.×qShiδiZyZ¤d↨Cζⅈr⪪Hσ ωWJ”⁴FΦθ№κ…ι²FΦ⁻θ⟦κ⟧№λ✂ι²Wλ⊞κ⊟λ›²LΦθι
```
[Try it online!](https://tio.run/##XVLBbtswDL33K4yebCC7FLv1REhurNikDEuRoxQ7BIGXGDWcNHE27Ouz53VAhx2eH00@PokQ98fdZX/aDfc7Xa/9YUx5d07deein1Izn2@SmSz8e0myRPAGv/Td837Pnh@@nS/JX90hlS1S9VFQtweyo8kJNRdSwBRw1tqRmzvkNbRUBlrbCQKDt2isqjCIJimyjbOmUlRxgZW2pLOq2jcozKS/gxmjFWqtAOgfnstJ5TS84e0miluQAL4ZMZYjBbA1JbshpQ60xmr3REoy2MFojbgmIUIupSjD0FXSCWBhsi9IxbiV56WxZRsQRueihCFTGNlTEriK/YZICiEyNYQqedU2sA9AGzlEzFmgNi2gWByDGrIw52XphB3jUPGq@jaKcEgwtmFW005LPQL4IXlYSZVWT4Dpo2givvQTbSABH5GPwtqjJFm2wpd/YpqWa2uAwK4S0hn/A/@Mi@ZplyZ/nfOmHqbuk74tEnW7jlL4h@LUfOnU8ndN@3oDsPyn34@06N7y@zYvx0TYsEjf0@@6z5eexH7okHbKkvl2Ps28NxyHDHtVYryldXrrd7Pe0SKpuPEzHf@7SzxbP9/vHHuAd@OH@5cfwGw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of two-letter pairs. Note that Charcoal requires a trailing newline to identify an empty string. Output is a Charcoal boolean, i.e. `-` for connected, nothing for disconnected. Explanation:
```
≔E⪪S²⟦ι⟧θ
```
Split the input into states and create a list for each state.
```
F⪪”....”⁴
```
Split the compressed adjacency list into individual entries and loop over them.
```
FΦθ№κ…ι²
```
Loop over any entries in the input list that contain the first adjacent state.
```
FΦ⁻θ⟦κ⟧№λ✂ι²
```
Loop over any other entries in the input list that contain the second adjacent state.
```
Wλ⊞κ⊟λ
```
Merge all the states from the adjacent entry.
```
›²LΦθι
```
Check that there is only one list of states left.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~632~~ ~~596~~ ~~550~~ ~~549~~ ~~545~~ 550 bytes
It's long but it works.
-36: Use regex and remove , and ; from compressed string (@nthnchu)
-46: Shorten for loops, compress lists (@ovs)
-1: Change `print(len(i)==0)` to `print len(i)==0` (@nthnchu)
-4: Change `len(i)==0` to `i==[]` (@nthnchu)
+5: Fix for `[]` by replacing `f(i[0])` with `if i:f(i[0])` (@nthnchu)
```
import re
i=input()
l=[re.findall('..',x)for x in re.findall("....","eJwVj2GyAyEIg8+WUdulCuwoi7X3P8jL+/FNECIa9A2M18B4U3VhhGEOYKqThekd878XX/wKiONnShK/JwouKbAs8Fm8r+LWiBb3Xpxz36eEooRRp9SitZZEbdRmn9puvPj2G1beWCRMIEOgVHWBNcGqgi1SNaRaSnUuelhvkEO3yehU+gd9xtqU6ldfyl9Z68t7P6wPeyfoSPSzc0DXQHwVdpGjmKLI0HpDa5Kd2jgTJ1vUrKotwppZlTnVw3SR4Cw4i32srGIMbcxqdVVr/7B/ZdjHjn1uGL/DS1/TJyx9WlIP+yfDrxt+7fQeX58bN3YuZqURD/cnz3+qZoSc".decode("base64").decode("zip"))]
def f(s):i.remove(s);[f(a)for a in[a[1-a.index(s)]for a in l if s in a]if a in i]
if i:f(i[0])
print i==[]
```
[Try it online!](https://tio.run/##TZHLjqJQFEXnfgVhUhJsELEUq@PAB6WIIgXyEMIAvBe5FnIBQcCft7GS7vQZ7KysPTiDnTZFhJPB84muKc4LIocdNEVJWhZdqhNP3RwyIUqAH8fdN4Z569VUiHOiJlBC/FeRTHtkj4SbyrwMVs2sEaWzQFsGKONFWWE0tnlVuGxp9lMRF5I/mQ12nDAfGrwZRStxf5SzQwS/gTAWbJutZLRXEj2S2U2FSzmY3YTPq5DTWwvNA95O6wc/giLGmpZOdFQ4jhgA7ZpM0vKutt@5AFoLbSeJ@7O5tubKaZWdEacrvubriVHCOLp/i3u@gZFBn8GkLjJjFIOwiSfOSCjG6qhSYRNiXdUfp/7S/lpXJkhXl6u8lfrrdOm/y2BwOR823N3IZVxUaerEh8SseF0bLqoh4ge3fCXtglOdAdPM2fGcdcBlfUm4crVllzrHHjZNPbFiSaWbcJnXBT0Ov6D9LgQKfyydzNCW7Cl58HTmYP1EMgCeMIBdMvBvcDQkqX/igVKSorwOgCERdm/UB2JyeMV32PJvN@z6P2P57Viu73K/fKadC9Zt6f31REygkLi9yPda@nHI67SIPsIucvse1UlzlBQEmk5d7/l0SeNA9ghysX@ldXylrL9S2ZHeHw "Python 2 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 647 bytes
```
func[b][
s:{AKWA ALFLGAMSTN ARLAMOMSOKTNTX AZCACONMNVUT CAHINVOR COKSNENMOKUTWY CTMANYRI DCMDVA DEMDNJPA FLGA GANCSCTN IAILMNMONESDWI IDMTNVORUTWAWY ILINKYMOWI INKYMIOH KSMONEOK KYMOOHTNVAWV LAMSTX MANHNYRIVT MDPAVAWV MENH MIOHWI MNNDSDWI MONEOKTN MSTN MTNDSDWY NCSCTNVA NDSD NESDWY NHVT NJNYPA NMOKTXUT NVORUT NYPAVT OHPAWV OKTX ORWA PAWV SDWY TNVA UTWY VAWV}m:
copy#()foreach a split s sp[t: parse a[collect any[keep 2 skip]]u: take t
either m/:u[append m/:u t][put m u t]foreach v t[either m/:v[append m/:v u][put
m v to[]mold u]]]r: on if 1 < length? b[foreach a b[r: r and series?
find collect[d: copy b alter d a foreach e d[keep m/:e]]a]]r]
```
[Try it online!](https://tio.run/##ZVLLjpswFN3zFUfppl1V7RJVGlmQDgzYjoA8qMWCBNOgEEDgRBpV/fb0msx0Ourmcl/ncS1GXd0SXanCqd1bfekOal8oZ3J/sWjLwOLv8SPjaSbAkphxyVMZZSLbgf3wmCcFF5t1Bo8FodjIBJ6MUrEUXEbrbJvDyzgTeRLC97i/YfCX3BdPKwbLikcmvNQj6pCFMSeQWKb@NkTo88yyEQUjkjAORZRzaSc2CWWAKLXbMoIdyIDW2XaD2DrdgTQDq7rJwP0Vm0d8KQJYKLFwIfxZ6M5BBuYDSdS2c9xdkV1bYzZFzYDoxJPIyb29L9vR3XeXsE2aymBlpewMMqHXm8sZPdPNT2Ld/D67zqEfnj98/FT3oy4PR5SYhrYxmOirjIuhHCeNUh36ttUHg7J7VietB3zFdGqGori4MOVJwzi6MUc94vzZvahyGHRXzTlMoYaLwRk2fdW5wqg3wPUfwBWXGeCc7VKvinPfVtQritFF36Gp8QXf0Orupzk@YK/erO8VrYzkscKkx0ZPD07dUPFiXlUu7LnYo2wNKVeEeUVrVPfDyIIuipLkitswNp1BDfor/6YLFi/eldECiy2jIJN3g3VGPU/aaU4hSikI/j/Wwm5/AA "Red – Try It Online")
This is a horribly long and naive solution...
] |
[Question]
[
When making phone calls internationally, phone numbers are prefixed with a code indicating what country the number is located in. These codes are [prefix codes](https://en.wikipedia.org/wiki/Prefix_code), meaning that no code is a prefix of another.
Now, earlier today you missed a call, and you're kind of curious where that call might have come from. So you want to look up the calling code. But, being a prefix code, you're not quite sure where it ends, so you decide to write a program to separate the calling code from the rest of the number.
# Input
As input, you will recieve a string consisting of the digits `0-9`. The first few digits will be one of the country calling codes listed below (this means the first digit will never be `0`). After the country calling code, the rest of the input will contain zero or more digits in any order - it is *not* guaranteed to be a valid phone number. Your program must be able to handle inputs containing at least 15 digits
# Output
Your program should output the unique country calling code that is a prefix of the number. The valid outputs are as follows:
```
1
20
211
212
213
216
218
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
260
261
262
263
264
265
266
267
268
269
27
290
291
297
298
299
30
31
32
33
34
350
351
352
353
354
355
356
357
358
359
36
370
371
372
373
374
375
376
377
378
379
380
381
382
383
385
386
387
389
39
40
41
420
421
423
43
44
45
46
47
48
49
500
501
502
503
504
505
506
507
508
509
51
52
53
54
55
56
57
58
590
591
592
593
594
595
596
597
598
5993
5994
5997
5999
60
61
62
63
64
65
66
670
672
673
674
675
676
677
678
679
680
681
682
683
685
686
687
688
689
690
691
692
7
800
808
81
82
84
850
852
853
855
856
86
870
875
876
877
878
879
880
881
882
883
886
888
90
91
92
93
94
95
960
961
962
963
964
965
966
967
968
970
971
972
973
974
975
976
977
979
98
991
992
993
994
995
996
998
```
This list is based on the codes listed on Wikipedia's [list of country calling codes](https://en.wikipedia.org/wiki/List_of_country_calling_codes) page as of revision 915410826, with a few modifications
* All codes listed as unassigned or discontinued and some codes listed as reserved for future use were omitted
* If a code listed on Wikipedia is a prefix of another, the latter was omitted
* If a single country or territory would have more than one code, and if those codes would have a common prefix, those codes are omitted in favour of their common prefix.
This may result in independent countries being lumped together, or disputed territories being lumped in with a particular claimant. This is not intended as a political statement, and decisions about the inclusion or omission of territories and states were made based on the codes, not any beliefs I hold regarding the ownership or sovereignty of the entities using them.
If given an input that does not begin with any of these codes, your program's behaviour is undefined.
And finally:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewer bytes of code is better
* Your submission may be either a function or a full program
* Any of the [default I/O methods](https://codegolf.meta.stackexchange.com/q/2447) are fine
* [The standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden
# Test cases
| input | output |
| --- | --- |
| 5292649259 | 52 |
| 3264296721 | 32 |
| 1550 | 1 |
| 33121394 | 33 |
| 7 | 7 |
| 2542112543 | 254 |
| 2005992972 | 20 |
| 350 | 350 |
| 360 | 36 |
| 8505234469 | 850 |
| 9795586334 | 979 |
| 148985513598795 | 1 |
| 222222 | 222 |
| 5999995 | 5999 |
[Answer]
# JavaScript (ES6), ~~75 73~~ 71 bytes
*Saved 1 byte thanks to @Shaggy*
*Saved 2 bytes thanks to @Neil*
```
s=>/1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.)./.exec(s)[0]
```
[Try it online!](https://tio.run/##ddDNTsMwDAfwO0/RW9oDbWLHSXwYPEhUpKl0CDStiKJph7x7yYZA@QAfIsX9xXL/b/vzfp0@Xt8/70/L87wddtu6exhUsKEF/yTtGNCTdWPQEIj5MZAMxlvHY3Be3r6wNzZe@64f@vkyT@3aeTlu03Jal@PcH5eX9tAKAgajGYhFc62ua4ahIbgrHEYFbCyo1GHlFJH8Fk3iVDUOFShkLTKGWDqbzvp1tmRAGpSKJ6bbxXsFpYxxAVvIoKz2y//iZz@qofkTmtI5kgSotclydvVAtkzkDKJOYexWSWvHjkghsYtvxD9Jw61EsWBslTDmEotEDq/d7Qs "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ ~~25~~ 24 bytes
```
η•A󾫸tEΓ∞ζ∊u½d•.¥¤ØªKн
```
[Try it online!](https://tio.run/##HYstDsJAEIX9nKJBA9md2dnuGBoEilNAQKAQ/CRNEMgGi0EhCBiQJIApYusbztCLLAufeHl5P/PFaDybhs06z1pJp5e0sjzUz2Z76ld3//Y3/1oO6n1THOtHU@xWvpzErusv/lwd/HX4KUM7MApaI8gCFA2KTVGDZlZApFGTGEgB2aDWUQlQKRZBSRHoN7IKHCtGMsYKSCrMzhIZ0MaJY9bE4mIK@AfiOcJf "05AB1E – Try It Online")
```
η # prefixes of the input
•A󾫸tEΓ∞ζ∊u½d• # compressed integer 211112166111113621489811655218129
.¥ # undelta: [0, 2, 3, 4, 5, 6, 8, 9, 15, 21, 22, 23, 24, 25, 26, 29, 35, 37, 38, 42, 50, 59, 67, 68, 69, 75, 80, 85, 87, 88, 96, 97, 99, 108]
¤ # last element of that list: 108
Ø # nth prime: 599
ª # append it to the list
K # remove all those values from the list of prefixes
н # get the first prefix left
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 60 bytes
```
!`^(2[1-69]?|3[578]?|42?|599?|50?|6[789]?|8[578]?|9[679]?)?.
```
[Try it online!](https://tio.run/##LU4xDsJADNvzChiQYCi6OJfcZaEjj6hAZWBgYUCM/XvJXckQ27Fk5/P8vt6P9XC8zut@vh8x8WB@GxeZtNTAjHFR91hpXGwqtZn1b/pkJfRpPK@rwmHZob4bLjsFSUi4FXA7CIhVU6NMIgwWz90QKg0LQTOYY0vTgYSUohte0C@JZEsIILGNGlVNCsnZenMo8uKq1UR6QyjiXL2qsqjXMLc30KdHAxRNMd1q9Ac "Retina 0.8.2 – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 328 ~~341~~ ~~410~~ bytes
Not very competitive for a golfing score, but each of these helps my bash skills!
Saved 13 bytes by eliminating handling 2 byte run-length values; storing only 3 bytes adds 8 bytes to T, but makes the case statement much simpler.
Saved 69 bytes by changing approach from bash expansion to storing deltas. The previous TIO link is at the bottom of my answer.
```
T='16D73r423112r62r72r6F1224r53-03511322rZr32r9L1611-01Fr9BrD2112V12-025r9-029r8-0202rB2r7-0308-162121E5r832-02082r72Cr52-3UR132'
A(){
V=$[V+36#$1]
S="$S $V"
}
R(){
read -n$1 d
}
while read -n1 c;do
case $c in -)R 3;A $d;;r)R 1;for((i=1;$i<=36#$d;i++)){ A 1;};;*)A $c;;esac;done<<<$T
for s in $S;do [[ $1 =~ ^$s ]]&&echo $s;done
```
[Try it online!](https://tio.run/##LZBBa8JAEIXv@ysGu6ipLGRmszFhk4PWeupJbQ4VC2mSYqAoTA49iP3r6Wzp5TG8mffNMB/1cB7HQznDdLO0nJBFJE6Jl6JbJErYWRNbh2iJ@I0tcf6CKaKJccv5mjckiQrJxOQ4F805E42J10KRaJwZTAkJnx1nNszFWeA/sSNjX3cCnqnVPLqpqtTHamHTB40ntS8neg@6mqi72oUud3UL5qIRWrG@z/1XB/8eQuPbq2rqoQPdQH8BE@3A@hXo1nuWGv3nlefzvkSv@6IMO1rfLxZRdIOVdO/eP0Yy3njfDXWgXbqiKPRBSQ6GgNR7ceF4BLmg/IF3PcDpNJ12zfkKevhLjONILgkPcYn9BQ "Bash – Try It Online")
* Sorted the list of prefixes numerically
* T is a "sort of" run-length encoded string showing the delta from the previous value. Each character is one of the following:
+ A base36 value showing the increase from the previous value
+ 'r': indicates that the next character indicates the the base36 encoded number of repeated delta values of 1.
+ '-': indicates that the next 3 characters are the next delta value
The string T="16D73r42 [...] -3UR132" following the rules above becomes a list of deltas: "1 6 D 7 3 r4 2 [...] 4995 1 3 2"
Could save 2-3 more bytes by using a higher radix than 36 (like 62-64) but Excel only natively supports up to 36, and that's what used to do the list of deltas and their conversions.
* On running, T is parsed and expanded into the string S used for the comparison of the phone number given in command line argument 1.
Expanding T, S becomes: "1 7 20 27 30 31 32 33 34 36 [...] 5993 5994 5997 5999"
~~[Try it online!](https://tio.run/##VY/BboMwEETv/opVhMJlibGNwW5Ff4IcckzaECUSgiq0EZLlb6e75lRLNjv2m9HweZnv63pscyV0KFEFhRoN1ugiBl0Wtadvg57faCh8pCVMCGVR0YvFhkgShNXoo6gSmKLQEGDYISxpz5iLYEsPNqg0eh8MVpRBzpoz64gNsUGzDR1fcYpNkkoUmtIa4UqCXBQEcF9qYjdzvdntPzv/TBSelSWVajDHpR2lKnZ6F3NxanNtPRhX0XbgrKJdgW9cLrr23L8uA/Rf9wmycJSykIdDPIvb9IQFHiNkp/frBF2bhU7uIFtgJyHS1dgnZk5Mx0y/fD8hU/AG2fwhr/1Ljr/DsN9v2TMNy@MnOdd11bbSStFp/gA "Bash – Try It Online")~~
[Answer]
# [Python 3](https://docs.python.org/3/), ~~120~~ 78 bytes
```
f=lambda n:{n//10+3}-{*b'
&()-5>FGHSXZ[cdf',602}and f(n//10)or n
```
[Try it online!](https://tio.run/##HY5LT8MwEIQPCMqjP4Cn5BNxYEPtXa@TrUSPwJ0LglNKZFGJulXlC4ry21PTOYxGo/mk2f6ln02kcQzPv@162bUqzvs4m1nzSEPVPyyL46OTyenZxfTy6vrm9k7d67Lixcvr2/vH59d3FwrwBoc2diroA1dudiqOIXtSq6gYBb0TZAHKAcXXaMEyGyCyaEkc1IDs0NrsBGgMi6DUCPQ/8gYaNozknBeQWpgbT@TAukYaZkssTW4BD4IMZ/H8XKntbhWTLvpBVQvVD8VTfrVuk04QdCrLctwD "Python 3 – Try It Online")
Contains some unprintables:
```
00000000: 663d 6c61 6d62 6461 206e 3a7b 6e2f 2f31 f=lambda n:{n//1
00000010: 302b 337d 2d7b 2a62 2705 0306 0708 090b 0+3}-{*b'.......
00000020: 0c18 191a 1b1c 1d20 2628 292d 353e 4647 ....... &()-5>FG
00000030: 4853 585a 5b63 6466 272c 3630 327d 616e HSXZ[cdf',602}an
00000040: 6420 6628 6e2f 2f31 3029 6f72 206e d f(n//10)or n
```
Somewhat ungolfed (earlier) version:
```
f=lambda n:{n/10}-{0,2,3,4,5,6,8,9,21,22,23,24,25,26,29,35,37,38,42,50,59,599,67,68,69,80,85,87,88,96,97,99}and f(n/10)or n
```
[Try it online!](https://tio.run/##FY/BagMxDETv/QrfsguT1pYsWwq0/7IlLA00Tgi@lGW/fSsLMQgh5o2ef/3n0eg41s/f5f59XUK7bO0jxf28RRAYGYIChYESiEAMyiABFZCBBVzBikyQCDFvQ6koimLQCBVohbpDgVWY7Uu7hnUalPnxCu1YXXu4tSBkVLKRu7APZKU6NIkbMydKbBnV2ZlScvUkMTqOrHrScVQGLgpxzg63aiJamDNSVlORxGLqW39k1MjqJZe3EJ6vW@unbQ/nr7Dtp3cPdV/61LFOfZ6Pfw "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) (-p), 44 bytes
```
$\=chop until/^599$/+vec"\x7D\x03\xE0\x27\x68\x04\x04\x08\x38\x00\xA1\x01\x0B",$_,1
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxjY5I79AoTSvJDNHP87U0lJFX7ssNVkppsLcJabCwDimwtUgpsLIPKbCzALIN4FiINsYxAfKORoCaRB2UtJRidcx/P/f0NTU4F9@QUlmfl7xf90CAA "Perl 5 – Try It Online")
Both TIO and SO have troubles with unprintable chars, so the program is shown with escape sequences. Here's a hexdump of the actual 44 bytes:
```
0000000: 245c 3d63 686f 7020 756e 7469 6c2f 5e35 $\=chop until/^5
0000010: 3939 242f 2b76 6563 227d 03e0 2768 0404 99$/+vec"}..'h..
0000020: 0838 00a1 010b 222c 245f 2c31 .8....",$_,1
```
[Answer]
# [PHP](https://php.net/), 219 bytes
I feel like there's a lot of room for improving the regex - golfed it as far as I can go but I'll bet it can be way shorter....
```
preg_match('/(1|7|2(0|1[12368]|[2346].|5[^9]|7|9[01789])|3[578]?.|42?[013]|5([1-8]|0.|99?[3479])|6([0-6]|7[^1]|8[^4]|9[012])|8(0[08]|[1246]|5[02356]|7[05-9]|8[0-368])|9([0-58]|6[^9]|7[^8]|9[1-8]))/',$argn,$r);echo$r[0];
```
[Try it online!](https://tio.run/##JY7NasMwEIRfxhAJIme1@rFECr71JRa5hBDiHBoLN8d99qqr9DKH3Zn5pq61fcxVtO63@9f35XVd1eGkLE@MCtiSRRdTYULnYxk50JKLPDOBnVIumh2FKZV5ZI@zHF3hoMgaycDIOc/k/NR9URGYKFlabOFEiy/vFpRfUkDQKRaFIhBAF95eCCZ3N5g@Q3PuLUGs8X8ILanXdJ7Wp8NxuOz353HY9fl2XbdhJyjn1jB4tFbUtd@tvh7b86eZzz8 "PHP – Try It Online")
[Answer]
# Java 8, 84 bytes
```
s->s.replaceAll("(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*","$1");
```
Port of [*@Arnauld*'s JavaScript regex](https://codegolf.stackexchange.com/a/193109/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##ZVHLTsMwELz3K6yIQ0JpFD82tqkAcYdeeoyCFNKAUtI0qt1KCPfbwzYEKYa1ZHlm1zvj9bY4FYvt5qMvm8IY8lzU7deMkLq11eGtKCuyukBC1vZQt@@kDMeDiZbIn2e4GVvYuiQr0pK73izuTXyougbvPjZNGITUSRey7CWRueMZSJU7wRxo/eAgcWkmlc6dypIho7NUIowjXNfBTXBFg2jZLy8y3fG1QZlR7bSvN2SHbkdDWU6K6MeqrYwNgWmWCs1APw1OR5ojyXQqGfVoCpB4ZZwyyrWYcnIKGAhGKe7c68OSBB/GtGS@6p/uqQcVJMC4EKlvVUsNoFLOhW9VKK0AKAetsMKXH2LKoBsM@PdZw/iGimaPv1m33dGO41t/Glvt4v3Rxh1O1jZtOKTnwS0J5m1c/sIgGtue@28)
**Explanation:**
```
s-> // Method with String as both parameter and return-type
s.replaceAll("(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*",
// Replace this regex-match
"$1"); // With this replacement
```
*Regex explanation:*
```
(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).* // MATCH:
1 // a 1
|7 // or a 7
|( ) // or:
2[^07] // a 2 not followed 0 nor 7
|3[578] // or a 3 followed by 5, 7, or 8
|42 // or a 42
|599? // or a 59 or a 599
|50 // or a 50
|6[789] // or a 6 followed by 7, 8, or 9
|8[0578] // or an 8 followed by 0, 5, 7, or 8
|9[679] // or a 9 followed by 6, 7, or 9
|. // or any single digit
. // followed by any single digit
( ) // All captured in capture group 1
.* // With 0 or more digits following
$1 // REPLACEMENT:
$1 // The match of capture group 1,
// (effectively removing the
// remaining digits of `.*`)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 96 bytes
```
lambda s:re.sub('(1|7|(2[^07]|3[578]|42|599?|50|6[789]|8[0578]|9[679]|.).).*',r'\1',s)
import re
```
[Try it online!](https://tio.run/##HU7RasMwDHzXV@QtzijFkizbKpR9iJtBy1IaaNPgpIyB/z3zeoLjdDrBzb/r7Tnxdj2etvv5cfk@N8shD/vldTGtwRKKofRlQ184SYh9cVRE9bOILT6FqH2Jyb4vmnyo676r89HucnvCdrd0MD7mZ16bPGw/t/E@NHiY8zit5mrGaX6tpuu6TUjJOyVR4CpIfSAEFLHAjISsDgKQOEKszEDW1hqkgYD/Q95CFCvEznkFDSoSPbMDdFGjCLJorC7QG1CfK@QP "Python 3 – Try It Online")
[Port of Arnauld's JavaScript answer.](https://codegolf.stackexchange.com/a/193109/87681)
[Answer]
# [Scala](http://www.scala-lang.org/), 411 402 330 bytes
This is assuming that the argument only contains digits.
```
"(1|(2(0|(1[12368])|([2346]\\d)|(5[^9])|7|(9[^2-6])))|(3(([0-4])|([57]\\d)|6|(8[^48])|9))|(4([^2]|(2[013])))|(5((0\\d)|[^09]|(9([^9]|(9[3479])))))|(6([0-6]|(7[^1])|(8[^4])|(9[0-2])))|7|(8((0[08])|[1246]|(5[02356])|(7[05-9])|(8[^4579])))|(9([0-58]|(6[^9])|(7[^8])|(9[^079]))))(.*)".r.unapplySeq(args(0)).foreach(l=>println(l.head))
```
[Try it online!](https://tio.run/##RVHNboMwDL73KaKeyCRQCEkgSN20B9ip2sklUgr0Z2K0o2xStfXZWRLT7WDJjr8fx77UtrPTdNq@tfVIXuyxJ98LQpp2R95dEdlhfynJ8zDYK6zH4djvK1qS1/44klVAEvJlO9KvllH6Ez2V3AXzSQopz1RRUV8Az4SqNpsmVBKMdu@5zzUYHquK0tDJXHg4i8VMlDnSlK8KMMIrakQLDzC8Cr7AUn6XkSjDAhMM0wGiA3zOIRO59nhkKHRVoZmDSdHeG2KmXRf1w9jF7ADMz@O@KpAqgfFMKuTkwGSs/5UkOv7NwmJZBJbChaB1cTc0bJ4wSh7oMhnCsvvks7fnc3ddtx/hOBGjNNmdhtbWh8iuHs/uRmPnDpccWttQ6li3xW2aJncOYbd18ws "Scala – Try It Online")
] |
[Question]
[
*This challenge sounds too simple to not already exist, so let me know if it is a duplicate.*
## The task
Print `Hello, world!`
## The rules
Your code has to be in "byte order". This means that every character / byte has a higher or equal byte value than the preceding character / byte.
Exceptions to this rule are the [whitespace](https://esolangs.org/wiki/Whitespace) characters, which may occur anywhere.
The [usual loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
**Edit**: Using built-in functions / constants resolving to `Hello, world!` is not allowed.
**Edit 2**: The output may be a(n anonymous) function returning the string, an expression resolving to the string, or any other way you think should be allowed.
### example
`HW` is valid: `0x48 (H) <= 0x57 (W)`
`print` is invalid: `0x72 (r) > 0x69 (i)`
but `PRint` is valid: `0x50 (P) <= 0x52 (R) <= 0x69 (i) <= 0x6e (n) <= 0x74 (t)`
## The scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the score is the number of characters / bytes. The lower the score, the higher the ranking.
[Answer]
# WhiteSpace, 146 bytes
Since all whitespace may occur everywhere, this is is just the golfed Hello World program. Since whitespace doesn't show properly here, take the following program and replace all `.` by spaces, `>` by tabs and `;` by newlines.
```
...;..>>..>.>.;..>>>>;...>;...>>>;...>..;..>>.>..;..>>..>.>>;..>>>>>>>;...>..;...>;.;...>>>.;..>>...>>;;..;.;.;>.>;...>>.>.>>;>...>;..;.;;;..>;;;;
```
# Note
I didn't golf this, LukStorms did. His answer can be found [here](https://codegolf.stackexchange.com/a/55447/63774).
[Answer]
# Headsecks - ~~124~~ 82 chars
*Thanks to @MartinEnder for pointing me to a smaller hello-world!*
Headsecks looks to be the right language for the job, because its brainfuck except that it takes each character mod 8.
```
+19AISYchpx£¨°»ÁËÐÞàèðøĀĈĐĘĦīİĸŀňŐŘŠŨųŻƀƈƐƘƠƪƲƺǁǏǒǟǣǫǴǸȃȈȐțȤȫȴȼɀɋɓɜɠɫɱɹʃʉʑʞʣʩʴʺ˂ˏ
```
You can try it by going here: <https://repl.it/G2I5/1>, then here: <https://sange.fi/esoteric/brainfuck/impl/interp/i.html>
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 784 bytes
```
"
"
"
"')`er~
```
[Try it online!](https://tio.run/nexus/cjam#@6/EqcBFJCBeJT2MGQKmYRjIqUB1C@jk8uEbWUBTlLiUOLmU1DUTUovq/v8HAA "CJam – TIO Nexus")
Not winning anything with that byte count, but this was still fun to make.
**Explanation**
The first large string encodes `Hello, world!` using only whitespace. Each character is mapped to a tab, a space, and a number of linefeeds equal to its codepoint minus 32.
Next, the string is transliterated by replacing tabs with `'` and linefeeds with `)`. This results in many sequences of a literal space character followed by some number of increments. The string is eval'ed with `~`, pushing the spaces and incrementing them to proper characters.
The stack is implicitly output at the end of the program.
] |
[Question]
[
## The task
Write a program or function that given three strings `A, B, C` produces an output string where each instance of `B` in `A` has been recursively substituted with `C`.
Recursively substituting means repeating a substitution where at each step all non-overlapping instances of `B` in `A` (chosen greedily from left to right) are replaced with `C` until `B` is no more contained in `A`.
## Input/Output
* You may use any of the [default methods for I/O](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes).
* Strings will contain only printable ASCII characters (and may contain *any* of them) .
* `B` will never be an empty string, while `A` and `C` might be.
* Strings are to be considered plaintext, you can't for example treat `B` as a Regex pattern.
* Some combinations of inputs will never terminate. Your program can do anything in those cases.
## Test cases
These are in the format: `A/B/C\nOutput`
```
Hello, world!/world!/PPCG
Hello, PPCG
Uppercase is up/up/down
Uppercase is down
ababababa/aba/ccc
cccbcccba
delete/e/{empty string}
dlt
{empty string}/no/effect
{empty string}
llllrrrr/lr/rl
rrrrllll
+-+-+-+/+-+/+
+
ababababa/aba/bada
badabbadbada
abaaba/aba/ab
abb
((())())())/()/{empty string}
)
```
Examples that don't terminate:
```
grow/ow/oow
loop/lo/lo
```
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda s,*l:eval('s'+'.replace(*l)'*len(s))
```
[Try it online!](https://tio.run/nexus/python2#fYoxCoAwEAR7X2G3uSg@QPAnNpcYQVhFEvH7MaKFlbMwzc48jJm6uknr1Fr24VQaJDToYtipPhhLgWXYTBLJe1y2o54N1L1Di8dOJ4VUP4X3/huwEAvl4a1ISL4A "Python 2 – TIO Nexus")
Evaluates a string of the form
```
s.replace(*l).replace(*l).replace(*l) ...
```
To reach a fixed point if one exists, it suffices to do replacements equal to the length of the original string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
`:
```
[Try it online!](https://tio.run/nexus/05ab1e#@59g9f9/tFJiEhQq6SgoQank5GSlWAA "05AB1E – TIO Nexus")
**Explanation**
```
` # split input to stack
: # replace (until string doesn't change)
```
This could be `:` for **1 byte** if we didn't have to deal with empty strings.
[Answer]
# ES6 (Javascript), ~~47~~, 43 bytes
* Saved 4 bytes using currying (Thanks @Neil !)
**Golfed**
```
c=>b=>R=a=>(x=a.split(b).join(c))==a?x:R(x)
```
**Try It**
```
Q=c=>b=>R=a=>(x=a.split(b).join(c))==a?x:R(x)
function doit() {
console.log(Q(C.value)(B.value)(A.value));
}
```
```
A: <input type="text" value="abaaba" id="A"/> B: <input type="text" value="aba" id="B"/> C: <input type="text" value="ab" id="C"/> <input type="submit" onclick="doit();" value="REPLACE"/>
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 27 bytes
Byte count assumes ISO 8859-1 encoding.
```
+`(.+)(?=.*¶\1¶(.*))
$2
G1`
```
Input should be linefeed-separated.
[Try it online!](https://tio.run/nexus/retina#XYyxCsIwFEX39xURFNJG@6i7ODjUsSBuDkmTVxAeTUgr/bN@QH8s1tLJe@7hbvcgHxqT0rJQmbxeinyeXuU8ySLPMtifoSp1Sndi9kcx@shuh9vU9a2CZwgUrelJvHvxCbjU@bED02zgT2stOGIaCAkBO4/UtmQH4CVxCXLEyKBOK7j699EYZ74 "Retina – TIO Nexus") (For convenience, uses a test-suite input format where each line is a slash-separated test cases.)
[Answer]
**C#, 44 Bytes**
**Short Version:**
```
r=(a,b,c)=>a==(a=a.Replace(b,c))?a:r(a,b,c);
```
**Example Program:**
```
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Func<string, string, string, string> r = null;
r=(a,b,c)=>a==(a=a.Replace(b,c))?a:r(a,b,c);
Action <string, string, string, string> test =
(a, b, c, answer) =>
{
var result = r(a, b, c);
Console.WriteLine("A: \"{0}\"\r\nB: \"{1}\"\r\nC: \"{2}\"\r\nResult: \"{3}\"\r\n{4}\r\n\r\n",
a, b, c, result, result == answer ? "CORRECT" : "INCORRECT"
);
};
test("Hello, world!", "world!", "PPCG", "Hello, PPCG");
test("Uppercase is up", "up", "down", "Uppercase is down");
test("ababababa", "aba", "ccc", "cccbcccba");
test("delete", "e", "", "dlt");
test("", "no", "effect", "");
test("llllrrrr", "lr", "rl", "rrrrllll");
test("+-+-+-+", "+-+", "+", "+");
test("ababababa", "aba", "bada", "badabbadbada");
test("abaaba", "aba", "ab", "abb");
test("((())())())", "()", "", ")");
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
}
```
**Explanation:**
The function is written as a tail recursive expression, avoiding the return keyword and curly brackets by exploiting the following:
* An assignment within parenthesis returns the value assigned
* The left side of the equality check will be evaluated before the right side assignment, allowing us to compare before/after inline, and still access the result
This lets us keep it to a single statement.
**EDIT:**
Went back to omitting the type of function r, since that appears to be acceptable. With type declaration using arrays, it is 68 characters. Without, it is 44 characters.
[Answer]
## Ruby, 29 bytes
```
->a,b,c{1while a.gsub! b,c;a}
```
Given 3 arguments, apply substitution to the first until there is nothing to substitute anymore.
### Explanation
* `1` before the `while` is simply a nop
* `gsub!` returns the string or `nil`if no substitution occurred
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 bytes
```
@¥(U=UqV qW}a@U
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=QKUoVT1VcVYgcVd9YUBV&input=IistKy0rLSstKyIgIistKyIgIisi)
### How it works
```
@¥(U=UqV qW}a@U // Implicit: U, V, W = input strings
a@U // Return the first non-negative integer mapped by the function X => U
@ } // that returns truthily when mapped through this function:
UqV qW // Split U at instances of V, and rejoin with W.
(U= // Set U to this new value.
¥ // Return (old U == new U). This stops the loop when U stops changing.
// Implicit: output result of last expression
```
Japt has a recursive-replace built-in, but it sees the first input as a regex. If the inputs were guaranteed to only contain alphanumeric characters this three-byte solution would work:
```
eVW
```
If the input were allowed to contain any char except `^`, `\`, or `]`, this 12-byte solution would be valid instead:
```
eV®"[{Z}]"ÃW
```
[Answer]
## C#, ~~33~~ 49 bytes
Probably, one of the smallest snippets written in C#... And since `Replace` is native to the `string` struct, there's no need for `using`s ( *At least not on VS built-in feature, C# Interactive...* )
Also, since `B` always has a value, the code doesn't need any validations.
---
**Golfed**
```
(a,b,c)=>{while(a!=(a=a.Replace(b,c)));return a;}
```
---
**Ungolfed**
```
(a, b, c) => {
while( a != ( a = a.Replace( b, c ) ) );
return a;
}
```
---
**Full code**
```
using System;
namespace Namespace {
class Program {
static void Main( string[] args ) {
Func<string, string, string, string> func = (a, b, c) => {
// Recursively ( now truly recursive ) replaces every 'b' for 'c' on 'a',
// while saving the value to 'a' and checking against it. Crazy, isn't it?
while( a != ( a = a.Replace( b, c ) ) );
return a;
};
int index = 1;
// Cycle through the args, skipping the first ( it's the path to the .exe )
while( index + 3 < args.Length ) {
Console.WriteLine( func(
args[index++],
args[index++],
args[index++]) );
}
Console.ReadLine();
}
}
}
```
---
**Releases**
* **v1.1** - `+19 bytes` - Fixed solution not being recursive.
* **v1.0** - `33 bytes` - Initial solution.
[Answer]
# Processing, ~~75~~ 72 bytes
```
void g(String a,String[]s){for(;a!=(a=a.replace(s[0],s[1])););print(a);}
```
Prints the results. Call it like `g("llllrrrr", new String[]{"lr","rl"});`
```
void Q110278(String a, String[]s){ //a is the string to be replaced
//s is the array containing the subsitution
for(; a!=
(a = a.replace(s[0], s[1])) ;);
//for-loop where we continuously perform substitution on a
//until a is equal to substituted a
//at the end, print the final version of a
print(a);
}
```
[Answer]
# Mathematica, ~~35~~ 32 Bytes
```
#//.x_:>StringReplace[x,#2->#3]&
```
Arguments given as a sequence. Never terminates for `grow` example, returns `loop` for `loop` example. Three bytes off thanks to Martin's suggestion.
[Answer]
## Pyke, 6 bytes
```
hVQtX:
```
[Try it here!](http://pyke.catbus.co.uk/?code=hVQtX%3A&input=%22llllrrrr%22%2C%22rl%22%2C%22lr%22&warnings=0)
[Answer]
## [///](https://esolangs.org/wiki////), 3 bytes
```
///
```
Put string B after the first slash, C after the second and A at the end, ie:
```
/<B>/<C>/<A>
```
[Try it online!](https://tio.run/nexus/slashes#@6@fU6RflKOfAwRFQPD/PwA "/// – TIO Nexus")
[Answer]
## JavaScript (Firefox 48 or earlier), 43 bytes
```
c=>b=>g=a=>a==(a=a.replace(b,c,'g'))?a:g(a)
```
Takes arguments curried in reverse order. Firefox used to have a non-standard third parameter to `replace` which specified regexp flags. This parameter was removed in Firefox 49.
[Answer]
# SmileBASIC, ~~72~~ 68 bytes
```
I=0DEF R A,B,C
I=INSTR(A,B)?A*(I<0)A=SUBST$(A,I,LEN(B),C)R A,B,C
END
```
One of the rare cases where making a function is actually SHORTER in SmileBASIC.
[Answer]
## Javascript 130 bytes
```
f=(a,b,c)=>a.indexOf(b)<0?a:f(eval("a.replace(/"+b.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&")+"/g,c)"),b,c)
```
Javascript will only replace all simultaneously if you give it a regex. In order to make this regex work for all values, all characters that are used for regex need to be replaced with the escaped version. Finally, the replace is evaluated to replace all instances of B in A with C and passing that back around to the function again.
[Answer]
# q, 15 bytes
```
{ssr[;y;z]/[x]}
```
Example:
```
q){ssr[;y;z]/[x]}["llllrrrr";"lr";"rl"]
"rrrrllll"
```
[link](https://kx.com/download/) to interpreter download
Explanation: [ssr](http://code.kx.com/wiki/Reference/ssr), [/ (converge)](http://code.kx.com/wiki/Reference/Slash#converge)
[Answer]
# Cheddar, 37 bytes
```
(a,b,c)f->a has b?f(a.sub(b,c),b,c):a
```
On phone so TIO link is a bit difficult to add. Basically uses recursion while checking is b is in a. Solution could of been `(a,b,c)->a.sub(Regex{b,"cr"},c)` but doesn't work for some reason.
[Answer]
# [Perl 6](https://perl6.org), 40 bytes
```
{$^b;$^c;($^a,{S:g/$b/$c/}...*eq*)[*-1]}
```
[Try it](https://tio.run/nexus/perl6#bVHNThsxEL7PU0zRit0NiR04UIkVl7aUIiEUUXpqGmnXOwELx15sB4jSPFlvfaee6XgbDkS1Pfb8fJ4Zf/5wdn5xhXoOiNlgcnZ9KZRbdNqQF7ZekDAK6QFzX98vW5czan//P9BH8kE7iw3NnSd8PBofvhfjI1gzNtQrzG/udMAnbQxaF/HJ@XtUzntS0axQW9wmCOjmeN3Xwgl5g8fYee08RofxjvAzNZhyoydDdaC8ei3gab4M2t4mpF/aPkDPOlawgWXglo6FqnrthkKs8OzqE7bO0iiyyfcqmHi30IGEtsXhuBRczp7gOuXYwGKF@8q1hKcv62zWVNlMVUU2q4frrye3MmtkpuRGCDGgh0H5fTA6/LF5yQYXV8KaEb/uFPemdmr3KmB60GhLoSgxkcOJi6m2wyk9d0wGtSWDRY/4/UuEzuhY5DIvk7FsAhtrWnRxhSF67nqTD/O8TG9lelODxU9tyyG@Zhsyt@JShyg6ZpO5ePlCxrhh@gHTvpPbYzL5eA7bSK/Dt44vKGY4JV52klfrnuxbf@@ButlOmUQpBSxNkhqg5X@KJElCayLA2@aldZLmc@50JwBgeHge0njpDSQ1uQAORv2UvcDBbvmmbmtIW8NbbyTAa7Ru2GoAiqIoy39LFqXcKV7@sW6kanVHfwE "Perl 6 – TIO Nexus") (if tio.run gets updated)
[Try an altered version](https://tio.run/nexus/perl6#XVDNbtswDL7zKdTCqKXWltrLDjV62oZtwFAEWHdaFsCSmVaAIhmW0h943ov11nfaOaW89NCQ/Ch@JEUR2kZk9x@kaWBL0Q3G1LDP159YFzzWiaj1tw0shrCxEaX1/OJcyHSH/pKN@GjTBJsndmJCh@xqNxYr3RQr0/Bi1Vbj3x@Xt6rQqjBqklKOR5vMJvHrtL74Pe2K02/X0rvaenbFjpd@6Y8bWIeBOesxcsFGYIym86X11RIfezQJO0HNcu54eZaxdzbxUpUik62OREbc9OmJxTTQ6lNZlaVoaJCNLG/J/1gvKvY2rWLWy@82Jtnj4BqYdl/RuVCxhzC47kjtj8Xi4xfYV@YYfvZ0wbT0ZzR42yuyLjz49/k5A63eq8owxgBBZ7QAHTpMqFBB5xLA@@WVDwrXa9r0oADgSAYS5QY1OMhhTgGc1bOqGXB2@Lxuuxay0@Rmkhveqq0mpgE450L8N8WFOnhc/POhNq25w1c "Perl 6 – TIO Nexus")
## Expanded:
```
{
$^b; # declare second parameter ( not used here )
$^c; # declare third parameter ( not used here )
(
$^a, # declare first parameter, and use it to seed the sequence
{S:g/$b/$c/} # replace globally
... # keep doing that
* eq * # until there are two that match
)[*-1]
}
```
[Answer]
# PHP, 46 bytes
```
function g($a,$b,$c){echo strtr($a,[$b=>$c]);}
```
[Answer]
# PHP, 102 bytes
```
list($n,$s,$a,$b)=$argv;$f=str_replace($a,$b,$s);while($s!=$f){$s=$f;$f=str_replace($a,$b,$s);}echo$f;
```
[**Test cases (functional)**](https://eval.in/739433)
[**Test case with loop error**](https://eval.in/739436)
[Answer]
# Java - 157 bytes
```
String r(String f){if(f.length()<1)return "";String[]x=f.split("/");if(x[0].contains(x[1]))return r(x[0].replace(x[1],x[2])+'/'+x[1]+'/'+x[2]);return x[0];}
```
For empty input it returns an empty string.
Crashes with `StackOverflowException` error when `B` is empty or it is fed with data like this `A/A/A`.
How it works:
```
r("ABCD/A/F") returns value of r("FBCD/A/F") which returns FBCD
If there is no more characters to be replaced it returns the final output
```
Ungolfed code code with comments:
```
String r (String f) {
if(f.length() < 1)
return ""; // For empty input return empty output
String[] x = f.split("/"); // Get all 3 parameters
if (x[0].contains(x[1])) // If input contains replaced value
return r(x[0].replace(x[1],x[2])+'/'+x[1]+'/'+x[2]); // Return value of r() with one character replaced
return x[0]; // If nothing to replace return the output(modified input)
}
```
[Answer]
# AutoHotkey, 87 bytes
```
StringCaseSense,On
Loop{
IfNotInString,1,%2%,Break
StringReplace,1,1,%2%,%3%
}
Send,%1%
```
`%1%`,`%2%`, and `%3%` are the first 3 arguments passed to a function
If a function expects a variable argument, the `%`s are dropped
] |
[Question]
[
The digital root (also repeated digital sum) of a positive integer is the (single digit) value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached.
For example, the digital root of **65536** is **7**, because **6 + 5 + 5 + 3 + 6 = 25** and **2 + 5 = 7**.
---
Sorting all digital roots doesn't make much sense, since it would just start with infinitely many **1**s.
Instead, we'll create lists of all the single digits integers along with their digital roots, then all double digit numbers along with their digital roots, then the triple, quadruple and so on.
Now, for each of those lists, we'll sort it so that all the integers with digital roots of **1** appear first, then all integers with digital roots of **2** and so on. The sorting will be stable, so that the list of integers with a certain digital roots should be in ascending order after the sorting.
Finally we'll concatenate these lists into one single sequence. This sequence will start with all single digit numbers, then all double digit numbers (sorted by their digital root), then all triple digit numbers and so on.
---
### Challenge:
Take a **positive** integer **n** as input, and output the **n**'th number in the sequence described above. You may choose if the list is **0**-indexed of **1**-indexed.
The sequence goes like this:
```
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 11, 20, 29 ...
72, 81, 90, 99, 100, 109, 118, ...
981, 990, 999, 1000, 1009, 1018, 1027, ...
```
### Test cases:
The test cases are 1-indexed.
```
n f(n)
9 9
10 10
11 19
40 13
41 22
42 31
43 40
44 49
45 58
600 105
601 114
602 123
603 132
604 141
605 150
4050 1453
4051 1462
4052 1471
4053 1480
4054 1489
4055 1498
```
Easier to copy:
```
n = 9, 10, 11, 40, 41, 42, 43, 44, 45, 600, 601, 602, 603, 604, 605, 4050, 4051, 4052, 4053, 4054, 4055,
f(n) = 9, 10, 19, 13, 22, 31, 40, 49, 58, 105, 114, 123, 132, 141, 150, 1453, 1462, 1471, 1480, 1489, 1498
```
### Clarifications:
* You may not output all **n** first elements. You shall only output the **n**'th.
* The code must theoretically work for all integers up to **10^9**, but it's OK if it times out on TIO (or other interpreters with time restrictions) for inputs larger than **999**.
* Explanations are encouraged.
It's [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins! Don't be discouraged by other solutions in the language you want to golf in, even if they are shorter than what you can manage!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~60~~ ~~52~~ ~~46~~ 45 bytes
-6 bytes thanks to [G B](https://codegolf.stackexchange.com/users/18535/g-b).
-1 byte thanks to [Jakob](https://codegolf.stackexchange.com/users/44945/jakob).
```
n=input()
b=10**~-len(`n`)
print~-b+n/b+n%b*9
```
[Try it online!](https://tio.run/##JYxBCoMwEEX3c4ogFNQiTeKkYMGl3XbTA1jtQKUSQ4i0brx6OqGL9@Yv/h@3hddidRyXJ7VZlkXbTtatIS9gaJUsy72ayea97QtwfrJhr4ajPTGHoWwiLwA@r2kmcfcrXUCI4Ld0hKAvjSL9hZRHckF0t2vn/eL/hcHT4x0bUBKUApSAbA1YAyKggbOUjGI0UzPIGG4amZQ2RifVSZhkfg "Python 2 – Try It Online")
Finally reached a closed form, 1-indexed.
---
# [Python 2](https://docs.python.org/2/), 78 bytes
0-indexed.
```
d=10;k=1
exec'\nk+=9\nif k>d+7:k=d;d*=10\nif k>=d:k-=d/10*9-1'*input()
print k
```
[Try it online!](https://tio.run/##LY0xDsIwDEV3n8LqUiiqSFoXSFHYYGVhZIEmiCooraIg4PQlFgzv2bK@/MdPvA@@mrrBWB2yLJuMlmLrtAT7tl1@9m6h1dn3N3Q7s1i3TputKVLmf9OmdaU2SykKVcq86P34jLM5jKH3Ed2UXgK87v3D4ik8bQuIMXx4IHIDcjPw3tkx4v542IcwhF/gGuzFTRtQIAXUCkgASaAKqAYiaJSClRAJmagSdYJSjDjbCJZkVayaRV8 "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 80 bytes
```
f=lambda i,k=1:k>i and sorted(range(k//10,k),key=lambda n:n%-9)[i-k]or f(i,k*10)
```
[Try it online!](https://tio.run/##jY/BTsMwEETP9VesVFVNqkS1GwepgfRWJE58AOLgki1dOTjBuIVc@PWwVkDqkcO8w2hntNMP4dS5YpzDQ0BvAl0Q8P1MF9OiC5WYA9XkQkKuP4ckTW9trSS7nydqEexdTZVdTVbv4@FH5wM2iTfuFRO7XiuZ2TSzONSteTs0Blz1nbvFNn2i3D6Pxz@bMm6u7I7AuAb@0eIW@W9J5@GYcH6lZDpOj6lKzIIfmDOCGq4XsDV9Shks890yi@Fo49cL9gH2j/d77zsfswePxo5bwfuUEloKzdwIXQithS7FjZQsxdqwCpZmlXxZyoiYKTcRRYSOKH8A "Python 3 – Try It Online")
1-indexed. This is the best I could manage in Python 3 (well, except for the [78-byter](https://tio.run/##NYxBDoIwEEXXzCm6MbYGkhZaE0hwp1sPoC5QqzZiIUONcnqcGl28t5j///RjuHW@mC71fmqbx/HcMFcNHQZ75tj4q@UqVXKxaK3nQ0DuhBDp3Y71r@wr/o88JX6WlULsXKYO0@vmWstUBUnAkZw4VjPnA3e@fwYuBJ16/B5SNs9W85Rd4n9I7Ptk@8DW280ascO4PaJt7lMJSoJSoCVocg66AK1BG1hKSSgiJwpCE4aaRkbFjcmjiigdZT4), which is a port of my Python 2 solution below; I think this one is much cooler, though). Python 2 full programs are advantaged for this particular challenge, because `input()` needs a conversion to `int` in Python 3 (+5 bytes), `exec` is a function, rather than a statement (+2 bytes) and `/` performs integer division by default if its arguments are integers in Py 2 (+1 byte), so this is *definitely shorter* than porting [ovs' answer](https://codegolf.stackexchange.com/a/166960/59487).
## How it works
**Setup**
```
f=lambda i,k=1:k>i and ... or f(i,k*10)
```
This defines a recursive function **f** that takes one integer argument **i** and another one, **k**, which defaults to **1**. While **k ≤ i**, the function **f** returns **f(i,10k)**, multiplying **k** by **10** each time until it becomes greater than **i**.
**Target range and correct indexing**
```
...range(k//10,k)...[i-k]
```
After this set of operation, we're left with **i**, the initial input and the variable **k** which represents the smallest power of **10** greater than **i**. This way, we are able to generate the (integer) range **[floor(k/10), k)**, which basically includes all integers that are:
* greater than or equal to the highest power of **10** less than or equal to **i**
* less than **k**, the smallest power of **10** greater than **i**
Since we disregard the integers smaller than **x = floor(k/10)**, we must shift the indexing so that we account for the missing numbers. The obvious way is to subtract their count, **x**, from **i**, so that we index into the list (after sorting, which is described below), therefore having **i-x**. However, since the list contains **9k/10**, items, and indexing in a list at index **-y** for some positive **y** yields the **yth** element from the end in Python, this is simply equivalent to indexing with **i-k**, hence saving 4 bytes.
**Sorting each *chunk* by the digital root**
```
sorted(...,key=lambda n:n%-9)
```
The formula for the digital root function is **1+((n-1) mod 9)** (see the *Congruence formula* section of [this Wikipedia article](https://en.wikipedia.org/wiki/Digital_root)). As **1** would this way be added to each of them, it is superfluous when sorting, so we're left with **(n-1) mod 9**. The way Python's `%` operator works when given negative numbers on the RHS is very convenient, because we can use **n pymod -9** instead to save yet anther byte.
---
# [Python 2](https://docs.python.org/2/), 72 bytes
Inspired by [Chas Brown's submission](https://codegolf.stackexchange.com/a/166979/59487).
```
lambda i:sorted(range(1,10**len(`i`)),key=lambda n:(len(`n`),n%-9))[i-1]
```
[Try it online!](https://tio.run/##LYtBCsIwFAXX/lNkIyaSQpImgoW6060HUKHVphqsaYkR7enrj7iYWQzvDWO89V5NbXmcuvpxbmriimcfom1oqP3VUsmlWC4762nlKsb43Y7lf@kL@uu@YtzPszVjB5fJ0/S@uc4SWcAshhE9c6Qkzkfq/PCKlDFMQ/gFThbZZsFJS13K9nOxQyTb/W4bQh/S9xxsfZ/WIAVICVqARivQOWgN2sBKCEQiCskRjRhcGpGUPkYl5Uk6yXwB "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~73~~ ~~71~~ 70 bytes
```
lambda n:sorted(range(10**len(`n`)),key=lambda i:(len(`~i`),i%9))[n]+1
```
[Try it online!](https://tio.run/##NZDdSsQwEIWv9SnmRkjWETLJZG0L@yS10Mq2GlzTpZaFvfHVY/68@84h5wvJ9b5/rl6H5fQWLtP3@3kC3/2s2z6fxTb5j1mQOhwusxejH6XEr/l@qudcJ3L/60aJ7qmVsvfDM4Vl3cDhDZyHvm8R2gGhJ4VAKhNFyh2nzmSKndaZNIKhTAaB84I5UllYBNskOqostIWTkrhwFJA2hU26QBeOEmIqHDVki1vZJGJrakoqPuqakoxfqaak4@Z/l4VNfYlNSm6bYegeH66b83v8A7ghLMK9kAzhDw "Python 2 – Try It Online")
2 bytes thx to [Mr. XCoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder); and
1 byte thx to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz).
This is 0-indexed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15 14 10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
D,Ḣ$‘Ḍḅ9’
```
**[Try it online!](https://tio.run/##AR8A4P9qZWxsef//RCzhuKIk4oCY4biM4biFOeKAmf///zEx "Jelly – Try It Online")**
### How?
Uses a golfed version of the closed-form solution created by [ovs in their Python answer](https://codegolf.stackexchange.com/a/166960/53748)...
The formula exposed by ovs is: **9\*(n%b) + (n/b) + b - 1** where **b=10floor(log(n,10))**
Now if **c** is the count of decimal digits of **n** then **b-1** is **c-1** nines in decimal.
This is the same as nine times the value of **c-1** ones in decimal (e.g. `111*9=999`).
Furthermore **n/b** is the leading digit of **n** and **n%b** is the rest of the digits as a decimal number.
A formula like **b\*x+y** may be implemented as a conversion of `[x,y]` from base **b**
(i.e. **b^1\*x + b^0\*y = b\*x+y**)
As such we can take a number, **n** (for example `7045`), split it into the leading and trailing digits, placing the leading digit at the end (`[[0,4,5],7]`), add one to all of the digits of the first item to cater for the addition of **b-1** (`[[1,5,6],7]`) convert these from decimal lists to integers (`[156,7]`), and convert that from base nine (`1411`).
In the implementation below we add one to all of the digits of both items when catering for **b-1** (`[[0,4,5],8]`), convert from decimal lists to integers (`[156,8]`), convert from base nine (`1412`) and then subtract the one this process added (`1411`).
```
D,Ḣ$‘Ḍḅ9’ - Link: positive integer, n e.g. 4091
D - to base ten [4, 0, 9, 1]
$ - last two links as a monad:
Ḣ - head (modifies the list too) 4
, - pair (the modified list) with [[0, 9, 1], 4]
‘ - increment (vectorises) [[1, 10, 2], 5]
Ḍ - from base ten (vectorises) [202, 5] (since 1*10^2+10*10^1+2*10^0 = 100+100+2 = 202)
ḅ9 - convert from base 9 1823 (since 202*9^1 + 5*9^0 = 202*9 + 6*9 = 1818 + 5 = 1823)
’ - decrement 1822
```
---
Previous, 14 byter:
```
æċ⁵DL,’%9ƊƲÞị@
```
**[Try it online!](https://tio.run/##AScA2P9qZWxsef//w6bEi@KBtURMLOKAmSU5xorGssOe4buLQP///zQwNTU "Jelly – Try It Online")**
This one builds the list up to the next power of **10** above the input by sorting these natural numbers by `[digitalRoot, digitCount]` then finds the value at the inputted index.
[Answer]
# [Haskell](https://www.haskell.org/), ~~94~~ 88 bytes
```
([n|x<-[0..],i<-[1..9],n<-[10^x..10^(x+1)-1],until(<10)(sum.map(read.pure).show)n==i]!!)
```
[Try it online!](https://tio.run/##TY7PaoQwEMbvPkUWekjYGDKabBU2p77AHgs2FdlqV6qp6Eo99NlrZwKFHuY3wzf/vluzfLTDsHfMvey8Ct/bOa20Ul72WIBSpZeBKv26KYXk2xFECl6u4d4P/Axa8GUd1dhMfG6bNzWtcyvUcvv8EsG53h8OYh@bPjDHprkPd/bAcJZ1LNSaOce6OiRJqAH7VSkZaAyQzGA2lDOMHMNgWMlOWhOAkBFygiFY2rI6Ml6wWWQeaSKtT@Lf6IGncBToAxI08f8/ZdzKcD//84KaLahvySBegyynMZwBMgr0GQx9A3OK6iPJpoh6QTdNWfhk/7l2Q/O@7Onz0@XyCw "Haskell – Try It Online") 0-indexed.
**Explanation:**
The list comprehension generates the sequence as infinite list in which we index with `!!`:
* `x` is one less than the current number of digits and is drawn from the infinite list `[0,1,2,3, ...]`
* `i` iterates over the range from `1` to `9` and is used for sorting by the digital roots
* `n` iterates over all numbers with `x+1` digits
* `until(<10)(sum.map(read.pure).show)` computes the digital root ([see here for an explanation](https://codegolf.stackexchange.com/a/97760/56433))
* `n` is added to the list if its digital root equals `i`.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 65 bytes
```
.
9
.+
*
L$`
$`
O$`_(_{9})*(_*)
$2
_+
$.&
N$`
$.&
"$+L`^|\d+"^~G`
```
[Try it online!](https://tio.run/##K0otycxLNPz/X4/LkktPm0uLy0clgQuI/FUS4jXiqy1rNbU04rU0uVSMuOK1uVT01Lj8QAqAtJKKtk9CXE1MirZSXJ17wv//JkYA "Retina – Try It Online") 1-indexed. Explanation:
```
.
9
.+
*
L$`
$`
```
Build up a list of lines of `_`s from 0 until the next power of 10 (exclusive).
```
O$`_(_{9})*(_*)
$2
```
Sort them all in order of digital root.
```
_+
$.&
```
Convert from unary to decimal.
```
N$`
$.&
```
Sort them in order of length.
```
"$+L`^|\d+"^~G`
```
Extract the `n`th element.
[Answer]
# [Pyth](https://pyth.readthedocs.io), ~~36 31 25 24 23~~ 22 bytes
1-indexed.
```
@o%tN9rFK^LThBlt`Q-QhK
```
[Test suite!](https://pyth.herokuapp.com/?code=%40o%25tN9rFK%5ELThBlt%60Q-QhK&test_suite=1&test_suite_input=9%0A10%0A11%0A40%0A41%0A42%0A43%0A44%0A45%0A600%0A601%0A602%0A603%0A604%0A605%0A4050%0A4051%0A4052%0A4053%0A4054%0A4055&debug=0)
### How it works (outdated)
```
@smo%tN9dcU^TKhs.lQT^LTSK – Full program. Q = input.
Khs.lQT – Take floor(log10(Q))+1 and store it in K.
U^T – Generate [0 ... T^K).
c – Cut at locations...
^LTSK – Of the powers of 10 less than K.
m d – Map over those.
o N – Sort them by...
%t 9 – Themselves decremented, modulo 9.
@s – Flatten the result and retrieve the Q'th entry.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 11 bytes
Port of [my Python answer](https://codegolf.stackexchange.com/a/166960/71256).
-6 bytes(!) thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
g<°©‰`9*®O<
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/3ebQhkMrHzVsSLDUOrTO3@b/fxMDU1MA "05AB1E – Try It Online")
```
Code Explanation Stack
implicit input [n]
g length [len(n)]
< decrement [len(n)-1]
° 10 ** a [10**(len(n) - 1)]
© store value [10**(len(n) - 1)]
‰ divmod [[n // 10**(len(n) - 1), n % 10**(len(n) - 1)]]
` push items to stack [n // 10**(len(n) - 1), n % 10**(len(n) - 1)]
9* multiply by 9 [n // 10**(len(n) - 1), n % 10**(len(n) - 1) * 9]
® retrieve value [n // 10**(len(n) - 1), n % 10**(len(n) - 1) * 9, 10**(len(n) - 1)]
O sum the stack [n // 10**(len(n) - 1) + n % 10**(len(n) - 1) * 9 + 10**(len(n) - 1)]
< decrement [n // 10**(len(n) - 1) + n % 10**(len(n) - 1) * 9 + 10**(len(n) - 1) - 1]
implicit output
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 23 bytes
```
@o%tN9rF_mJ^TsdtBl`Q-QJ
```
[Try it here.](http://pyth.herokuapp.com/?code=%40o%25tN9rF_mJ%5ETsdtBl%60Q-QJ&input=10&debug=0)
-3 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
1-indexed.
[Answer]
# [Perl 6](https://perl6.org), ~~68~~ 58 bytes
```
{({|(10**$++..^10**++$).sort({({.comb.sum}…*==*).tail})}…*)[$_]}
```
[Test it](https://tio.run/##Tc5LTsMwEAbgvU8xqgLk0Vp24oRGVRCHYIcAldSVIiVNFKc8VCJxGjYcgV2PwkWCZ1yJZvVlHv@4032dTXuj4SXj5Yqx5h0uy3ajoZgO/uHDlyIMvSji/BEVRV7ATdsPvm3ysm2eudk34@/nV1gUYcCHdVWPAf0H997TwzjZvNtBmwEKiI7fdbXT5vjDX9t@Y@w1PHxnuyvW1esdRDRq69u2P60tbsAHr9p1@2EOnn7rdDnoDQRwYACVAXyr7/qwABmcDc1h5hp82wz@1YUyVwHAf/@sPGPjZFs50JfbaCmIUqClM9bVqZ6gXT2O0TE5keiErHBXKWfaTcnpkkEmhItP0ZQjpUJTjowTdOJOxWjKkUqiKUemgimRCiqnCVqSsxgdk68lOiEvaV455@iUnC//AA "Perl 6 – Try It Online") 0-based
```
{sort({.chars,({.comb.sum}…*==*).tail},^10**.chars)[$_]}
```
[Test it](https://tio.run/##Tc5fToNAEAbw9z3FpKkWKJJddhdLGoyH8M2oQbqNJFAIS/2ThsTT@OIRfOtRvAgys00sT798M/sNremqZNxbA69JVKwZqz/gsmg2BrLxYJuu9w5R8ZJ3NkQ09XNk9/Xw@/kVZFngR31eVkP4KHgQuDX/fv70MIxTy21vbA8ZLI/fVbkz9vgTvTXdxk438NzdNF2ztsp3sKTVKd823enZ1Q14MC937b4PYW7eW1P0ZgM@HBhAaQH/0HNz/2whhJkLo23de4sLZRc@wP/8LJ6xYZxGKdCXTrWCEwVHC2fM1SmXaJfHMTomS4GWZIVvlXKmt5qsVwwSzl29RlOPEApNPSKWaOlOxWjqEUqgqUdozhTXnGIt0YKcxOiYfC3QkryifeWcojU5Xf0B "Perl 6 – Try It Online") 1-based
## Expanded:
```
{ # bare block lambda with implicit parameter $_
sort(
{
.chars, # sort by the length first
( # generate sequence to find digital sum
{ .comb.sum } # one round of digital sum
… * == * # stop when the digital sum matches itself (1..9)
).tail # get the last value
},
^ # Range up to (and excluding)
10 ** .chars # the next power of 10
)[ $_ ] # index into the sequence
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~43~~ 38 bytes
```
->x{9*(x%b=10**~-x.to_s.size)+x/b+b-1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf166i2lJLo0I1ydbQQEurTrdCryQ/vlivOLMqVVO7Qj9JO0nXsPa/hqGenqGBgYGmXm5iQXVNRQ1XgUJ0hU5adEWsToUuiIrlqv0PAA "Ruby – Try It Online")
Originally a port of the excellent Python answer by ovs, then simplified some more.
[Answer]
# Java 8, 68 bytes
```
n->{int b=(int)Math.pow(10,(n+"").length()-1);return~-b+n/b+n%b*9;}
```
Boring port of [*@ovs*' Python 2 answer](https://codegolf.stackexchange.com/a/166960/52210), so make sure to upvote him!
-1 byte thanks to *@Jakob*
[Try it online.](https://tio.run/##LZDLbsJADEX3fIUVqVKmeTRPJIjoH8CGJWUxCQMMDU6UTEBVlP56ak9Z3GON5bm@8k0@ZHA7fc9VLfsetlLjuADQaFR3lpWCHT9tAyqXiaKgzrQg9EYaXcEOEDYwY/A58kC54TmxleYats3TjSPfRc9xRFgrvJirK4JYFJ0yQ4e/QenhB@mtfF8V01ywbTuUNdm@3B@NPsGdcrl702m8HI4gxX@oc9PZSBrWgOrJIQ/HceUDrYQ49iGjmnFNSCkpI@U@LKOIETMSRsrIGDn/yiNL65AnlqllZplPwu4H2P/0Rt3DZjBhS@FMja72nPWXcTwM6V7idaxp/gM)
[Answer]
# [K4](http://kx.com/download/), 38 bytes
**Solution:**
```
-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:
```
**Examples:**
```
q)k)-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:40
13
q)k)-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:601
114
q)k)-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\:4051
1462
```
**Explanation:**
Port of Jonathan Allan's solution as I run out of memory building the digital roots from 1 to 1e9.
```
-1+9/:10/:'(0;c-1)_1_(1+c:#x)#x:1+10\: / the solution
10\: / convert to base 10
1+ / add 1
x: / save as x
# / take from x
( ) / do together
#x / count x
c: / save as c
1+ / add 1
1_ / drop the first
_ / cut at these indices
( ; ) / 2-item list
c-1 / length - 1
0 / .. zero
10/:' / convert each from base 10
9/: / convert from base 9
-1+ / subtract 1
```
**Bonus:**
Translation of ovs' solution is simpler but longer:
```
-1+b+/1 9*(_%;.q.mod).\:x,b:10 xexp#1_$x:
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
æḟ©ræċɗ⁵Ṗ%Þ-9⁸‘_®¤ị
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//w6bhuJ/CqXLDpsSLyZfigbXhuZYlw54tOeKBuOKAmF/CrsKk4buL////NDA1NQ "Jelly – Try It Online")
-1 thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder).
1-indexed.
[Answer]
# J, 24 bytes
```
(]/:([:+/[:".&>":)^:_"0)
```
This *tacit* expression is wrapped in parens to signify that it should be treated on its own rather than as part of any following expression (like the arguments).
The phrase ']/:' orders (ascending '/:') the original array ']' by the sum '+/' of the digits The expression
```
". &> ":
```
converts a number to a character vector with '":', then applies its inverse '".' - character to number - applied to each '&>' item. So, 65536 -> '65536' -> 6 5 5 3 6.
The power conjunction '^:' near the end of the expression applies the code we just explained (on the left) a specified number of times. In this case, the specified number of times is infinity '\_' which means to keep applying until the result stops changing.
The final '"0' means to apply the whole expression on the left to each scalar (0-dimensional) item on the right, which would be the array of numbers to which we want to apply this.
[Answer]
# [Elixir](https://elixir-lang.org/), 239 bytes
```
q=:math
e=Enum
r=fn x,f->cond do
x<10->x
1->f.(e.sum(Integer.digits x),f)end end
fn p->e.at(e.at(Stream.unfold({0,[0]},fn {a,c}->{c,{a+1,c++e.sort(trunc(q.pow 10,a)..trunc(q.pow 10,a+1)-1,&r.(&1,r)<=r.(&2,r))}}end),1+trunc q.log10 p),p)end
```
[Try it online!](https://tio.run/##XU6xbsQgFNvzFUwnUB5PoepUXdhuuKlDx6oDIpBGSoAQUJHSfHvK3djBlmXZls08lSme59q/LSp9N6a/ubw0sbeOFLBcau8GMvimXEXHZWkElxapwS0v9O6SGU3EYRqntJHCwDJT4xVN7QcuDapEn/SRolELZmf9PNC9g8/u64Ca2hXog8tdw65aAbpt67iPiaaYnaYrBv9DRAeKIf63WsG4gEtEehEQ2bV/qJeq2HHUEwxE@6yQFWc/io4EBuFx8UT6Khj5leT@jiGn7fwD "Elixir – Try It Online")
Explanation incoming (slowly)! I don't think it can get much shorter than this, but I'm always open to suggestions
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 27 bytes
```
$_=9x$#F+$_%10**$#F*9+$F[0]
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3tayQkXZTVslXtXQQEsLyNSy1FZxizaI/f/fxMDU5F9@QUlmfl7xf11fUz0DQ4P/ugVuAA "Perl 5 – Try It Online")
Uses @ovs's formula and @JonathanAllen's explanations to come up with a nice compact piece of code.
] |
[Question]
[
*This challenge is related to some of the MATL language's features, as part of the [May 2018 Language of the Month](https://codegolf.meta.stackexchange.com/questions/16337/language-of-the-month-for-may-2018-matl) event.*
---
## Introduction
In MATL, many two-input functions work **element-wise** with **broadcast**. This means the following:
* **Element-wise** (or **vectorized**): the function takes as inputs two arrays with matching sizes. The operation defined by the function is applied to each pair of corresponding entries. For example, using post-fix notation:
```
[2 4 6] [10 20 30] +
```
[gives](https://tio.run/##y00syfn/P9pIwUTBLFYh2tBAwchAwdggVkH7/38A) the ouput
```
[12 24 36]
```
This also works with multi-dimensional arrays. The notation `[1 2 3; 4 5 6]` represents the `2`×`3` array (matrix)
```
1 2 3
4 5 6
```
which has size `2` along the first dimension (vertical) and `3` along the second (horizontal). So for example
```
[2 4 6; 3 5 7] [10 20 30; 40 60 80] *
```
[gives](https://tio.run/##BcE7EgAQEETBq7xYNH5LlaMogZzM/Vf33e@4z0TBBplKW8woksgaFGGiaxHcPw)
```
[20 80 180; 120 300 560]
```
* **Broadcasting** or (**singleton expansion**): the two input arrays do not have matching sizes, but in each non-matching dimension one of the arrays has size `1`. This array is implicitly replicated along the other dimensions to make sizes match; and then the operation is applied element-wise as above. For example, consider two input arrays with sizes `1`×`2` and `3`×`1`:
```
[10 20] [1; 2; 5] /
```
Thanks to broadcasting, this is equivalent to
```
[10 20; 10 20; 10 20] [1 1; 2 2; 5 5] /
```
and so it [gives](https://tio.run/##y00syfn/P9rQQMHIIFYh2tBawchawTRWQf//fwA)
```
[10 20; 5 10; 2 4]
```
Similarly, with sizes `3`×`2` and `3`×`1` (broadcasting now acts along the second dimension only),
```
[9 8; 7 6; 5 4] [10; 20; 30] +
```
[gives](https://tio.run/##y00syfn/P9pSwcJawVzBzFrBVMEkViHa0MBawQiIjQ1iFbT//wcA)
```
[19 18; 27 26; 35 34]
```
The number of dimensions may even be different. For example, inputs with sizes 3×2 and 3×1×5 are compatible, and give a 3×2×5 result. In fact, size 3×2 is the same as 3×2×1 (there are arbitrarily many implicit trailing singleton dimensions).
On the other hand, a pair of `2`×`2` and `3`×`1` arrays would give an error, because the sizes along the first dimension are `2` and `3`: they are not equal and none of them is `1`.
## Definition of modular broadcasting
Modular broadcasting is a generalization of broadcasting that works even if none of the non-matching sizes are `1`. Consider for example the following `2`×`2` and `3`×`1` arrays as inputs of the function `+`:
```
[2 4; 6 8] [10; 20; 30] +
```
The rule is as follows: for each dimension, **the array that is smaller along that dimension is replicated modularly (cyclically)** to match the size of the other array. This would make the above equivalent to
```
[2 4; 6 8; 2 4] [10 10; 20 20; 30 30] +
```
with the result
```
[12 14; 26 28; 32 34]
```
As a second example,
```
[5 10; 15 20] [0 0 0 0; 1 2 3 4; 0 0 0 0; 5 6 7 8; 0 0 0 0] +
```
would produce
```
[5 10 5 10; 16 22 18 24; 5 10 5 10; 20 26 22 28; 5 10 5 10]
```
In general, inputs with sizes `a`×`b` and `c`×`d` give a result of size `max(a,b)`×`max(c,d)`.
## The challenge
Implement **addition** for **two-dimensional** arrays with **modular broadcasting** as defined above.
The arrays will be **rectangular** (not ragged), will only contain **non-negative integers**, and will have **size at least `1`** in each dimension.
Aditional rules:
* Input and output can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Their format is flexible as usual.
* Programs or functions are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes are forbidden](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default).
* Shortest code in bytes wins.
## Test cases
The following uses `;` as row separator (as in the examples above). Each test case shows the two inputs and then the output.
```
[2 4; 6 8]
[10; 20; 30]
[12 14; 26 28; 32 34]
[5 10; 15 20]
[0 0 0 0; 1 2 3 4; 0 0 0 0; 5 6 7 8; 0 0 0 0]
[5 10 5 10; 16 22 18 24; 5 10 5 10; 20 26 22 28; 5 10 5 10]
[1]
[2]
[3]
[1; 2]
[10]
[11; 12]
[1 2 3 4 5]
[10 20 30]
[11 22 33 14 25]
[9 12 5; 5 4 2]
[4 2; 7 3; 15 6; 4 0; 3 3]
[13 14 9;12 7 9;24 18 20;9 4 6;12 15 8]
[9 12 5; 5 4 2]
[4 2 6 7; 7 3 7 3; 15 6 0 1; 4 0 1 16; 3 3 3 8]
[13 14 11 16; 12 7 9 8; 24 18 5 10; 9 4 3 21; 12 15 8 17]
[6 7 9]
[4 2 5]
[10 9 14]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 23 bytes
```
~~Aθ~~IE⌈EθLιE⌈EθL§λ⁰ΣEθ§§νιλ
```
[Try it online!](https://tio.run/##dYzNCsIwEITvfYo9JrBC/9IqnsSToCB4DDmEWmwgjVqj9O3jpqV4Mkw2M3yzaTo9NHdtQzgPxnm21y/PTvpBdzT9u5/8E@HYupvvmOEc4T/e@YO7tiOzCCnnsXv5dRa4vA7BUMPy@WxDkDKRcoOQ5QhCIUiBUCLkSiVIJFqECqGOrEYoyNKMKRMTSWk5xnK2pCrGYuqS1vSVUmH1sV8 "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a 3-dimensional array. Explanation:
```
Aθ
```
Input everything.
```
θ Input
E Map over arrays
ι Current array
L Length
⌈ Maximum
E Map over implicit range
θ Input
E Map over arrays
λ Current array
§ ⁰ First element
L Length
⌈ Maximum
E Map over implicit range
θ Input
E Map over arrays
ν Current array
§ ι Cyclically index using outer loop index
§ λ Cyclically index using inner loop index
Σ Sum
I Cast to string
Implicitly print on separate lines and paragraphs
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~25~~ 24 bytes
```
,iZy]vX>XKx,@GK:KP:3$)]+
```
[Try it online!](https://tio.run/##y00syfn/XyczqjK2LMIuwrtCx8Hd28o7wMpYRTNW@///aEsFQyMFU2sFUwUTBaNYrmggqWCmYG6tYK5gDMLWCoamQAEDBUNroAogpWBoZg2UAkGLWAA "MATL – Try It Online")
Finally! It only took a week for the Language of the Month-inspired challenge to be answered by the [Language of the Month!](https://codegolf.meta.stackexchange.com/questions/16337/language-of-the-month-for-may-2018-matl)
My guess is that it's not quite as short as possible, but I'm happy enough because my initial version was over 40 bytes. *edit: I was right, Luis found another byte to squeeze out!*
```
,iZy] # do twice: read input and find the size of each dimension
vX> # find the maximum along each dimension
XKx # save this into clipboard K and delete from stack. Stack is now empty.
, # do twice:
@G # push the input at index i where i=0,1.
# MATL indexes modularly, so 0 corresponds to the second input
K: # push the range 1...K[1]
KP: # push the range 1...K[2]
3$) # use 3-input ) function, which uses modular indexing
# to expand the rows and columns to the appropriate broadcasted size
] # end of loop
+ # sum the now appropriately-sized matrices and implicitly display
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ṁ€ZL$Z€Ɗ⁺S
```
Takes a matrix pair (two arrays of rows) as input and returns a matrix.
[Try it online!](https://tio.run/##fU8rEsIwFPQ9BQK5Ip8mba@ARdFMJIapQyGLYQaJ4hBcoFgG7tFeJLzklcYxmcl7u3m7b3PYd90phHHop/Oj3axbKp/r1D@34aheF0Lv2zjcqe5CcMXKOYXSw1nU3oOgFIRUvLQgJk4YJFIaKMFDAulEEgo6OWTOwKIiv8yxj2SxWiBSz0tnju1gfjytxBKkgVT0FDeUmKWxgaugOaGlUqYUmqi/spiSpchyiivZAhLSsg@devaKP2uyRcxZ@C8 "Jelly – Try It Online")
### How it works
```
ṁ€ZL$Z€Ɗ⁺S Main link. Argument: [M, N] (matrix pair)
Z $ Zip M with N (i.e., transpose the matrix of arrays [M, N], ...
L then take the length (number of rows) of the result.
ṁ€ Mold M and N like the indices, cyclically repeating their rows as many
times as needed to reach the length to the right.
Z€ Zip each; transpose both M and N.
Ɗ⁺ Combine the three links to the left into a chain and duplicate it.
The first run enlarges the columns, the second run the rows.
S Take the sum of the modified matrices.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 127 126 125 bytes
*golfed a byte by changing `sum(m)` to `m+n`*
*One more byte thanks to @Jonathan Frech*
```
lambda y:[[m+n for n,m,j in Z(l)]for*l,i in Z(y)]
from itertools import*
Z=lambda y:zip(*map(cycle,y),range(max(map(len,y))))
```
Takes input as a list of two 2-dimensional arrays.
* The `Z` lambda takes two arrays as input and returns an iterator yielding an index and merged values from both arrays, until the index reaches the largest array's length. The index variable isn't useful to me and costs me bytes, but I don't know how to do without it... ([related](https://stackoverflow.com/questions/818828/is-it-possible-to-implement-a-python-for-range-loop-without-an-iterator-variable))
* The main lambda just takes the input arrays and calls `Z` on the outer and inner arrays. The innermost values are added together.
[Try it online!](https://tio.run/##fVLNboMwDL7zFD4G5gN/pWslXqQsB9bBlikJKOQw9vLMCbSCtmuEHGN/9mc77kf71elsasu3Sdbq/aOG8VhV6kVD2xnQqPAbhIYTkyEnSyRRzP9jyIPWdAqEbYztOjmAUH1nbBScymuqX9GzSNU9O49n2eAYoqn1Z8NU/cOcWTaajHQm2wx2gBKqAOjM0mtVipBzhKpAeOUcV54kdvbUyyy@@JZrnWKHMGMT0tJ4myVGWD6PIABCtnBufRRMReypDrxx/k@dbMnSZ1CivmvwOXyuFGF3G@faJOez@AMNJXWhc2f5HXvuCVzHDrL3XE5eBln45hM/i3zRISn8a3hwtnqxBwXMszw8Ir32wwMeBG4V3X64zfN7cvS@3ghtWcuciTboDw "Python 3 – Try It Online")
Using `itertools.cycle` feels a bit like cheating but I think I've been punished enough by the sheer import statement length :)
I'm sure this could be golfed some more, especially the iteration method that leaves these useless `i` and `j` variables. I would be grateful on any tips on how to golf that, I'm probably missing something obvious.
[Answer]
# JavaScript (ES6), 131 bytes
Not the right tool for the job, and probably not the right approach either. Oh well... ¯\\_(ツ)\_/¯
```
a=>b=>(g=(a,b,c)=>[...Array((a[b[L='length']]?a:b)[L])].map(c))(a,b,(_,y)=>g(a[0],b[0],(_,x)=>(h=a=>a[y%a[L]][x%a[0][L]])(a)+h(b)))
```
[Try it online!](https://tio.run/##lU/dSsMwGL33KXIzlg9jaTvXbUIq3u8NQpCkdq1S29ENWZ@@ni@zMmS7EPJzcr7zQz7clzsU/fv@@NB2b@W406PTude5rLR0yquCdG6iKHrpezdI6Yw3Wz1vyrY61nNrn92TJ7O1ZKNPt5cFUXDJVzXAWEEfW@X5AHUCJWuNAmeGmYPNmtOMJQzhpPtaeiIai649dE0ZNV0ld9KYVIlHq4TJlFiz0pgk5ncazkUMju7@mpKzMr0xZPtv1lWJEuhdoFqJ5aQEh32jcaNEkrIY2cvg@2kICOQKVr4TTDMGGJy/wIN/RyJEidUUDHgZj2R4pxJArGzqCmt9tTELOZvLFv49jd8 "JavaScript (Node.js) – Try It Online")
### How?
The helper function **g()** creates an array which is as large as the largest input array (**a** or **b**) and invokes the callback function **c** over it:
```
g = (a, b, c) =>
[...Array(
(a[b[L = 'length']] ? a : b)[L]
)].map(c)
```
The helper function **h()** reads the 2D-array **a** at **(x, y)** with modular broadcasting:
```
h = a => a[y % a[L]][x % a[0][L]]
```
The main code now simply reads as:
```
a => b =>
g(a, b, (_, y) =>
g(a[0], b[0], (_, x) =>
h(a) + h(b)
)
)
```
---
# Recursive version, 134 bytes
```
a=>b=>(R=[],g=x=>a[y]||b[y]?a[0][x]+1|b[0][x]+1?g(x+1,(R[y]=R[y]||[])[x]=(h=a=>a[y%a.length][x%a[0].length])(a)+h(b)):g(+!++y):R)(y=0)
```
[Try it online!](https://tio.run/##lU/daoMwGL3fU2QXhYRkxdjV/sBn38HbkIvYWd0QHWsZCn13d5I2o4z2YhDj@b7zRz7ctzvuv94/Ty9d/1ZNB5oc5SXlvCBjVU0D5c6M9nwuce@cSawZrNQYr2hX80FqxQvwVASpsQIU8YZccM/cvK26@tTAMfMRcRTcCdnwUohtzeWzlKPYFoKPlIhp33fHvq3mbV/zAzcmVezVKmYyxdYWTmN04uc03IsEO/H016QvyvQB6e2/WXcliqF3gWrFllGJHb4HjRvFdOrFyF4G37UhICxXsPq/Bpt5AOLyBE/8OxIhiq1iMOBtPJLhjSWAOFnsCmd9tzELOZvbFv96Mf0A "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
2FεIζg∍ø]øεø¨}O
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fyO3cVs9z29IfdfQe3hF7eMe5rYd3HFpR6///f3R0tKmOgqFBrI5CtCGQZWQQC2JGG@goQBFYBiiho2Cso2AC4qHKATWZ6SiY6yhYoMnFxgIA "05AB1E – Try It Online")
---
### Old version, 25 bytes
```
é`DŠg∍)Σнg}`DŠнgδ∍€˜)ø€øO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8MoEl6ML0h919GqeW3xhb3otiAukz20BCj1qWnN6jubhHUD68A7///@jo6NNdRQMDWJ1FKINgSwjg1gQM9pARwGKwDJACR0FYx0FExAPVQ6oyUxHwVxHwQJNLjYWAA "05AB1E – Try It Online")
### Explanation
15-byter:
```
2FεIζg∍ø]øεø¨}O – Full program. Takes input as a 3D [A, B] list from STDIN.
2F – Apply twice:
ε – For each in [A, B]:
Iζ – Transpose the input (filling gaps with spaces).
g – Length (retrieve the number of rows).
∍ – Extend the current item (A or B) to the necessary length.
ø – Transpose.
] – Close all loops.
ø – Transpose again.
ε – For each row in ^ (column of the loops result):
ø – Transpose the column.
¨} – Remove the last element and close the map-loop.
O – Sum.
```
25-byter:
```
é`DŠg∍)Σнg}`DŠнgδ∍€˜)ø€øO – Full program. Takes input as a 3D list from STDIN.
é – Sort the list by length.
`D – Dump contents separately onto the stack, duplicate the ToS.
Š – Perform a triple swap. a, b, c -> c, a, b.
g – Get the length of the ToS.
∍ – Extend the shorter list (in height) accordingly.
)Σ } – Wrap the whole stack into a list and sort it by:
нg – The length of its first item.
`DŠ – Same as above.
нg – The length of the first element.
δ∍€˜ – Extend the shorter list (in width) accordingly.
)ø – Wrap the stack into a list and transpose (zip) it.
€ø - Then zip each list.
O – Apply vectorised summation.
```
[Answer]
# [R](https://www.r-project.org/), ~~136 104 103 95~~ 93 bytes
Golfed down a whopping ~~33~~ 35 bytes following Giuseppe's advice. Managed to get under 100 bytes by using an operator as a function name.
See history for more legible code.
```
function(x,y,d=pmax(dim(x),dim(y)))y/d[2]/d[1]+x/d[2]/d[1]
"/"=function(x,j)apply(x,1,rep,,j)
```
[Try it online!](https://tio.run/##bZHJbsIwEIbveYoRXOL2R3iJAxRy7AtU7anikCYtCiKLIqraT5/aiMURSJY9mpnvn8X9sNvMhp/fpjhWbRMbWJRZV@cmLqs6Ngz@sYwxOy8/5dZdYvtsbnY0mU@yAN@zvOsO1lkC/XcH5xgMbWZU58e@MnERS6RIsGRoivaQSRbZICz4E4kXhaZv/zLFoumY1RAcQkPyC44v61Pf3z5eXbYdZXPQ9QiQBClQEjjd0aAUtAAtQ/9ZPRmp@1au2isnKU@4PmnKM6JGiA2RBBILKN@/3wB3pno8Rji0YGsKx5J3S0md6upS/m4Jvqq@Rc3aRjv/zWz4Bw "R – Try It Online")
[Answer]
# [K (ngn/k)](https://github.com/ngn/k), 23 bytes
```
{+/2{+:'(|/#:'x)#'x}/x}
```
[Try it online!](https://tio.run/##dVDbasMwDH3fVwg6aEw8YsmXXPQppdC9dIyODkofUrru17Njp1nZwzDYSD4X6Rxejm/HadoP17qRaz2sq69mNaxHs1qPt2a8Tefh@ry5fJ@GPY26@zxotdu/vn/oqBc9me3t6bypKqGgiTqjtWVH4sg7oxULcVBJJJ16IR/MtqAjsVOOwAHkqBxlAgIySx0pUUvdUhtAM49mMjQh3pEEfXThK@UDfr/d2dNaVmvF4PJzA34o8K@WmVhKt7b3MSj@WaXOGAh7j41I4rxHDxqAEXAoV7i1JZ83Sxqwgiefx@ZC6hXgFo@EMrjTHryUuyB05j/JHEOWpUUaaXCWJ0ydsgdO9/Dh0p69EN/sVuLJfp6EF0vi9h5OKoPZ7BZzHg5UDtvpBw "K (ngn/k) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes
```
éR`UvXNèy‚é`©g∍®+ˆ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8MqghNCyCL/DKyofNcw6vDLh0Mr0Rx29h9Zpn277/z86OtpUR8HQIFZHIdoQyDIyiAUxow10FKAILAOU0FEw1lEwAfFQ5YCazHQUzHUULNDkYmMB "05AB1E – Try It Online")
**Explanation**
```
éR # sort by length, descending
`U # store the shorter list in X
v # for each list y, index N in the longer list
XNè # get the nth element of the shorter list
y‚é # pair with y and sort by length
`©g∍ # repeat the shorter list to the same length as the longer
®+ # elementwise addition of the lists
ˆ # add to global list
# implicitly print global list
```
[Answer]
# Pyth, 24 bytes
```
KeSmlhdQmm+Fm@@bdkQKeSlM
```
[Try it here](https://pyth.herokuapp.com/?code=KeSmlhdQmm%2BFm%40%40bdkQKeSlM&input=%5B%5B9%2C%2012%2C%205%5D%2C%20%5B5%2C%204%2C%202%5D%5D%2C%20%5B%5B4%2C%202%5D%2C%20%5B7%2C%203%5D%2C%20%5B15%2C%206%5D%2C%20%5B4%2C%200%5D%2C%20%5B3%2C%203%5D%5D&debug=0)
### Explanation
```
KeSmlhdQmm+Fm@@bdkQKeSlM
eSlMQ Get the maximum length of (implicit) input...
KeSmlhdQ K ... and the maximum row length.
mm For each 2d index ...
+Fm@@bdkQ ... get the sum of the appropriate elements.
```
[Answer]
# Java 8, 172 bytes
```
A->B->{int m=A.length,o=A[0].length,d=B.length,u=B[0].length,l=m>d?m:d,a=o>u?o:u,r[][]=new int[l][a],$;for(;l-->0;)for($=a;$-->0;)r[l][$]=A[l%m][$%o]+B[l%d][$%u];return r;}
```
[Try it online.](https://tio.run/##xVJNb6MwEL33V/iQSqAdEJCQflBTJYe97al7Qz64gXTJGhuB3SpC/PbsGJJND6XaQ6qVETzPDH7Pb2bHX7m3y38fNoK3LfnBS9ldEdJqrssN2WHWN7oU/tbIjS6V9L8fwUMpdcYyBv9WdARpSraEHlZeuvbSDoOkoitfFPJF/wJFV1nATrucrk/Q0PW7hKBVmj9W9zlwqlLzqO4NNPZwKou3gUiwjDOYJVvVOInwvDRIXItnlCezcdvYohlDRnFdIbpW7NsacW6xYUlTaNNI0iT9IUE/8KnNs0BLjs68qjInFbrlPOmmlC8ZI9y1zhHytG91UfnKaL/GlBbSOVu0ahq@b/28KOqfavzV2fq8rsXeOcnHq3RdBIseuiXc9r37UT4MMB3Z1zzAEtdNLkgew3B8GEMUTPAHMCxbBRHMB7XnWAxLuEHt59ilJYYTuqIvYILh1IkuXJxutBPiSUpsCnxB0@8gjJDVNm8BUxe2GehuYD6OxxI/i6Hjcwz9L0V22EZVcFaGUxeO6iCEcDlKxHV7cZl21O8@URf/Zeyv@sMf)
**Explanation:**
```
A->B->{ // Method with integer-matrix as both parameters and return-type
int m=A.length, // Rows of `A` (we got an M)
o=A[0].length, // Columns of `A` (we got an O)
d=B.length, // Rows of `B` (we got a D)
u=B[0].length, // Columns of `B` (we got a U)
l=m>d?m:d, // Maximum of both rows (we got an L)
a=o>u?o:u, // Maximum of both columns (we got an A)
r[][]=new int[l][a],// Result-matrix of size `l` by `a` (and we got an R)
$; // Temp integer (which $pells? ;P)
for(;l-->0;) // Loop over the rows
for($=a;$-->0;) // Inner loop over the columns
r[l][$]= // Set the current cell in the result-matrix to:
A[l%m][$%o] // The value at {`l` modulo-`m`, `$` modulo-`o`} in `A`
+B[l%d][$%u]; // Plus the value at {`l` modulo-`d`, `$` modulo-`u`} in `B`
return r;} // Return the result matrix
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~23~~ 21 bytes
```
↑{+⌿⍺[⍵|[0]⍳⍴⍺]}2,¨⍴¨
```
[Try it online!](https://tio.run/##fVDLSgNBELznK/q2O2hgpmdf8VdCDkskElyIJLlIzE0CQVf04Ad4C7mqFy9CPmV@ZK2e2Wz0IgO7M1XdVdVd3lT9y9uyml31x1W5WEzHjXt6nc7c5lk3E3zd5mV15h6/Xf01dPXn3VCPXP3u6g8AozWfH3a4H3ZNs0TxChVu@zbHdQL@IppdR@7hPpqU0yoCAHq@7sXQjJkSFWdUKBW7em80sSar1VI4w2TAckZcqNgy2USFrpSMVrFJUS2NQDT5A5BQJ6IdklJGORw6JKiLBrVCcIBXQZyo3ziysKfE/4T3fFQfmKFV721AiNshPGgMGRZiGzhJRak6AqdJw9uIj7WYmDgNUw4gIB0pGrmdU25xTtZPnym8kdPi3a7MCwyU7C6XPyd@LhQNoJJ5Ap2F@tdCNuZtqLPC5oy3I8yVeU@c4o@vCVTwlo0H97BM8bfEpotAJlfH/WQhbXhIgLRbjIaUSX4A "APL (Dyalog Classic) – Try It Online")
this could be the only time ever I get a chance to use `|[0]`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~124~~ 116 bytes
```
l=len
A,B=sorted(input(),key=l)
A*=l(B)
for i in eval(`zip(A,B)`):a,b=sorted(i,key=l);a*=l(b);print map(sum,zip(*i))
```
[Try it online!](https://tio.run/##nY/LbsIwEEXX@CusbLCjqZQ4hKe8gN@wrGLAbS2ME4VQlf586kehiGVlyZbv3HNnpr32H41jw745aMxxlmWD5VY7tIYNPzddrw/EuPbSEwpHfeWWonXOLdlQ9NZ02GDjsP5Ulmy/TUs8RLd0qWB3Z3@plQrUjq7azrgen1RLzpcTBCg3lA6@MYqJryGxU@5dkxldopH@0nscpkOjhI5fxvm8GIQQDCYSsJjCXIZXlEV4WLyrQkqJvKmGJJc1@Er0FRBPVIFBlWIe1BqmMPOpD2oK@xcZWj5NEcPKVGK3bwqE@raMd0L1Zw6r3fdMYui1SNrE056UPw "Python 2 – Try It Online")
Explanation:
Takes list of two 2-d lists as input.
```
l=len
A,B=sorted(input(),key=l) # Sort inputed lists by length
A*=l(B) # Extend shorter list
for i in eval(`zip(A,B)`): # Zip and remove copied references
a,b=sorted(i,key=l) # Sort lists in each pair (keep references)
a*=l(b) # Extend shorter list
print map(sum,zip(*i)) # Zip and sum
```
[Answer]
# [Python 2](https://docs.python.org/2/), 101 97 105 bytes
*Edit: Thanks (again !) to Dead Possum for saving 4 bytes*
*Edit 2: lost 8 bytes, some tests cases weren't passing*
A mix between [Dead Possum's earlier solution](https://codegolf.stackexchange.com/a/164104/79471) (thanks to him !), and [my own Python 3 solution](https://codegolf.stackexchange.com/a/164077/79471).
```
lambda y:[map(sum,P(i))for i in P(y)]
def P(y):y=sorted(y,key=len);y[0]*=len(y[1]);return eval(`zip(*y)`)
```
[Try it online!](https://tio.run/##fVLLboMwELzzFXu0Ix@wIaQh4h9ydy2FCqOi8hI4ldyfp/ZCKkjSIGSvPLOenfX21nx2rZjK7H2q8@ajyMGmssl7Ml4bdiYVpWU3QAVVC2diqQoKXWKU2mzsBqMLYtmXtlmtW3qyMlQ7HxIruaKnQZvr0IL@zmty@al6srP0QiejRzNCBjIA980rRlIwiBUDmTB4U4qtEB76c4FrFN6wZVtfsWcwc7mLRLi9JWSw/MhwBAbRornFXLIr4uDqYHfg/9J8KyZeUZ30g8HX9LlSBvv7PG/Tga/yj64pwqfOzuIH9RgFvGNPOaCWX2@NTNA8x17ESww8wddAcrR6sScFzL08PhP986MCFQR@3Px8@InDOUkR64eqNaQk/ojS6Rc "Python 2 – Try It Online")
Same input as my Python 3 solution (a pair of 2 dimensional lists).
Commented code:
```
# Iterate over the nested lists, resized & joined by P(),
# and sum the inner joined items
lambda y:[map(sum,P(i))for i in P(y)]
def P(y):
y=sorted(y,key=len) # Sort the two input lists by length
y[0]*=len(y[1]) # Multiply the smallest one by the biggest one's length
# (The smallest list is now the previously largest one)
return eval(`zip(*y)`) # Return paired list elements up to the smallest list's length
```
[Answer]
# [Julia 0.6](http://julialang.org/), 85 83 bytes
```
M\N=(((r,c),(s,d))=size.((M,N));repmat(M,s,d)+repmat(N,r,c))[1:max(r,s),1:max(c,d)]
```
[Try it online!](https://tio.run/##PY7BasMwEETv/oo57tJtseRYdSLSP4hPvik6iNRQlzgYO4XSn3dXbgnLstrRzJM@v65Dcut6OrdHIprlwkKLvDMfl@GnfyE6Scvs534a012XfPf0v7WS/RzMYUzfml1Y/o4XNcV1TBN1z2/TPNzu1xt1wcRzF2xkQUEFhRqm9DA1bBkFocRWqsCiws7jodRweEXzUBSheZs9Do2G5375SFNPIROtdqXISgxvxj2MRZ0xO9j8lI5M9Aqtcm@/cEo2Xi06YJwytmoiF8zrLw "Julia 0.6 – Try It Online")
*(Replace `⧻` with `\` thanks to [Jo King](https://codegolf.stackexchange.com/questions/167872/2d-array-middle-point/167902#comment405656_167902))*
Works by repeating each matrix horizontally and vertically so they both have the same size (product of row sizes x product of column sizes), adding those up and extracting out the correct region from that. (Row vector inputs or column vector inputs need a `reshape` call to be cast as 2-dimensional arrays, which I'm assuming is fine since the question specifies "Implement addition for two-dimensional arrays" and "Input and output can be taken by any reasonable means. Their format is flexible as usual.")
] |
[Question]
[
# Problem
given input `a,b,c`
where `a,b,c` are positive even integers
and `a > b > c`
Make a box of any allowed character with dimensions `a x a`
Center a box of a different allowed character with dimensions `b x b` within the previous
Center a box of another different allowed character with dimensions `c x c` within the previous
Allowed Characters are ASCII characters are in `[a-zA-z0-9!@#$%^&*()+,./<>?:";=_-+]`
Input `a=6, b=4, c=2`
```
######
#****#
#*@@*#
#*@@*#
#****#
######
```
Input `a=8, b=6, c=2`
```
########
#******#
#******#
#**@@**#
#**@@**#
#******#
#******#
########
```
Input `a=12, b=6, c=2`
```
############
############
############
###******###
###******###
###**@@**###
###**@@**###
###******###
###******###
############
############
############
```
# Rules
* **Shortest code wins**
* Remember that you can choose which char to print within the range given
* Trailing newlines accepted
* Trailing whitespace accepted
* functions may return string with newlines, string array, or print it
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
F#*@UO÷N²ι‖C←↑
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBQ0lZy0FJk0sBCPyTcvLz0jVcMssyU1I1PPMKSkv8SnOTUos0NHUUjIA4U9OaKyg1LSc1ucQ5v6BSwyq0QEfByic1rUTT@v9/QyMFMwWj/7pl/3WLcwA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte using the quick ``` to avoid a link, as suggested by Erik the Outgolfer.
```
H»þ`€Ḣ>ЀHSUṚm€0m0Y
```
A full program taking a list `[a,b,c]` printing the boxes using `a:2 b:1 c:0`
... in fact, as is, it will work for up to **10** boxes, where the innermost box is `0` ([for example](https://tio.run/##y0rNyan8/9/j0O7D@xIeNa15uGOR3eEJQIZHcOjDnbNygSyDXIPI////Rxtb6Bib6Rib6BhZ6BiZ6RgZ6Ria6Bga6JjpmMQCAA "Jelly – Try It Online")).
**[Try it online!](https://tio.run/##y0rNyan8/9/j0O7D@xIeNa15uGOR3eEJQIZHcOjDnbNygSyDXIPI////Rxsa6ZjpGMUCAA "Jelly – Try It Online")**
### How?
```
H»þ`€Ḣ>ЀHSUṚm€0m0Y - Main link: list of boxes, B = [a, b, c]
H - halve B = [a/2, b/2, c/2]
€ - for €ach:
` - repeat left argument as the right argument of the dyadic operation:
þ - outer product with the dyadic operation:
» - maximum
- ... Note: implicit range building causes this to yield
- [[max(1,1),max(1,2),...,max(1,n)],
- [max(2,1),max(2,2),...,max(2,n)],
- ...
- [max(n,1),max(n,2),...,max(n,n)]]
- for n in [a/2,b/2,c/2]
Ḣ - head (we only really want n=a/2 - an enumeration of a quadrant)
H - halve B = [a/2, b/2, c/2]
Ѐ - map across right with dyadic operation:
> - is greater than?
- ...this yields three copies of the lower-right quadrant
- with 0 if the location is within each box and 1 if not
S - sum ...yielding one with 0 for the innermost box, 1 for the next, ...
U - upend (reverse each) ...making it the lower-left
Ṛ - reverse ...making it the upper-right
m€0 - reflect €ach row (mod-index, m, with right argument 0 reflects)
m0 - reflect the rows ...now we have the whole thing with integers
Y - join with newlines ...making a mixed list of integers and characters
- implicit print - the representation of a mixed list is "smashed"
```
[Answer]
# Python 2, ~~107~~ 103 bytes
```
a,b,c=input()
r=range(1-a,a,2)
for y in r:
s=''
for x in r:m=max(x,y,-x,-y);s+=`(m>c)+(m>b)`
print s
```
Full program, prints boxes with `a=2`,`b=1`,`c=0`
Slightly worse answer, with list comprehension (104 bytes):
```
a,b,c=input()
r=range(1-a,a,2)
for y in r:print''.join(`(m>c)+(m>b)`for x in r for m in[max(x,y,-x,-y)])
```
[Answer]
# C#, ~~274~~ 232 bytes
```
using System.Linq;(a,b,c)=>{var r=new string[a].Select(l=>new string('#',a)).ToArray();for(int i=0,j,m=(a-b)/2,n=(a-c)/2;i<b;++i)for(j=0;j<b;)r[i+m]=r[i+m].Remove(j+m,1).Insert(j+++m,i+m>=n&i+m<n+c&j+m>n&j+m<=n+c?"@":"*");return r;}
```
Terrible even for C# so can definitely be golfed but my mind has gone blank.
Full/Formatted version:
```
using System;
using System.Linq;
class P
{
static void Main()
{
Func<int, int, int, string[]> f = (a,b,c) =>
{
var r = new string[a].Select(l => new string('#', a)).ToArray();
for (int i = 0, j, m = (a - b) / 2, n = (a - c) / 2; i < b; ++i)
for (j = 0; j < b;)
r[i + m] = r[i + m].Remove(j + m, 1).Insert(j++ + m,
i + m >= n & i + m < n + c &
j + m > n & j + m <= n + c ? "@" : "*");
return r;
};
Console.WriteLine(string.Join("\n", f(6,4,2)) + "\n");
Console.WriteLine(string.Join("\n", f(8,6,2)) + "\n");
Console.WriteLine(string.Join("\n", f(12,6,2)) + "\n");
Console.ReadLine();
}
}
```
[Answer]
# [Haskell](https://www.haskell.org/), 126 bytes
```
f a b c=r[r["#*@"!!(v c+v b)|x<-[1..d a],let v k|x>a#k&&y>a#k=1|2>1=0]|y<-[1..d a]]where r x=x++reverse x;d=(`div`2);x#y=d$x-y
```
[Try it online!](https://tio.run/##RcpNC4IwAAbgv/L6gWimpEQXm/QD6tRRJKebKH4g09aE/fdFp07P5enoOvBxNKYFRY2GiEIUtnO42ZblSzShRB1odY2KJI4ZaHkc@QaJQaucOoPn7T9IotM8IadS7/9ZfjouOAQUUWEouORi5VAZI37FelmlQaacnTBXRbuZaD@DYKLL44XlvT03cZ/hosUFZ6TmCw "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), ~~174~~ ~~170~~ 147 bytes
```
a=>b=>c=>(d=("#"[r="repeat"](a)+`
`)[r](f=a/2-b/2))+(e=((g="#"[r](f))+"*"[r](b)+g+`
`)[r](h=b/2-c/2))+(g+(i="*"[r](h))+"@"[r](c)+i+g+`
`)[r](c)+e+d
```
---
## Try it
```
fn=
a=>b=>c=>(d=("#"[r="repeat"](a)+`
`)[r](f=a/2-b/2))+(e=((g="#"[r](f))+"*"[r](b)+g+`
`)[r](h=b/2-c/2))+(g+(i="*"[r](h))+"@"[r](c)+i+g+`
`)[r](c)+e+d
oninput=_=>+x.value>+y.value&&+y.value>+z.value&&(o.innerText=fn(+x.value)(+y.value)(+z.value))
o.innerText=fn(x.value=12)(y.value=6)(z.value=2)
```
```
label,input{font-family:sans-serif;}
input{margin:0 5px 0 0;width:50px;}
```
```
<label for=x>a: </label><input id=x min=6 type=number step=2><label for=y>b: </label><input id=y min=4 type=number step=2><label for=z>c: </label><input id=z min=2 type=number step=2><pre id=o>
```
---
## Explanation
```
a=>b=>c=> :Anonymous function taking the 3 integers as input via parameters a, b & c
(d=...) :Assign to variable d...
("#"[r="repeat"](a) : # repeated a times, with the repeat method aliased to variable r in the process.
+`\n`) : Append a literal newline.
[r](f=a/2-b/2) : Repeat the resulting string a/2-b/2 times, assigning the result of that calculation to variable f.
+ :Append.
(e=...) :Assign to variable e...
(g=...) : Assign to variable g...
"#"[r](f) : # repeated f times.
+"*"[r](b) : Append * repeated b times.
+g+`\n`) : Append g and a literal newline.
[r](h=b/2-c/2) : Repeat the resulting string b/2-c/2 times, assigning the result of that calculation to variable h.
+(...) :Append ...
g+ : g
(i=...) : Assign to variable i...
"*"[r](h) : * repeated h times.
+"@"[r](c) : @ repeated c times
+i+g+`\n`) : Append i, g and a literal newline.
[r](c) :...repeated c times.
+e+d :Append e and d.
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~70, 44~~, 42 bytes
```
Àé#@aÄÀG@b|{r*ÀG@c|{r@òjdòÍ.“.
ç./æ$pYHP
```
[Try it online!](https://tio.run/##K/v//3DD4ZXKDomHWw43uDsk1YhVF2mBWMkglsPhTVkphzcd7tU7NFmP6/ByPf3Dy1QKIj0C/v//b2j23@y/CQA "V – Try It Online")
~~This is hideous. Eww.~~ Much better. Still not the shortest, but at least *somewhat* golfy.
Saved two bytes thanks to @nmjmcman101!
Hexdump:
```
00000000: c0e9 2340 61c4 c047 4062 7c16 7b72 2ac0 ..#@a..G@b|.{r*.
00000010: 4740 637c 167b 7240 f26a 64f2 cd2e 932e G@c|.{[[email protected]](/cdn-cgi/l/email-protection).....
00000020: 0ae7 2e2f e624 7059 4850 .../.$pYHP
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 97 bytes
```
x,y;f(a,b,c){for(y=1-a;y<a;y+=2,puts(""))for(x=1-a;x<a;x+=2)printf(x/c|y/c?x/b|y/b?"#":"*":"@");}
```
[Try it online!](https://tio.run/##HczBCsIwEATQf1kvu7olNAcPxtL@SrIQ6cFaagsbtN8etx6GgXkw0jxEalUuIWPkxEKf/FqwdG0TQ7lbLp3neVvfCEB0mP5NzdSM5mWc1ozq5Fuc9OqSderhBDc4WwagsNdnHCe0b2w9X9kf0w8 "C (gcc) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~26~~ ~~23~~ ~~22~~ ~~20~~ 18 bytes
```
2/t:<sPtPh!Vt!2$X>
```
Input is a column vector `[a; b; c]`. Output uses characters `2`, `1`, `0`.
[**Try it online!**](https://tio.run/##y00syfn/30i/xMqmOKAkIEMxrETRSCXC7v//aEMjawUzawWjWAA)
As an aside, it works for up to ten boxes, not just three. Here's an [example with five boxes](https://tio.run/##y00syfn/30i/xMqmOKAkIEMxrETRSCXC7v//aGMDawUjIDY0slYwAzJjAQ).
[Answer]
# Mathematica, 49 bytes
```
Print@@@Fold[#~CenterArray~{#2,#2}+1&,{{}},{##}]&
```
Takes input `[c, b, a]`. The output is `a=1, b=2, c=3`.
### How?
```
Print@@@Fold[#~CenterArray~{#2,#2}+1&,{{}},{##}]&
& (* Function *)
Fold[ ,{{}},{##}] (* Begin with an empty 2D array.
iterate through the input: *)
& (* Function *)
#~CenterArray~{#2,#2} (* Create a 0-filled array, size
(input)x(input), with the array
from the previous iteration
in the center *)
+1 (* Add one *)
Print@@@ (* Print the result *)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Takes input in reverse (`c,b,a`) and outputs an array of lines using `=` for the outer box, `!` for the middle one and `-` for the inner one.
```
Æç-
4Æ=Õû¦gXz)NÅgXz
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=xuctCjTGPdX7pmdYeilOxWdYeg&input=MiA2IDEyCi1S)
```
Æç-\n4Æ=Õû¦gXz)NÅgXz :Implicit input of integers U=c, V=b & W=a
Æ :Map the range [0,U)
ç- : Repeat "-" U times
\n :Reassign to U
4Æ :Map each X in the range [0,4)
= : Reassign to U ...
Õ : Transpose U
û : Centre pad each element with (1) to length (2)
¦ : "!=" (1)
g : Get character at index (1)
Xz : X floor divided by 2 (1)
) : End index (1)
N : Array of all inputs, i.e. [U,V,W] (2)
Å : Slice off the first element (2)
gXz : As above (2)
:Implicit output of last element of resulting array
```
[Answer]
# PHP>=7.1, 180 bytes
In this case i hate that variables begin with a `$` in PHP
```
for([,$x,$y,$z]=$argv;$i<$x*$x;$p=$r%$x)echo XYZ[($o<($l=$x-$a=($x-$y)/2)&$o>($k=$a-1)&$p>$k&$p<$l)+($o>($m=$k+$b=($y-$z)/2)&$o<($n=$l-$b)&$p>$m&$p<$n)],($o=++$i%$x)?"":"\n".!++$r;
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/1e4347e37d478798af08eaf11bb09c8ba6500961)
[Answer]
# Mathematica, 173 bytes
```
(d=((a=#1)-(b=#2))/2;e=(b-(c=#3))/2;z=1+d;x=a-d;h=Table["*",a,a];h[[z;;x,z;;x]]=h[[z;;x,z;;x]]/.{"*"->"#"};h[[z+e;;x-e,z+e;;x-e]]=h[[z+e;;x-e,z+e;;x-e]]/.{"#"->"@"};Grid@h)&
```
**input**
>
> [12,6,2]
>
>
>
[Answer]
# [Python 2](https://docs.python.org/2/), 87 bytes
```
a,_,_=t=input();r=~a
exec"r+=2;print sum(10**x/9*10**((a-x)/2)*(r*r<x*x)for x in t);"*a
```
[Try it online!](https://tio.run/##FcXBCoMwDADQ@76ieEqyiprDQLp@i5ThsIfVEiNkl/16h@/y6le3vXBryS9@iRpzqacCBom/dFttfXVyjxyq5KLuOD8wjUQ2zHQNkHrDgZFASJ5Ghu9dnLlcnGLoKLXGo394/gM "Python 2 – Try It Online")
Arithmetically computes the numbers to print by adding numbers of the form `111100`. There's a lot of ugliness, probably room for improvement.
[Answer]
# JavaScript (ES6), 112
Anonymous function returning a multi line string. Characters 0,1,2
```
(a,b,c)=>eval("for(o='',i=-a;i<a;o+=`\n`,i+=2)for(j=-a;j<a;j+=2)o+=(i>=c|i<-c|j>=c|j<-c)+(i>=b|i<-b|j>=b|j<-b)")
```
*Less golfed*
```
(a,b,c)=>{
for(o='',i=-a;i<a;o+=`\n`,i+=2)
for(j=-a;j<a;j+=2)
o+=(i>=c|i<-c|j>=c|j<-c)+(i>=b|i<-b|j>=b|j<-b)
return o
}
```
```
var F=
(a,b,c)=>eval("for(o='',i=-a;i<a;o+=`\n`,i+=2)for(j=-a;j<a;j+=2)o+=(i>=c|i<-c|j>=c|j<-c)+(i>=b|i<-b|j>=b|j<-b)")
function update()
{
var [a,b,c]=I.value.match(/\d+/g)
O.textContent=F(a,b,c)
}
update()
```
```
a,b,c <input id=I value='10 6 2' oninput='update()'>
<pre id=O></pre>
```
[Answer]
# PHP >= 5.6, 121 bytes
```
for($r=A;$p?:$p=($z=$argv[++$i])**2;)$r[((--$p/$z|0)+$o=($w=$w?:$z)-$z>>1)*$w+$p%$z+$o]=_BCD[$i];echo chunk_split($r,$w);
```
Run with `-nr` or [test it online](http://sandbox.onlinephpfunctions.com/code/253363638e55ecca2f2f6c7401b6fbea672b06ac).
Combined loops again ... I love them!
**breakdown**
```
for($r=A; # initialize $r (result) to string
$p?:$p=($z=$argv[++$i])**2;) # loop $z through arguments, loop $p from $z**2-1 to 0
$r[((--$p/$z|0)+$o=
($w=$w?:$z) # set $w (total width) to first argument
-$z>>1)*$w+$p%$z+$o] # calculate position: (y+offset)*$w+x+offset
=_BCD[$i]; # paint allowed character (depending on $i)
echo chunk_split($r,$w); # insert newline every $w characters and print
```
[Answer]
# Java 10, ~~265~~ ~~252~~ ~~218~~ ~~181~~ 172 bytes
```
(a,b,c)->{int r[][]=new int[a][a],t=a-b>>1,u=a-c>>1,x=b*b;for(;x-->0;r[x/b+t][x%b+t]=1)if(x<c*c)r[x/c+u][x%c+u]=8;var s="";for(var q:r){for(int Q:q)s+=Q;s+="\n";}return s;}
```
-34 bytes thanks to *@ceilingcat*.
**Explanation:**
[Try it online.](https://tio.run/##jVFBasMwELznFYuhICWyW6dNCFHlY28NhB4dHyTFLkodOZGl1CX47a6U@lpaWGZ3mGHRrA78wuPD/mNQx1NjLBw8T5xVdVI5La1qdPIyDnQia9628MqVvk4AlLalqbgsYRMowJs1Sr@DRF4BTgKKG0pMvaGfeGgtt0rCBjQwGBAngkgcZ9dgM3mRF0yXn2F1zgtfxDIeiyxLifODDEPHxFTQqjGIdnGcPVCTd/diZou8uwuNpVhVqHuWU4mDJGcuSKGxFb1wAy2LotuCQM5rg6@BhBds12fcztiWeoh2OqK9Ka0zGlraDyGDr5MTtU8wBrk0ag9HfxH0kz4vgOPxHF@tLY9J42xy8pKtNdKJREvyROb4dpFfPSuy/NOTzv9hmi9IuiCPePyAfvgG)
```
(a,b,c)->{ // Method with three integer parameters and String return-type
int r[][]=new int[a][a], // Create a grid with dimensions `a` by `a`,
// filled with 0s by default
t=a-b>>1, // Calculate (a-b)/2
u=a-c>>1, // Calculate (a-c)/2 as well
x=b*b;for(;x-->0; // Loop `x` in the range (b*b, 0]:
r[x/b+t][x%b+t]=1; // Fill the cells for the second square with 1s
if(x<c*c) // And if `x` is smaller than c*c:
r[x/c+u][x%c+u]=8; // Also start filling the center square cells with 8s
var s=""; // Then create a return-String, starting empty
for(var q:r){ // Loop over the rows of the matrix:
for(int Q:q) // Inner loop over the columns of the row:
s+=Q; // Append the current digit to the result-String
s+="\n";} // Append a trailing new-line after every row
return s;} // Return the result-String
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 14 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
#*@H╶:*l⁸∔½:╋}
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JTIzKkAldUZGMjgldTI1NzYldUZGMUEldUZGMEEldUZGNEMldTIwNzgldTIyMTQlQkQldUZGMUEldTI1NEIldUZGNUQ_,i=OCUwQTYlMEEy,v=8)
] |
[Question]
[
# Background
A Pythagorean triangle is a right triangle where each side length is an integer (that is, the side lengths form a [Pythagorean triple](http://en.wikipedia.org/wiki/Pythagorean_triple)):

Using the sides of this triangle, we can attach two more non-congruent Pythagorean triangles as follows:

We can continue with this pattern as we see fit, so long as no two triangles overlap, and connecting sides have equal length:

The question is, how many non-congruent Pythagorean triangles can we fit in a given space?
# The Input
You will receive two integers as input, `W` and `H`, through function arguments, STDIN, strings, or whatever you like. The integers may be received as decimal, hexadecimal, binary, unary (good luck, [Retina](https://github.com/mbuettner/retina)), or any other integer base. You may assume that `max(W, H) <= 2^15 - 1`.
# The Output
Your program or function should calculate a list of non-overlapping connected non-congruent Pythagorean triangles and output a list of sets of three coordinates each, where the coordinates in a set form one of the Pythagorean triangles when connected by lines. Coordinates must be real numbers in our space (`x` must be in the interval `[0, W]` and `y` must be in the interval `[0, H]`), and distance should be accurate to machine precision. The order of the triangles and the exact format of each coordinate is not important.
It must be possible to "walk" from one triangle to any other only stepping over connected boundaries.
Using the above diagram as an example, let our input be `W = 60`, `H = 60`.
Our output could then be the following list of coordinates:
```
(0, 15), (0, 21), (8, 15)
(0, 21), (14.4, 40.2), (8, 15)
(0, 15), (8, 0), (8, 15)
(8, 0), (8, 15), (28, 15)
(8, 15), (28, 15), (28, 36)
(28, 15), (28, 36), (56, 36)
```
Now, 6 triangles is most certainly not the best we can do given our space. Can you do better?
# Rules and Scoring
* Your score for this challenge is the number of triangles your program generates given the input of `W = 1000, H = 1000`. I reserve the right to change this input if I suspect someone hardcoding this case.
* You may not use builtins that calculate Pythagorean triples, and you may not hardcode a list of more than 2 Pythagorean triples (if you hardcode your program to always start with a (3, 4, 5) triangle, or some similar starting circumstance, that is okay).
* You may write your submission in any language. Readability and commenting are encouraged.
* You may find a list of Pythagorean triples [here](http://www.tsm-resources.com/alists/trip.html).
* [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
[Answer]
# Python 3, 109
This was certainly a deceptively hard challenge. There were many times writing the code that I found myself questioning my basic geometry abilities. That being said, I'm pretty happy with the result. I put no effort in to coming up with a complex algorithm for placing the triangles, and instead my code just blunders through always placing the smallest it can find. I hope I can improve this later on, or my answer will spurn others to find a better algorithm! All in all, a very fun problem, and it produces some interesting pictures.
Here's the code:
```
import time
import math
W = int(input("Enter W: "))
H = int(input("Enter H: "))
middle_x = math.floor(W/2)
middle_y = math.floor(H/2)
sides = [ # each side is in the format [length, [x0, y0], [x1, y1]]
[3,[middle_x,middle_y],[middle_x+3,middle_y]],
[4,[middle_x,middle_y],[middle_x,middle_y+4]],
[5,[middle_x+3,middle_y],[middle_x,middle_y+4]]
]
triangles = [[0,1,2]] # each triangle is in the format [a, b, c] where a, b and c are the indexes of sides
used_triangles = [[3,4,5]] # a list of used Pythagorean triples, where lengths are ordered (a < b < c)
max_bounds_length = math.sqrt(W**2 + H**2)
def check_if_pyth_triple(a,b): # accepts two lists of the form [l, [x0,y0], [x1,y1]] defining two line segments
# returns 0 if there are no triples, 1 if there is a triple with a right angle on a,
# and 2 if there is a triple with the right angle opposite a
c = math.sqrt(a[0]**2 + b[0]**2)
if c.is_integer():
if not sorted([a[0], b[0], c]) in used_triangles:
return 1
return 0
else:
if a[0] > b[0]:
c = math.sqrt(a[0]**2 - b[0]**2)
if c.is_integer() and not sorted([a[0], b[0], c]) in used_triangles:
return 2
return 0
def check_if_out_of_bounds(p):
out = False
if p[0] < 0 or p[0] > W:
out = True
if p[1] < 0 or p[1] > H:
out = True
return out
def in_between(a,b,c):
maxi = max(a,c)
mini = min(a,c)
return mini < b < maxi
def sides_intersect(AB,CD): # accepts two lists of the form [l, [x0,y0], [x1,y1]] defining two line segments
# doesn't count overlapping lines
A = AB[1]
B = AB[2]
C = CD[1]
D = CD[2]
if A[0] == B[0]: # AB is vertical
if C[0] == D[0]: # CD is vertical
return False
else:
m1 = (C[1] - D[1])/(C[0] - D[0]) # slope of CD
y = m1*(A[0] - C[0]) + C[1] # the y value of CD at AB's x value
return in_between(A[1], y, B[1]) and in_between(C[0], A[0], D[0])
else:
m0 = (A[1] - B[1])/(A[0] - B[0]) # slope of AB
if C[0] == D[0]: # CD is vertical
y = m0*(C[0] - A[0]) + A[1] # the y value of CD at AB's x value
return in_between(C[1], y, D[1]) and in_between(A[0],C[0],B[0])
else:
m1 = (C[1] - D[1])/(C[0] - D[0]) # slope of CD
if m0 == m1:
return False
else:
x = (m0*A[0] - m1*C[0] - A[1] + C[1])/(m0 - m1)
return in_between(A[0], x, B[0]) and in_between(C[0], x, D[0])
def check_all_sides(b,triangle):
no_intersections = True
for side in sides:
if sides_intersect(side, b):
no_intersections = False
break
return no_intersections
def check_point_still_has_room(A): # This function is needed for the weird case when all 2pi degrees
# around a point are filled by triangles, but you could fit in a small triangle into another one
# already built around the point. Doing this won't cause sides_intersect() to detect it because
# the sides will all be parallel. Crazy stuff.
connecting_sides = []
for side in sides:
if A in side:
connecting_sides.append(side)
match_count = 0
slopes = []
for side in connecting_sides:
B = side[1]
if A == B:
B = side[2]
if not A[0] == B[0]:
slope = round((A[1]-B[1])/(A[0]-B[0]),4)
else:
if A[1] < B[1]:
slope = "infinity"
else:
slope = "neg_infinity"
if slope in slopes:
match_count -= 1
else:
slopes.append(slope)
match_count += 1
return match_count != 0
def construct_b(a,b,pyth_triple_info,straight_b_direction,bent_b_direction):
# this function finds the correct third point of the triangle given a and the length of b
# pyth_triple_info determines if a is a leg or the hypotenuse
# the b_directions determine on which side of a the triangle should be formed
a_p = 2 # this is the index of the point in a that is not the shared point with b
if a[1] != b[1]:
a_p = 1
vx = a[a_p][0] - b[1][0] # v is our vector, and these are the coordinates, adjusted so that
vy = a[a_p][1] - b[1][1] # the shared point is the origin
if pyth_triple_info == 1:
# because the dot product of orthogonal vectors is zero, we can use that and the Pythagorean formula
# to get this simple formula for generating the coordinates of b's second point
if vy == 0:
x = 0
y = b[0]
else:
x = b[0]/math.sqrt(1+((-vx/vy)**2)) # b[0] is the desired length
y = -vx*x/vy
x = x*straight_b_direction # since the vector is orthagonal, if we want to reverse the direction,
y = y*straight_b_direction # it just means finding the mirror point
elif pyth_triple_info == 2: # this finds the intersection of the two circles of radii b[0] and c
# around a's endpoints, which is the third point of the triangle if a is the hypotenuse
c = math.sqrt(a[0]**2 - b[0]**2)
D = a[0]
A = (b[0]**2 - c**2 + D**2 ) / (2*D)
h = math.sqrt(b[0]**2 - A**2)
x2 = vx*(A/D)
y2 = vy*(A/D)
x = x2 + h*vy/D
y = y2 - h*vx/D
if bent_b_direction == -1: # this constitutes reflection of the vector (-x,-y) around the normal vector n,
# which accounts for finding the triangle on the opposite side of a
dx = -x
dy = -y
v_length = math.sqrt(vx**2 + vy**2)
nx = vx/v_length
ny = vy/v_length
d_dot_n = dx*nx + dy*ny
x = dx - 2*d_dot_n*nx
y = dy - 2*d_dot_n*ny
x = x + b[1][0] # adjust back to the original frame
y = y + b[1][1]
return [x,y]
def construct_triangle(side_index):
a = sides[side_index] # a is the base of the triangle
a_p = 1
b = [1, a[a_p], []] # side b, c is hypotenuse
for index, triangle in enumerate(triangles):
if side_index in triangle:
triangle_index = index
break
triangle = list(triangles[triangle_index])
triangle.remove(side_index)
add_tri = False
straight_b = construct_b(a,b,1,1,1)
bent_b = construct_b(a,b,2,1,1)
A = sides[triangle[0]][1]
if A in a:
A = sides[triangle[0]][2]
Ax = A[0] - b[1][0] # adjusting A so that it's a vector
Ay = A[1] - b[1][1]
# these are for determining if construct_b() is going to the correct side
triangle_on_side = (a[2][0]-a[1][0])*(A[1]-a[1][1]) - (a[2][1]-a[1][1])*(A[0]-a[1][0])
straight_b_on_side = (a[2][0]-a[1][0])*(straight_b[1]-a[1][1]) - (a[2][1]-a[1][1])*(straight_b[0]-a[1][0])
bent_b_on_side = (a[2][0]-a[1][0])*(bent_b[1]-a[1][1]) - (a[2][1]-a[1][1])*(bent_b[0]-a[1][0])
straight_b_direction = 1
if (triangle_on_side > 0 and straight_b_on_side > 0) or (triangle_on_side < 0 and straight_b_on_side < 0):
straight_b_direction = -1
bent_b_direction = 1
if (triangle_on_side > 0 and bent_b_on_side > 0) or (triangle_on_side < 0 and bent_b_on_side < 0):
bent_b_direction = -1
a_ps = []
for x in [1,2]:
if check_point_still_has_room(a[x]): # here we check for that weird exception
a_ps.append(x)
while True:
out_of_bounds = False
if b[0] > max_bounds_length:
break
pyth_triple_info = check_if_pyth_triple(a,b)
for a_p in a_ps:
if a_p == 1: # this accounts for the change in direction when switching a's points
new_bent_b_direction = bent_b_direction
else:
new_bent_b_direction = -bent_b_direction
b[1] = a[a_p]
if pyth_triple_info > 0:
b[2] = construct_b(a,b,pyth_triple_info,straight_b_direction,new_bent_b_direction)
if check_if_out_of_bounds(b[2]): # here is the check to make sure we don't go out of bounds
out_of_bounds = True
break
if check_all_sides(b,triangle):
if pyth_triple_info == 1:
c = [math.sqrt(a[0]**2 + b[0]**2), a[3-a_p], b[2]]
else:
c = [math.sqrt(a[0]**2 - b[0]**2), a[3-a_p], b[2]]
if check_all_sides(c,triangle):
add_tri = True
break
if out_of_bounds or add_tri:
break
b[0] += 1 # increment the length of b every time the loop goes through
if add_tri: # this adds a new triangle
sides.append(b)
sides.append(c)
sides_len = len(sides)
triangles.append([side_index, sides_len - 2, sides_len - 1])
used_triangles.append(sorted([a[0], b[0], c[0]])) # so we don't use the same triangle again
def build_all_triangles(): # this iterates through every side to see if a new triangle can be constructed
# this is probably where real optimization would take place so more optimal triangles are placed first
t0 = time.clock()
index = 0
while index < len(sides):
construct_triangle(index)
index += 1
t1 = time.clock()
triangles_points = [] # this is all for printing points
for triangle in triangles:
point_list = []
for x in [1,2]:
for side_index in triangle:
point = sides[side_index][x]
if not point in point_list:
point_list.append(point)
triangles_points.append(point_list)
for triangle in triangles_points:
print(triangle)
print(len(triangles), "triangles placed in", round(t1-t0,3), "seconds.")
def matplotlib_graph(): # this displays the triangles with matplotlib
import pylab as pl
import matplotlib.pyplot as plt
from matplotlib import collections as mc
lines = []
for side in sides:
lines.append([side[1],side[2]])
lc = mc.LineCollection(lines)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
plt.show()
build_all_triangles()
```
Here's a graph of the output for `W = 1000` and `H = 1000` with 109 triangles:
[](https://i.stack.imgur.com/iyNWb.png)
Here is `W = 10000` and `H = 10000` with 724 triangles:
[](https://i.stack.imgur.com/43Zzh.png)
Call the `matplotlib_graph()` function after `build_all_triangles()` to graph the triangles.
I think the code runs reasonably fast: at `W = 1000` and `H = 1000` it takes 0.66 seconds, and at `W = 10000` and `H = 10000` it takes 45 seconds using my crappy laptop.
[Answer]
# C++, 146 triangles (part 1/2)
## Result as Image
[](https://i.stack.imgur.com/Wvz0W.png)
## Algorithm Description
This uses a breadth-first search of the solution space. In each step, it starts with all unique configurations of `k` triangles that fit in the box, and builds all unique configurations of `k + 1` triangles by enumerating all options of adding an unused triangle to any of the configurations.
The algorithm is basically set up to find the absolute maximum with an exhaustive BFS. And it does that successfully for smaller sizes. For example, for a box of 50x50, it finds the maximum in about 1 minute. But for 1000x1000, the solution space is way too big. To allow it to terminate, I trim the list of solutions after each step. The number of solutions that is kept is given by a command line argument. For the solution above, a value of 50 was used. This resulted in a runtime of about 10 minutes.
The outline of the main steps looks like this:
1. Generate all Pythagorean triangles that could potentially fit inside the box.
2. Generate the initial solution set consisting of solutions with 1 triangle each.
3. Loop over generations (triangle count).
1. Eliminate invalid solutions from the solution set. These are solutions that either do not fit inside the box, or have overlap.
2. If solution set is empty, we are done. The solution set from the previous generation contains the maxima.
3. Trim solution set to given size if trim option was enabled.
4. Loop over all solutions in current generation.
1. Loop over all sides in perimeter of solution.
1. Find all triangles that have a side length matching the perimeter side, and that are not in the solution yet.
2. Generate the new solutions resulting from adding the triangles, and add the solutions to the solution set of the new generation.
4. Print solutions.
One critical aspect in the whole scheme is that configurations will generally be generated multiple times, and we are only interested in unique configurations. So we need a unique key that defines a solution, which must be independent of the order of the triangles used while generating the solution. For example, using coordinates for the key would not work at all, since they can be completely different if we arrived at the same solution in multiple orders. What I used is the set of triangle indices in the global list, plus a set of "connector" objects that define how the triangles are connected. So the key only encodes the topology, independent of the construction order and position in 2D space.
While more an implementation aspect, another part that is not entirely trivial is deciding if and how the whole thing fits into the given box. If you really want to push the boundaries, it is obviously necessary to allow for rotation to fit inside the box.
I'll try and add some comments to the code in part 2 later, in case somebody wants to dive into the details of how this all works.
## Result in Official Text Format
```
(322.085, 641.587) (318.105, 641.979) (321.791, 638.602)
(318.105, 641.979) (309.998, 633.131) (321.791, 638.602)
(318.105, 641.979) (303.362, 639.211) (309.998, 633.131)
(318.105, 641.979) (301.886, 647.073) (303.362, 639.211)
(301.886, 647.073) (297.465, 638.103) (303.362, 639.211)
(301.886, 647.073) (280.358, 657.682) (297.465, 638.103)
(301.886, 647.073) (283.452, 663.961) (280.358, 657.682)
(301.886, 647.073) (298.195, 666.730) (283.452, 663.961)
(301.886, 647.073) (308.959, 661.425) (298.195, 666.730)
(301.886, 647.073) (335.868, 648.164) (308.959, 661.425)
(335.868, 648.164) (325.012, 669.568) (308.959, 661.425)
(308.959, 661.425) (313.666, 698.124) (298.195, 666.730)
(313.666, 698.124) (293.027, 694.249) (298.195, 666.730)
(313.666, 698.124) (289.336, 713.905) (293.027, 694.249)
(298.195, 666.730) (276.808, 699.343) (283.452, 663.961)
(335.868, 648.164) (353.550, 684.043) (325.012, 669.568)
(303.362, 639.211) (276.341, 609.717) (309.998, 633.131)
(276.808, 699.343) (250.272, 694.360) (283.452, 663.961)
(335.868, 648.164) (362.778, 634.902) (353.550, 684.043)
(362.778, 634.902) (367.483, 682.671) (353.550, 684.043)
(250.272, 694.360) (234.060, 676.664) (283.452, 663.961)
(362.778, 634.902) (382.682, 632.942) (367.483, 682.671)
(382.682, 632.942) (419.979, 644.341) (367.483, 682.671)
(419.979, 644.341) (379.809, 692.873) (367.483, 682.671)
(353.550, 684.043) (326.409, 737.553) (325.012, 669.568)
(353.550, 684.043) (361.864, 731.318) (326.409, 737.553)
(353.550, 684.043) (416.033, 721.791) (361.864, 731.318)
(416.033, 721.791) (385.938, 753.889) (361.864, 731.318)
(385.938, 753.889) (323.561, 772.170) (361.864, 731.318)
(385.938, 753.889) (383.201, 778.739) (323.561, 772.170)
(383.201, 778.739) (381.996, 789.673) (323.561, 772.170)
(323.561, 772.170) (292.922, 743.443) (361.864, 731.318)
(323.561, 772.170) (296.202, 801.350) (292.922, 743.443)
(250.272, 694.360) (182.446, 723.951) (234.060, 676.664)
(335.868, 648.164) (330.951, 570.319) (362.778, 634.902)
(330.951, 570.319) (381.615, 625.619) (362.778, 634.902)
(330.951, 570.319) (375.734, 565.908) (381.615, 625.619)
(330.951, 570.319) (372.989, 538.043) (375.734, 565.908)
(323.561, 772.170) (350.914, 852.648) (296.202, 801.350)
(323.561, 772.170) (362.438, 846.632) (350.914, 852.648)
(234.060, 676.664) (217.123, 610.807) (283.452, 663.961)
(217.123, 610.807) (249.415, 594.893) (283.452, 663.961)
(375.734, 565.908) (438.431, 559.733) (381.615, 625.619)
(382.682, 632.942) (443.362, 567.835) (419.979, 644.341)
(443.362, 567.835) (471.667, 606.601) (419.979, 644.341)
(323.561, 772.170) (393.464, 830.433) (362.438, 846.632)
(372.989, 538.043) (471.272, 556.499) (375.734, 565.908)
(372.989, 538.043) (444.749, 502.679) (471.272, 556.499)
(372.989, 538.043) (365.033, 521.897) (444.749, 502.679)
(443.362, 567.835) (544.353, 553.528) (471.667, 606.601)
(544.353, 553.528) (523.309, 622.384) (471.667, 606.601)
(544.353, 553.528) (606.515, 572.527) (523.309, 622.384)
(419.979, 644.341) (484.688, 697.901) (379.809, 692.873)
(444.749, 502.679) (552.898, 516.272) (471.272, 556.499)
(217.123, 610.807) (170.708, 516.623) (249.415, 594.893)
(484.688, 697.901) (482.006, 753.837) (379.809, 692.873)
(484.688, 697.901) (571.903, 758.147) (482.006, 753.837)
(419.979, 644.341) (535.698, 636.273) (484.688, 697.901)
(276.808, 699.343) (228.126, 812.299) (250.272, 694.360)
(228.126, 812.299) (185.689, 726.188) (250.272, 694.360)
(228.126, 812.299) (192.246, 829.981) (185.689, 726.188)
(393.464, 830.433) (449.003, 936.807) (362.438, 846.632)
(393.464, 830.433) (468.505, 926.625) (449.003, 936.807)
(416.033, 721.791) (471.289, 833.915) (385.938, 753.889)
(471.289, 833.915) (430.252, 852.379) (385.938, 753.889)
(350.914, 852.648) (227.804, 874.300) (296.202, 801.350)
(192.246, 829.981) (114.401, 834.898) (185.689, 726.188)
(114.401, 834.898) (155.433, 715.767) (185.689, 726.188)
(217.123, 610.807) (91.773, 555.523) (170.708, 516.623)
(91.773, 555.523) (141.533, 457.421) (170.708, 516.623)
(141.533, 457.421) (241.996, 407.912) (170.708, 516.623)
(141.533, 457.421) (235.365, 394.457) (241.996, 407.912)
(241.996, 407.912) (219.849, 525.851) (170.708, 516.623)
(241.996, 407.912) (304.896, 419.724) (219.849, 525.851)
(91.773, 555.523) (55.917, 413.995) (141.533, 457.421)
(571.903, 758.147) (476.260, 873.699) (482.006, 753.837)
(571.903, 758.147) (514.819, 890.349) (476.260, 873.699)
(571.903, 758.147) (587.510, 764.886) (514.819, 890.349)
(587.510, 764.886) (537.290, 898.778) (514.819, 890.349)
(587.510, 764.886) (592.254, 896.801) (537.290, 898.778)
(587.510, 764.886) (672.455, 761.831) (592.254, 896.801)
(55.917, 413.995) (113.819, 299.840) (141.533, 457.421)
(113.819, 299.840) (149.275, 293.604) (141.533, 457.421)
(544.353, 553.528) (652.112, 423.339) (606.515, 572.527)
(652.112, 423.339) (698.333, 461.597) (606.515, 572.527)
(535.698, 636.273) (651.250, 731.917) (484.688, 697.901)
(651.250, 731.917) (642.213, 756.296) (484.688, 697.901)
(304.896, 419.724) (299.444, 589.636) (219.849, 525.851)
(304.896, 419.724) (369.108, 452.294) (299.444, 589.636)
(304.896, 419.724) (365.965, 299.326) (369.108, 452.294)
(304.896, 419.724) (269.090, 347.067) (365.965, 299.326)
(114.401, 834.898) (0.942, 795.820) (155.433, 715.767)
(114.401, 834.898) (75.649, 947.412) (0.942, 795.820)
(192.246, 829.981) (124.489, 994.580) (114.401, 834.898)
(269.090, 347.067) (205.435, 217.901) (365.965, 299.326)
(205.435, 217.901) (214.030, 200.956) (365.965, 299.326)
(182.446, 723.951) (68.958, 600.078) (234.060, 676.664)
(182.446, 723.951) (32.828, 633.179) (68.958, 600.078)
(652.112, 423.339) (763.695, 288.528) (698.333, 461.597)
(763.695, 288.528) (808.220, 324.117) (698.333, 461.597)
(763.695, 288.528) (811.147, 229.162) (808.220, 324.117)
(652.112, 423.339) (627.572, 321.247) (763.695, 288.528)
(627.572, 321.247) (660.872, 244.129) (763.695, 288.528)
(652.112, 423.339) (530.342, 344.618) (627.572, 321.247)
(652.112, 423.339) (570.488, 453.449) (530.342, 344.618)
(627.572, 321.247) (503.633, 267.730) (660.872, 244.129)
(365.965, 299.326) (473.086, 450.157) (369.108, 452.294)
(365.965, 299.326) (506.922, 344.440) (473.086, 450.157)
(365.965, 299.326) (394.633, 260.827) (506.922, 344.440)
(394.633, 260.827) (537.381, 303.535) (506.922, 344.440)
(811.147, 229.162) (979.067, 234.338) (808.220, 324.117)
(698.333, 461.597) (706.660, 655.418) (606.515, 572.527)
(811.147, 229.162) (982.117, 135.385) (979.067, 234.338)
(982.117, 135.385) (999.058, 234.954) (979.067, 234.338)
(365.965, 299.326) (214.375, 186.448) (394.633, 260.827)
(811.147, 229.162) (803.145, 154.590) (982.117, 135.385)
(803.145, 154.590) (978.596, 102.573) (982.117, 135.385)
(214.375, 186.448) (314.969, 126.701) (394.633, 260.827)
(314.969, 126.701) (508.984, 192.909) (394.633, 260.827)
(314.969, 126.701) (338.497, 88.341) (508.984, 192.909)
(338.497, 88.341) (523.725, 138.884) (508.984, 192.909)
(338.497, 88.341) (359.556, 11.163) (523.725, 138.884)
(808.220, 324.117) (801.442, 544.012) (698.333, 461.597)
(801.442, 544.012) (739.631, 621.345) (698.333, 461.597)
(660.872, 244.129) (732.227, 78.877) (763.695, 288.528)
(660.872, 244.129) (644.092, 40.821) (732.227, 78.877)
(808.220, 324.117) (822.432, 544.659) (801.442, 544.012)
(660.872, 244.129) (559.380, 47.812) (644.092, 40.821)
(660.872, 244.129) (556.880, 242.796) (559.380, 47.812)
(556.880, 242.796) (528.882, 242.437) (559.380, 47.812)
(808.220, 324.117) (924.831, 449.189) (822.432, 544.659)
(924.831, 449.189) (922.677, 652.177) (822.432, 544.659)
(922.677, 652.177) (779.319, 785.836) (822.432, 544.659)
(779.319, 785.836) (696.630, 771.054) (822.432, 544.659)
(779.319, 785.836) (746.412, 969.918) (696.630, 771.054)
(779.319, 785.836) (848.467, 840.265) (746.412, 969.918)
(848.467, 840.265) (889.327, 872.428) (746.412, 969.918)
(746.412, 969.918) (619.097, 866.541) (696.630, 771.054)
(779.319, 785.836) (993.200, 656.395) (848.467, 840.265)
(993.200, 656.395) (935.157, 864.450) (848.467, 840.265)
(993.200, 656.395) (995.840, 881.379) (935.157, 864.450)
(338.497, 88.341) (34.607, 5.420) (359.556, 11.163)
(338.497, 88.341) (189.294, 204.357) (34.607, 5.420)
(189.294, 204.357) (158.507, 228.296) (34.607, 5.420)
(158.507, 228.296) (38.525, 230.386) (34.607, 5.420)
(158.507, 228.296) (41.694, 412.358) (38.525, 230.386)
```
## Code
See part 2 for the code. This was broken into 2 parts to work around post size limits.
The code is also available on [PasteBin](http://pastebin.com/raw/1QjwaaAq).
[Answer]
# C++, 146 triangles (part 2/2)
Continued from part 1. This was broken into 2 parts to work around post size limits.
## Code
Comments to be added.
```
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <sstream>
#include <iostream>
class Vec2 {
public:
Vec2()
: m_x(0.0f), m_y(0.0f) {
}
Vec2(float x, float y)
: m_x(x), m_y(y) {
}
float x() const {
return m_x;
}
float y() const {
return m_y;
}
void normalize() {
float s = 1.0f / sqrt(m_x * m_x + m_y * m_y);
m_x *= s;
m_y *= s;
}
Vec2 operator+(const Vec2& rhs) const {
return Vec2(m_x + rhs.m_x, m_y + rhs.m_y);
}
Vec2 operator-(const Vec2& rhs) const {
return Vec2(m_x - rhs.m_x, m_y - rhs.m_y);
}
Vec2 operator*(float s) const {
return Vec2(m_x * s, m_y * s);
}
private:
float m_x, m_y;
};
static float cross(const Vec2& v1, const Vec2& v2) {
return v1.x() * v2.y() - v1.y() * v2.x();
}
class Triangle {
public:
Triangle()
: m_sideLenA(0), m_sideLenB(0), m_sideLenC(0) {
}
Triangle(int sideLenA, int sideLenB, int sideLenC)
: m_sideLenA(sideLenA),
m_sideLenB(sideLenB),
m_sideLenC(sideLenC) {
}
int getSideLenA() const {
return m_sideLenA;
}
int getSideLenB() const {
return m_sideLenB;
}
int getSideLenC() const {
return m_sideLenC;
}
private:
int m_sideLenA, m_sideLenB, m_sideLenC;
};
class Connector {
public:
Connector(int sideLen, int triIdx1, int triIdx2, bool flipped);
bool operator<(const Connector& rhs) const;
void print() const {
std::cout << m_sideLen << "/" << m_triIdx1 << "/"
<< m_triIdx2 << "/" << m_flipped << " ";
}
private:
int m_sideLen;
int m_triIdx1, m_triIdx2;
bool m_flipped;
};
typedef std::vector<Triangle> TriangleVec;
typedef std::multimap<int, int> SideMap;
typedef std::set<int> TriangleSet;
typedef std::set<Connector> ConnectorSet;
class SolutionKey {
public:
SolutionKey() {
}
void init(int triIdx);
void add(int triIdx, const Connector& conn);
bool containsTriangle(int triIdx) const;
int minTriangle() const;
bool operator<(const SolutionKey& rhs) const;
void print() const;
private:
TriangleSet m_tris;
ConnectorSet m_conns;
};
typedef std::map<SolutionKey, class SolutionData> SolutionMap;
class SolutionData {
public:
SolutionData()
: m_lastPeriIdx(0),
m_rotAng(0.0f),
m_xShift(0.0f), m_yShift(0.0f) {
}
void init(int triIdx);
bool fitsInBox();
bool selfOverlaps() const;
void nextGeneration(
const SolutionKey& key, bool useTrim, SolutionMap& rNewSols) const;
void print() const;
private:
void addTriangle(
const SolutionKey& key, int periIdx, int newTriIdx,
SolutionMap& rNewSols) const;
std::vector<int> m_periTris;
std::vector<int> m_periLens;
std::vector<bool> m_periFlipped;
std::vector<Vec2> m_periPoints;
int m_lastPeriIdx;
std::vector<Vec2> m_triPoints;
float m_rotAng;
float m_xShift, m_yShift;
};
static int BoxW = 0;
static int BoxH = 0;
static int BoxD2 = 0;
static TriangleVec AllTriangles;
static SideMap AllSides;
Connector::Connector(
int sideLen, int triIdx1, int triIdx2, bool flipped)
: m_sideLen(sideLen),
m_flipped(flipped) {
if (triIdx1 < triIdx2) {
m_triIdx1 = triIdx1;
m_triIdx2 = triIdx2;
} else {
m_triIdx1 = triIdx2;
m_triIdx2 = triIdx1;
}
}
bool Connector::operator<(const Connector& rhs) const {
if (m_sideLen < rhs.m_sideLen) {
return true;
} else if (m_sideLen > rhs.m_sideLen) {
return false;
}
if (m_triIdx1 < rhs.m_triIdx1) {
return true;
} else if (m_triIdx1 > rhs.m_triIdx1) {
return false;
}
if (m_triIdx2 < rhs.m_triIdx2) {
return true;
} else if (m_triIdx2 > rhs.m_triIdx2) {
return false;
}
return m_flipped < rhs.m_flipped;
}
void SolutionKey::init(int triIdx) {
m_tris.insert(triIdx);
}
void SolutionKey::add(int triIdx, const Connector& conn) {
m_tris.insert(triIdx);
m_conns.insert(conn);
}
bool SolutionKey::containsTriangle(int triIdx) const {
return m_tris.count(triIdx);
}
int SolutionKey::minTriangle() const {
return *m_tris.begin();
}
bool SolutionKey::operator<(const SolutionKey& rhs) const {
if (m_tris.size() < rhs.m_tris.size()) {
return true;
} else if (m_tris.size() > rhs.m_tris.size()) {
return false;
}
TriangleSet::const_iterator triIt1 = m_tris.begin();
TriangleSet::const_iterator triIt2 = rhs.m_tris.begin();
while (triIt1 != m_tris.end()) {
if (*triIt1 < *triIt2) {
return true;
} else if (*triIt2 < *triIt1) {
return false;
}
++triIt1;
++triIt2;
}
if (m_conns.size() < rhs.m_conns.size()) {
return true;
} else if (m_conns.size() > rhs.m_conns.size()) {
return false;
}
ConnectorSet::const_iterator connIt1 = m_conns.begin();
ConnectorSet::const_iterator connIt2 = rhs.m_conns.begin();
while (connIt1 != m_conns.end()) {
if (*connIt1 < *connIt2) {
return true;
} else if (*connIt2 < *connIt1) {
return false;
}
++connIt1;
++connIt2;
}
return false;
}
void SolutionKey::print() const {
TriangleSet::const_iterator triIt = m_tris.begin();
while (triIt != m_tris.end()) {
std::cout << *triIt << " ";
++triIt;
}
std::cout << "\n";
ConnectorSet::const_iterator connIt = m_conns.begin();
while (connIt != m_conns.end()) {
connIt->print();
++connIt;
}
std::cout << "\n";
}
void SolutionData::init(int triIdx) {
const Triangle& tri = AllTriangles[triIdx];
m_periTris.push_back(triIdx);
m_periTris.push_back(triIdx);
m_periTris.push_back(triIdx);
m_periLens.push_back(tri.getSideLenB());
m_periLens.push_back(tri.getSideLenC());
m_periLens.push_back(tri.getSideLenA());
m_periFlipped.push_back(false);
m_periFlipped.push_back(false);
m_periFlipped.push_back(false);
m_periPoints.push_back(Vec2(0.0f, 0.0f));
m_periPoints.push_back(Vec2(tri.getSideLenB(), 0.0f));
m_periPoints.push_back(Vec2(0.0f, tri.getSideLenA()));
m_triPoints = m_periPoints;
m_periPoints.push_back(Vec2(0.0f, 0.0f));
}
bool SolutionData::fitsInBox() {
int nStep = 8;
float angInc = 0.5f * M_PI / nStep;
for (;;) {
bool mayFit = false;
float ang = 0.0f;
for (int iStep = 0; iStep <= nStep; ++iStep) {
float cosAng = cos(ang);
float sinAng = sin(ang);
float xMin = 0.0f;
float xMax = 0.0f;
float yMin = 0.0f;
float yMax = 0.0f;
bool isFirst = true;
for (int iPeri = 0; iPeri < m_periLens.size(); ++iPeri) {
const Vec2& pt = m_periPoints[iPeri];
float x = cosAng * pt.x() - sinAng * pt.y();
float y = sinAng * pt.x() + cosAng * pt.y();
if (isFirst) {
xMin = x;
xMax = x;
yMin = y;
yMax = y;
isFirst = false;
} else {
if (x < xMin) {
xMin = x;
} else if (x > xMax) {
xMax = x;
}
if (y < yMin) {
yMin = y;
} else if (y > yMax) {
yMax = y;
}
}
}
float w = xMax - xMin;
float h = yMax - yMin;
bool fits = false;
if ((BoxW >= BoxH) == (w >= h)) {
if (w <= BoxW && h <= BoxH) {
m_rotAng = ang;
m_xShift = 0.5f * BoxW - 0.5f * (xMax + xMin);
m_yShift = 0.5f * BoxH - 0.5f * (yMax + yMin);
return true;
}
} else {
if (h <= BoxW && w <= BoxH) {
m_rotAng = ang + 0.5f * M_PI;
m_xShift = 0.5f * BoxW + 0.5f * (yMax + yMin);
m_yShift = 0.5f * BoxH - 0.5f * (xMax + xMin);
return true;
}
}
w -= 0.125f * w * angInc * angInc + 0.5f * h * angInc;
h -= 0.125f * h * angInc * angInc + 0.5f * w * angInc;
if ((BoxW < BoxH) == (w < h)) {
if (w <= BoxW && h <= BoxH) {
mayFit = true;
}
} else {
if (h <= BoxW && w <= BoxH) {
mayFit = true;
}
}
ang += angInc;
}
if (!mayFit) {
break;
}
nStep *= 4;
angInc *= 0.25f;
}
return false;
}
static bool intersects(
const Vec2& p1, const Vec2& p2,
const Vec2& q1, const Vec2& q2) {
if (cross(p2 - p1, q1 - p1) * cross(p2 - p1, q2 - p1) > 0.0f) {
return false;
}
if (cross(q2 - q1, p1 - q1) * cross(q2 - q1, p2 - q1) > 0.0f) {
return false;
}
return true;
}
bool SolutionData::selfOverlaps() const {
int periSize = m_periPoints.size();
int triIdx = m_periTris[m_lastPeriIdx];
const Triangle& tri = AllTriangles[triIdx];
float offsScale = 0.0001f / tri.getSideLenC();
const Vec2& pt1 = m_periPoints[m_lastPeriIdx];
const Vec2& pt3 = m_periPoints[m_lastPeriIdx + 1];
const Vec2& pt2 = m_periPoints[m_lastPeriIdx + 2];
Vec2 pt1o = pt1 + ((pt2 - pt1) + (pt3 - pt1)) * offsScale;
Vec2 pt2o = pt2 + ((pt1 - pt2) + (pt3 - pt2)) * offsScale;
Vec2 pt3o = pt3 + ((pt1 - pt3) + (pt2 - pt3)) * offsScale;
float xMax = m_periPoints[0].x();
float yMax = m_periPoints[0].y();
for (int iPeri = 1; iPeri < m_periLens.size(); ++iPeri) {
if (m_periPoints[iPeri].x() > xMax) {
xMax = m_periPoints[iPeri].x();
}
if (m_periPoints[iPeri].y() > yMax) {
yMax = m_periPoints[iPeri].y();
}
}
Vec2 ptOut(xMax + 0.3f, yMax + 0.7f);
int nOutInter = 0;
for (int iPeri = 0; iPeri < m_periLens.size(); ++iPeri) {
int iNextPeri = iPeri + 1;
if (iPeri == m_lastPeriIdx) {
++iNextPeri;
} else if (iPeri == m_lastPeriIdx + 1) {
continue;
}
if (intersects(
m_periPoints[iPeri], m_periPoints[iNextPeri], pt1o, pt3o)) {
return true;
}
if (intersects(
m_periPoints[iPeri], m_periPoints[iNextPeri], pt2o, pt3o)) {
return true;
}
if (intersects(
m_periPoints[iPeri], m_periPoints[iNextPeri], pt3o, ptOut)) {
++nOutInter;
}
}
return nOutInter % 2;
}
void SolutionData::nextGeneration(
const SolutionKey& key, bool useTrim, SolutionMap& rNewSols) const
{
int nPeri = m_periLens.size();
for (int iPeri = (useTrim ? 0 : m_lastPeriIdx); iPeri < nPeri; ++iPeri) {
int len = m_periLens[iPeri];
SideMap::const_iterator itCand = AllSides.lower_bound(len);
SideMap::const_iterator itCandEnd = AllSides.upper_bound(len);
while (itCand != itCandEnd) {
int candTriIdx = itCand->second;
if (!key.containsTriangle(candTriIdx) &&
candTriIdx > key.minTriangle()) {
addTriangle(key, iPeri, candTriIdx, rNewSols);
}
++itCand;
}
}
}
void SolutionData::print() const {
float cosAng = cos(m_rotAng);
float sinAng = sin(m_rotAng);
int nPoint = m_triPoints.size();
for (int iPoint = 0; iPoint < nPoint; ++iPoint) {
const Vec2& pt = m_triPoints[iPoint];
float x = cosAng * pt.x() - sinAng * pt.y() + m_xShift;
float y = sinAng * pt.x() + cosAng * pt.y() + m_yShift;
std::cout << "(" << x << ", " << y << ")";
if (iPoint % 3 == 2) {
std::cout << std::endl;
} else {
std::cout << " ";
}
}
}
void SolutionData::addTriangle(
const SolutionKey& key, int periIdx, int newTriIdx,
SolutionMap& rNewSols) const {
int triIdx = m_periTris[periIdx];
bool flipped = m_periFlipped[periIdx];
int len = m_periLens[periIdx];
Connector conn1(len, triIdx, newTriIdx, flipped);
SolutionKey newKey1(key);
newKey1.add(newTriIdx, conn1);
bool isNew1 = (rNewSols.find(newKey1) == rNewSols.end());
Connector conn2(len, triIdx, newTriIdx, !flipped);
SolutionKey newKey2(key);
newKey2.add(newTriIdx, conn2);
bool isNew2 = (rNewSols.find(newKey2) == rNewSols.end());
if (!(isNew1 || isNew2)) {
return;
}
SolutionData data;
int periSize = m_periLens.size();
data.m_periTris.resize(periSize + 1);
data.m_periLens.resize(periSize + 1);
data.m_periFlipped.resize(periSize + 1);
data.m_periPoints.resize(periSize + 2);
for (int k = 0; k <= periIdx; ++k) {
data.m_periTris[k] = m_periTris[k];
data.m_periLens[k] = m_periLens[k];
data.m_periFlipped[k] = m_periFlipped[k];
data.m_periPoints[k] = m_periPoints[k];
}
for (int k = periIdx + 1; k < periSize; ++k) {
data.m_periTris[k + 1] = m_periTris[k];
data.m_periLens[k + 1] = m_periLens[k];
data.m_periFlipped[k + 1] = m_periFlipped[k];
data.m_periPoints[k + 1] = m_periPoints[k];
}
data.m_periPoints[periSize + 1] = m_periPoints[periSize];
data.m_lastPeriIdx = periIdx;
data.m_periTris[periIdx] = newTriIdx;
data.m_periTris[periIdx + 1] = newTriIdx;
int triSize = m_triPoints.size();
data.m_triPoints.resize(triSize + 3);
for (int k = 0; k < triSize; ++k) {
data.m_triPoints[k] = m_triPoints[k];
}
const Triangle& tri = AllTriangles[newTriIdx];
int lenA = tri.getSideLenA();
int lenB = tri.getSideLenB();
int lenC = tri.getSideLenC();
const Vec2& pt1 = m_periPoints[periIdx];
const Vec2& pt2 = m_periPoints[periIdx + 1];
Vec2 v = pt2 - pt1;
v.normalize();
Vec2 vn(v.y(), -v.x());
float dA = lenA;
float dB = lenB;
float dC = lenC;
int len1 = 0, len2 = 0;
Vec2 pt31, pt32;
if (len == lenA) {
len1 = lenB;
len2 = lenC;
pt31 = pt1 + vn * dB;
pt32 = pt2 + vn * dB;
} else if (len == lenB) {
len1 = lenC;
len2 = lenA;
pt31 = pt2 + vn * dA;
pt32 = pt1 + vn * dA;
} else {
len1 = lenA;
len2 = lenB;
pt31 = pt1 + v * (dA * dA / dC) + vn * (dA * dB / dC);
pt32 = pt1 + v * (dB * dB / dC) + vn * (dA * dB / dC);
}
if (isNew1) {
data.m_periLens[periIdx] = len1;
data.m_periLens[periIdx + 1] = len2;
data.m_periFlipped[periIdx] = false;
data.m_periFlipped[periIdx + 1] = false;
data.m_periPoints[periIdx + 1] = pt31;
data.m_triPoints[triSize] = pt1;
data.m_triPoints[triSize + 1] = pt31;
data.m_triPoints[triSize + 2] = pt2;
rNewSols.insert(std::make_pair(newKey1, data));
}
if (isNew2) {
data.m_periLens[periIdx] = len2;
data.m_periLens[periIdx + 1] = len1;
data.m_periFlipped[periIdx] = true;
data.m_periFlipped[periIdx + 1] = true;
data.m_periPoints[periIdx + 1] = pt32;
data.m_triPoints[triSize] = pt1;
data.m_triPoints[triSize + 1] = pt32;
data.m_triPoints[triSize + 2] = pt2;
rNewSols.insert(std::make_pair(newKey2, data));
}
}
static void enumerateTriangles() {
for (int c = 2; c * c <= BoxD2; ++c) {
for (int a = 1; 2 * a * a < c * c; ++a) {
int b = static_cast<int>(sqrt(c * c - a * a) + 0.5f);
if (a * a + b * b == c * c) {
Triangle tri(a, b, c);
int triIdx = AllTriangles.size();
AllTriangles.push_back(Triangle(a, b, c));
AllSides.insert(std::make_pair(a, triIdx));
AllSides.insert(std::make_pair(b, triIdx));
AllSides.insert(std::make_pair(c, triIdx));
}
}
}
}
static void eliminateInvalid(SolutionMap& rSols) {
SolutionMap::iterator it = rSols.begin();
while (it != rSols.end()) {
SolutionMap::iterator itNext = it;
++itNext;
SolutionData& rSolData = it->second;
if (!rSolData.fitsInBox()) {
rSols.erase(it);
} else if (rSolData.selfOverlaps()) {
rSols.erase(it);
}
it = itNext;
}
}
static void trimSolutions(SolutionMap& rSols, int trimCount) {
if (trimCount >= rSols.size()) {
return;
}
SolutionMap::iterator it = rSols.begin();
for (int iTrim = 0; iTrim < trimCount; ++iTrim) {
++it;
}
rSols.erase(it, rSols.end());
}
static void nextGeneration(
const SolutionMap& srcSols, bool useTrim, SolutionMap& rNewSols) {
SolutionMap::const_iterator it = srcSols.begin();
while (it != srcSols.end()) {
const SolutionKey& solKey = it->first;
const SolutionData& solData = it->second;
solData.nextGeneration(solKey, useTrim, rNewSols);
++it;
}
}
static void printSolutions(const SolutionMap& sols) {
std::cout << std::fixed;
std::cout.precision(3);
SolutionMap::const_iterator it = sols.begin();
while (it != sols.end()) {
const SolutionKey& solKey = it->first;
solKey.print();
const SolutionData& solData = it->second;
solData.print();
std::cout << std::endl;
++it;
}
}
int main(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << "usage: " << argv[0] << " width height [trimCount]"
<< std::endl;
return 1;
}
std::istringstream streamW(argv[1]);
streamW >> BoxW;
std::istringstream streamH(argv[2]);
streamH >> BoxH;
int trimCount = 0;
if (argc > 3) {
std::istringstream streamTrim(argv[3]);
streamTrim >> trimCount;
}
BoxD2 = BoxW * BoxW + BoxH * BoxH;
enumerateTriangles();
int nTri = AllTriangles.size();
SolutionMap solGen[2];
int srcGen = 0;
for (int iTri = 0; iTri < nTri; ++iTri) {
const Triangle& tri = AllTriangles[iTri];
SolutionKey solKey;
solKey.init(iTri);
SolutionData solData;
solData.init(iTri);
solGen[srcGen].insert(std::make_pair(solKey, solData));
}
int level = 1;
for (;;) {
eliminateInvalid(solGen[srcGen]);
std::cout << "level: " << level
<< " solutions: " << solGen[srcGen].size() << std::endl;
if (solGen[srcGen].empty()) {
break;
}
if (trimCount > 0) {
trimSolutions(solGen[srcGen], trimCount);
}
solGen[1 - srcGen].clear();
nextGeneration(solGen[srcGen], trimCount > 0, solGen[1 - srcGen]);
srcGen = 1 - srcGen;
++level;
}
printSolutions(solGen[1 - srcGen]);
return 0;
}
```
] |
[Question]
[
## Challenge
There are many numbers which can be expressed as the difference of two squares, or as the difference of two cubes, or maybe even higher powers. Talking about squares, there are various ways of writing a number, say 75, as the difference of 2 squares. You can write:
```
75 = (10)^2 - (5)^2
= (14)^2 - (11)^2
= (38)^2 - (37)^2
```
So let's talk about the challenge. Firstly, the user enters a number and then he enters a value for n. You need to display all the ways in which that number can be written in the form of aⁿ - bⁿ.
## Input and Output
The input will be the number and the value of n. Your output shall have all such pairs of 'a' and 'b' such that the above-stated condition is met. The first number in the pair must be larger than the second. Please note that **a, b, n and the input number are all positive integers, and n > 1**.
## Examples
```
50, 2 -> (none)
32, 2 -> (9,7), (6, 2)
7, 3 -> (2,1)
665, 6 -> (3, 2)
81, 4 -> (none)
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") , so the shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
p*ƓIFẹ+d
```
This is a monadic link that takes the number as argument and reads **n** from STDIN.
[Try it online!](https://tio.run/##y0rNyan8/79A69hkT7eHu3Zqp/z/b/Tf3BQA "Jelly – Try It Online")
### How it works
```
p*ƓIFẹ+d Main link. Argument: k
p Cartesian product; yield all pairs [b, a] with b and a in [1, ..., k].
Ɠ Get; read an integer n from STDIN.
* Power; map each [b, a] to [b**n, a**n].
I Increments; map each [b**n, a**n] to [a**n-b**n].
F Flatten the resulting list of singleton arrays.
ẹ Every; find all indices of k in the list we built.
+ Add k to the indices to correct the offset.
d Divmod; map each index j to [j/k, j%k].
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
k#n=[(a,b)|b<-[1..k],a<-[b..k],a^n-b^n==k]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1s5zzZaI1EnSbMmyUY32lBPLztWJxHISoKw4vJ0k@LybG2zY//nJmbmKdgqpORzKQBBQVFmXomCioK5qYKCsoIRipipAaaYsRGmmLkCSMwYRczMzBQoZvYfAA "Haskell – Try It Online")
## Ungolfed with [UniHaskell](https://github.com/totallyhuman/unihaskell) and `-XUnicodeSyntax`
```
import UniHaskell
f ∷ Int → Int → [(Int, Int)]
f k n = [(a, b) | b ← 1 … k, a ← b … k, a^n - b^n ≡ k]
```
Can't change much else...
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
Very inefficient for larger input values.
```
LãDImƹQÏ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5/BiF8/cw22HdgYe7v//39iIywgA "05AB1E – Try It Online")
**Explanation**
```
L # range [1 ... input_1]
ã # cartesian product with itself
D # duplicate
Im # raise each to the power of input_2
Æ # reduce each pair by subtraction
¹QÏ # keep only values in the first copy which are true in this copy
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 11 bytes
```
t:i^&-!=&fh
```
[Try it online!](https://tio.run/##y00syfn/v8QqM05NV9FWLS3j/39jIy4jAA) Or [verify all test cases](https://tio.run/##y00syfmf8L/EKjNOTVfRVi0t47@6rq6ueoRLyH9TAy4jLmMjIGHOZcxlZmbKZQYA).
### Explanation
```
t % Implicit input: M. Duplicate
: % Range [1 2 ... M]
i % Input: n
^ % Power, element-wise. Gives [1^n 2^n ... M^n]
&- % Matrix of pairwise differences (size n×n)
! % Transpose. Needed so the two numbers in each pair are sorted as required
= % Is equal? Element-wise. Gives true for entries of the matrix equal to M
&f % Row and column indices of true entries
h % Concatenate horizontally. Implicit display
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 21 bytes
```
{o/⍨⍵=-/¨⍺*⍨¨o←,⍳2⍴⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqfP1HvSse9W611dU/BKR3aQG5h1bkA6V0HvVuNnrUuwUoWfv/v5FCmoKxEZcxkDLnMgOSZmamAA "APL (Dyalog Unicode) – Try It Online")
Left argument is `n`.
[Answer]
# [Python 2](https://docs.python.org/2/), 65 bytes
```
lambda k,n:[(j%k,j/k)for j in range(k,k*k)if(j%k)**n-(j/k)**n==k]
```
[Try it online!](https://tio.run/##LY3BDoIwEETP@hVzaeiSJSoIGBL8EfWA0SJUF4Jw8OsrDZz2JfNmtv@Nr05iZ1Di6t7V5/6oYFmKi26V5XZnyXQDWjSCoZL6qS3b0FJjfE5hKJH20gxlaW/Oy7MCId/QecqIiaHT/QpJvELOSPzNstnJPJ0OjCMV200/NDIiUMnEUBOiM9Q3gFqGGWZ5QO4P "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
*Iċ³
ṗ2çÐf
```
A full program taking `i`, and `n` which prints out the pairs of `[b,a]` with an empty output when there are none.
**[Try it online!](https://tio.run/##AR4A4f9qZWxsef//KknEi8KzCuG5lzLDp8OQZv///zMy/zI "Jelly – Try It Online")**
### How?
```
*Iċ³ - Link 1, isValid?: pair of +ve integers, [b,a]; +ve integer, n
* - exponentiate -> [b^n,a^n]
I - incremental differences -> [a^n-b^n]
³ - program's third argument -> i
ċ - count occurrences -> 1 if a^n-b^n == i, otherwise 0
ṗ2çÐf - Main link: +ve integer i, +ve integer n
ṗ2 - second Cartesian power = [[1,1],[1,2],...,[1,i],[2,1],...,[2,i],...,[i,i]]
Ðf - filter keeping if:
ç - call last link (1) as a dyad (left = one of the pairs, right = n)
- implicit print of Jelly representation of the list
```
[Answer]
# JavaScript (ES7), 64 bytes
A recursive function taking input in currying syntax `(n)(p)`. Returns a space-separated list of pairs of integers, or an empty string if no solution exists. Uses the same algorithm as [user202729's Python answer](https://codegolf.stackexchange.com/a/153198/58563).
```
n=>p=>(g=x=>x--?((y=(x**p+n)**(1/p))%1?[]:[y,x]+' ')+g(x):[])(n)
```
Or **60 bytes** with 0-terminated, encapsulated arrays:
```
n=>p=>(g=x=>x--&&((y=(x**p+n)**(1/p))%1?g(x):[y,x,g(x)]))(n)
```
This would output `[ 9, 7, [ 6, 2, 0 ] ]` for **f(32)(2)**.
### Test cases
```
let f =
n=>p=>(g=x=>x--?((y=(x**p+n)**(1/p))%1?[]:[y,x]+' ')+g(x):[])(n)
console.log(f(50)(2))
console.log(f(32)(2))
console.log(f(7)(3))
console.log(f(665)(6))
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
```
f/.+^RvzTQ^SQ2
```
**[Try it here!](https://pyth.herokuapp.com/?code=f%2F.%2B%5ERvzTQ%5ESQ2&input=75%0A2&debug=0), [Alternative!](https://pyth.herokuapp.com/?code=f%2F.%2B%5ERvzTQ%2aSQS&input=75%0A2&debug=0)**
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
Thanks Mr.Xcoder for saving some bytes!
```
lambda x,n:[(a,b)for b in range(1,x)for a in[(b**n+x)**(1/n)]if a%1==0]
```
[Try it online!](https://tio.run/##VcjBCsIwDADQu1@Ri5DUgOvKKgj9krlDilYLmo2yQ/36KoKgx/eW53qb1bUUTu0uj3gWqKzHEYUjpblAhKxQRK8XtFw/Je8aMRqju0rGoN0rTTmBbG0I3dSWknXFhEPHPdHmS9f/8cDuR94P7InaCw "Python 3 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 69 bytes
```
lambda x,n:[(a,b)for b in range(1,x)for a in range(x)if a**n-b**n==x]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCJ88qWiNRJ0kzLb9IIUkhM0@hKDEvPVXDUKcCLJSIEKrQzExTSNTSytNNAhK2thWx/wuKMvNKNNI0TA10jDQ1uWBcYyMUrrmOMRLPzMxUx0xT8z8A "Python 3 – Try It Online")
Use totallyhuman's x^2 brute force approach actually saves bytes.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 80 bytes
```
function r=f(n,p)[X Y]=meshgrid(1:n,1:n);r=[X(:) Y(:)](X(:).^p-Y(:).^p==n,:);end
```
[Try it online!](https://tio.run/##LcrBDoIwEATQu1@xx91kNQJSTEn/g4ZgYqBVDi6kor9f28hhZt5hlnG7f12M/iPjNi8CwXgUXqnvwA7m5d7PR5gnLLRwCrXB9B1qAptqwMzTbT3a/xojrKl1MkWPTc1Q0sFjfd5RlTsahiqvUumjsq4Fw4XiDw)
[Answer]
# [Perl 6](http://perl6.org/), 45 bytes
```
->\k,\n{grep * **n-* **n==k,flat 1..k X 1..k}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtf1y4mWycmrzq9KLVAQUtBSytPF0za2mbrpOUkligY6ullK0SAqdr/aflFCjamBgpGdjoKNsZGENpcwRhEWRgqmNgp6NopRKtk6yio5MUqVCsUJ1YqKEG4Co/aJilUa6QpQLiaej6ZxSV6BUDH1Cop1P4HAA "Perl 6 – Try It Online")
] |
[Question]
[
>
> Thanks to [this](https://codegolf.stackexchange.com/questions/33221/write-a-domino-effect) question for some inspiration
>
>
>
In this challenge we will represent a line of dominoes as a string of `|`, `/` and `\`. You will be given a string of dominoes as input and you must determine what they look like when they have settled. Here are the rules for how dominoes fall over
* A standing domino, `|`, left of a left fallen domino, `\`, will become a left fallen domino as well.
* A standing domino, `|`, right of a right fallen domino, `/`, will become a right fallen domino as well.
* If a standing domino is between a left fallen `\` and a right fallen `/` domino, it will remain standing.
These rules are applied repeatedly until the arrangement no longer changes.
Here is an example of how a single input might arrive at its conclusion
```
|||||||\/|||||||\||\|||/||||||\|||||
||||||\\//|||||\\|\\|||//||||\\|||||
|||||\\\///|||\\\\\\|||///||\\\|||||
||||\\\\////|\\\\\\\|||////\\\\|||||
|||\\\\\////|\\\\\\\|||////\\\\|||||
||\\\\\\////|\\\\\\\|||////\\\\|||||
|\\\\\\\////|\\\\\\\|||////\\\\|||||
\\\\\\\\////|\\\\\\\|||////\\\\|||||
```
Your task is to write code that finds and outputs the end result of a input. You may assume that the input is always valid and contains at least 2 characters.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Test cases
```
|||/|||| -> |||/////
|||\|||| -> \\\\||||
|/||||\| -> |///\\\|
||/|||\| -> ||//|\\|
||\|||/| -> \\\|||//
```
[Answer]
## [Retina](https://github.com/m-ender/retina), 32 bytes
```
+`(/.\\)|(/)\||\|(\\)
$1$2$2$3$3
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wXztBQ18vJkazRkNfM6amJqZGA8jhUjFUMQJCYxXj//9rICBGH8YAoxp9OA8IuGACXDAhLgg/BiSiD2NA9AEA "Retina – Try It Online")
### Explanation
The `+` tells Retina to run the replacement in a loop until it fails to change the string. Each replacement computes one step the falling dominoes. The replacement itself is really three replacements in one, but this ensures that they happen simultaneously:
```
(/.\\)...
$1
```
This just matches `/|\` (as well as `/\\` and `/\\`, but those don't matter) and reinserts it unchanged. The purpose of this is to skip over `|` with fallen dominoes on both sides, because this is shorter than ruling out those cases with separate lookarounds in the other two cases.
```
...(/)\|...
$2$2
```
This matches `/|` and turns it into `//`.
```
...\|(\\)
$3$3
```
This matches `|\` and turns it into `\\`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~115~~ ~~114~~ ~~111~~ ~~108~~ ~~98~~ 95 bytes
-1 byte thanks to ovs
```
a=input()
for i in range(4)*len(a):a=a.replace('//|x||\ \\'[i::4],'/\/x|\/ \\'[3-i::4])
print a
```
[Try it online!](https://tio.run/##RYhBCsIwEEX3PcXsJhF1QLsK9CROF4NEDZRpCBEqzN1TaUEffPjv5U99zXppTYak@V2d7x5zgQRJoYg@o@v9YYrqxAcZ5FxinuQeHRLZYsbAjLcUQj8ekZgWY9rS9bRF3@WStIK0hrbDTL@3z@jvX3AF "Python 2 – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 23 bytes
```
òÓ¯À<!|¨Ü©ü¨¯©|ÜÀ!/±±²²
```
[Try it online!](https://tio.run/##K/v///Cmw5MPrT/cYKNYc2jF4TmHVh7ec2jFofWHVtYcnnO4QVH/0EYg3HRo0///NRAQow9jgFGNPpwHBAA "V – Try It Online")
Really, this is very similar to the retina answer, just that it looks uglier. Uses regex compression.
Hexdump:
```
00000000: f2d3 afc0 3c21 7ca8 dca9 fca8 afa9 7cdc ....<!|.......|.
00000010: c021 2fb1 b1b2 b2 .!/....
```
Explanation:
`ò` tells V to run until the string doesn't change. The rest is a compressed regex. Let's convert it into the vim equivalent...
```
:s/\v\/@<!\|(\\)|(\/)\|\\@!/\1\1\2\2/g
:s/ " Substitute...
\v " Turn on magic (use less escaping)
\| " A bar
(\\) " Followed by a captured backslash
@<! " That is not preceded by
\/ " A forward slash
| " OR...
(\/) " A captured forward slash
\| " Followed by a bar
\\@! " That is not followed by a backslash
/ " Replace this with
\1\1 " Pattern 1 twice (will be empty if we matched the second path)
\2\2 " Pattern 2 twice (will be empty if we matched the first path)
/g " Replace every match on this line
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~117~~ ~~115~~ ~~112~~ 111 bytes
```
D =INPUT
S D '/|\' ='_' :S(S)
E =D
D '/|' ='//'
D '|\' ='\\'
D E :F(S)
R D '_' ='/|\' :S(R)
OUTPUT =D
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NFwdbTLyA0hCsYyFTXr4lRV7BVj1fntArWCNbk4nRVsHXhgsiAJPT11cE8iLKYGDDPldPKDaQ4CCQTD1YGlAeZEAQ0wT80BGg8yBhXP5f//2tq9GtqamJqAA "SNOBOL4 (CSNOBOL4) – Try It Online")
Credit to [Rod's python answer](https://codegolf.stackexchange.com/a/152617/67312) for the idea for the stopping condition with a second variable to see changes rather than testing `D '/|' | '|\'`.
```
D =INPUT ;* read input
S D '/|\' ='_' :S(S) ;* replace '/|\' with '_', recursively
E =D ;* set E to D, this is the while loop
D '/|' ='//' ;* topple right
D '|\' ='\\' ;* topple left
D E :F(S) ;* if D doesn't match E, goto S
R D '_' ='/|\' :S(R) ;* replace '_' with '/|\' (inverse of statement S)
OUTPUT =D ;* output
END
```
[Answer]
# [Perl 5](https://www.perl.org/), 39 + 1 (`-p`) = 40 bytes
```
s%(?<!/)\|(\\)|(/)\|(?!\\)%$+$+%g&&redo
```
[Try it online!](https://tio.run/##K0gtyjH9/79YVcPeRlFfM6ZGIyZGs0YDzLJXBLJVVbRVtFXT1dSKUlPy//@vqdGvAYKYmn/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~114~~ 107 bytes
```
until=<<((==)=<<)$g
g s=t<$>zip3('|':s)s(tail s++"|")
t(l,'|',r)|l<'0',r/='\\'=l|r=='\\',l>'/'=r
t(_,e,_)=e
```
[Try it online!](https://tio.run/##PY3RCoMwDEXf@xVFhLZY6WBvw/glBSmiriwTsd3Llv36us65HQI5lwTu2YXLgJhGDtym2xw9QtNICaDyVuXEJh4gNmV798tRChKnoIKMziMPVVVQoViUqPNBr4qwEYcsBoS1ApBW2ExjK4yANb92etCdgiFdnZ9zqZ/jsLo@8pGzR83sjsnQ7kT0ibsSsfqZ6Is1P9mGzD9lXv2Ibgqp7pflDQ "Haskell – Try It Online") The first line defines an anonymous function.
### Explanation:
* `until=<<((==)=<<)$g` is a fix point function (see [here](https://codegolf.stackexchange.com/a/144402/56433) for an explanation) which applies the function `g` to the input string until the result no longer changes.
* `zip3('|':s)s(tail s++"|")` creates for each domino, that is character in the string `s`, a triple with the pre- and succeeding domino, padding with `|` at the edges. E.g. `/\|` becomes `[(|,/,\),(/,\,|),(\,|,|)]` (ignoring escaping).
* Then the function `t` is applied to each of the triples to compute the new position of the centre piece of the triple.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 132 bytes
```
+[]-->[].
+[47,124,92|T]-->"/|\\",+T.
+[47,47|T]-->"/|",+T.
+[92,92|T]-->"|\\",+T.
+[X|T]-->[X],+T.
X+Y:- +(N,X,[]),!,(X=N,Y=N;N+Y).
```
[Try it online!](https://tio.run/##TcpNCoMwEAXgvadoXSXMRKkIYosFL5CVi4Qk1GKlCC0pKrjJ3dMfW@2DgZlv3qO3N3tlw9R5D8owdlQmCkClGe6SFPPEVW8MY6d1iFB9f2m2@E/zZG3/lcVMSpgPCJB7tgHCUaAyFLdIRMFRFvzAQdLI@9rN0TpetnlcvN6v1CDxPNr7qbGXdiAlSopT340tKWkUBE8 "Prolog (SWI) – Try It Online")
This program defines a predicate `+/2` that is true if the second argument is the settled version of the first. Both arguments are lists of character codes.
## Explanation
This solution uses a DCG to figure out what the next step is and then repeatedly calculates the next step until the next step is the same as the current step.
### The DCG
```
+[]-->[].
+[47,124,92|T]-->"/|\\",+T.
+[47,47|T]-->"/|",+T.
+[92,92|T]-->"|\\",+T.
+[X|T]-->[X],+T.
```
These five lines of code define a DCG (Definite Clause Grammar) rule `+` that is used in the program to calculate a single step of dominoes toppling. DCGs in Prolog work by finding the first case of the rule whose right hand side matches the string and determining the argument of the rule on the left hand side through that process. If a case fails to match then it will backtrack and try a later case.
```
+[]-->[].
```
This line represents the base case of the `+` rule. It simply states that if there are no dominoes currently then in the next step there will still be no dominoes.
```
+[47,124,92|T]-->"/|\\",+T.
```
Since this program deals exclusively with lists of character codes it is important to note that the character codes for `/`, `\`, and `|` are 47, 92, and 124 respectively. This case of the `+` rule handles the `/|\` string.
```
+[47,47|T]-->"/|",+T.
```
This case handles a right falling domino knocking over the domino the right of it. Since it comes after the case for handling `/|\` it will not be used for that possibility.
```
+[92,92|T]-->"|\\",+T.
```
Handles the case for a left falling domino knocking over the domino to the left of it.
```
+[X|T]-->[X],+T.
```
This is the wildcard case. Since nothing else changes besides what is described above, so long as there is text left in the input string it will just copy it over to the output so long as it does not match any of the above cases.
### The Predicate
```
X+Y:- +(N,X,[]),!,(X=N,Y=N;N+Y).
```
The main predicate takes two arguments, the first one is the initial domino setup, the second is the settled dominoes. Since this is Prolog the second can be undetermined and the program will calculate it. The predicate in and of itself is fairly simple `+(N,X,[])` calls the DCG and calculates the next step of the dominoes storing it in `N`. `(X=N,Y=N;N+Y)` checks if the next step of the dominoes is the same as the current and if it is it sets `Y` to it since the dominoes must have settled and if it is not it recurses, calling the same predicate with the next step of the dominoes `N` instead of `X`.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 36 [bytes](https://github.com/abrudz/SBCS)
```
({(↑∘1¨3 ¯3)⍳⊂⍵≠'/|\'}⊃'\/',2⊃⊢)⌺3⍣≡
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X6Na41HbxEcdMwwPrTBWOLTeWPNR7@ZHXU2Perc@6lygrl8To177qKtZPUZfXccIyHjUtUjzUc8u40e9ix91Lvz//1HvXAXfxMw8hbTSvOSSzPw8BY3i0qTczOJiIFuTiytN4VHbBAXKbOHiAtkSklpcopCcWJxaDDJVvaamRh@Ia9ShnBgEByweA5PRR@bEgLWpAwA "APL (Dyalog Unicode) – Try It Online")
-3 partially thanks to [Cows Quack](https://codegolf.stackexchange.com/users/41805/cows-quack).
Feels so ungolfed...:(
[Answer]
## [face](https://github.com/KeyboardFire/face), 166 bytes
```
\|/,cm_/o>AvI[IIcP/+PP|m_/m*/Sl*Im1/11:~-_I|'|?_1-_P|?_1`I-III_|+II|'I.C:1-_I|?_C'|-_P|?_C_|'I-_I|`I?_!'I.C:!'|'|-III+II|'I:C_|-PPP+PPI'I?I~_I-PPP+PP|-**1?*~Sl*Iw*I*>
```
Takes input as a command line argument and outputs to STDOUT. This only works in commit 86494f6 and beyond due to a bugfix in that commit.
Wrapped for aesthetics:
```
\|/,cm_/o>AvI[IIcP/+PP|m_/m*/Sl*Im1/11:~-_I|'|?_1-_P|?_1`I
-III_|+II|'I.C:1-_I|?_C'|-_P|?_C_|'I-_I|`I?_!'I.C:!'|'|-III
+II|'I:C_|-PPP+PPI'I?I~_I-PPP+PP|-**1?*~Sl*Iw*I*>
```
And ungolfed / commented:
```
\|/,cm_/o> ( setup )
AvI[II ( store input into I )
cP/+PP|m_/ ( store 92, ascii for \, into P, meaning prev char )
m*/Sl*Im1/11 ( store length of input into counter variable * )
( main loop: )
:~
-_I|'|?_1 ( branch to 1 if the character is not \ )
-_P|?_1 ( also branch to 1 if the previous character wasn't | )
`I-III_|+II|'I ( we have a sequence |\ so prev needs to be toppled )
.C ( jump to C, the "continue" label at end of loop )
:1
-_I|?_C ( branch to C if the character is not | )
'|-_P|?_C ( also branch to C if the previous character wasn't / )
_|'I-_I|`I?_! ( branch to ! if the next character isn't \ )
'I.C:! ( otherwise, skip the next \ and branch to continue )
'|'|-III+II|'I ( if all conditions hold we have /|| or /|/ so topple )
:C
_| ( reset pointer to source )
-PPP+PPI ( update prev variable )
'I ( step through data )
?I~
_I-PPP+PP|-**1 ( reset input/prev and decrement counter )
?*~ ( repeat main loop as many times as there are chars )
Sl*Iw*I*> ( output final string to stdout )
```
There's a few subtle tricks in here that shave off a few extra bytes, such as
* the naming of the variables | and /, whose ASCII values are accessed via introspection later in the code
* the `'|` on the first line of the main loop, which is called there instead of on the second line in order to set the | pointer for use in the second section of the main loop
[Answer]
# [Perl 5](https://www.perl.org/), 52+1(-p) = 53 bytes
*-6 bytes thanks to mik*
Probably not the best possible for Perl, but it's what I could come up with.
```
0while(s/(?<!\/)\|(?=(\\))|(?<=(\/))\|(?!\\)/$1$2/g)
```
### Explanation
```
while(
s/
(?<!\/)\|(?=(//)) # If there's a | that precedes a \ but doesn't follow a /, capture /
| # Or
(?<=(\/))\|(?!//)/ # If there's a | that follows a / doesn't precede a \, capture /
/$1$2/ # Replace all | with capture group 1 or 2, as one of the two will always be empty
g # Repeat as much as possible for this string
)
```
[Try it online!](https://tio.run/##K0gtyjH9/9@gPCMzJ1WjWF/D3kYxRl8zpkbD3lYjJkZTE8iwAbL0NcFiikAhfRVDFSP9dM3//2sgIEYfxgCjGn04Dwj@5ReUZObnFf/XLQAA "Perl 5 – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), 98 bytes
```
import StdEnv
$['/|':t]=['//': $t]
$['|\\':t]=['\\\\': $t]
$[h:t]=[h: $t]
$e=e
f=until(\e=e== $e)$
```
[Try it online!](https://tio.run/##LY2xCsIwFEX3fkWGQHSQ7IW36SC4dTQdYprYQJKKvgpCvt3nq@RO95zhXpe8LZSXaU1eZBsLxfxYnigGnE7l3cmr0lX1OAIXrXohcdxkNaZZY7ba/Px3c0MPvguwFoxpZxgAhPR7SQNafgARBA/pyuGJkb4uJHt/0eF8oeOn2Bwdw@0H "Clean – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 44 bytes
```
1while s,(/)\|(?!\\)|(?<!/)\|(\\),$1$1$2$2,g
```
[Try it online!](https://tio.run/##K0gtyjH9/9@wPCMzJ1WhWEdDXzOmRsNeMSZGE0jZKIK5QI6OiiEQGqkY6aT//19TU6MPxDVcQBwDYYD5MSARfRgjBqzsX35BSWZ@XvF/3QIA "Perl 5 – Try It Online")
### Explanation
```
1while s, , ,g while anything found substitute globally
(/)\|(?!\\) $1$1 /| that is not followed by \ to //
| or
(?<!/)\|(\\) $2$2 |\ that is not preceded by / to \\
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
i@€Ø2jḅ3ị“½jỊA!S’ḃ3¤Ɗ3ƤƊÐLịɗ“\|/
```
[Try it online!](https://tio.run/##y0rNyan8/z/T4VHTmsMzjLIe7mg1fri7@1HDnEN7sx7u7nJUDH7UMPPhjmbjQ0uOdRkfAxKHJ/gAVZycDlQTU6P/////GgiI0YcxwKhGH84DAgA "Jelly – Try It Online")
There's probably a much better way to do this.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 83 bytes
Technically cheatable with `9.times`, or even just `999.times` but I don't feel like being cheap :)
Still has huge golfing potential. (Note: `y while undone` is far longer than `x.size.times`)
```
->x{x.size.times{x.gsub! /\/\|\\?|\|\\/,'/|\\'=>'/|\\','/|'=>'//','|\\'=>'\\\\'}
x}
```
[Try it online!](https://tio.run/##XY7BDsIgDIbvPMWMBy5ufYLhg1gvSzazg4mRkaCyZ8d2BWT@AdrC97c83fCKUx9b4z@@s/N77Jb5PloqbtYNhwYQMCCeA59w0kBB90Yil1sBlKYHJOlV@TU@3GKb6UIMS1/VsREFEUJOthWgVCSV3Zn50Si78Jj7VxaQK5rYGp4HrBoQVyb40/upkFqXHuRnqOoBfwQhYU@kbxIRvw "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 114 bytes
```
function(d){g=gsub
for(i in 1:nchar(d))d=g("/|","//",g("|\\","\\\\",g("/|\\","_",d,f=T),f=T),f=T)
g("_","/|\\",d)}
```
[Try it online!](https://tio.run/##RYsxDsMgDEV3ToE8YckV6lqVW3REilKQKQuRSDPVPTt1WDrYfl/Pvw@298vgo6V33ZrL@Cmh7MfT8NZdtbXZ662l19pVYQ7FgRcg8B5IWWLUEON5ppp5AcrE4YH/ZdQuZ29@ZPwOdntamyMARCMiXkcU4uTxAw "R – Try It Online")
Returns an escaped string.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 183 bytes
```
D,i;f(char*S){char*s=malloc(-~strlen(S));for(D=1;D--;strcpy(S,s))for(strcpy(s,S),i=0;s[i];i++)s[i]>92&&(S[-~i]==92&&S[~-i]!=47&&(s[i]=92,D=1)||S[~-i]==47&&S[-~i]!=92&&(s[i]=47,D=1));}
```
[Try it online!](https://tio.run/##bc/daoMwFAfw6/UpUqElaRNcR6GUkEI1PkEu1QsJcwtYW0xvRlNf3eXDCR1eGM3/nPw8keRLymHgWNEayu@q2wj08G/NLlXTXCUkvb53zWcLBUK0vnaQsx3lhFAby9sPFFgj5PJxr7FAWLF3qnNVUrXdIvdxOn6s11DkpFclY24j8p6ocsn2B1twLTbF1kbGhBLzpXBk6Y@Etv3BtyH6HC6VaiF6LN7cyOCclywyxsT2MRGgt0619xpGKx3hs50d2uUvA4CcwEoXrS@NQDICReGFFyBxQDILJBOQesD/3xqvQOqAdBZIJ4CHCeI5gDuAzwJ8ArIA@BvE/4DMAdksYNPFc/gF "C (gcc) – Try It Online")
] |
[Question]
[
The "standard" polyhedral game dice have 4, 6, 8, 10, 12 and 20 sides. (Yes, I know that there are two 10-sided dice which together make a d100, but we're ignoring that right now.)
If I want to generate a random number between 1 and \$n\$ where \$n\$ is not one of those sides, I have a couple of options.
One option is to pick a die with more sides than my maximum and just re-roll if the result is larger than I want. For example, if I want a number between 1 and 7, I can roll the 8-sided die: if it's between 1 and 7, that's great; if it's 8, I can just re-roll until it is between 1 and 7.
Re-rolling is a bit of a pain though, but if your number \$n\$ is a factor of one of the die's side counts, you can just double-count some of the faces. Specifically, if your number is \$n\$, you can choose an \$(n\times m)\$-sided die, roll it, and then take the result modulo \$m\$. For example, if you want to generate a number between 1 and 3, then you can roll a six-sided die: if the result is between 1 and 3, you are done; if it's greater than 3, just subtract 3 to get the result.
We can even use both at once! For example, if I want to generate a number from 1 to 9, I can use a 20-sided die to generate a number from 1 to 18 with Method 1. 18 is a multiple of 9, so I can use Method 2 to get a number from 1 to 9.
So there are multiple ways to roll certain numbers. How do we decide which is best? Well, I have a couple of criteria I use:
* First, I count the number of dead faces where we would have to re-roll. The method with fewer dead faces is better.
* If the dead faces are equal, then the method using the die with fewer faces is better.
# Task
Your task is to take a set of integers representing the polyhedral dice, and an integer representing the size of a range to generate a random int on (range from 1 to \$n\$).
You should output which polyhedral die in the input set has the best method as described above.
You may take the set in any reasonable format, including a strictly ascending or descending list. The size of the range will always be at most equal to the maximum of the set and at least 1.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimize the size of your source code as measured in bytes.
# Test cases
```
set = {4,6,8,10,12,20}
1 -> 4
2 -> 4
3 -> 6
4 -> 4
5 -> 10
6 -> 6
7 -> 8
8 -> 8
9 -> 10
10 -> 10
11 -> 12
12 -> 12
13 -> 20
14 -> 20
19 -> 20
20 -> 20
set = {12,16}
5 -> 16
set = {3,5}
2 -> 3
```
[Answer]
# [J](http://jsoftware.com/), 9 bytes
```
0{]/:>,.|
```
[Try it online!](https://tio.run/##JYqxCsJAEAX7fMUjFrkj67p7JkEWtVCwEgvbkCp4qI0fcPn38yDFFDPMN9fcRJwMDQgCK2wZ1@f9liVNOzsTL9lXjwtD0uhKWfzRNlP1mt8/OG0/HMTDjSBDrJNHRwMdSIU0UJD16xGhATqsGoru0ec/ "J – Try It Online")
* `]/:` Set of dice sorted by...
* `>,.|` 2 number list for each dice consisting of `<is dice less than the input>, <modulus>`. The first number will sort all dice that are too low to make the requested number after those that are big enough, and the 2nd number will prioritize those with fewer dead faces.
* `0{` Take the first.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~68~~ \$\cdots\$ ~~55~~ 48 bytes
```
d;f(a,n)int*a;{d=*a?f(a+1,n)<n|*a%n<d%n?*a:d:0;}
```
[Try it online!](https://tio.run/##1ZJdT4MwFIbv/RUnJCR8dJHChtsY7sL4K9yyECiTOLsFSCRO/rp42vI1vPFWQkt7@vD29LyNZ8c4bpokSI2IcDPjpRUF1yS0oi1GbIqxDf@yIp1vEp1vrWidrJ2gbhCE9yjjhgnXO8BHBEpWlPRQsPJlDyFcXYcAdbHhd0nAJzAn4NTBDe8OPPUVP0W8AVkQ8G4ASxID0KdA4N8M3WEojzo5vggdTup4vizj31@spjuV4ygFst5y3ZO2YGEF/yCdWuFEmEZpayAyFCGKC8JUAY9lWXVhcckSleNcCiq3hYovNZdqQrs74SqpcRP@e61sfOZFCfFrlFvYs/iN5Upd21XP7q5aPWFbaATGc09r/07PORgis4wnrMLfnKAdbqDIPtk5Nbqczfs2YPWRAGxb0qYUU/e7v2/oBgr2t06C@2DMgDRsBKF7CgMb6C3KO4z/UhoO0R5AJC/EZH5mz4nnkiOYGppe6AkWJduKyqy1K35kkntzkiFKpoa8dnyyxHCpN3SaU7dPTUBPYPYoer3YcdyH41ak96oIQ9ZtWt/VzXecnqJj0cw@fgA "C (gcc) – Try It Online")
*Saved ~~3~~ ~~7~~ 13 bytes thanks to a discussion with [Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes)!!!*
*Saved 7 bytes thanks to [att](https://codegolf.stackexchange.com/users/81203/att)!!!*
Inputs \$n\$ and a pointer to a zero-terminated (because pointers in C carry no length info) descendingly-sorted array of integers representing the dice.
Returns the best die for \$n\$.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
@ÏΣ¹%}н
```
[Try it online](https://tio.run/##yy9OTMpM/f/f4XD/ucWHdqrWXtj7/78pV7ShkY6hWSwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFJxaYqWgZF/posOlcHiBq5@9koKuHVjA79DK/w6H@88tPrROtfbC3v86/6OjTXTMdCx0DA10DI10jAxidaKBtKEZkDbWMY2NBQA).
**Explanation:**
```
@ # Check if the values in the second (implicit) input-list are >= the
# first (implicit) input-integer
Ï # Only keep those values from the second (implicit) input-list
Σ }н # Get the minimum by:
Σ } # Sort by,
н # and pop and push the first element afterwards
¹% # Modulo the current value by the first input-integer
# (after which the result is output implicitly)
```
[Answer]
# [Coconut](http://coconut-lang.org/), 24 bytes
A curried function taking the integer first, then the set of dice.
```
x->min$(key=->(_<x,_%x))
```
[Try it online!](https://tio.run/##jcxBCsIwEIXhfU4xC6UJTKCJtoiYXKSWIqWRUkwkrTCePgZ1WcHdW/zv60Mf/GNJzpwTSXsb/YZPw9NIy7sTYbclIdIMBpo91nhAVaLSqMuW3ePoFz4L5kIEgtFDvPjrwBWCVuLIAD4FYSFtgY6TyLVg32MebzZrql7Tmqr9G9lhtUro30R6AQ "Coconut – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
<;%ɗÞḢ
```
[Try it online!](https://tio.run/##y0rNyan8/9/GWvXk9MPzHu5Y9P///2gTHTMdCx1DAx1DIx0jg9j/pgA "Jelly – Try It Online")
```
ɗÞ Sort by...
< less than (return 0 if the set element is greater or equal to the range size)
; concatenated with
% modulus.
Ḣ Get the first element.
```
The same algorithm as [Jonah's answer in J](https://codegolf.stackexchange.com/a/248026/25180).
[Answer]
# Python 3, ~~34~~ ~~56~~ ~~55~~ 40 bytes
```
lambda x,y:min((z<x,z%x,z)for z in y)[2]
```
Takes a strictly ascending list.
[Answer]
# JavaScript (ES6), 48 bytes
Expects `(list)(integer)`.
```
a=>n=>a.sort((x,y)=>x<n|-(y<n)||x%n-y%n||x-y)[0]
```
[Try it online!](https://tio.run/##fdHRCoMgFAbg@z2FN4GClVpzxbIXiS6i1dgIHRUjoXdvQbUrO3fCdzzi/7@rbzXU/esz@to8mqVVS6VyrfIqGEw/YjxRS1Q@ZXr2sc00mefJ07719HrwLSlYuQzNiBQqYippQjmjXFDByvulNnowXRN05olbvE4RjDghKAxR7EQBYbShdGIM3bxuyJlTJbT3tmHixATCFHqUM1D3kLhwqgB1j0m4N8egppAK9te98LVnLk96PjKXx3BEryej@3@i5Qc "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = die list
n => // n = target integer
a.sort((x, y) => // for each pair (x, y) from a[] to be sorted:
x < n | // move away x if it's less than n
-(y < n) // move away y if it's less than n
// (if both values are invalid, y is moved away
// but it actually doesn't matter)
|| // or:
x % n - y % n // move away the value which is higher modulo n
|| // or:
x - y // move away the highest value
)[0] // end of sort(); return the leading entry
```
---
# JavaScript (ES10), 47 bytes
This version was suggested by [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen). It assumes that the list is given in ascending order and that the sort is stable (which used to depend on the implementation but is a requirement since ECMAScript 2019).
Expects `(list)(integer)`.
```
a=>n=>a.filter(v=>v>=n).sort((x,y)=>x%n-y%n)[0]
```
[Try it online!](https://tio.run/##fdHRCoMgFAbg@z2FN4GClVq5YuiLRBfRajRCR0nU07egtis719/vOfifdz3XUzP2Hxca@2y3Tm210kbpOur6wbUjnpWetTIkmuzoMF7oSpReAhOugSElq7apdUihMqWS5pQzygUVrHrcGmsmO7TRYF@4w3uKYMQJQXGMUi8KCJMDpRdT6GV2IGdeldDc@4G5F3MIC2gpZ6CeJXHhVQHqWZPwT05BLSAV7K/nwfc7c3lx51/n8hdOaHYRPf@TbF8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes
```
ti&\g/&X<)
```
Inputs are an ascending numerical vector and a number.
[Try it online!](https://tio.run/##y00syfn/vyRTLSZdXy3CRvP//2gTHTMdCx1DAx1DIx0jg1guUwA) Or [verify all test cases](https://tio.run/##bc8xCoAwEETR3oMIwoKZVWMES49gIaiglQja5f4x2M52y2tm/3vGJx0p3uV21eUyVmma09qKlyBwAhV1e4GCSJkappapY/JMPVNgGpjgDDP@hxEAowBGAoxdzbv5hP8LG@kyfQ).
### How it works
Consider inputs `[4,6,8,10,12,20]`, `5`.
```
ti % Implict input. Duplicate, then take second input
% STACK: [4 6 8 10 12 20], 5
&\ % Two-output modulus: gives modulus, then quotient
% STACK: [4 6 8 10 12 20], [4 1 3 0 2 0], [0 1 1 2 2 4]
g % Convert to logical
% STACK: [4 6 8 10 12 20], [4 1 3 0 2 0], [0 1 1 1 1 1]
/ % Divide, element-wise
% STACK: [4 6 8 10 12 20], [inf 1 3 0 2 0]
&X< % Index (1-based) of first minimizing entry
% STACK: [4 6 8 10 12 20], 4
) % Use as index. Implicit display
% STACK: 10
```
[Answer]
# [Factor](https://factorcode.org), 48 bytes
```
[| s n | s [ n < ] reject [ n mod ] infimum-by ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZKxTsMwEIYlxjzF_wKt4rSEQCtWxMKC6FJ1MMZJXcV2sJ2hlDxJlyx06wPB0-A2AwiJ80m-u_-zpdNv7w8lF8G6_uti8fR4_3B3A-69FR5evrbSCOnHlTTS8Vq98aCs8ait4LWH5mH9cwqNkyFsG6dMQOVs2yhTYZYkuwRx7WJMkaMAS8EyZCk6MHT_w4yCEwpOKXhJwZyCVxQsKHhNwVhSlPSIkSYx0iVG2sTImbPfM0eR5X-cnZy68xN2H20oR8VnunyHh8FpX8Y8xwpObqQI51bblygoUyrd6tHzFqvh3rEc_uOt5g3Gg9b3Q_4G)
* `s [ n < ] reject` Remove elements of the set that are less than n.
* `[ n mod ] infimum-by` Find the element that is smallest modulo n.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
nFirst@*SortBy[n>#||#~Mod~n&]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P@/9pIVumUXFJQ5awflFJU6V0Xl2yjU1ynW@@Sl1eWqx/wOKMvNKopV17dKilWMdqk10zHQsdAwNdAyNdIwMamPV6oKTE/PqghLz0lMdjAz@AwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
µ⁰₍<%;h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCteKBsOKCjTwlO2giLCIiLCJbNCw2LDgsMTAsMTIsMjBdXG41Il0=)
## How?
```
µ⁰₍<%;h
µ ; # Sort by:
⁰ # Push second input
₍ # Apply both of the next two commands, and wrap the results into a list:
< # Less than...
% # And modulo
# This would produce [a < b, a % b], where a is the current item and b is the second input.
h # First element (this is acting as a minimum-by)
```
[Answer]
# [R](https://www.r-project.org), ~~67~~ ~~33~~ 27 bytes
```
\(s,n)s[order(s<n,s%%n)[1]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBBCsIwEEVx6ykCUkhgCplpjClYzyHUrrRdVmjqadxUwVN4E09jJWkkWYX35g9M_v0xTM-uet3GLjfvE7fQC1tfh0s7cLvvwWZZL2psGpf4rI7ctiOr2Jkr0GAAJSABSSHW3W8EKDYsPzDlkWIsHGqPKp5uHaL0rOP0zqHxaGIsk2WUqfCnIS2CUuHPo7CiUlEmgmQQoZm5ENShkOVT-h8oZiniggpX8DS59ws)
Change of approach after looking at other answers.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
≔Φ笋ιθηI§η⌕﹪ηθ⌊﹪ηθ
```
[Try it online!](https://tio.run/##VYqxCoMwFAD3fkXGF3gFlbYUnKQgFLR0F4dgQvMgJpg8pX@f1m697Y6brIpTUC7nJiV6eWjJsYlgUTwCQ2dSAkKxSClRWFkfnpE8w00lhobvXpv3/rbkNfRBry7sunznnjzN6/xXf9Q5D2ccTnjBK5YFlhVWxTjm4@Y@ "Charcoal – Try It Online") Link is to verbose version of code. Takes the list of dice in ascending order. Explanation:
```
≔Φ笋ιθη
```
Remove dice that are too small.
```
I§η⌕﹪ηθ⌊﹪ηθ
```
Output the first die with the smallest remainder.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~65~~ 42 bytes
```
\d+
$*
sO^$`¶(?<=^(1+).+?)\1+(1*)
$2
r`1\G
```
[Try it online!](https://tio.run/##ZdAxDsIwDIXh3ecIUtJYKC9tQ5FAHRkZWKMqSDB0YSicjQNwsZDZnmJ9i39ne37W173u7K1wzQ9PpqP3dTHl97Xz6bxYeLf3s8vwFp0jE2kryJdawQMnnhiBETkGihJ6CYOEUUKScJAwSThKaIMU1QoVC1ULlQu1KwZ9UnuR2m/0PP4B "Retina 0.8.2 – Try It Online") Takes input on separate lines, but link is to test suite that splits on comma for convenience. Target value comes first followed by the list of dice in ascending order. Explanation:
```
\d+
$*
```
Convert to unary.
```
sO^$`¶(?<=^(1+).+?)\1+(1*)
$2
```
Sort the dice that are as least as large as the target value in order of their remainder when divided by the target value, then reverse the list of those dice so that the desired die is at the very end. (Dice that are too small remain at the start of the list.)
```
r`1\G
```
Convert the desired die to decimal.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~10~~ 8 bytes
```
ho%NQ-EU
```
[Try it online!](https://tio.run/##K6gsyfj/PyNf1S9Q1zX0/39DA65oEx0zHQsdQwMdQyMdI4NYAA "Pyth – Try It Online")
Accepts an integer and an ascending list on separate lines of STDIN
```
-EU # Remove all elements in the range 0 to (input integer) from the input list
o%NQ # Order by (element) modulo (input integer)
h # Take the first element
```
The sort should be stable since it's implemented using Python's `sorted` method.
[Answer]
# [Desmos](https://desmos.com/calculator), 41 bytes
```
f(l,n)=L[A=A.min][1]
L=l[l>=n]
A=mod(L,n)
```
Surprisingly golfy
[Try It On Desmos!](https://www.desmos.com/calculator/eea1umekhk)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/dd5flwayts)
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 40 bytes
```
f(s,i)=vecsort([[d<i,d%i,d]|d<-s])[1][3]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NCsIwFIT3nmIoCAm8lv6ouGi9yOMhobUSKBqaKggFD-LGjXgmb2Pqz2LgGxhm5vZ0prfbvbvfH6ehjdcv1SpPVlfnXe2P_aCYm9JSMw-SsSljL5oz4UJ--atHBV4QVoQ1IUuDckKeysw4112UQbyB6-1hCBhNJkJtuk61BKM1oT4eajMNeYIVjLAoY3CWJKFECMw8NWarwMuPL76Qi2j9vfG__wY)
[Answer]
# [Zsh](https://www.zsh.org/), 60 bytes
```
D=`<&0`
for d;for ((i=D;i<=d;i+=D))a[1+d-i]=$d
<<<${${a}[1]}
```
[Try it online!](https://tio.run/##HctBCsMgFIThvaeYhRQlJKhtQkHdBS8RAgnY0rcKNF2Uime3MZuBb@D/7a8ShBT744P2W0a/uIta2HN7I9q6QpAfLTkfLTV@lHKddBNbmj2PzDnHE09rnvSci2RnRxBJd51RWSLAKGgDrXDHgBtqQYwF6KH@B9EfQg9cT5nyBw "Zsh – Try It Online")
Takes possible dice as a strictly descending list of arguments, takes our target die on stdin.
```
D=`<&0` # read in our goal $D
for d; # for every possible die (pre-sorted descending)
for ((i=D;i<=d;i+=D)) # for each multiple of our goal up to the die size
a[1 + d - i]=$d # save the die size to a[1 + num_dead_faces]
<<<${${a}[1]} # output the first non-empty element
```
[Answer]
# [Arturo](https://arturo-lang.io), 32 bytes
```
$[s,n]->[[email protected]](/cdn-cgi/l/email-protection)=>[&%n]
```
[Try it](http://arturo-lang.io/playground?0y88W0)
] |
[Question]
[
Starting with the string `ABC`, consider the result of repeatedly appending the last half of itself to itself (using the larger half if the length is odd).
We get the progression:
```
ABC
ABCBC
ABCBCCBC
ABCBCCBCCCBC
ABCBCCBCCCBCBCCCBC
etc...
```
Let `S` represent the resulting infinite string (or sequence) that results as this procedure is repeated forever.
# Goal
The goal in this code challenge is to find the index of the first occurrence of runs of `C`'s in `S`.
It's easy at first: `C` first occurs at index `2`, `CC` at `4`, `CCC` at `7`, `CCCC` at `26`, but `CCCCC` is all the way at index `27308`! After that my memory runs out.
The winner will be the submission that correctly generates the most run indices (in order, starting at `C`). You can use any sort of algorithm but be sure to explain it if you aren't using basic brute force. The input and output can be in any easy to understand format.
**Important Note:** I do not officially know whether or not `S` actually contains all runs of `C`'s. This question is derived from [this one on the Mathematics Stack Exchange](https://math.stackexchange.com/questions/876937/do-runs-of-every-length-occur-in-this-string), in which the author hasn't found `CCCCCC` either. I'm curious if anyone here can. (That question is in turn based on [my original question on the topic](https://math.stackexchange.com/questions/861836/does-this-sequence-have-any-mathematical-significance).)
If you can prove that not all runs of `C` occur in `S` then you will win automatically since this question will no longer be valid. If no one can prove that nor find `CCCCCC` then the winner will be the person who can get the highest lower bound on the index of `CCCCCC` (or whatever the largest unsolved run is if `CCCCCC` is found).
**Update:** Humongous kudos to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg) and [r.e.s.](https://codegolf.stackexchange.com/users/3440/r-e-s) who have found `CCCCCC` at the astronomical index of 2.124\*10^519. At this rate I can't imagine finding `CCCCCCC` with any method that relies on brute force. Good work guys!
[Answer]
# CCCCCC found at 2.124\*10^519.
Precise index is 2124002227156710537549582070283786072301315855169987260450819829164756027922998360364044010386660076550764749849261595395734745608255162468143483136030403857241667604197146133343367628903022619551535534430377929831860918493875279894519909944379122620704864579366098015086419629439009415947634870592393974557860358412680068086381231577773140182376767811142988329838752964017382641454691037714240414750501535213021638601291385412206075763857490254382670426605045419312312880204888045665938646319068208885093114686859061215
Found by r.e.s., using the (old version of) code below, after 3.5 hours of searching.
Around that index, the string is: `...BCCBCBCCCBCCCCCCBCCB...`
To verify, change the indicated line in the code below to start at 2946, instead of 5. Verification takes 20 seconds.
**Update: Improved program. Old program searched ~10x more locations than necessary.**
New version finds the `CCCCCC` in only 33 minutes.
How the code works: Basically, I only look at the regions which correspond to the ends of incremental strings, and calculate the letters by looking recursively back to the original string. Note that it uses a memo table, which may fill up your memory. Put a cap on the length of the memo table if necessary.
```
import time
import sys
sys.setrecursionlimit(4000)
ULIMIT=4000
end_positions=[]
current_end=2
while len(end_positions)<ULIMIT+3:
end_positions.append(current_end)
next_end=((current_end+1)*3+1)//2-1
current_end=next_end
memo={}
def find_letter(pos):
if pos in memo:
return memo[pos]
if pos<3:
return 'ABC'[pos]
for end_num in range(len(end_positions)-1):
if pos>end_positions[end_num] and pos<=end_positions[end_num+1]:
delta=end_positions[end_num+1]-end_positions[end_num]
if len(memo)>5*10**6:
return find_letter(pos-delta)
memo[pos]=find_letter(pos-delta)
return memo[pos]
time.clock()
for end_num in range(5,ULIMIT+1): # This line.
diff = 1 # Because end_num is guaranteed to be a C
while True:
last_letter=find_letter(end_positions[end_num]+diff)
if not last_letter=='C':
break
diff+=1
if end_num%100==0:
pos_str=str(end_positions[end_num])
print(end_num,'%s.%s*10^%i'%(pos_str[0],pos_str[1:5],len(pos_str)-1),
len(memo),diff,time.clock())
if diff>=6:
print(end_num,end_positions[end_num],diff,time.clock())
```
Current max searched to: 4000 iterations
`CCCCCC` found at iteration(s):
2946
[Answer]
### CCCCCC found at 2.124\*10^519.
The following ruby code was used to search for `CCCCCC`.
```
SEARCH = 6
k = [5,3]
getc=->i{
j=i
k.unshift(k[0]+(k[0]+1)/2)while(k[0]<=j)
k.each_cons(2){|f,g|j-=f-g if j>=g}
"ABC"[j]
}
while true
x=k[0]
x-=1 while getc[x]=="C"
x+=1
l=1
l+=1 while getc[x+l]=="C"
break if l>=SEARCH
end
puts x
puts (x-14..x+l+13).map{|i|getc[i]}*""
```
The index is the same as in [@isaacg](https://codegolf.stackexchange.com/users/20080/isaacg)'s answer.
The runtime of above code for 6 is in the order of ten seconds on my computer. Nevertheless, it is still search for an answer for `CCCCCCC` (if you want to try it yourself set constant `SEARCH` to `7`).
You can use `getc` to find the character at a specific position `i` as it is done in the last line where the string around the index is printed.
[Answer]
(Not an answer, but too long for a comment.)
The following is a Python translation of [@Howard's Ruby program](https://codegolf.stackexchange.com/a/35258/3440) (sped up by a factor near 3 by having only one `getc` in the search loop). On my system, this finds the first C^6 in 3 seconds. In 93 hours, it finds no C^7 in 231,000 iterations, so the first C^7 (if it exists) must occur after the leftmost 10^40677 positions in the infinite string.
```
import time
L = [5, 3] #list grows "backwards" (by insertion on the left)
def getc(i): #return the letter at index i
while L[0] <= i: L.insert(0,L[0] + (L[0] + 1)//2)
for k in range(len(L)-1):
if i >= L[k+1]: i -= L[k] - L[k+1]
return 'abc'[i]
def search(k): #find the first occurrence of c^k
start = time.time()
iter = 0
while True:
iter += 1
if iter % 1000 == 0: print iter, time.time()-start
p = L[0] - 1
l = 1
while getc(p+l)=='c': l += 1
if l == k: break
return p, iter, time.time()-start
k = 6
(indx, iter, extime) = search(k)
print 'run length:', k
print 'index:', indx, ' (',len(str(indx)),'digits )'
print 'iteration count:', iter
print 'neighborhood:', ''.join([getc(i) for i in range(indx-1,indx+k+10)])
print 'execution time:', extime
```
] |
[Question]
[
Today, you're going to be writing Polish. No, not Polish notation—*Polish*, the actual language spoken in Poland.
Given a number and a noun, output a Polish sentence telling me that there are that many of that thing, using the appropriate template below.
The input consists of an integer in the range from 0 to 200, and a string of 1 to 10 lowercase ASCII letters (the "input noun"). You may accept these inputs in any reasonable format.
The output must consist of one of the below output templates, where the number in the template (if any) has been replaced with the input integer, and the word `kot` in the template has been replaced with the input noun.
## Output templates
If the input number is 0, then use the output template
```
Nie ma żadnych kotów.
```
If the input number is 1, then use the output template
```
Jest 1 kot.
```
If the input number ends with 2, 3, or 4, but does **not** end with 12, 13, or 14, then use the output template
```
Są 4 koty.
```
In any other case, use the output template
```
Jest 8 kotów.
```
Note that the special characters used in these templates are:
* ż (in "żadnych") – U+017C Latin small letter Z with dot above (ż)
* ó (in the suffix "-ów") – U+00F3 Latin small letter O with acute (ó)
* ą (in "Są") – U+0105 Latin small letter A with ogonek (ą)
You may output these characters in any reasonably common character encoding (including HTML entities), and you may use combining characters instead of precomposed characters (or even a mixture of the two).
Note that in [ISO-8859-2](https://en.wikipedia.org/wiki/ISO/IEC_8859-2), all ASCII characters as well as the three special characters above are represented with one byte. Therefore, if your program uses no non-ASCII characters besides these three, then you can count each of these three characters as one byte.
## Test cases
```
0 pomidor -> Nie ma żadnych pomidorów.
1 kwiat -> Jest 1 kwiat.
2 dom -> Są 2 domy.
5 wilk -> Jest 5 wilków.
13 komputer -> Jest 13 komputerów.
24 but -> Są 24 buty.
101 kurczak -> Jest 101 kurczaków.
104 wieloryb -> Są 104 wieloryby.
112 post -> Jest 112 postów.
122 balon -> Są 122 balony.
```
## Do plurals in Polish really work that way?
No, plurals in Polish are actually a lot more complicated than this.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in each language wins.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 88 bytes
```
.+
Jest $&ów.
Jest 0
Nie ma żadnych
( 1 .+)...
$1.
Jest (.*(?<!1)[2-4] .+)...
Są $1y.
```
[Try it online!](https://tio.run/##NcyxCsIwFIXh/T7FFYpUiyE31k1wd3BxFIe0DRjaNCVNKXX3iVzd1OeKAXU78H8cp7xuZQgsg73qPSbz531k383hoBUaie@HrNqpvECKhCxbMMYgoZ9K2TLdbWe0OIlVfv7n4@uGCU0sBI6dNbqyDgjrUUsPAitrYIOjbmqgNdbWdINXDkSOxeCBeJSDK68yZp5HpxrrpgKIRDzroxACC9nY9gM "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
Jest $&ów.
```
Assume none of the special cases apply.
```
Jest 0
Nie ma żadnych
```
Fix up if the input was `0`.
```
( 1 .+)...
$1.
```
Fix up if the input was `1`.
```
Jest (.*(?<!1)[2-4] .+)...
Są $1y.
```
Fix up for the `2-4` but not `12-14` endings.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~105~~ ~~92~~ 89 bytes
*-16 thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).*
```
„ówU’Jî• ’V>iXIŽ1}ç’NíÓ íà ÿ‹¤½Áh ’rJë¹iY…ÿ1 ìë¹Ƶ…S©Å¿O¹®T+Å¿O_*i¹Ƶ¡ç"Sÿ ÿ ÿy"ëY¹ðIXJ]'.J
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcO8w5vLQx81zPQ6vO5RwyIFICvMLjPC8@hew9rDy4E8v8NrD09WABILFA7vf9Sw89CSQ3sPN2aAFBZ5HV59aGdm5KOGZYf3GyocXgPiHtsK5AYfWnm49dB@/0M7D60L0QYz47UyQZKHFh5erhR8eL8CGFUqHV4deWjn4Q2eEV6x6npe//8bGphwlWem5uQXVSYBAA "05AB1E – Try It Online") Takes input separated by a newline.
[Answer]
# [Factor](https://factorcode.org), 160 bytes
```
[| n s | n s t n 0 = n 1 = n present R/ .*(?<!1)[234]/ matches? 3array index ?1+
{ "Jest %d %sów.""Nie ma żadnych %sów.""Jest %d %s.""Są %d %sy."} nth sprintf ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVG7TsMwFBVrvoDxYKkSD_WRtEiIhzoiGDpQMVUdXOe2jZrawXbUhtKRr2DpAPwAKxvwEfA1OE2h8XDse3zP0dW5T69DLqzSq5-d3dvuVefyFFxrnhlwY5QwGCo95dZGcoRIYUJaUoxYCR4buI8xEk2GpIWmEc0TGLpLSQoyOPO8hQd3FmiAJWoahUozLDecDzaZRdxumQAsVNNtfQw2i-JJSdJ0GjVNUkslo6AFNkhLPn4j9061uOdlcaOV-1GsdDYo0X6QD2fK-sBRAx4rmXNL7yW1w-rJ93PvARIGBVqHDVw49Nf4F8NNHbXD_fb5nn_QC5qtfj1PSYzJtNFcJ4tIhjRH2z_yFmDXZCwqISrm421WY6wTkRPg652HMhPjf37b54ru52PxzmpsCemWYBIdSTtEfzMr62HNoA_hAlOGin1WiTtTERPXRedqVdy_)
### How?
```
! n = 122, s = "balon"
n ! 122
s ! 122 "balon"
t ! 122 "balon" t
n ! 122 "balon" t 122
0 ! 122 "balon" t 122 0
= ! 122 "balon" t f
n ! 122 "balon" t f 122
1 ! 122 "balon" t f 122 1
= ! 122 "balon" t f f
n ! 122 "balon" t f f 122
present ! 122 "balon" t f f "122"
R/ .*(?<!1)[234]/ ! 122 "balon" t f f "122" R/ .*(?<!1)[234]/
matches? ! 122 "balon" t f f t
3array ! 122 "balon" t { f f t }
index ! 122 "balon" 2
?1+ ! 122 "balon" 3
{ ... } ! 122 "balon" 3 { ... }
nth ! 122 "balon" "Są %d %sy."
sprintf ! "Są 122 balony."
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~109~~ 106 bytes
```
lambda n,s:[['Nie ma żadnych ','Jest %s '%n][n>0]+s+'ów'*(n!=1),f'Są {n} {s}y'][n//10%10!=1<n%10<5]+'.'
```
[Try it online!](https://tio.run/##XY@xboMwEIZ3nuI6RIaGOpgkSxTyAB26dKQZTABhATbCRohGGftEXbu1fS5qAyFRF9v33@/v7q86lQm@7tPgrS9oGcUUuCt3YYheWAIlhd8vGvPulAFy0XMiFSwkoAU/hvzgHZdyib4/W/Ro84eAOG6KXn8@4MwvcJaXDmnTakW8BfF0d8/1vd8elwijvs1YkQDZWcB45YJoVAWBeTfKdrCsCqZsBE8HQI6lFwI5dqeO1qqacWWntjm5ow0OBMHAcXoPKlGyWNQG8D/G1NJbY4tA3jKqjG2INtXY8iEWpZFNnKHosLWFlhX5bB7LkbOGXJR696S@sW7a4PE3EDVqZg6VhhJPD23q0zu9ke@0Ee9t9KykEHUXXQH3msEQXyeTd1EmYQT4PkS0EHz@fRU6/Ac "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-pl056`, 79 bytes in ISO-8859-2
```
/ /;$_=/(?<!1)[234] /?"Są ${_}y":$`?"Jest $_"."ów"x($`>1):"Nie ma żadnych $'ów"
```
[Try it online!](https://tio.run/##XY/NUoMwFEb3fYprytTWGRKgxUVRundGNy4dp01LFAQSJgmD6Lj0idy6U19LDNC/cXlPbs53v4LJzG8UATvEZ4QEMHwqlYaYSQYPQoKOGWxEUZOCKm2QFHnHNDNbG6qYagiQwFpekvHi4sSd3HnT2T2QBbr9fgfrdflWo7m1WqCr9oO1RBh9fVToeWytQncyRzcJg5zCzyeNeL2JwTptn5vAwqE7GilaIxQMc5oy1cVKpspMK2BUJcxcJwyhEVQx4yBLzhP@CLkwt@uYchC8P7RxoBB5Epk@dgj/I7dPJhcPXEirhOp2rTt4O@OBB5FpbnBbqxtqPPChSrJ0v9yPvWcKqciLUjN5cB1Yt@PNYF3qvbObjNR1TGgpNy/0YD5ivd6ZmSyWCVmvd4Jj1mpczzRTR1W2oBd4HqxpJvj@9w7U@FcUOhFcNXaROf55Y1/72HGdPw "Perl 5 – Try It Online")
## Explanation
Match space with `/ /` which stores the number in prematch (`$`` ) and the noun in postmatch (`$'`). Next `$_` (which is automatically output, thanks to `-p`) is set to `"Są ${_}y"` (where `$_` is the implicit input from the implicit `-n` via `-p`) if it matches the regex `/(?<!1)[234] /` (number ends `[234]` but not `1[234]`), otherwise if `$`` is not `0` it's set to `"Jest $_"."ów"x($`>1)`, where the` "ów"`suffix is added if`$'`is greater than`1`, otherwise, finally for the` 0`case it's set to`"Nie ma żadnych $'ów"`.
Thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali) for saving 9 bytes!
[Answer]
# [Python](https://www.python.org), ~~138~~ ~~123~~ 111 bytes
```
lambda n,s:("Nie ma żadnych ",("Jest","Są")[(z:=n//10%10!=1<n%10<5)]+f' {n} ')[n>0]+s+(n!=1)*"óyw"[z::2]+'.'
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZLBbptAFEWl7Myi3_AyUgTEJIGJLVUoZNNdFtl0SVmMw0yDAjOIGeRgy8t-RTaWovYHvO0uzUe0X9MHY5uqq9G793LuY-DlR92ZRyW3ryL58r014uLjb1WyapEzkIGOPXJfcKgYvP9kueweHoEEHrnj2pCAfP71jfipt4oTeXUVhWdReJpENxLPm7mfTYULa7kB10_lbZhN9dST6Pvn5G3XLUm6imOaTd1L19b-OflgEKuT1EnDAEitqiJXDdb8v8HeedstL0kWOGmE6adlwXAlGFaDCIbZ2hTVXFW9iQsDBRw6a81RWxbl0_HBOfTjSL7u0aqqW8ObkX4NB-2YpDN0F605tswAp31NFA4rts3Dio1dqMJeGwvD2bASL1XTLQ4wVOGgHZARHe5I__PSEYVeGGG0zyxYqeSRRCkMgsVkjlANyLYKQJumkF8DaLhuSwOFhOFrxM6kEOA9x4nw-pyN-f5pYoPoT2qUjCfIJ6Y5uGuMbQJY2-TGBcGKkudwAao1eGmgBIaeNy7xnQkvNR8RllAzrXlOfPtbbLf2_As)
[Answer]
# JavaScript (ES6), 113 bytes\*
*\* counting each special letter as 1 byte, as allowed by the challenge*
Expects `(integer)(word)`.
```
n=>w=>[`Jest`,`Są`,`Nie ma żadnych`][i=n<2?n+2:28>>n%10&n*9%98%9!=1,i%3]+` ${n?n+' '+w:w}${[[,'y','ów'][i||2]]}.`
```
[Try it online!](https://tio.run/##bZFBU4JQFIX3/YrbGwlNQt5TZ9QJ2rdo05JhBgSsl/CeAxhD6rJf5LZd9bvoQjqlsGFx7vnuPefx4r16qZ/wVXYjZBCWC7MUppWblu3eh2nmau7j1zt@H3gIsQffH14gCv/ZdWxuilt2J/psxiaWJRRqXInrqTKdKNNLk2pcGTp9FzobgR4V1H4@y3edjW1raqFq6uc@V3HHdsscZ6e7pS9FKqNQj@RTd9EFMHpdspIxD2RCoNeDwQDOIsBhjJv0i3OcIr7MuZcRgANe1QEKtdoEGAKBjCv7EcDiwADFomkfoz3n0ZLA6f4xVGpbJDqsIsl4tc7ChPyPNISj3MaxEXLzddZINgJUG9GoUVdfJ/6btyQn1Q0s/6u33KHGqK4URjIp5uTvDg7gKDevUVb/pzQ7fwicQKW3nWIVNPciKchJJRxALRd6@QM "JavaScript (Node.js) – Try It Online")
### How?
To test whether \$n\$ ends with \$2\$, \$3\$ or \$4\$ and does not end with \$12\$, \$13\$ or \$14\$, we use the expression:
```
28>>n%10&n*9%98%9!=1 // 20 bytes
```
Explanation:
```
28 // the bitmask 0b0000011100
>> n % 10 // right-shifted by n mod 10
& //
n * 9 % 98 % 9 != 1 // this is false for 12, 13, 14, 112, 113, 114
// and true for other values ending with 2, 3, 4
// (for anything else, it doesn't matter)
```
This is somewhat convoluted but shorter than using a test with a regular expression (which would also require ES9+ for the negative lookbehind assertion):
```
/(?<!1)[234]$/.test(n) // 22 bytes
```
[Try it online!](https://tio.run/##NY5BTsMwFET3OcVUAvzdGjdJu2hp0x6iy6oLqw1VqmA7jsUGuAESG5ZwD87TC3CE8L3gL@aP5s1iLubZ9MfQ@Hhv3akehkcXqK0jLCrkK37rCmWe3GQi8ZIBiXqm5QKbDRduUeSK83Qd5xZjLDldLpL8k8DE4w7UYVShkKuMwdHZ3rW1bt2Z9lbBK3QKQaV2hSlt16NC7svZ/HAz1bHuI1mJLcTvz8f165NV4AHi@v0uDvrJeOLRvEhHt4uhsWeS2pvTLpoQaSalvrjGksArhJTZ2zD8AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 73 bytes
```
≡θ0«Nie ma żadnych ηów»¿›№234§θ±¹⁼1§θ±²«Są θ ηy»«Jest θ η¿⁻1θów».
```
[Try it online!](https://tio.run/##S85ILErOT8z5/7@4PLMkOUNBo1BToZorObE4VUHJQMkKyOYMKMrMK9FQ8stMVchNVDi6JzElrxKoUknTGiaXgWAqHd5cDpKp5UpJTUsszSmxUshMU9BwL0pNLEkt0nDOLwUpMjI2UdJRcCzxzEtJrdAo1FHwS00HymsYampq6ii4FpYm5hRrKBliVWOkCQJIDgs@0orsmEIkx@ByZCXYiQqpOUBvIgzySi0uIdokkK98M/NKoe4sBDoJPQRquaAiekD@//@GRkYKSYk5@Xn/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≡θ0«Nie ma żadnych ηów»
```
If the first input (`θ`) is `0`, then print `Nie ma żadnych ηów`, where `η` is the second input.
```
¿›№234§θ±¹⁼1§θ±²«Są θ ηy»
```
If it ends in `2`, `3` or `4` but not `12`, `13` or `14`, then print `Są θ ηy`.
```
«Jest θ η¿⁻1θów»
```
Otherwise print `Jest θ η`, and then print `ów` if the first input is not `1`.
```
.
```
Print the final `.`.
Note that the deverbosifier thinks that `ó` doesn't need to be encoded but it actually takes three bytes to encode. (It calculates the byte count correctly for ż and ą.)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 74 bytes
```
`J½Ḣ Π Π.`¹ċ[Ṫ£234¹tc¹Ṫtċ∧[⁺żC`SΠ Π Πy.`|⁺ċC¹[¥`ΠΠw.`|⁰`Nie ma \ż…ṅƒ꘍ ΠΠw.
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgSsK94biiIM6gIM6gLmDCucSLW+G5qsKjMjM0wrl0Y8K54bmqdMSL4oinW+KBusW8Q2BTzqAgzqAgzqB5LmB84oG6xItDwrlbwqVgzqDOoHcuYHzigbBgTmllIG1hIFxcxbzigKbhuYXGkuqYjSDOoM6gdy4iLCIiLCIxMDRcbndpZWxvcnliIl0=)
## How?
```
`J½Ḣ Π Π.`¹ċ[Ṫ£234¹tc¹Ṫtċ∧[⁺żC`SΠ Π Πy.`|⁺ċC¹[¥`ΠΠw.`|⁰`Nie ma \ż…ṅƒ꘍ ΠΠw.
`J½Ḣ Π Π.` # Push string "Jest {implicit first input} {implicit second input}."
¹ċ # Is the first input not one?
[ # If so:
Ṫ # Remove the last character (the period) from the string
£ # Pop and put it in the register.
234¹tc # Is the last digit of the first input one of 2, 3, 4?...
¹Ṫtċ∧ # ...and is the second last digit of the first input not one?
[ # If so:
⁺żC # Push "ą"
`SΠ Π Πy.` # Push string "S{'ą'} {implicit first input} {implicit second input}y." (which is implicitly output)
| # Otherwise:
⁺ċC # Push "ó"
¹ # Is the first input truthy? (not zero)
[ # If so:
¥`ΠΠw.` # Push string "{register}{'ó'}w." (which is implicitly output)
| # Otherwise (the input is zero):
⁰`Nie ma \ż…ṅƒ꘍ ΠΠw. # Push string "Nie ma żadnych {second input}{'ó'}w." (which is implicitly output)
# All strings and if statements implicitly closed.
# If the first if statement was falsy (aka the input was one), then the string pushed at the beginning will be implicitly output.
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 105 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍺=0:∊'Nie ma żadnych '⍵'ów.'⋄⍺=1:∊'Jest 1 '⍵⋄1 0≡(2 3 4∘+¨0 10)∨/⍤∊¨10 100|⍺:∊'Są'⍺⍵'y.'⋄∊'Jest'⍺⍵'ów.'}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu8vWwOpRR5e6X2aqQm6iwtE9iSl5lckZCuqPereqH95crqf@qLsFpMwQrMwrtbhEwRAsCxQ3VDB41LlQw0jBWMHkUccM7UMrDBQMDTQfdazQf9S7BKj@0ApDkIhBDdAEsP7gI61AvbtAhldCjIYaChMFW1kLAA&f=XZA9DoIwGIZ3T/FtTBIosHoABxdPUKDGBkoJlhDcddO4OHoKVzf1Ij2JbUOxsD7v39fK612ebwHsvJozmvPGA3l5wHIFG0qAYfi@cF712R4G/f3s/IU0qVClio5iMWbW5CAgBAOtCylXztno2X5OgECR3joS5ehoWUxrEtDMnYv0Hmd1K0gzm4zACk4AxSqQtmI6HYNC43YYmFe0TXbEswO0NAjuFUFsziUlb/p0Uq0lK/wHQmQ@9zD/JcU1dauRtqa45NW0V3FDe/8H&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Ironic.
] |
[Question]
[
## Challenge:
Your challenge is to write an interpreter for [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php). Given a string consisting of spaces, tabs, newlines, and potentially other characters, as well as possible inputs for the Whitespace program itself, output the result of the given Whitespace program.
## Here is an overview of the [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php) language and its builtins:
Whitespace is a stack-based language which uses only three characters: spaces (ASCII codepoint 32); tabs (ASCII codepoint 9); and newlines (ASCII codepoint 10); all other characters are ignored.
It only has a couple of basic builtins, which I will go over below. Whitespace has a stack, which can only consist of integers, as well as a heap, which is a map of integers (both the key and value).
From here on out I will be using `S` for spaces, `T` for tabs, and `N` for newlines to make the text more compact.
*Stack Manipulation (always starts with leading `S`):*
* Push a number to the stack: `SS`, followed by either an `S`/`T` for positive/negative respectively, followed by some `S` and/or `T` which is the binary representation of the number (`S=0`; `T=1`), followed by a trailing newline `N`. Some examples:
+ `SSSTN` pushes the number `1`; a positive integer with binary `1`.
+ `SSTTSN` pushes the number `-2`; a negative integer with binary `10`.
+ `SSSTSTSN` pushes the number `10`; a positive integer with binary `1010`.
+ `SSTTTSSTSSN` pushes the number `-100`; a negative integer with binary `1100100`.
+ Pushing number `0` is an edge case, since it can be done in multiple ways. Some examples:
- `SSSN`: push a positive integer without any binary digits.
- `SSTN`: push a negative integer without any binary digits.
- `SSSSN`: push a positive integer with binary `0`.
- `SSTSSSN`: push a negative integer with binary `000`.
* Duplicate the top of the stack: `SNS`.
* Copy the 0-based \$n\$th item from the top of the stack to the top of the stack: `STS` followed by a number similar as mentioned earlier (excluding the leading `SS`). I.e. let's say the stack currently contains the integers `[47,12,0,55]`, then we could use `STSSTSN` to copy the 0-based 2nd item (which is the `12` in this case) to the top. So the stack becomes: `[47,12,0,55,12]`.
+ NOTE: This index may not be negative. On TIO this [would result in a negative index error](https://tio.run/##K8/ILEktLkhMTv3/PzpYAQRDOP244gNKizPiDWPhQsEKMEEjhCBCpTGySoRaE2RhhGpTkDBECCFooJuUWJyaEq9rWFwSD3RUbmw0SBKkKD6gKDOvJL4kvyA@sTgeyExNTy2K/f8fAA), but that same program would push a `0` in [the vii5ard interpreter](http://vii5ard.github.io/whitespace/), and it could even be different in yet another interpreter. For the sake of this challenge, you can therefore assume a given copy will never be negative. So the copy will always start with `STSS`, followed by the binary of the top-to-bottom index, followed by a trailing `N`.
* Swap the top two items on the stack: `SNT`.
* Discard the top item of the stack: `SNN`.
* Discard/slice \$n\$ items from the top of the stack, but keep the top item: `STN`, followed by a number similar as mentioned earlier (excluding the leading `SS`). I.e. let's say the stack currently contains the integers `[1,2,3,4,5,6,7]`, then we could use `STNSTTN` to discard 3 items from the stack (except the top one). So the stack becomes: `[1,2,3,7]`.
+ You can again assume no negative slice values will be used, so this will always start with `STNS`, followed by the amount to slice, followed by a trailing `N`.
*Arithmetic (always starts with leading `TS`):*
* Addition; add the top two items on the stack together: `TSSS`.
* Subtraction; subtract the top item of the stack from the (top-1)th item of the stack: `TSST`.
* Multiplication; multiply the top two items on the stack: `TSSN`.
* Integer division; integer divide the (top-1)th item of the stack by the top item of the stack: `TSTS`. (NOTE: Since Whitespace only has integers, this will always be integer division and never result in decimal values.)
* Modulo; take the modulo of the (top-1)th item of the stack with the top item of the stack: `TSTT`.
+ You can assume no negative values will be used for the modulo.
For each of these two argument builtins the same applies: if none or only a single integer is on the stack, this will result in an error. How you implement this error in your interpreter is up to you, as long as the program stops when this occurs. I thought about not allowing it for the sake of this challenge, but decided not to because it's a commonly used strategy to stop a program with an error when printing hardcoded texts, [using the approach explained in this Whitespace codegolfing tip](https://codegolf.stackexchange.com/a/158232/52210).
*Heap Access (always starts with leading `TT`):*
* Pop the top two items of the stack, and store the top item in the (top-1)th address of the heap: `TTS`. I.e. let's say the stack contains the integers `[1,2,3,4,5]` and the heap already contains `[{2:10}]`. When you use this store builtin twice in a row, the stack would contain `[1]` and the heap will contain `[{2:3},{4:5}]` (note how the `{2:10}` has been replaced with the `{2:3}`).
+ NOTE: Just like with the Arithmetic builtins, if no or a single argument is given, it will cause an error. But for the sake of this challenge you can assume this will never be given for this builtin.
* Pop the top item of the stack, and push the item corresponding with that heap address to the top of the stack: `TTT`. I.e. let's say the stack contains the integers `[1,4]` and the heap contains `[{2:3},{4:5}]`. If you now use the retrieve builtin once, the stack would become `[1,5]` (and the heap will remain the same).
+ NOTE: If you use an address that isn't in the heap yet (or the heap is empty), it will push a `0` to the stack instead. But for the sake of this challenge you can also ignore this.
*Flow Control (always starts with leading `N`):*
* Mark a location in the program with a label: `NSS`, followed by some (optional) `S`/`T` which aren't used by other labels/subroutines, followed by an `N`. I.e. if you're only using a single label in your full program, `NSSN` would be what to use when code-golfing. If you need two or three labels, you can add `NSSSN` and/or `NSSTN`.
+ Although it is possible to have multiple of the same labels in the TIO and vii5args interpreters, it will cause issues, so we assume the input will always only create a label/subroutine once.
+ Also, although `NSSN` would be a logical first label to use, it's completely valid to use a label `NSSTSTSTTTSN` instead as only label in the program.
* Call a subroutine with the given label: `NST`, followed by some (optional) `S`/`T` which aren't used by other labels/subroutines, followed by an `N`. I.e. `NSTTSTSTTTSN` would jump to the label `TSTSTTTS` as subroutine.
* Jump unconditionally to a label: `NSN`, followed by some (optional) `S`/`T`, followed by an `N`. I.e. `NSNN` would jump to the (empty) label `N` and continue the program flow from there.
* Pop the top integer, and jump to a label if it is exactly 0: `NTS`, followed by some (optional) `S`/`T`, followed by an `N`. I.e. if the stack is currently `[4,1,0]` and we'd use `NTSSN`, it would jump to the label `SN` and continue the program flow from there (with stack `[4,1]`). If instead the stack is currently `[4,1]` and we'd use the `NTSSN`, it would jump past it to the next builtin below it (with stack `[4]`).
* Pop the top integer, and jump to a label if it is negative: `NTT`, followed by some (optional) `S`/`T`, followed by an `N`. I.e. if the stack is currently `[4,1,-10]` and we'd use `NTTTN`, it would jump to the label `TN` and continue the program flow from there (with stack `[4,1]`). If instead the stack is currently `[4,1]` and we'd use the `NTTTN`, it would jump past it to the next builtin below it (with stack `[4]`).
+ Minor note: There is no *Jump to label if positive* builtin available in Whitespace.
* End a subroutine, and go back to the caller (a.k.a. return): `NTN`.
* End the entire program: `NNN` (everything after that becomes no-ops).
*I/O (always starts with leading `TN`):*
* Pop the top integer, and print as character with that codepoint to STDOUT: `TNSS`. I.e. if the stack is currently `[10,101]` and we'd call the `TNSS` twice, it will output a lowercase `e` followed by a newline to STDOUT.
* Pop the top integer, and print as integer to STDOUT: `TNST`.
* Pop the top integer, and read a character from STDIN, for which its codepoint-integer will be stored in the heap with the popped integer as address: `TNTS`. I.e. if the stack is `[0,0]`, the heap is empty, and STDIN contains the capital letter `I`, and we'd use `TNTS`. The stack will become `[0]` and the heap `[{0:73}]`. (After which we could use the retrieve builtin `TTT` to put this input on the stack.)
* Pop the top integer, and read an integer from STDIN, which will be stored in the heap with the popped integer as address: `TNTT`.
## Challenge rules:
* You can assume the Whitespace input is always valid with the builtins above. So the compilation phase would always succeed.
* You can assume executing the Whitespace input will never result in any errors, **except when the Arithmetic builtins will only get 0 or 1 stack-arguments instead of the required 2**. Although there are loads of other possible errors when executing a Whitespace program, like negative indices, jumps to labels that doesn't exist, read from STDIN when it's empty, etc. For the sake of this challenge you can assume none of those kind of errors will occur, and the input-program is error-free (except for the Arithmetic builtins).
* You can assume the additional inputs given will be valid as well. So an integer when we want to read an integer or a character / string of multiple characters if we want to read those.
* The Whitespace program-input can be taken in any reasonable format. Could be a string, list of characters, list of codepoint-integers, etc. Same applies to the other inputs.
* Any non-whitespace character in the Whitespace-program input is ignored. You can assume the no-op characters will only be printable ASCII. So the Whitespace input will only contain the UTF-8/ASCII characters with the codepoints [9, 10, 32..126].
* Whitespace numbers can in theory be as large as you want, but for the sake of this challenge you can assume the integers used will be in the range [-9223372036854775808, 9223372036854775807] (signed 64 bit integer).
## 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 with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), 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 (i.e. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
***You should copy the actual test cases from the Try it online links to verify your interpreter.***
```
Input(s):
SSTTSTTTTNSSSTSNSSSTNSTSSTNSSTTSTNSSTTSNSNSSSSTNSTSSTNSSTTSSTTTSNSSTTTSSTTNSSSNSSTTSTNSSTTTNSSSTSNSSTTNSSSTTTNSSSTSNSSTTSSTTTSNSSSTSNSSTTNSSSTTTNSSTTSNSSSTSNSSTTSSTTTSNSSTTTSSTTNSSTTTNSSTTSNSSTTSTNSSTTNSSTTSSTTTSNSSTTNSSSTTTNSSTTSTNSSSNSSTTSTNSSTTSNSNSSSSTNSSTTTTTSNNSSNSSSTTSTTTSNTSSSTNSSNSNN
Builtins used:
Push num; duplicate; copy; add; create label; jump to label; print as char
Output:
Pollinium milk; plump pumpkin; lollipop?
```
[Try it online as actual program using raw spaces, tabs, newlines.](https://tio.run/##rVNdi4JAFH3OX@EfCJxqMdiHiPZpCRPsTeQwawNKloOOLPvr3UYbZ6IvpRAGPPd4zrn3Or9JKljJaczqOgzswN6OtqP2lI9nwa/KBOOZi0XUEGQxsFVhAq5hBRLkEpS8M7zK@R9IKRRbuXT6H0jNSodPkEncswIbXxXP0pgK1sG9bTNTXLVn2LhzNEPQNE3UGQk@lasCHRz7dGTgU@wfDvKCTHDQZLPionqq0qPT92S4vbNXsz3dwr3B3ovzeEXX/Q7IOXhYt1IM/qteuyf6ll8oTR34USiFGnBVMKm0pj8sw3qz8c32rmdDiBOF7dhOSZa7nXxrxeAX6VGAlogTWrQWnnX68Ls6cIjc9Kjrfw)
[See this Whitespace answer of mine for an explanation.](https://codegolf.stackexchange.com/a/157709/52210)
```
Input(s):
SSTTSNSNSTSSNTNST
Builtins used:
Push num; duplicate; multiply; print as int
Output:
4
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##K8/ILEktLkhMTv3/PzpYIVghhDOEM1jBjys@oLQ4I17XKDYaxAtWiHcpLcjJTE4sSY2NBqkAq8ktzSnJLMipBAmBFIVwxgcUZeaVxCcWxwOp1PTUotj//wE)
```
Input(s):
SSTTNTNSTNNNTSNTNTSSS
Builtins used:
Push num; print as int; stop program; (no-ops)
Output:
-1
```
[Try it online as actual program using raw spaces, tabs, newlines.](https://tio.run/##K8/ILEktLkhMTv3/X0GBk5OLk0uBk4uLi1MByOJUUFD4/x8A)
[See this Whitespace answer of mine for an explanation.](https://codegolf.stackexchange.com/a/192993/52210)
```
Input(s):
SSSNSNSSNSTNTTTTTNSSNSNSTNSTSSSTSTSNTNSSSNTSSSTNTSSSSTSSTNSTSSTNSNSSSSTSSNTSTTSNSNTSSNSSSTNTSSTSNSNTSTNSSSTNTSSTNTSSSNSNTSTSSTNTSSTNSNNNSSSNSNNTSTSSTSSTSNSTSSTSNTSTTNTSNNNNNSSTNSNNTSSNNSNNNSSSSNTSSSNSNN
21
Builtins used:
Push num; duplicate; swap; copy; discard; add; subtract; multiply; divide; modulo; retrieve; create label; jump to label; jump to label if 0; stop program; read as int; print as char; print as int
Output:
21
21
23
20
5
25
31
24
3
27
37
26
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##jVPvboIwEP@MT@EjqNsLGOsHFlAy2JLFmEulnTZBINDKfHrWa0U0FrcQPtDr/f7d0RyE5HVJU962m3iMz2oEkaoPMNlu8CMeA1FlJlIq@dBZ4q1GiZd48M4pgzgh/gpoDSKXfM8rrF@qshL8xHWhVHK7QSDDt6g4IgV0xzMI1uvIQSOL0hLFYw0VVRr8jsOKTzz7diamE8h5k4mcd80a9NqcHmhFU2nb0QLEDS2RCmRT9JhXNASxhzBnDC/Yb3NlUZRnmOUMdKTHv2oud72F3sCrpTT5hQVTWTHUjfovnf43TOBNHdHKJVXif/pk@cQSmlc7iXk8ZzC9DobwI0j8KPj6L0end0jxnJDBsQwn6yRCFH31im82zC7D4/71SZkmIuqUVqzbP8utT0@C8VspFgjFvDhWwFV9mKtNxJ1Gp9loWv4Iqbe42Ff02BmxYdwauR2I24ohC1UmRZmdXUHdUdu4HgMzg7r/L54hte1s@gs)
[See this Whitespace answer of mine for an explanation.](https://codegolf.stackexchange.com/a/193850/52210)
```
Input(s):
NSSNSSSNSNSTNTSTTTSNSSSSTSTSNTSSTNTSSNSSSNSNSTNTSTTTTSSTNTSNSSSNTNSTNSSSN
TThhiiss iiss ddoouubblee ssppeeaakk!!\n
Builtins used:
Push num; duplicate; subtract; retrieve; create label; jump to label if 0; read as char; read as int
Output:
0
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##tVHLDoIwEDzLV9Q/wG9QDxqDRHowIWSzwGobUZo@9PORLXpSj6Zpm8xMZ3a7D6U9OYMNDUOZJYUoRJbA0hJ6gh3W1MFuv8@rkpnI5cEpSBlgOayC6XTD6hGTsyyRsxE9ELagbyZ4QAeNQouNJ8sKXiPvraY7fbGJr955bMb7nbuIIRMDRag9@1bllBplmxOksA1XA75/NbA@buT/GvhZzvdifvwmB0eX3OpbzBwvOnPiNJXPucS2hkFKpbR2TojpbNu@D6GuOyIhnDOGCPFymc@TJw)
[See this Whitespace answer of mine for an explanation.](https://codegolf.stackexchange.com/a/189381/52210)
```
Inputs(s):
SSSNSNSTNTTTTTSSSNSNSTNTTTTTTSSSTNST
-3
5
Builtins used:
Push num; duplicate; add; retrieve; read as int; print as int
Output:
2
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##K8/ILEktLkhMTv3/PzpYAQT9uOIDSosz4g1io0GcYIV4l9KCnMzkxJLU2OgQTj@uEM4Qzvig1MSU@OAQF0@/@MTi@My8ktT01CKQPFS2pCgztSw1liZmhnBCTI13TEmBaA9WACoIKAJqQdb5/7@uMZcpAA)
[See this Whitespace answer of mine for an explanation.](https://codegolf.stackexchange.com/a/157996/52210)
```
Input(s):
SSSTSSSTTTTTSSSSSSSTTSSSTSTTTTTSSTTSNTNST
Builtins used:
Push num; print as int
Output:
4815162342
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##K8/ILEktLkhMTv3/PzpYAQRDOGE0DEL4MIgQAdGoqiC0H1d8QGlxRryJhaGpoZmRsYlRbHQIpx8XSD4@oCgzryQ@rzQ3KbUo9v9/AA)
[See this Whitespace answer of mine for an explanation.](https://codegolf.stackexchange.com/a/175317/52210)
```
Input(s):
SSSTTTNTNTSSSSTSSSSTNSSSTSTSNNSSTTNSSSTNTSSTSNSNTTSNSTSSTNSNTNSNTTNNSSSNSSSTTTNTTTSTNSSSTSTNTNSTSSSTSNNSSTNSNTSNNSNTTNSSSSSTSNTSTSSNSNTSSSNNSNTNNSSSSNNNN
„Äπ
Builtins used:
Push num; duplicate; swap; discard; copy; slice; retrieve; create label; jump to label; jump to label if 0; jump to label if negative; exit program; read as char; print as char; print as int
Output:
12345!!
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##dVJLboMwEF0np0gPUClpVHXVRRWyoIoIillUitDIgSmxmoBlTNLueq2epwehHhxDPlQWAux5n5nn41ZoLCVPsK7XbEQrGtAKhhBW5Rae4jX9RAM2ghXyFFjk@QHwEpItVzzRqOIWaN/05eDTKdydn9PjzvLnyTheB0MnavZnCrlGWPAN7mCxXIYd1qEmZMhuAas2mjyALiToY0HVxAdeJZGoibYR9N8hxwxeq70pLE4CbOHP5vASeBCu/CAitKMmL4X8gvH9hpeYwqTUbS9EC@zIZSdLolbNAC9FbBe2y8bKRY89Fv7JgJZJQCuBBwSRy0pbw47ajtdg2E4kCI/wgShFnpFLG2Izs1CJXFN@5oXZZXpO8KGL5dpwa7NnCrRp6j1RJlylVre30JnuzPRepjM77u4Y8oNIsSfodr4m6nGbwfzNj7p4bsI5deNGeJuPwzeNzT@FNpaLTPF9XNe/3z9/)
```
Inputs(s):
SSSTTNSNSSNSSNSTTSSSSTTTNTTSNSTNTNSSNNNSSTNNSSNTTTNTNSSTN
Builtins used:
Push num; duplicate; store; retrieve; call subroutine; return; exit program; print as char; (no-ops)
Output:
(character with unicode value 7)
```
[Try it online as actual program using spaces, tabs, newlines, and comments.](https://tio.run/##hY5BCsIwEEXX7Sl6AUFw4QGqgptYTF1JGWIZbKAmYZqot4@ZdlERivzVn5n3/7w67XFwqsUYr7Jg1VmdiRyqMHSwadJQ5LKAXXD43zKbrPSWsPnKmxO3v0fMj@tS9T3IcCMbvDYIh4so6@NJMMBHCalIGw9qgLZTxCgL9m/twZG9k3pMpXPdGoxdWTfV8LNQEiqPS0UsOKMnjc/xuTEqDQKZpewYPw)
[Answer]
# [Vim](https://www.vim.org), 2366 bytes
```
:let@z=''
:%s/\S//eg
:%s/ /S/&
:%s/ /T/&
:%s/\n/N/&
$xo"Zyl:if"<C-v><C-r>z"=="SS"||"<C-v><C-r>z"=="STS"||"<C-v><C-r>z"=="STN"||"<C-v><C-r>z"=="NST"||"<C-v><C-r>z"=="NSN"||"<C-v><C-r>z"=="NTS"||"<C-v><C-r>z"=="NTT"<C-v>
norm fN<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="SNS"||"<C-v><C-r>z"=="SNT"||"<C-v><C-r>z"=="SNN"||"<C-v><C-r>z"=="TSSS"||"<C-v><C-r>z"=="TSST"||"<C-v><C-r>z"=="TSSN"||"<C-v><C-r>z"=="TSTS"||"<C-v><C-r>z"=="TSTT"||"<C-v><C-r>z"=="TTS"||"<C-v><C-r>z"=="TTT"||"<C-v><C-r>z"=="NTN"||"<C-v><C-r>z"=="TNSS"||"<C-v><C-r>z"=="TNST"||"<C-v><C-r>z"=="TNTS"||"<C-v><C-r>z"=="TNTT"||"<C-v><C-r>z"=="NNN"<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NSS"<C-v>
norm hhxxrmfN<C-v>
let@z=''<C-v>
en<C-v>
l@t<Esc>^"tC"Zyl:if"<C-v><C-r>z"=="SS"<C-v>
norm @a<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="STS"<C-v>
norm @b<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="STN"<C-v>
norm @c<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="SNS"<C-v>
norm @d<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="SNT"<C-v>
norm @e<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="SNN"<C-v>
norm @f<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TSSS"<C-v>
norm @g<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TSST"<C-v>
norm @h<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TSSN"<C-v>
norm @i<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TSTS"<C-v>
norm @j<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TSTT"<C-v>
norm @k<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TTS"<C-v>
norm @l<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TTT"<C-v>
norm @m<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NST"<C-v>
norm @o<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NSN"<C-v>
norm @p<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NTS"<C-v>
norm @q<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NTT"<C-v>
norm @r<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NTN"<C-v>
norm @s<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TNSS"<C-v>
norm @u<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TNST"<C-v>
norm @v<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TNTS"<C-v>
norm @w<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="TNTT"<C-v>
norm @x<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="m"<C-v>
norm fNl<C-v>
let@z=''<C-v>
elsei"<C-v><C-r>z"=="NNN"<C-v>
k<C-v>
el<C-v>
norm l<C-v>
en<C-v>
@n<Esc>^"nClylmc'sO<C-v><Esc>p:s/T/-/e<C-v>
:s/S/+/e<C-v>
"9xms`cytN'sp^x@y^"9PC<C-v><C-r>=<C-v><C-r>"<C-v>
<C-v><Esc>ms`cfNl<Esc>^"aCllytNmc'sO<C-v><Esc>p@y<C-v><C-a>^Dms@"jy$'spms`cfNl<Esc>^"bCllytNmc'so<C-v><Esc>p@y^DJ@"dd`cfNl<Esc>^"cCmc'sy$O<C-v><C-r>"<C-v><Esc>ms`cl<Esc>^"dCmc'sddpkms`cl<Esc>^"eCmc'sddms`cl<Esc>^"fCmc'sy$ddmsC<C-v><C-r>=<C-v><C-r>0+<C-v><C-r>"<C-v>
<C-v><Esc>`cl<Esc>^"gCmc'sy$ddmsC<C-v><C-r>=-<C-v><C-r>0+<C-v><C-r>"<C-v>
<C-v><Esc>`cl<Esc>^"hCmc'sy$ddmsC<C-v><C-r>=<C-v><C-r>"*<C-v><C-r>0<C-v>
<C-v><Esc>`cl<Esc>^"iCmc'sy$ddmsC<C-v><C-r>=<C-v><C-r>"/<C-v><C-r>0<C-v>
<C-v><Esc>`cl<Esc>^"jCmc'sy$ddmsC<C-v><C-r>=<C-v><C-r>"%<C-v><C-r>0<C-v>
<C-v><Esc>`cl<Esc>^"kCmc'sy$ddDJms'h:s/ <C-v><C-r>"(\d*)//eg<C-v>
A <C-v><C-r>"(<C-v><C-r>0)<C-v><Esc>`cl<Esc>^"lCmc'sy$'h/ <C-v><C-r>"(<C-v>
%yT('sC<C-v><C-r>0<C-v><Esc>`cl<Esc>^"mCfN:let@9=col('.')+1<C-v>
vTNy/m<C-v><C-r>"<C-v>
fNlmc'xO<C-v><Esc>"9pmx`c<Esc>^"oCfNvTNy/m<C-v><C-r>"<C-v>
fNl<Esc>^"pCmc'sDJ`c:if<C-v><C-r>"==0<C-v>
norm fNvTNlly/m<C-v><C-v><C-v><C-r>"<C-v><C-v><C-v>
fNl<C-v>
el<C-v>
norm fNl<C-v>
en<C-v>
<Esc>^"qC
mc'sDJ`c:if<C-v><C-r>"<0<C-v>
norm fNvTNlly/m<C-v><C-v><C-v><C-r>"<C-v><C-v><C-v>
fNl<C-v>
el<C-v>
norm fNl<C-v>
en<C-v>
<Esc>^"rCmc'xDJmx`c@"|<Esc>^"sCmc'sDJms`oA<C-v><C-r>=nr2char(<C-v><C-r>-)<C-v>
<C-v><Esc>mo`cl<Esc>^"uCmc'sDJms`o$"-pmo`cl<Esc>^"vCmc'iDJ'sO<C-v><C-r>=char2nr('<C-v><C-r>"')<C-v>
<C-v><Esc>ms`c@l<Esc>^"wCmc'iDJ'sO<C-v><C-r>"<C-v><Esc>ms`c@l<Esc>^"xC0i0<C-v><Esc>y$@=len("<C-v><C-r>"")<C-v>
I(<C-v><Esc>^x:s/S/*2)/eg<C-v>
:s/T/*2+1)/&<C-v>
^C<C-v><C-r>=<C-v><C-r>"<C-v>
<C-v><Esc><Esc>^"yDo<Esc>mxo
Stack:
<Esc>mso
Heap:
<Esc>mho
Input:
<Esc>mio
Output:
<Esc>mo:let@z=''
```
[Try it online!](https://tio.run/##rZbPb9pIFMe1x/iYgy9c0IjUkIg10F1lwy6qI3PYosog2adNwoTYBjv4V7FJ7Sr/e/aNfzAzpXaT7SpKNO/N533fj5mBPL28jD07Ub5OJEkYn8XyrS7L9iZftmVdfpevTmSjXN0GsgbLThqifzJv7K6RePoVTSZI19Hz88EweEtjLE03OIvb4@I0w0CiEIQ7v73WRKEqUxRsL7bdg7rG5dIMzmLVDZ0rEkyDN3nY4GGDg/lNbk/j2jU0PinfvsF3bGi8EpRf2zfRLafjOGm687@ZUQCWkrSWKFGPj6oMVFb1YzUo9dBAaQfKbDyiirIaqMNxK3YDRTOua6n8qCts04TRnE4TRpO6DRgzs8cmjCbd1mOMmNdAUS2/4a5QKmygaJdRPcXU9bmBohl3DRTNGNf3yFx1Zd@E0ZxPDRjTwJcmjKqltZhPP6HqD6l4x1viLWmveKBKAO8zUL3M800pnoutaBzDR21fhvsPK12@ICt0lfrxvZklmhRHy1TJluhqoYqnE/EUZMUW2YT0ILVSPQ@wSkzJxF@WUz9W0GPWgVgKPlAwzMHldKYgy6r2TZVsZZ05SZEnIF4r91pWtK08dump7HUZRzxFhYOLssoC2HwD9I8I50gCnQNEAfcYkDng8Rg444DtAZjO/FhyYNRtgLq31nmPfPuJwnVuQ1CvivHKGMkpWFE4y4yuRBIMKsZX11r@bXo1MUOvK/0q9S6GovBkaJns503CdEEmhcNBV5Gf3psQFUIUj4AzytNNZ/cmfHCDfzIZHC4awHB6gIskQMxDmLtVWHC7QOazKvA6f/0nmR2pJoVhQcUKegZPXNYHBx9ew4yD3ch0VjsYWb@X38mwGMme4TqoH1X@J@J3pzNyUU8nJHQU7LoSVCL1qjutEPALCyJmI1UHLkw@6ygTzw668NYQgtCPXbG1TPPHcz7q5YeZv6nz0cWwJ78ThSXzckAmm4YtPw0FPVmZ27EA@qHwt72KyNIJhY9BtE/I2g2F@T4pjZD@z/Sy2SgJ/AYvN3pbbxsnxknxl/xoAl7sYwf3f7vEH@5ygGzq7WpjhCPqrpxDHBIn4Uq3GkYZHsZJRVdZDvq/Y5fdOfhH2CN@TdDbeLqPPNdcJfbB/eq0HitetcekufwDx9HKtClGQVrjEP9ZZa2cAxy8piPG/x5vGwfJwUPsU5jducT7H6q8otP/p4bvn9nP1vbDU6gbbF05zUd03O8b6nzzsL5XxZtv1c@9E/rKOaX3A7y4uyFCuVPd2UTp0@rB9vCn@XzBtnc8m@FwcHdTjA0qubYsYhVieLFzgwSvYkw@LYsUmgCBs70f4SRkc/wL "V (vim) – Try It Online")
I sure do love me a thicc Vim program.
This program replaces all of the spaces, tabs, and newlines with the letters `STN`. This is only necessary for the newlines, because Vim is primarily a text editor and treats them differently, but it does it to each character for consistency. It then takes each Whitespace command and puts it into its own macro. [Here's a list of all of the macros, and what command they map to.](https://gist.github.com/AMiller42/8c887e9921b7fc53e31fd4f3f2ff6470) After creating all of the macros, it goes through a compilation phase, followed by an execution phase.
The compilation phase goes through the program, and for every `NSS` command, it replaces the `NSS` with an `m`, to be able to easily jump to it later.
The execution phase collects characters into the `"z` register, and once the register matches a command, the macro for that command is executed, and the `"z` register is cleared.
The stack is simply a bunch of lines containing a number, with the top of the stack having the label `s`. When we want to access the top of the stack, we just jump to the label, then we can use the `c` label to jump back to the code.
The heap is a line that stores many values in the form `key(value)`. To set a value, the program deletes the matching key/value pair if it exists, then adds the key/value to the end of the heap. To get the value, it just does `/ key(`, which finds the key, then it uses `%yT(` to copy only the value.
Input can be passed to the program by adding ``ii<input>` to the beginning of the footer. Each value must be on a separate line to work: [Try it online!](https://tio.run/##tZbLT@MwEIe1x/rIIZdeKquQFtRNYbWHVhspqD0sHAza@LRAH5ukTWheJGlJEP87O86jjqmaw0orhOSZ@eY347HddvfxMXatRHtTZRmNT2PlUVcUa50vO4qunOWrlkLL1aOvEFh20wD/ztyxs8LSyRtWVazr@P19b1DRIjWL6FSwhJiQRyjFEvKDyOusiISqNiVkubHl7NWJUItQwaqrU11oEkwqmiJMRZgKsBgUYkTYLiViUXH7VNwxJaIStH9030y3nI5tp2nkfZqRD5aWtGc4mRweVZmoLY@PlXLqTwNF9pTReEQVZTZQ@@PWrAaKV1wdpfKjrrB1E8Zr2k0YL@o0YLWZPTdhvOjmOFYTcxsoruU13BVOBQ0U32V4nKr19dJA8YpRA8Urxsf3WLvq2rYJ4zV3DVhtA69NGFdLj2Ie/4Q6fkjFO94wb0m7xQPVfHif/sTNXM@Q4zupHY5j@KgdKHD/YaUrF2yFR6kXL4wsIXIczlItm@HR/UQ6UaUTkJXaLAjlQWo5cV3AKjEtk77Mpl6s4eesC7kc/MPBIAdn01sNm2YVNyYslHXvWIm8APOaudc0w03lsUpPZa/KPOYpOhxelF0WwPoTMDgg7AMJfA4QB5xDQBGA50PgVAA2e2B668WyDaPuANR7NM/77NtPQte5DUn9Ksctc2S7YCV0mtGezAoMK8abrEj@bTpSjcDtyV/l/sWlhHaUZIqXbxKmCzIpHA4ehV66MCArgCwRAWeYl5veLgz44Aa/qg73Fw1gOD3AJZYg5Sm1u1VYcLtA5mWCRJ0f/yQTsW5SGBZ0rOF38MRlf3DwwTXM2I@uDHsZwcgG/fxOBsVItjWuiwdh5d8xvzO9ZRf1RGWpV37Uk6ETuV/daY2Br3UQ1wLpZOjA5LOuprqW34O3hjGk3vSk9izNH8/5VT8/zPxNnV9dXPaVMwnNai8HZLJp0PbSAOnJ0tiMEegH6Ke1DNnSDtCNH24TtnYCdLdNSiPgv5k@Fo4z@Ia@t9F6rSXw73886B32R9D8fhvb8@HTAzP0zny6DV3HWCbW0wNtEURbtDX/ZS3NuU6nN2S@jOeOn1hrK2LxMppEjrWznv6LJm0VqvNr0yzS9Q4A9xGk1DP/Ag "V (vim) – Try It Online") The `gg@tgg@n` at the end of the footer compiles and runs the program. To view only the output of the Whitespace program, add ``idH` to the end of the footer.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~ 608 597 586 ~~ 551 bytes
Takes input as `(source)(input)`, where *input* is an array containing single characters and/or integers.
```
s=>I=>eval([..."@CDEJKLMNQTUWYZ^_bkmqw"].reduce((s,c)=>(a=s.split(c)).join(a.pop()),"(R=X=>(H={},o=P=[],S=[],z=x=p=i=0,gUs[p]?~(j=` \n`.indexOf(s[p++]N?j:gK:3,hUgK<2?Mn*2+j):V=n,GUx=z--&&S.pop(y=x),FUg(x=`mbQQ$mS[z+~(b])TSCce((z-=V=b-1,V)$mkJLmyJkTTLH[x]=y$mHD)qR[M1)]=_?R[P@p),V]:_Y_&!kY_&k<0Yp$E?P.popK:pT$^QQQQQqW+yw-yw*yw/y|0w%yN:^QTTo+=Buffer(D)$o+=k$Z.codePointAtKZ`Ct`$`[n-9],x&&eval(x,n=1N<3&&F(n*3+jN(1N(0)||R(1)||owN:^$WqTT$mz=S@kGKbgK?-M0):M0N_p$M1),E^E?g:pZ$HD=I[i++]Y?R[V]:Wz>1?(LmxU=n=>T$$QqqN))Mh(Lk,k,K()J),mx)$Ep=XD[k][[email protected]](/cdn-cgi/l/email-protection)"))
```
[Try it online!](https://tio.run/##bVR/V9pIFP17/RQxm6UzJkTQs38sdcBdobUCs2IGrcYoEAJCIAkklEBtT79WP89@EHd@gYDlwGTy5r773rt3DsP2l3bsTgdRkg3CrvfSQy8xKn5CRe9LewRs0zTV07Ny5aJaq@MGad7c3j08dvzxZK465tTrzlwPgNhwISqCNorNOBoNEuBCaA7DQQDaZhRGAEJDBVfoM8Wco6/fjBBdItsxLLYsUYoiNEA5o9@M7cgpfQdD1FJ@uw9a5iDoeum/PUDjuu7g0rDQrxaOjadmv3pyVKoHB0f6EBauUWB8bKZomc1mMhYvuEApND40@yBFrXGn0dDGlr3Uv4OOA4l1xlpeZtE16mTzxjXUxv5Fbby48Ampndupgxba@LwMJ1d2PQ8d9Fi6si9PI2hcO4XH28fMvk8X/yR3G2mV0iUrVy1ERHtosM/kRl/Ms4v5wWJ@uHjOzf9Y4MJDg5BQR//Mej1vCspQoy@@dme6VO5LKlLyd1K9a50lLa1lB9m/HCPNZLj4qRGgPD45zmQ@gODgWB9ikMcgB5@fr0CeruGckms3E0K08RJZp/7HaqdfLWXrOVio5/BjpNEBjMpDpdQvRHfaeRl9sgdUyFs6ER3mZlnMl0BtnDZRgIpE0xqTCYaw/gRqvuEbVQAvoDFOoVaJ0Oey7Ttn3N1TM5rFdRXCl2SqICVWUFGJ6VWIRm0q7KF52DcUlwVV5T64T1RbtTBR11660IF7iRcnNBcwCQxlEESzBLKUr4obBnE48sxR2AfvCIO57dhTfn@n6Iquu0EC329heiCZchoIgeChgG97FEj5c@/3eCmgWhYh9EsItujW4iumG7byI/HA/GT7iKVZWDwsQbCZ88oot1uRdfZbyHb8F2U2Yetyu@AtvjfNbQzEp6cBbImyRHAQeUqBWDUUW5ojFWPpFIGZIG9OeRRjzFg4zw5CFGcYIpXndJyR/ngaQ4kWCO9zQ3ssA5jITojsnG1kgLwGOIEIrkN0JqEIlmGRKB6Ej8AgDEQEiOkjkqwVIZflKL8eTAooZiFrf@VEsvYOQobFuFj6xHjZ3yshT0@DQRwrili73TCczTqdkecpShxHkee1276/v38fqLvySm2336Sn3LHssaH8uZlFrNVVEB8i3ZBdkl@aza/Yq0eWFN4S94mQHV9WImNORt@lDZJndVPZY30dVibwHRaUK5@kscIdIu3Bwhn1vx8/1e1W5b1jTYhmeVGhD7Ys6TfbibHYmxj45X8 "JavaScript (Node.js) – Try It Online") (all test cases without comments)
[Try it online!](https://tio.run/##jVRrc6JIFP3s/IpsirW6I7KazJe10pqsOBMfEBU0Y1jSIrQGkYc8IjjZ@evZBmIeFc0uFl3Vffuec8@5F5fagxbovumFZcc1yNMcPQWo3kZ18qCtgMJx3PFFk291uj1BHMijm8ntHZ5Z9npzrHI@MSKdABCwOkR1oKGAC7yVGQIdQm7pmg7QOM/1AITsMRiiH/TOFfr5D@uiPlJUVkqXLYqRh0xUYRejQPHUxi@wRNOjwt/OlDMdg8TXc0DPSyVVbCxri27tjL0fLbrnpw3BOTktLWFtjBz2@yhG23K5WJQywgTFkP02WoAYTe3ZYMDYkrIt/QIzFcpSMy15W0ZjNCtX2TFkbKvTs5OOJcu9KyVWUcLYVzxcDxWhClWEG0Olf@FBdqzW8AQXf7PoYp1XJh7TavRTum7Nk5m7Qfqsb0rJppxsTpLNH8ljZfN7ItbuBrLsltBf0XxOfMBDhm4s5pbTqd19alJ4GXZvp81wykwVp/ynysbFYmZ@zDqoKp6fFYvfgHNyVlqKoCqCCnx8HIIqXd0NBWdu1rLM2FskXVjfu7NFt1EWKrAmVETsMVQA27prNRY175a54lFbMamRE6qIirnZ1qsN0LPjEXJQXWaYwXotQijcg57FWmwXwA5k7RgyLQ/94BVLbWbdveC8KBCOIXzSXSdwV4RbuQswB1NFOkp/4hfcj4J7XFGVdCMdYT6iaboWkkNnckH8IhfkAh4SzcCSzLdFrAWYWkMWxE/jz9HQN8kDoQEvClUlBcr4mj5JkXrajKxw7/q6v4cmdL2cSDqiUH2fgr/jyIuXC/m7E1GtYIdsVqZDdskU9CVZv9d8TQ/z9FQCljaal1LhcOO@Yr6gpSD5Ib40jPRCvs@uNF0vwaeOgc2Q2P8V26fuVcKrgK85Zeaf4BrRyj2Undb/nNme4wruRHYq5dlVvj1u861PJKXio1mY@vE5Q5a7h0EY9eR2vzf5vxy7eg9VfMnzB9ty2Nm9RCkKvfqCn01YPgwf5@/VqSyJNwNd843d/OXc9PTBNMjbUnKgtJizPSOwL/qhr7kj@93Y1ZzV1IrNkE6xu/A1eyckN@OtkLcN2S8lIxOiVWh6q2SfUe@oc7s@GpY16v138RnSFALltKrS/59/AQ "JavaScript (Node.js) – Try It Online") (an example with a commented source code as input)
### How?
Because the code is packed with [RegPack](https://siorki.github.io/regPack.html), it is more efficient to repeat the same pieces of code over and over rather than defining too many helper functions.
The sequences of spaces, tabs and linefeeds are converted to an integer in base 3 with a leading \$1\$ until they match a known value:
```
seq. | mnemonic | base 3 | decimal
------+----------+--------+---------
SS | PSH | 100 | 9
STS | CPY | 1010 | 30
STN | SLI | 1012 | 32
SNS | DUP | 1020 | 33
SNT | SWP | 1021 | 34
SNN | DIS | 1022 | 35
------+----------+--------+---------
TTS | PUT | 1110 | 39
TTT | GET | 1111 | 40
------+----------+--------+---------
NSS | LBL | 1200 | 45
NST | JSR | 1201 | 46
NSN | JMP | 1202 | 47
NTS | JZE | 1210 | 48
NTT | JMI | 1211 | 49
NTN | RTN | 1212 | 50
NNN | END | 1222 | 53
------+----------+--------+---------
TSSS | ADD | 11000 | 108
TSST | SUB | 11001 | 109
TSSN | MUL | 11002 | 110
TSTS | DIV | 11010 | 111
TSTT | MOD | 11011 | 112
------+----------+--------+---------
TNSS | CHR | 11200 | 126
TNST | INT | 11201 | 127
TNTS | RCH | 11210 | 129
TNTT | RNU | 11211 | 130
```
The commands are simply stored in a lookup table and executed with `eval()`.
Everything is wrapped within the function \$R\$ which is called twice:
* First pass (\$X=0\$): the jumps and the stack errors are ignored so that the whole code is parsed linearly and all labels are stored
* Second pass (\$X=1\$): the code is executed normally
### Unpacked and formatted
```
s => I => (
R = X => (
H = {},
o = P = [],
S = [],
z = x = p = i = 0,
g = n => s[p] ? ~(j = ` \t\n`.indexOf(s[p++])) ? j : g() : 3,
h = n => g() < 2 ? h(n * 2 + j) : V = n,
G = n => x = z-- && S.pop(y = x),
F = n => g(
x = [
/* PSH */ "z=S.push(g()?-h(0):h(0))",,,,,,,,,,,,,,,,,,,,,
/* CPY */ "z=S.push(S[z+~(g()?-h(0):h(0))])",,
/* SLI */ "S.splice((z-=V=g()?-h(0):h(0))-1,V)",
/* DUP */ "z=S.push(G()),z=S.push(x)",
/* SWP */ "G(),G(),z=S.push(y),z=S.push(x)",
/* DIS */ "G()",,,,
/* PUT */ "G(),G(),H[x]=y",
/* GET */ "z=S.push(H[G()])",,,,,
/* LBL */ "R[h(1)]=p",
/* JSR */ "h(1),p=X?R[P.push(p),V]:p",
/* JMP */ "h(1),p=X?R[V]:p",
/* JZE */ "h(1),p=X&!G()?R[V]:p",
/* JMI */ "h(1),p=X&G()<0?R[V]:p",
/* RTN */ "p=X?P.pop():p",,,
/* END */ "p=X?g:p",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
/* ADD */ "z>1?(G(),G(),z=S.push(x+y)):p=X?g:p",
/* SUB */ "z>1?(G(),G(),z=S.push(x-y)):p=X?g:p",
/* MUL */ "z>1?(G(),G(),z=S.push(x*y)):p=X?g:p",
/* DIV */ "z>1?(G(),G(),z=S.push(x/y|0)):p=X?g:p",
/* MOD */ "z>1?(G(),G(),z=S.push(x%y)):p=X?g:p",,,,,,,,,,,,,,
/* CHR */ "o+=Buffer([G()])",
/* INT */ "o+=G()",,
/* RCH */ "H[G()]=I[i++].codePointAt()",
/* RNU */ "H[G()]=I[i++]"
][n - 9],
x && eval(x, n = 1)
) < 3 && F(n * 3 + j)
)(1)
)(0) || R(1) || o
```
[Answer]
# [Pip Classic](https://github.com/dloscutoff/pip/releases/tag/v0.18), ~~441~~ ~~399~~ 377 bytes
```
,:mn:@>gs:lt:v**@_*FBTM_a:(Ja@wTR"
"012`(00|01.|20.|21[01]).*?2|1[02]..|...`)M{!a@<2?"lPU(t".a@>2.')a@<3=10?"lPUl@(t".a@>3.')a@<3=12?"l:@lALl@>++(t".a@>3.')2=@a?("7080I!370I3<z70i:POs00sPUi7"^0a@<3%13).a@>3a=20?"lPU@l"a=21?"S@ll@o"a=22?3a=110?"Y36"a=111?"lPUm@3"a@1?("O C30O30Y APO@60YPO6"^0a)98J['*x"//"'%'+'-]@a}Wi<#a{Va@iR9"Y3l?lPU3"R8"y;Vk"R7"i:a@?"R6"nm@3:y"R3C`POl`++i}
```
[Try it online!](https://tio.run/##dVLtTtswFP0NT1E8oX6N4MRaCxkQs5ZJQaWJksCGqsw1rSkWaRolKdBRpL3WnmcP0tkJaenoZEVx7sc5596TiEeLxUd9HOr4ZJToQao/1GqY1L5@8S4I1SvnFD96DihtbQOoav0KhHOoKnMNikftQdWvKjVDm4ur5ivKXFGUfvXieYfiI80AgX1ZSYFC8YmmlKsiho5VmIUD/JpAy4Ss13Fw2gnwSb3@Jq0dY2pUQBMeQHMHNaGJjn42IddtK4EwsS95E/yAEmNXRdWsiR5rOQ0OgLirBnBxEOCJ/NAMkValjGvUAPKqZqVjjADFqiCySi0ELQSvS6e2hRvw2rYakqF6eHDeK9eewP4@KO@W6@U9H9OXb/zoA32@opg7hwIyMAQWAs4BmH2@ugdOE3CdYgM4DRAKCn0GHNTq21bQr9f5y2Kx6LklebwtebrbxJ4md6Tp9@SHt@WWiMPokLhe2@wSmpDBHY3pIGWxv2zM3/JWtCNEdt7m5VPkQmGB3@tuF6Qi3ooZTRnp0BsWkI5l2aveokuVgvIQcac3qdRA0klE0seJrJZ4pD2NmISWsBmheUtCNiLn07EonLwSuB2zdUZOu21iO2bXk90FtNQyiWYE7t3QhA2JmqTLWSQscR9ptKKVpDmbaFwnyafIp8ykrM24QcJ/PJBHOJDGnD0wwsNomuaCC@h8vaLHDfiAkU/knrGIhyOpMjcx25kd8zCV/okXG627VxBqK1v@FbyUuWELMijq2zwZ0HiY824sLESvxGz8md7IKf4dAf7Ah2yD0cv9Cqvh0oOz76a3suedOa/TFCt870/Rnw129sRTIXkyiunYX/z59fsv "Pip – Try It Online")
Takes the Whitespace code as its first command-line argument, and the arguments to the Whitespace program as the following command-line arguments. (A string of characters should be given as a single argument.) The heap has a fixed size of 1000 entries.
### How?
The broad-strokes version:
* Strip non-whitespace characters from code
* Transliterate space, tab, and newline to 0, 1, and 2
* Use regex to break the program into a list of valid statements
* Translate each statement into Pip code
* While the program counter (initially set to 0) is less than the length of the program, execute the statement at that index and increment the program counter
When the program needs to halt, either because the Halt instruction was executed or because there were not enough operands for an arithmetic operation, it does so by throwing an error using the idiom `Vk` (explained in [this tip](https://codegolf.stackexchange.com/a/229080/16766)).
### Ungolfed & commented
Here's the ungolfed version that I started from. **Note:** this is written in modern Pip, so it won't work on TIO. I've restructured the golfed version a bit, particularly to compress some of the cases in the translation section, but the basic approach is the same.
```
;;;;;;;;;;;
;; Setup ;;
;;;;;;;;;;;
; Use S/T/N temporarily for ease of development
$codepage : "STN"
; Stack starts out empty
$stack : []
; Heap size is 1000 (initial values don't matter)
$heap : u RL 1000
; Whitespace code is first command-line argument
$code : a
; Program inputs are remaining command-line args
$inputs : g @> 1
; Program counter starts at 0
$pc : 0
; To handle subroutines, we need to store a stack of return-to line numbers
$return_addrs : []
; Function to decode number literals
$to_int : {
$magnitude : FB TM a
$sign : (-1) E @a
$sign * $magnitude
}
;;;;;;;;;;;;;
;; Parsing ;;
;;;;;;;;;;;;;
; Remove characters from code that aren't in codepage
$code FI: _ N $codepage
; Transliterate code from codepage to 0 (space), 1 (tab), and 2 (newline)
$code TR: $codepage 012
; Split code into separate instructions
$command_rgx : `(00|01.|20.|21[01]).*?2|1[02]..|...`
P $code : (J $code) @ $command_rgx
; Translate each instruction into Pip commands
$program : $code M {
$instr : a
; Push a number
$instr @< 2 Q 00 ? "$stack PU " . ($to_int $instr @> 2)
; Copy nth number on stack
$instr @< 3 Q 010 ? "$stack PU $stack @ " . ($to_int $instr @> 3)
; Slide n numbers off from under top of stack
$instr @< 3 Q 012 ? "$stack : $stack @ 0 AL $stack @> " . 1 + ($to_int $instr @> 3)
; Label (no-op)
$instr @< 3 Q 200 ? $instr @> 3
; Gosub label
$instr @< 3 Q 201 ? "$return_addrs PU $pc; $pc : $program @? " . $instr @> 3
; Goto label
$instr @< 3 Q 202 ? "$pc : $program @? " . $instr @> 3
; If top of stack is zero, goto label
$instr @< 3 Q 210 ? "I PO $stack = 0 $pc : $program @? " . $instr @> 3
; If top of stack is negative, goto label
$instr @< 3 Q 211 ? "I PO $stack < 0 $pc : $program @? " . $instr @> 3
; Dup
$instr Q 020 ? "$stack PU $stack @ 0"
; Swap
$instr Q 021 ? "$stack @ 0 :: $stack @ 1"
; Drop
$instr Q 022 ? "PO $stack"
; Add
$instr Q 1000 ? "Y PO $stack; $stack ? $stack PU (PO $stack) + y; V k"
; Subtract
$instr Q 1001 ? "Y PO $stack; $stack ? $stack PU (PO $stack) - y; V k"
; Multiply
$instr Q 1002 ? "Y PO $stack; $stack ? $stack PU (PO $stack) * y; V k"
; Divide
$instr Q 1010 ? "Y PO $stack; $stack ? $stack PU (PO $stack) // y; V k"
; Modulo
$instr Q 1011 ? "Y PO $stack; $stack ? $stack PU (PO $stack) % y; V k"
; Store top of stack on heap at second-on-stack address
$instr Q 110 ? "Y PO $stack; $addr : PO $stack; $heap @ $addr : y"
; Recall number from heap at top-of-stack address
$instr Q 111 ? "$stack PU $heap @ PO $stack"
; Print as char
$instr Q 1200 ? "O C PO $stack"
; Print as number
$instr Q 1201 ? "O PO $stack"
; Read char and store it on heap at top-of-stack address
$instr Q 1210 ? "Y A PO $inputs @ 0; $addr : PO $stack; $heap @ $addr : y"
; Read number and store it on heap at top-of-stack address
$instr Q 1211 ? "Y PO $inputs; $addr : PO $stack; $heap @ $addr : y"
; Return from subroutine
$instr Q 212 ? "$pc : PO $return_addrs"
; Halt
$instr Q 222 ? "V k"
; Unrecognized instruction
""
}
P $program
P "------------"
;;;;;;;;;;;;;;;
;; Execution ;;
;;;;;;;;;;;;;;;
; Loop while the program counter hasn't gone past the end of the program
W $pc < # $program {
; Eval the current statement
V $program @ $pc
; Increment the program counter
U $pc
}
```
] |
[Question]
[
Golf a program or function which gives the \$n^{\text{th}}\$ location of the [wildebeest](https://en.wikipedia.org/wiki/Wildebeest_Chess "Wikipedia") who starts at square \$1\$ on an infinite [chessboard](https://en.wikipedia.org/wiki/Chessboard "Wikipedia") which is numbered in an anti-clockwise square spiral, where the wildebeest always visits the lowest numbered square she can reach that she has not yet visited.
Inspiration: [The Trapped Knight](https://youtu.be/RGQe8waGJ4w "Numberphile, YouTube") and [OEIS A316667](https://oeis.org/A316667 "The On-Line Encyclopedia of Integer Sequences").
Edit: This sequence is now on the OEIS as [A323763](https://oeis.org/A323763 "The On-Line Encyclopedia of Integer Sequences").
The code may produce the \$n^{\text{th}}\$ location, the first \$n\$ locations, or generate the sequence taking no input.
Feel free to give her location after (or up to) \$n\$ leaps instead, but if so please state this clearly in your answer and make sure that an input of \$n=0\$ yields `1` (or `[1]` if appropriate).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the aim is to produce working code in as few bytes as possible in your chosen language.
Note: the wildebeest becomes trapped (much like the knight does at his \$2016^{\text{th}}\$ location, square \$2084\$, and the camel does at his \$3723^{\text{rd}}\$, square \$7081\$) at her \$12899744968^{\text{th}}\$ location on square \$12851850258\$. The behaviour of your code may be undefined for \$n\$ larger than this. (Thanks to Deadcode for the [C++ code](https://github.com/Davidebyzero/path-of-the-wildebeest "GitHub") that found this!)
### Detail
The board looks like the below, and continues indefinitely:
```
101 100 99 98 97 96 95 94 93 92 91
102 65 64 63 62 61 60 59 58 57 90
103 66 37 36 35 34 33 32 31 56 89
104 67 38 17 16 15 14 13 30 55 88
105 68 39 18 5 4 3 12 29 54 87
106 69 40 19 6 1 2 11 28 53 86
107 70 41 20 7 8 9 10 27 52 85
108 71 42 21 22 23 24 25 26 51 84
109 72 43 44 45 46 47 48 49 50 83
110 73 74 75 76 77 78 79 80 81 82
111 112 113 114 115 116 117 118 119 120 121
```
A [wildebeest](https://en.wikipedia.org/wiki/Wildebeest_Chess "Wikipedia") is a "gnu" [fairy chess piece](https://en.wikipedia.org/wiki/Fairy_chess_piece "Wikipedia") - a non-standard chess piece which may move both as a [knight](https://en.wikipedia.org/wiki/Knight_(chess) "Wikipedia") (a \$(1,2)\$-leaper) and as a [camel](https://en.wikipedia.org/wiki/Camel_(chess) "Wikipedia") (a \$(1,3)\$-leaper).
As such she could move to any of these locations from her starting location of \$1\$:
```
. . . . . . . . . . .
. . . . 35 . 33 . . . .
. . . . 16 . 14 . . . .
. . 39 18 . . . 12 29 . .
. . . . . (1) . . . . .
. . 41 20 . . . 10 27 . .
. . . . 22 . 24 . . . .
. . . . 45 . 47 . . . .
. . . . . . . . . . .
```
The lowest of these is \$10\$ and she has not yet visited that square, so \$10\$ is the second term in the sequence.
Next she could move from \$10\$ to any of these locations:
```
. . . . . . . . . . .
. . . . . . 14 . 30 . .
. . . . . . 3 . 29 . .
. . . . 6 1 . . . 53 86
. . . . . . . (10) . . .
. . . . 22 23 . . . 51 84
. . . . . . 47 . 49 . .
. . . . . . 78 . 80 . .
. . . . . . . . . . .
```
However, she has already visited square \$1\$ so her third location is square \$3\$, the lowest she has not yet visited.
---
The first \$100\$ terms of the path of the wildebeest are:
```
1, 10, 3, 6, 9, 4, 7, 2, 5, 8, 11, 14, 18, 15, 12, 16, 19, 22, 41, 17, 33, 30, 34, 13, 27, 23, 20, 24, 44, 40, 21, 39, 36, 60, 31, 53, 26, 46, 25, 28, 32, 29, 51, 47, 75, 42, 45, 71, 74, 70, 38, 35, 59, 56, 86, 50, 78, 49, 52, 80, 83, 79, 115, 73, 107, 67, 64, 68, 37, 61, 93, 55, 58, 54, 84, 48, 76, 43, 69, 103, 63, 66, 62, 94, 57, 87, 125, 82, 118, 77, 113, 72, 106, 148, 65, 97, 137, 91, 129, 85
```
The first \$11\$ leaps are knight moves so the first \$12\$ terms coincide with [A316667](https://oeis.org/A316667 "The On-Line Encyclopedia of Integer Sequences").
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~191 ... 166~~ 164 bytes
*Saved 2 bytes thanks to [@grimy](https://codegolf.stackexchange.com/users/6484/grimy).*
Returns the \$N\$th term.
```
n=>(g=(x,y)=>n--?g(Buffer('QPNP1O?O@242Q3C3').map(m=c=>g[i=4*((x+=c%6-2)*x>(y+=c%7-2)*y?x:y)**2,i-=(x>y||-1)*(i**.5+x+y)]|i>m||(H=x,V=y,m=i))&&H,V,g[m]=1):m+1)(1,2)
```
[Try it online!](https://tio.run/##FYzNasJAFEb3PsUsrN47P8GJtgXtnZR246rqxo0IhjQJU5yJxLZkSHz2GFfnO/BxftL/9JrV9vKrfPWd9wX1ngyUBI0MSMYrlZTw8VcUeQ3T3fZrqzfJ5j1exLv553yKkUsv4CgjUx4sLThAIyh7elEx8sZAeMjrQ0LSLANyHkurhrgJXac0crCcR8@iEQGPnTWu62BNjdxTkI4s4mSylntZHtyRNC6d0AhaxtgXVQ2eEdMr5tnbwNlsWEIga0eMZZW/Vuc8OlclnFIYt/6Gw3ncFuDxdsLV6NbfAQ "JavaScript (Node.js) – Try It Online") or [See a formatted version](https://tio.run/##XVFNb4JAFLzzK@Zg9a18RNC2iRZp2ounqhcvxkRCgdDIYrBtJOBvx0cLBXvaefPmzc7b/XC/3ZOXRsdPXSbvfhnYpYQ9BylACBt01pAJZrgGpK7D@UHcpRoAL19B4Kc0WK/eVubSWT5bE2s9fh0PxJ/EiN0jxWzoNV61y7ZTABErJhiCblhwDKjV7B0eoMMSLDmDU2YN/djQGRxuTZHdOHBnCEv7d5de7cc2GYoCulmNU1QpjXuo7KLy6p2RXQcXPD5H3GUK0ILj84Nt@Mg0VOtGrYFAv49Fm2HTwnAb71hs1sTvzLSuYs5hKoJMjTcsgyQlWWlnkHjiczRipKoCOeu9RJ6Sg28ckpD2LvVyeeHPQy8PSIrLXsyUS3kF)
## How?
### Spiral indices
In order to convert the coordinates \$(x,y)\$ into the spiral index \$I\$, we first compute the layer \$L\$ with:
$$L=\max(|x|,|y|)$$
Which gives:
$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&3&3&3&3&3&3&3\\
-2&3&2&2&2&2&2&3\\
-1&3&2&1&1&1&2&3\\
0&3&2&1&0&1&2&3\\
+1&3&2&1&1&1&2&3\\
+2&3&2&2&2&2&2&3\\
+3&3&3&3&3&3&3&3
\end{array}$$
We then compute the position \$P\$ in the layer with:
$$P=\begin{cases}
2L+x+y&\text{if }x>y\\
-(2L+x+y)&\text{if }x\le y
\end{cases}$$
Which gives:
$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&0&1&2&3&4&5&6\\
-2&-1&0&1&2&3&4&7\\
-1&-2&-1&0&1&2&5&8\\
0&-3&-2&-1&0&3&6&9\\
+1&-4&-3&-2&-3&-4&7&10\\
+2&-5&-4&-5&-6&-7&-8&11\\
+3&-6&-7&-8&-9&-10&-11&-12
\end{array}$$
The final index \$I\$ is given by:
$$I=4L^2-P$$
NB: The above formula gives a 0-indexed spiral.
In the JS code, we actually compute \$4L^2\$ right away with:
```
i = 4 * (x * x > y * y ? x : y) ** 2
```
And then subtract \$P\$ with:
```
i -= (x > y || -1) * (i ** 0.5 + x + y)
```
### Moves of the wildebeest
Given the current position \$(x,y)\$, the 16 possible target squares of the wildebeest are tested in the following order:
$$\begin{array}{c|cccccccc}
&-3&-2&-1&x&+1&+2&+3\\
\hline
-3&\cdot&\cdot&9&\cdot&11&\cdot&\cdot\\
-2&\cdot&\cdot&8&\cdot&10&\cdot&\cdot\\
-1&7&6&\cdot&\cdot&\cdot&12&13\\
y&\cdot&\cdot&\cdot&\bullet&\cdot&\cdot&\cdot\\
+1&5&4&\cdot&\cdot&\cdot&14&15\\
+2&\cdot&\cdot&2&\cdot&0&\cdot&\cdot\\
+3&\cdot&\cdot&3&\cdot&1&\cdot&\cdot
\end{array}$$
We walk through them by applying 16 pairs of signed values \$(dx,dy)\$. Each pair is encoded as a single ASCII character.
```
ID | char. | ASCII code | c%6-2 | c%7-2 | cumulated
----+-------+------------+-------+-------+-----------
0 | 'Q' | 81 | +1 | +2 | (+1,+2)
1 | 'P' | 80 | 0 | +1 | (+1,+3)
2 | 'N' | 78 | -2 | -1 | (-1,+2)
3 | 'P' | 80 | 0 | +1 | (-1,+3)
4 | '1' | 49 | -1 | -2 | (-2,+1)
5 | 'O' | 79 | -1 | 0 | (-3,+1)
6 | '?' | 63 | +1 | -2 | (-2,-1)
7 | 'O' | 79 | -1 | 0 | (-3,-1)
8 | '@' | 64 | +2 | -1 | (-1,-2)
9 | '2' | 50 | 0 | -1 | (-1,-3)
10 | '4' | 52 | +2 | +1 | (+1,-2)
11 | '2' | 50 | 0 | -1 | (+1,-3)
12 | 'Q' | 81 | +1 | +2 | (+2,-1)
13 | '3' | 51 | +1 | 0 | (+3,-1)
14 | 'C' | 67 | -1 | +2 | (+2,+1)
15 | '3' | 51 | +1 | 0 | (+3,+1)
```
We keep track of the minimum encountered value in \$m\$ and of the coordinates of the corresponding cell in \$(H,V)\$.
Once the best candidate has been found, we mark it as visited by setting a flag in the object \$g\$, which is also our main recursive function.
On the first iteration, we start with \$x=1\$ and \$y=2\$. This ensures that the first selected cell is \$(0,0)\$ and that it's the first cell to be marked as visited.
[Answer]
# [Coconut](http://coconut-lang.org/), ~~337~~ 276 bytes
```
import math
def g((x,y))=
A=abs(abs(x)-abs(y))+abs(x)+abs(y)
int(A**2+math.copysign(A+x-y,.5-x-y)+1)
def f():
p=x,y=0,0;s={p};z=[2,3,1,1]*2
while 1:yield g(p);p=x,y=min(((a+x,b+y)for a,b in zip((1,1,2,-2,-1,-1,3,-3)*2,z+[-v for v in z])if(a+x,b+y)not in s),key=g);s.add(p)
```
Returns a generator of values. Could probably be golfed more. (Especially the sequence of difference tuples.) Spiral algorithm taken from [this math.se answer](https://math.stackexchange.com/a/2639611/293996).
[Try it online!](https://tio.run/##PVDbboMwDH3PV/gxJg4Cqr0UpVK/o@oD5dZoQCKSddBt386SMk3yRceyj49dm9pMH37b9GjN7GGs/J01bQc95wutiIrBWVU3x6MvKGMKZbFDsUMGevL8nCSFiARpbezqdD/xs1jkSjIEkaVvKHJ8kXccjwysChtURlnp1Jf9KZ/qUtCBcsqvScHg866HFvLjqtuhCXoslvvEqCfOeSUWuokVOzNDRbegAJ7ach7GqSAZLI92IHnApKCnuMgHxObHq/WKuvvnmIyPRYf03q6qx9KlVdOEjVs3mxG0b2dvzODg70sJY9oNum55uIQgzzKE7xMM2vmY7Rzesf0C "Coconut – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~77~~ ~~65~~ ~~58~~ ~~57~~ 52 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Xˆ0UF3D(Ÿ0KãʒÄ1¢}εX+}Dε·nàDtyÆ+yO·<.±*->}D¯KßDˆkèU}¯
```
-6 bytes thanks to *@Arnauld* by using a port of his formula.
Outputs the first \$n+1\$ values as a list (of decimals).
[Try it online](https://tio.run/##AVQAq/9vc2FiaWX//1jLhjBVRjNEKMW4MEvDo8qSw4QxwqJ9zrVYK31EzrXCt27DoER0ecOGK3lPwrc8LsKxKi0@fUTCr0vDn0TLhmvDqFV9wq//w6//MTU) (the `ï` in the footer removes the `.0` to make the output more compact, but feel free to remove it to see the actual result).
**Code explanation:**
```
Xˆ # Put integer 1 in the global_array (global_array is empty by default)
0U # Set variable `X` to 0 (`X` is 1 by default)
F # Loop the (implicit) input amount of times:
3D(Ÿ # Push the list in the range [-3,3]: [-3,-2,-1,0,1,2,3]
0K # Remove the 0: [-3,-2,-1,1,2,3]
ã # Cartesian product with itself, creating each possible pair: [[3,3],[3,2],[3,1],[3,-1],[3,-2],[3,-3],[2,3],[2,2],[2,1],[2,-1],[2,-2],[2,-3],[1,3],[1,2],[1,1],[1,-1],[1,-2],[1,-3],[-1,3],[-1,2],[-1,1],[-1,-1],[-1,-2],[-1,-3],[-2,3],[-2,2],[-2,1],[-2,-1],[-2,-2],[-2,-3],[-3,3],[-3,2],[-3,1],[-3,-1],[-3,-2],[-3,-3]]
ʒ } # Filter this list of pairs by:
Ä # Where the absolute values of the pair
1¢ # Contains exactly one 1
# (We now have the following pairs left: [[3,1],[3,-1],[2,1],[2,-1],[1,3],[1,2],[1,-2],[1,-3],[-1,3],[-1,2],[-1,-2],[-1,-3],[-2,1],[-2,-1],[-3,1],[-3,-1]])
εX+} # Add the variable `X` (previous coordinate) to each item in the list
D # Duplicate this list of coordinates
ε # Map each `x,y`-coordinate to:
· # Double both the `x` and `y` in the coordinate
n # Then take the square of each
à # And then pop and push the maximum of the two
Dt # Duplicate this maximum, and take its square-root
yÆ # Calculate `x-y`
+ # And add it to the square-root
yO # Calculate `x+y`
· # Double it
< # Decrease it by 1
.± # And pop and push its signum (-1 if < 0; 0 if 0; 1 if > 0)
* # Multiply these two together
- # And subtract it from the duplicated maximum
> # And finally increase it by 1 to make it 1-based instead of 0-based
}D # After the map: Duplicate that list with values
¯K # Remove all values that are already present in the global_array
ß # Pop the list of (remaining) values and push the minimum
Dˆ # Duplicate this minimum, and pop and add the copy to the global_array
k # Then get its index in the complete list of values
è # And use that index to get the corresponding coordinate
U # Pop and store this coordinate in variable `X` for the next iteration
}¯ # After the outer loop: push the global_array (which is output implicitly)
```
**General explanation:**
We hold all results (and therefore values we've already encountered) in the `global_array`, which is initially started as `[1]`.
We hold the current \$x,y\$-coordinate in variable `X`, which is initially `[0,0]`.
The list of coordinates we can reach based on the current \$x,y\$-coordinate are:
```
[[x+3,y+1], [x+3,y-1], [x+2,y+1], [x+2,y-1], [x+1,y+3], [x+1,y+2], [x+1,y-2], [x+1,y-3], [x-1,y+3], [x-1,y+2], [x-1,y-2], [x-1,y-3], [x-2,y+1], [x-2,y-1], [x-3,y+1], [x-3,y-1]]
```
The list I mention in the code explanation above holds these values we can jump to, after which the current \$x,y\$ (stored in variable `X`) is added.
Then it will calculate the spiral values based on these \$x,y\$-coordinates. It does this by using the following formula for a given \$x,y\$-coordinate:
$${T = max((2 \* x) ^ 2, (2 \* y) ^ 2)}$$
$${R = T - (x - y + √T) \* signum((x + y) \* 2 - 1) + 1}$$
Which is the same formula [*@Arnauld* is using in his answer](https://codegolf.stackexchange.com/a/179158/52210), but written differently to make use of 05AB1E's builtins for double, square, -1, +1, etc.
(If you want to see just this spiral part of the code in action: [Try it online](https://tio.run/##PY2xDcJQDERXiVJCjPy/KRFp6BkgigRIFDRQBCGlQKLKAJRUrECBQp30DJFFPuDzp7ln687nQ7Xe7LYhvJ9du@/vi2PdN@N62bWzSfcY0fw8XG7961SvqjxNhuaapHkWQlFwxmVWOFP3VVYlF8EAwVPY5iNYFbNX32vY41ThIxzAANlKliVcEmoUZsofTsGqmGGIhkUvRWsEpYIfConwgAMYIFvJXLJTsiZCL@EJ4aPCstMfyg8).)
After we've got all the values we can reach for the given \$x,y\$-coordinate, we remove all values that are already present in the `global_array`, and we then get the minimum of the (remaining) values.
This minimum is then added to the `global_array`, and variable `X` is replaced with the \$x,y\$-coordinate of this minimum.
After we've looped the `input` amount of times, the program will output this `global_array` as result.
] |
[Question]
[
Here is an ASCII [saltine cracker](http://en.wikipedia.org/wiki/Saltine_cracker):
```
_________________
| . . . |
| . . |
| . . . |
| . . |
| . . . |
|_________________|
```
Here are two crackers stacked:
```
_________________
| . . . |
| . __________|______
| . | . . . |
| .| . . |
| . | . . . |
|______| . . |
| . . . |
|_________________|
```
Write the shortest program possible that takes a positive integer and draws a stack of that many ASCII saltine crackers.
Input may come from stdin, command line, or you may simply write a function. The input will always be valid. Output must go to stdout or closest alternative.
Each stacked cracker is always shifted 2 characters down and 7 characters right of the cracker below it. There should be no trailing spaces or extraneous newlines.
The shortest program [in bytes](https://mothereff.in/byte-counter) wins.
# Examples
If the input is `1` the output is
```
_________________
| . . . |
| . . |
| . . . |
| . . |
| . . . |
|_________________|
```
If the input is `2` the output is
```
_________________
| . . . |
| . __________|______
| . | . . . |
| .| . . |
| . | . . . |
|______| . . |
| . . . |
|_________________|
```
If the input is `3` the output is
```
_________________
| . . . |
| . __________|______
| . | . . . |
| .| . __________|______
| . | . | . . . |
|______| .| . . |
| . | . . . |
|______| . . |
| . . . |
|_________________|
```
And so on.
*[the real saltine challenge](http://en.wikipedia.org/wiki/Saltine_cracker_challenge)*
[Answer]
## JavaScript (E6) 249 ~~259 289 304 345~~
~~Not so confident about the string compression.~~
Found a good compression for the strings. ~~The simple 1 cracker case seems difficult to manage. There may be a better way...~~
```
F=n=>{
for(B=",|4.,|1.2,|1.4.4.1|,|5,|4.4.4|, 9|5, 87 ,|87|".replace(/\d/g,c=>' _'[c>4|0][R='repeat'](-~c)).split(','),
O=(c,b=0,a=0)=>console.log(' '[R](y)+B[a]+B[b][R](x)+B[c]),
r=x=y=0,
O(7);
O(3,2),
!(z=++r>2)|x;)
x+=(v=r<n)-z,O(v+5,1,z*4),y+=z*7;
O(8)
}
```
**Ungolfed** more or less
That is the basic code, before I started golfing. It's not exactly the same and works only for n > 2
```
F=n=>{
O=t=>console.log(t)
r=0
x=0
y=0
O(' _________________')
O(' '.repeat(y)+'| . '.repeat(x)+'| . . . |')
while (++r<n)
{
x++;
if (r>2)
{
x--;
O(' '.repeat(y)+'|______'+'| .'.repeat(x)+' __________|______')
y+=7;
O(' '.repeat(y)+'| . '.repeat(x)+'| . . |')
}
else
{
O(' '.repeat(y)+'| .'.repeat(x)+' __________|______')
O(' '.repeat(y)+'| . '.repeat(x)+'| . . . |')
}
}
while(x--)
{
O(' '.repeat(y)+'|______'+'| .'.repeat(x)+'| . . . |')
y+=7;
O(' '.repeat(y)+'| . '.repeat(x)+'| . . |')
}
O(' '.repeat(y)+'|_________________|')
}
```
**Test** In FireFox/FireBug console
```
F(4)
```
*Output*
```
_________________
| . . . |
| . __________|______
| . | . . . |
| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . . |
| . | . . . |
|______| . . |
| . . . |
|_________________|
```
[Answer]
# Python, ~~252~~ 241 characters
```
s="eJxTiIeDGgiloBBRo6CgpwACcLIGJKaAKlxDmbp4dFADAL+oIFI=".decode('base64').decode('zip').split('X')
N=input()
R=range
G=map(list,[' '*(7*N+12)]*(2*N+5))
for n in R(N):
for y in R(7):G[2*n+y][7*n:]=s[y]
G[0][11]='_'
for g in G:print''.join(g)
```
Thanks to FryAmTheEggman and Vincent for snipping off 11 characters.
A preponderance of crackers:
```
$ echo 17 | python saltines.py
_________________
| . . . |
| . __________|______
| . | . . . |
| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . __________|______
| . | . | . . . |
|______| .| . . |
| . | . . . |
|______| . . |
| . . . |
|_________________|
```
This code seems really inefficient, but other answers will tell. It just copies and pastes the saltine cracker into an array at the right spot, accounts for the bottom-most cracker being 1-character off, then prints it all.
I can get it down to **230 characters** if I use an external file (202 code + 38 file size + 1 file name).
[Answer]
# Perl 189
Stealing some string compression ideas from choroba, I got it down to:
```
echo 4 | perl -E 's/\d/($&<8?$":_)x$&/ge for@l=("|2.5.5.2|"," 98","|5.5.5|","|98|",7)[102020344=~/./g];map{say for@l[0,1];$l[$_]=substr($l[$_+2],0,7).$l[$_]for 0..6;substr$l[0],-7,1,"|"}2..<>;say for@l[0..6]'
```
For easier viewing in your browser:
```
s/\d/($&<8?$":_)x$&/ge for@l=
("|2.5.5.2|"," 98","|5.5.5|","|98|",7)[102020344=~/./g];map{
say for@l[0,1];
$l[$_]=substr($l[$_+2],0,7).$l[$_]for 0..6;
substr$l[0],-7,1,"|"
}2..<>;say for@l[0..6]
```
For context, my best before that:
# Perl 207
```
$u='_'x11;s/:/ . /g,s/.(.)/$&$1/g,$_.=$/for@l=("|:: . |"," $u","| :: |","|$u|",$"x5)[102020344=~/./g];map{print@l[0,1];$l[$_]=substr($l[$_+2],0,7).$l[$_]for 0..6;substr$l[0],-8,1,'|'}2..pop;print@l[0..6]
```
Adding newlines and indentation for ease of reading in your browser:
```
$u="_"x11;
s/:/ . /g,s/.(.)/$&$1/g,$_.=$/for@l=
("|:: . |"," $u","| :: |","|$u|",$"x5)[102020344=~/./g];
map{
print@l[0,1];
$l[$_]=substr($l[$_+2],0,7).$l[$_]for 0..6;
substr$l[0],-8,1,"|"
}2..pop;
print@l[0..6]
```
You can replace "pop" with "<>" to take the count from STDIN instead of as a command-line parameter and get to 206 bytes. Going to STDERR would drop it to 204 bytes.
If I could enable the 'say' feature without a byte penalty, then I could get to 202.
```
$u="_"x11;s/:/ . /g,s/.(.)/$&$1/g for@l=("|:: . |"," $u","| :: |","|$u|",$"x5)[102020344=~/./g];map{say for@l[0,1];$l[$_]=substr($l[$_+2],0,7).$l[$_]for 0..6;substr$l[0],-7,1,"|"}2..<>;say for@l[0..6]
```
invoked as:
```
echo 4 | perl -E '$u="_"x11;s/:/ . /g,s/.(.)/$&$1/g for@l=("|:: . |"," $u","| :: |","|$u|",$"x5)[102020344=~/./g];map{say for@l[0,1];$l[$_]=substr($l[$_+2],0,7).$l[$_]for 0..6;substr$l[0],-7,1,"|"}2..<>;say for@l[0..6]'
```
[Answer]
# CJam, ~~140~~ ~~125~~ ~~119~~ 116 bytes
```
li__7*C+S*a\2*5+*\{5m>S'|6*+_" ."5*5/{'__@\++}:U%3*0@t{S5*U_}%\a+zsB'|tJ/{\(J>@\+a+}/{7m<}%}*{Cm<0{;)_' =}g+}%N*B'_t
```
[Try it online.](http://cjam.aditsu.net/ "CJam interpreter")
### A single saltine
The code snippet
```
S'|6*+_ " Push ' ||||||' twice. ";
" ."5*5/ " Push [' . . ' '. . .']. ";
{'__@\++}:U% " Prepend and append an underscore to each string in the previous array. ";
3* " Repeat the resulting array thrice. ";
0@t " Replace its first element with ' ||||||'. ";
{S5*U_}% " Insert '_ _' after each element of the array. ";
\a+ " Append ' ||||||' to the array. ";
z " Zip; transpose rows with columns. ";
sB'\t " Flatten the array of strings and replace the 12th element with a '|'. ";
19/ " Split into chunks of length 19. ";
```
leaves the following on the stack:
```
[
" __________|______ "
"| . . . |"
"| . . |"
"| . . . |"
"| . . |"
"| . . . |"
"|_________________|"
]
```
### Stacked saltines
Assume the saltine from above is saved in Z.
```
li " I := int(input()) ";
__7*C+S*a\2*5+* " R:= [(I * 7 + 12) * ' '] * (I * 2 + 5) ";
\{ " Repeat I times: ";
5m> " R := R[-5:] + R[:-5] ";
Z " Push a single saltine, as an array of lines. ";
{ " For each line L of the saltine: ";
\(J>@\+a+ " R := R[1:] + [R[0][19:] + L] ";
}/ " ";
{7m<}% " R := [ L[7:] + L[:7] : L in R ] ";
}* " ";
{ " R := [ ";
Cm< " (L[12:] + L[:12]) ";
0{;)_' =}g+ " .rstrip() ";
}% " : L in R ] ";
N* " R := '\n'.join(R) ";
B'_t " R[11] := '|' ";
```
[Answer]
# Perl 201
(remove newlines except the first one to get the #)
```
$_=" 46|6
15.5.5|15.5.5|198|";
s/1/| .5.5. ||/g;
s/\d/(5^$&?_:$")x$&/ge;
@o=@l=/.{18}.?/g;
map{
$s=$_*7;
substr$o[$_-5],$s,12,$l[$_]for 0..4;
push@o,($"x$s).$l[$_]for 5,6
}1..-1+pop;
$o[$,=$/]=~y/|/_/;
print@o
```
`say` + `<>` = 198.
[Answer]
# Haskell, 215 bytes
This one builds up the cracker stack inductively, pulling cracker parts and spacing out of a couple of cyclic lists:
```
(b:u:i)=" _|"
(%)=replicate
z=5%b++'.':z
m!n=i++map(z!!)[m..n]
s=7%b:s
d=3!19++i
e=0!16++i
y=i++6%u
g 1=[e,d,e,d,i++17%u++i]
g k=zipWith(++)(0!5:3!8:0!5:3!8:y:s)$(b:10%u++y):d:g(k-1)
f k=mapM putStrLn$(b:17%u):d:g k
```
The control flow is pretty straightforward; most of the trickery is in reusing as much of the cracker parts as possible.
**Ungolfed:**
```
top = " _________________"
top' = " __________|______"
dots3 = "| . . . |"
dots2 = "| . . |"
bot = "|_________________|"
halfR = "| ."
halfL = "| . "
halfBot = "|______"
spacer = " "
spaces = repeat spacer
saltine = above ++ [dots2, dots3, dots2, dots3, bot]
above = [top, dots3]
left = [halfR, halfL, halfR, halfL, halfBot] ++ spaces
another (oldTop:oldCracker) = above ++ zipWith (++) left (top' : oldCracker)
crackers 1 = saltine
crackers k = another $ crackers (k - 1)
test = putStr . unlines . crackers
```
[Answer]
# Python, 299
I thought I was being clever but the solution turned out to be overly complicated and longer than any straight forward approach, yet I couldn't resist to post it. The program explicitly calculates which character has to be plotted at the different positions of the output string, without looping over the individual crackers.
```
N=input()
m,n,c,r=12+7*N,5+2*N,3.5,range
print''.join(i>m-2and'\n'or(i%7<(i/c<j<7+i/c)*(i<N*7)or(i+4)%7<(i/c<j+4<2+4*(i>m-3)+i/c)*(i>16))and'|'or j%2<(j*c<i<17+j*c)*(j<n-5)+(j*c<i+22<8+10*(j>n-3)+j*c)*(j>5)and'_'or(i-j*3-min(i/7,~-j/2,N-1)+1)%6<(-3<-~i/7-j/2<3)and'.'or' 'for j in r(n)for i in r(m))
```
And the last line expanded to see what's going on:
```
print ''.join(
'\n' if i>m-2 else
'|' if i%7<(i/c<j<7+i/c)*(i<N*7) or (i+4)%7<(i/c<j+4<2+4*(i>m-3)+i/c)*(i>16) else
'_' if j%2<(j*c<i<17+j*c)*(j<n-5)+(j*c<i+22<8+10*(j>n-3)+j*c)*(j>5) else
'.' if (i-j*3-min(i/7,~-j/2,N-1)+1)%6<(-3<-~i/7-j/2<3) else
' '
for j in r(n)
for i in r(m)
)
```
[Answer]
# C,284
For the function `f` and the `#define`s, excluding unnecessary whitespace and `main`. In accordance with edc65's comment, I have included a 128-bit integer type (which I was going to do anyway) but I miscalculated *again* and I can only do 29 crackers before the tops start going missing.
Complete function and test program below. Will comment it later.
```
#define C b,b,c,b,b
#define S s[i/v*7-i%v
f(n){
__int128 a=4095,b=a+2,c=6281,d=4641,w=998,v=19,s[998]={a,C,d,C,d,C,a},i=v;
for(;i<n*v;i++)S+18]|=S+11]*16&-1<<(12+i/v*2-i%v/18)*(i%v>7);
for(i=(5+n*2)*w;i--;i%w||puts(""))i%w>i/w/2*7-21+i/w%2*6&&s[i%w]&&putchar(" _.|"[(s[i%w]>>i/w*2)&3]);
}
main(){
int m;
scanf("%d",&m);f(m);
}
```
There are only four different characters in the output. These are decoded from binary numbers 0-3 by `" _.|"`. The array `s[]` contains an integer for each column of the output, 2 bits per symbol, which is intitialised to contain the rightmost cracker.
The first `for` loop copies the previous cracker, leftshifts it to move it up, deletes the bottom right corner using `&` and ORs it with the previous cracker, 7 steps to the left.
The second `for` loop decodes the 2-bit representation of each character into the actual character and prints the character. There's a lot of code here just to suppress unnecesary whitespace in the output. I'm disappointed that my score went up instead of down from my previous revision.
**Output**
That's 29 crackers. I replaced the space with a `-` for a different look, and to show that no trailing spaces or extraneous newlines in the output.
```
-_________________
|--.-----.-----.--|
|-----.-__________|______
|--.---|--.-----.-----.--|
|-----.|-----.-__________|______
|--.---|--.---|--.-----.-----.--|
|______|-----.|-----.-__________|______
-------|--.---|--.---|--.-----.-----.--|
-------|______|-----.|-----.-__________|______
--------------|--.---|--.---|--.-----.-----.--|
--------------|______|-----.|-----.-__________|______
---------------------|--.---|--.---|--.-----.-----.--|
---------------------|______|-----.|-----.-__________|______
----------------------------|--.---|--.---|--.-----.-----.--|
----------------------------|______|-----.|-----.-__________|______
-----------------------------------|--.---|--.---|--.-----.-----.--|
-----------------------------------|______|-----.|-----.-__________|______
------------------------------------------|--.---|--.---|--.-----.-----.--|
------------------------------------------|______|-----.|-----.-__________|______
-------------------------------------------------|--.---|--.---|--.-----.-----.--|
-------------------------------------------------|______|-----.|-----.-__________|______
--------------------------------------------------------|--.---|--.---|--.-----.-----.--|
--------------------------------------------------------|______|-----.|-----.-__________|______
---------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
---------------------------------------------------------------|______|-----.|-----.-__________|______
----------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
----------------------------------------------------------------------|______|-----.|-----.-__________|______
-----------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
-----------------------------------------------------------------------------|______|-----.|-----.-__________|______
------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
-------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
-------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
--------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
--------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
---------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
---------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
----------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
----------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
-----------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
-----------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
-------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
-------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
--------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
--------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
---------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
---------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
----------------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
----------------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
-----------------------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
-----------------------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
------------------------------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-__________|______
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.---|--.-----.-----.--|
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.|-----.-----.-----|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--.---|--.-----.-----.--|
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|______|-----.-----.-----|
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--.-----.-----.--|
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|_________________|
```
[Answer]
# JavaScript (ES6) HTML5 - 233 236 bytes
Probably not a valid answer, but I just couldn't resist posting, sorry :-P
```
F=n=>{d="______";b="\n| . . . |";a=b+"\n| . . |";for(i=0;i<n;)document.body.innerHTML+="<pre style='background:#fff;position:fixed;top:"+i*28+"px;left:"+i*56+"px'> ____"+d+'|_'[+!i++]+d+a+a+b+"\n|"+d+d+"_____|"}
```
Test in Firefox with `F(1)`, `F(2)`, `F(3)`, etc.
**Example:** <http://jsfiddle.net/Lvmg9fe8/7/>
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 54 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
H┐“)4╪xω╷┘IQ+azQ┴¾4*↔⌐∔v│↶++z2;e\1p9H+m}`1L²‟19┤n;83╋╋
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXUyNTEwJXUyMDFDJTI5NCV1MjU2QXgldTAzQzkldTI1NzcldTI1MThJJXVGRjMxK2EldUZGNUFRJXUyNTM0JUJFJXVGRjE0JXVGRjBBJXUyMTk0JXUyMzEwJXUyMjE0diV1MjUwMiV1MjFCNisrejIldUZGMUIldUZGNDUldUZGM0MldUZGMTEldUZGNTA5SCttJTdEJTYwMSV1RkYyQyVCMiV1MjAxRjE5JXUyNTI0JXVGRjRFJXVGRjFCJXVGRjE4JXVGRjEzJXUyNTRCJXUyNTRC,i=Mw__,v=8)
] |
[Question]
[
Our classic snake has developed an inbalance of [growth hormones](http://en.wikipedia.org/wiki/Growth_hormone). To make matters worse, his tail is frozen in place! Given directional input as specified in `Figure 1`, write a program to determine where he will grow.

*Figure 1.* Directional input.
# Program specifications
* Read the **input** character by character on `STDIN`.
* After reading a character, **output** the snake to `STDOUT`. Please include a blank line in between each time you print a snake.
* The snake consists of `<>v^` and a head. The head of the snake may be any round character of your choosing, such as `o`, `0`, `O`, or `☺`.
* Any combination of `wasd` is valid for input.
* Your program should not assume the input is within a certain length.
* The snake can pile on top of itself, overwriting `<>v^`. See examples for snake growing mechanics.
* Trailing whitespace is okay, but your snake must look correct.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Your score is the number of characters in your program. Lowest score wins!
# Example snakes:
**Input:** `ddddssaassdddddww`
**Output:**
```
>>>>v
v
v<< ☺
v ^
>>>>>^
```
---
**Input:** `dddsssaaawww`
**Output:**
```
☺>>v
^ v
^ v
^<<<
```
---
**Input:** `dddsssdddddasddddwww`
**Output:**
```
>>>v
v ☺
v ^
>>>>v< ^
>>>>^
```
---
**Input:** `dddwwdddssssaaaaaaaaawww`
**Output:**
```
>>>v
☺ ^ v
^ >>>^ v
^ v
^<<<<<<<<<
```
---
**Input:** `ddddssssaawwddddd`
**Output:**
```
>>>>v
v
>>>>>☺
^ v
^<<
```
---
**Input:** `dddddssaawwwwddddd`
**Output:**
```
>>>>>☺
^
>>>^>v
^ v
^<<
```
---
**Input:**
```
ddddaaaasssssdddddddddddwwwwwaaaasssssdddddddddddwwwwwwwwwwsssssaaaasssssdddddddwwwwwddddssaaaasssddddaaaassssssssssdddwwwwwwwddddswaaaassssddaasssaaaaaaaaaawwwwddddssssaaaaaaaaaaawwwwddddsssssssssaaaa
```
**Output:**
```
v
v
v
v
v
v<<<< v<<<< v<<<< >>>>v
v v ^ v ^ ^ v
v v ^ v ^ v<<<<
v v ^ v ^ v
v v ^ v ^ v
>>>>>>>>>>>>>>>>>>>>>v<<<<
v
v
v v<<<<
v v ^
v v
>>>>v >>>>v v v
^ v ^ v v v<<
^ v ^ v v v
^ v ^ v v v
^<<<v<<<<<<<<<<<<<
v
v
v
v
O<<<<
```
[Answer]
# ECMAScript 6 Javascript (399 ~~401~~ ~~431~~)
Has to be run in a browser supporting ECMAScript 6 due to the arrow functions.
Here are fiddles which have been altered to run in any (common) browser by not using arrow functions. They also print to a `textarea` instead:
* [Normal](http://jsfiddle.net/924aw5o7/1/)
* [Animated](http://jsfiddle.net/924aw5o7/2/)
## Golfed Version
```
i=prompt(),v=[],c=0,x=[0],y=[0],s='unshift',k='slice',t='sort',h=[0,-1,0,1,0]
while(c<i.length){m='wasd'.indexOf(i[c++]);v[s]('^<v>'[m]);x[s](x[0]+h[m]);y[s](y[0]+h[m+1])}f=(a,b)=>a-b
q=x[k]()[t](f)[0],e=x[k]()[t]((a,b)=>b-a)[0],w=y[k]()[t](f)[0],o=[]
while((i=y.pop())!=null){i-=w;j=x.pop()-q;t=(o[i]||Array(e+1-q).join(" ")).split("");t.splice(j,1,v.pop()||"@");o[i]=t.join("")}alert(o.join("\n"))
```
## Animated GIF:
One of the OP's examples:

The example from [Stretch Maniac](https://codegolf.stackexchange.com/a/37095/26765):

## Ungolfed
Here is a (slightly) ungolfed version from sometime before I started *really* golfing it down:
```
var input = prompt(),
values = [],
c = 0,
x = [0],
y = [0],
s = 'unshift';
while (c < input.length) {
var mapped = 'wasd'.indexOf(input[c++]);
values[s]('^<v>'[mapped]);
x[s](x[0]+[0, -1, 0, 1][mapped]);
y[s](y[0]+[-1, 0, 1, 0][mapped]);
}
var minX = x.slice().sort(function (a,b){return a-b})[0];
var maxX = x.slice().sort(function (a,b){return b-a})[0];
var minY = y.slice().sort(function (a,b){return a-b})[0];
var output = [];
while((i=y.pop())!=null) {
i-=minY;
j=x.pop()-minX;
t=(output[i]||Array(maxX+1-minX).join(" ")).split("");
t.splice(j,1,values.pop()||"@");
output[i]=t.join("");
}
console.log(output.join("\n"));
```
[Answer]
# sed, 71
```
s/w/\^\x1B[D\x1B[A/g
s/a/<\x1B[2D/g
s/s/v\x1B[B\x1B[D/g
s/d/>/g
s/$/@/
```
# Golfscript, ~~165~~ 126
```
' '*"\33[":e{e'D'}:-{[e'C'+'<'--]]}:a{[-+'>']]}:d{[e'B'+'^'-e'A']]}:w{[e'A'+'v'-e'B']]}:s{][\[}:+7{;}*''\~[e'H'e'J']\'@'e'20H'
```
Same approach as my previous answer, but correctly positioning the cursor before and afterwards. I'm pretty proud of the approach to cursor positioning -- basically, it first runs the snake in reverse, without printing out characters.
[Answer]
# Ruby, 207 characters
```
b=[];x=y=0;gets.chars{|c|b[y]||=[];b[y][x]={?\n=>->{?0},?w=>->{y>0?y-=1:b=[[]]+b;?^},?a=>->{x>0?x-=1:b.map!{|r|[' ']+r};b[y][1]=?<},?s=>->{y+=1;?v},?d=>->{x+=1;?>}}[c][]};puts b.map{|r|r.map{|c|c||' '}.join}
```
Ungolfed:
```
b=[] #board
x=y=0 #position
gets.each_char{|c|
b[y] ||= []
b[y][x] = {
"\n" => lambda{0},
"w" => lambda{if y>0 then y-=1 else b=[[]]+b; "^"},
"a" => lambda{if x>0 then x-=1 else b.map!{|r|[' ']+r}; b[y][1]="<"},
"s" => lambda{y+=1; "v"},
"d" => lambda{x+=1; ">"}
}[c].call}
puts b.map{|r|r.map{|c|c||' '}.join}
```
(the lambda for `a` writes back because the row the assignment above writes to is no longer on the board)
[Answer]
# Java - 646
Might as well be the first one!
I bet you all can beat this.
un(sort of)golfed
```
import java.util.*;
public class Snake{
public static void main(String[]a) {
int x,y,minX,minY,maxX,maxY;
x=y=minX=maxX=minY=maxY=0;
List<Integer>xs,ys=new ArrayList<Integer>();
xs=new ArrayList<Integer>();
List<Character>p=new ArrayList<Character>();
for(int b=0;b<a[0].length();b++){
int newX=x,newY=y;
switch(a[0].charAt(b)){
case'a':newX--;p.add('<');break;
case's':newY++;p.add('v');break;
case'd':newX++;p.add('>');break;
case'w':newY--;p.add('^');break;
}
xs.add(x);ys.add(y);
x=newX;y=newY;
if(x<minX){minX=x;}
if(x>maxX){maxX=x;}
if(y<minY){minY=y;}
if(y>maxY){maxY=y;}
}
char[][]c=new char[maxY-minY+1][maxX-minX+1];
for(int i=0;i<xs.size();i++)c[ys.get(i)-minY][xs.get(i)-minX]=p.get(i);
c[y-minY][x-minX]='@';
for(char[]k:c){for(char l:k){System.out.print(l);}System.out.println();}
}
}
```
Smaller -
```
import java.util.*;class S{public static void main(String[]a){int x,y,o,z,s,u;x=y=o=s=z=u=0;List<Integer>j,t=new ArrayList<Integer>();j=new ArrayList<Integer>();List<Character>p=new ArrayList<Character>();for(int b=0;b<a[0].length();b++){int e=x,r=y;switch(a[0].charAt(b)){case'a':e--;p.add('<');break;case's':r++;p.add('v');break;case'd':e++;p.add('>');break;case'w':r--;p.add('^');break;}j.add(x);t.add(y);x=e;y=r;if(x<o)o=x;if(x>s)s=x;if(y<z)z=y;if(y>u)u=y;}char[][]c=new char[u-z+1][s-o+1];for(int i=0;i<j.size();i++)c[t.get(i)-z][j.get(i)-o]=p.get(i);c[y-z][x-o]='@';for(char[]k:c){for(char l:k){System.out.print(l);}System.out.println();}}}
```
input - dddsssdddwwwwaaaaaaaassssssssssddddddddddddddddd
```
v<<<<<<<<
v >>>v ^
v v ^
v v ^
v >>>^
v
v
v
v
v
>>>>>>>>>>>>>>>>>@
```
input - dddsssdddddasddddwww
```
>>>v
v @
v ^
>>>>v< ^
>>>>^
```
my personal favorite - dwdwdwddaasassdddddwdwdwddsdswawaasassdddddddwdwdwddsdswawaasassddddwwwwwwwssssssdsdddwwwwddaassddaassddddsssdddwdwdwddaasasassddddwwwwssssssssasasaaawdwwdwddwwdddddddwdwdwddsdswawaasassddddddddddwwdwwwwaasssassdsdddddddwdwdwwwwasasssssssssssdwwwwwwwddd
```
v
v
v
v v<<
v<< v<< v<<v v
v< v< ^< v< ^v v<< v<< v<
>v >v ^ >v >v v v ^ v<^
>^>>>>>^>>>>>>>^>>>>^>>>>>>>v v<v v ^ v ^
v v< v v<< v< ^ v ^
v v< v v< ^< v >^ v>^
>>>v v >v ^ >v^ v>>>@
>>>>>>>>>>^>>>>>>>>>>>>>>>>v^
^v v^
>>^v v^
>^ v v^
^ v< v^
>^ v< v^
^<<< >^
```
[Answer]
# C# 607
```
namespace System{using B=Text.StringBuilder;class P{static void Main(){var f=new Collections.Generic.List<B>(){new B("O")};int w=1,r=0,c=0;for(Action R=()=>f[r].Append(' ',w-f[r].Length+1);1>0;){var key=Console.ReadKey(1>0).KeyChar;if(key=='w'){f[r][c]='^';if(--r<0)f.Insert(r=0,new B());R();f[r][c]='O';}if(key=='a'){f[r][c]='<';if(--c<0){foreach(var s in f)s.Insert(c=0,' ');w++;}R();f[r][c]='O';}if(key=='s'){f[r][c]='v';if(++r>f.Count-1)f.Add(new B());R();f[r][c]='O';}if(key=='d'){f[r][c]='>';if(++c>w++)foreach(var s in f)s.Append(' ');R();f[r][c]='O';}Console.WriteLine(string.Join("\n",f)+"\n");}}}}
```
"Ungolfed" with whitespace (this will not be kept in sync with the golfed version):
```
namespace System
{
using B = Text.StringBuilder;
class P
{
static void Main()
{
var f = new Collections.Generic.List<B>() { new B("O") };
int w = 1, r = 0, c = 0;
Action R = () => f[r].Append(' ', w - f[r].Length + 1);
while (true)
{
char key = Console.ReadKey(1>0).KeyChar;
if (key == 'w')
{
f[r][c] = '^';
if (--r < 0) { f.Insert(0, new B()); r = 0; }
R();
f[r][c] = 'O';
}
if (key == 'a')
{
f[r][c] = '<';
if (--c < 0)
{
foreach (var s in f)
s.Insert(0, ' ');
w++;
c = 0;
}
R();
f[r][c] = 'O';
}
if (key == 's')
{
f[r][c] = 'v';
if (++r > f.Count - 1) f.Add(new B());
R();
f[r][c] = 'O';
}
if (key == 'd')
{
f[r][c] = '>';
if (++c > w++)
{
foreach (var s in f)
s.Append(' ');
}
R();
f[r][c] = 'O';
}
Console.WriteLine(string.Join("\n", f) + "\n");
}
}
}
}
```
[Answer]
# Python 3: 259 Bytes
```
x=y=0
b,p,r={},(0,-1,0,1),range
while 1:
d='wasd'.index(input());b[(x,y)]='^<v>'[d];x+=p[d];y-=p[~d];b[(x,y)]='☺';l,m=([k[i]for k in b]for i in(0,1))
for j in r(min(m),max(m)+1):print(''.join(b[(i,j)]if(i,j)in b else' 'for i in r(min(l),max(l)+1)))
print()
```
I decided to store the snake in a dict, with coordinates for the keys. Then find and iterate over the output range, substituting blank spaces.
```
x = y = 0
board = {}
while 1:
d = 'wasd'.index(input())
board[(x, y)] = '^<v>'[d] # body
x += (0, -1, 0, 1)[d]
y -= list(reversed((0, -1, 0, 1)))[d]
board[(x,y)] = '☺' # head
xs, ys= ([coord[dim] for coord in board] for dim in(0, 1))
for j in range(min(ys), max(ys)+1):
print(''.join(board[(i,j)] if (i,j) in board else ' '
for i in range(min(xs), max(xs)+1)))
print()
```
PS.
My first Golf :)
Let me know if my answer is inappropriate
[Answer]
## Python 2.7 - 274 bytes
```
x,y,m,d,r=0,0,{},(0,-1,0,1),range
for c in raw_input():b='wasd'.index(c);m[(x,y)]='^<v>'[b];x+=d[b];y-=d[~b];m[(x,y)]='@';l,n=([k[h] for k in m] for h in (0, 1))
for j in range(min(n),max(n)+1):print(''.join(m[(i,j)] if (i,j) in m else ' 'for i in range(min(l),max(l)+1)))
```
## Ungolfed version
```
x,y,matrix,delta = 0,0,{},(0, -1, 0, 1)
for c in raw_input('Command: '):
d = 'wasd'.index(c)
matrix[(x, y)] = '^<v>'[d]
x += delta[d]
y -= list(reversed(delta))[d]
matrix[(x, y)] = '@'
xs, ys = ([xy[i] for xy in matrix] for i in (0, 1))
for j in range(min(ys), max(ys)+1):
print(''.join(matrix[(i, j)] if (i, j) in matrix else ' '
for i in range(min(xs), max(xs)+1)))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~35~~ ~~34~~ ~~30~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.•₃º•"<>v^"©‡0ªÐUĀ>sŽO^®XkèΛ
```
Uses `0` as head of the snake.
-4 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##yy9OTMpM/f9f71HDokdNzYd2AWklG7uyOKVDKx81LDQ4tOrwhNAjDXbFR/f6xx1aF5F9eMW52f//pwBBIhAUg0AKApSDAE4JMADLoCsBy4AYcCkUG2BKoUaAFcKtAamDGgkBCLOQRVGE4Y4AAA) (no test suite for all test cases at once, because there is no way to reset the Canvas, so outputs would overlap..).
**Explanation:**
```
.•₃º• # Push compressed string "adsw"
"<>v^" # Push string "<>v^"
© # Save it in variable `r` (without popping)
‡ # Transliterate the (implicit) input-string,
# replacing all "adsw" with "<>v^" respectively
# i.e. "ddddssaassdddddww" → ">>>>vv<<vv>>>>>^^"
0ª # Convert the string to a list of characters, and append a 0 (for the head)
# → [">",">",">",">","v","v","<","<","v","v",">",">",">",">",">","^","^","0"]
Ð # Triplicate this list of characters
U # Pop and store one of the three lists in variable `X`
Ā # Trutify each character ("0" remains 0; everything else becomes 1)
> # And then increase each integer by 1
# → [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1]
s # Swap the two lists on the stack
®Xk # Get the index of each character of variable `X` in variable `r` ("<>v^")
# i.e. [">",">",">",">","v","v","<","<","v","v",">",">",">",">",">","^","^","0"]
# → [1,1,1,1,2,2,0,0,2,2,1,1,1,1,1,3,3,-1]
ŽO^ è # And use those to index into the compressed number 6240
# → [2,2,2,2,4,4,6,6,4,4,2,2,2,2,2,0,0,0]
Λ # Use the Canvas builtin with these three lists
```
[See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•₃º•` is `"adsw"` and `ŽO^` is `6240`.
As for a brief explanation of the Canvas builtin `Λ` and its three arguments:
**First argument: length(s):** the sizes of the lines we want to draw. Since we have to keep in mind overlapping, we use size 2 for every character, and an additional 1 for the head of the snake.
**Second argument: string(s):** the characters we want to display. Which are the characters in this case, appended with the head-character of the snake.
**Third argument: direction(s):** the directions these character-lines of the given length should be drawn in. In general we have the directions `[0,7]` which map to these directions:
```
7 0 1
↖ ↑ ↗
6 ← X → 2
↙ ↓ ↘
5 4 3
```
Which is why we have the integer `6240` for the directions \$[←,→,↓,↑]\$ respectively.
[See this 05AB1E tip of mine for a more detailed explanation about the Canvas builtin `Λ`.](https://codegolf.stackexchange.com/a/175520/52210)
[Answer]
# Perl - 394
Not the shortest, but it beats Javascript, C# and Java at least.
```
use List::Util qw(min max);sub c{()=$_[0]=~/$_[1]/g}%l=(a,['<',-1,0],d,['>',1,0],w,['^',0,-1],s=>['v',0,1]);($s,$x,$y,$w,$h)=($ARGV[0],0,0,max(c($s,a),c($s,d)),max(c($s,w),c($s,'s')));@s=split'',$s;map$x=min($x,$i+=$l{$_}[1]),@s;$i=0;map$y=min($y,$i+=$l{$_}[2]),@s;$x=abs $x;$y=abs $y;map{$m[$y][$x]=$l{$_}[0];$x+=$l{$_}[1];$y+=$l{$_}[2]}@s;$m[$y][$x]='o';map{map{print$_||' '}@$_;print"\n"}@m
```
Some tricks:
* Warnings and strict not turned on to allow barewords and not declaring variables before using them
* Thin commas instead of fat commas to save a few characters
* Not setting initial values for variables when not necessary
* Leaving out semi-colons when possible
* Defining arrays and hashes not as references to avoid having to use ->
* Allowing width, height to be larger than necessary to avoid having to calculate them accurately (which would take extra code)
Things that hurt:
* No built-in way to count number of characters in a string (might have been longer anyway)
* No built-in min/max functions, thus need to waste 27 characters to import library that does it (less than defining our own)
[Answer]
# C - 273 bytes - with Interactive Input!
```
#define F for(i=w*w
*g,*G,x,i,j,w,W,u;main(w){putch(1);F;j=-~getch();g=G){if(!(x%w&&~-~x%w&&x/w&&x/w^~-w)){W=w+6;G=calloc(W*W,4);F-1;u=i%w+i/w*W-~W*3,i==x?x=u:8,i;)G[u]=g[i--];free(g);w=W;}G[x]="<^X>v"[j%=7];G[x+=1-G[x]%3+W*(!!j-j/2)]=1;F;i;)putch(i--%W?G[i]?G[i]:32:10);}}
```
The field is printed each time a character is entered and grows if the snake's head nears the edge. I don't know how portable it is--someone on the Internet said getch() doesn't work on non-Windows platforms. Hard to say whether ASCII 1 will look like a smiley face either.
The golfed version is quite annoying as there is no way to gracefully exit the program. Control-C doesn't work for me. On the other hand, the ungolfed version terminates if a character other than 'w', 'a', 's', or 'd' is entered.
So-called "ungolfed":
```
#define SMILEYFACE 1
int main()
{
int o;
int w = 1;
int *g = 0, *g2;
int c, n;
int x = 0;
for( putch(SMILEYFACE);c = getch(); ) {
if(c!='w'&&c!='a'&&c!='s'&&c!='d')
return 1;
if(!(x%w) | !(~-~x%w) | !(x/w) | !(x/w-~-w) ) {
int wnew = w + 4;
int off = 2;
g2 = calloc(wnew*wnew,sizeof(int));
for(n = w*w; --n; )
g2[ n%w+off + (n/w+off)*wnew ] = g[n];
free(g);
g = g2;
x = (x/w+off)*wnew + x%w + off;
w = wnew;
}
int i = -~c%7;
g[x] = "<^X>v"[i];
int dx = 1-g[x]%3 + w * (!!i-i/2);
x += dx;
g[x] = SMILEYFACE;
for(o = w*w; o; )
putch(o--%w?g[o]?g[o]:32:10);
}
return 0;
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes
```
Ç7%DÉ+D"^>>v"ºsè0ªDĀ>rΛ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cLu5qsvhTm0XpTg7uzKlQ7uKD68wOLTK5UiDXdG52f//pwBBIhAUg0AKApSDAE4JMADLoCsBy4AYcCkUG2BKoUaAFcKtAamDGgkBCLOQRVGE4Y4AAA "05AB1E – Try It Online")
Explanation:
```
# implicit input (eg: "wasd")
Ç # codepoints (eg: [119, 97, 115, 100])
7% # modulo 7 (eg: [0, 6, 3, 2])
DÉ+ # plus itself modulo 2 (eg: [0, 6, 4, 2])
# This is the list of directions that will be passed to 05AB1E's canvas function, Λ.
# 0 means up, 6 left, 4 right, 2 down.
"^>>v"º # "^>>v", horizontally mirrored (namely "^>>vv<<^")
D sè # index into this with a copy of the list of directions
0ª # append "0"
# This is the list of strings that will be drawn.
D # duplicate the list of strings
Ā # truthify (maps letters to 1, 0 stays 0)
> # increment each
# This is the list of lengths to draw.
r # reverse the stack because Λ takes arguments in the opposite order
Λ # draw!
```
] |
[Question]
[
Write a program or function that takes in a positive integer N and outputs the first N numbers of this amplifying zigzag pattern, using only the lines needed:
```
26
25 27 .
10 24 28 .
9 11 23 29 .
2 8 12 22 30 44
1 3 7 13 21 31 43
4 6 14 20 32 42
5 15 19 33 41
16 18 34 40
17 35 39
36 38
37
```
So, if N is `1` the output is
```
1
```
If N is `2`, the output is
```
2
1
```
If N is `3` the output is
```
2
1 3
```
If N is `4` the output is
```
2
1 3
4
```
If N is `10` the output is
```
10
9
2 8
1 3 7
4 6
5
```
If N is `19` the output is
```
10
9 11
2 8 12
1 3 7 13
4 6 14
5 15 19
16 18
17
```
and so on.
# Notes
* Each peak or trough of the zigzag reaches its point one more line away from the line with the `1` on it than the previous peak or trough.
* N is not limited to `44`. The zigzag grows in the same pattern and larger N should be supported.
* Numbers with multiple digits should only "touch" at their corners, as depicted. Make sure this works when N is `100` and above.
* There should be no empty (or space only) lines in the output except one optional trailing newline.
* Any line may have any amount of trailing spaces.
# Scoring
The shortest code in bytes wins. Tiebreaker is earlier answer.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~41~~ ~~37~~ 29 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷
```
[Try it online!](http://jelly.tryitonline.net/#code=UkTCteG4jOKAmcK9xIotKl9ceMKpTOKCrOG5oi7hu4vCruG6oeKCrOKBtuG6i2oiRlpq4oG3&input=&args=NDQ)
### How it works
```
RDµḌ’½Ċ-*_\x©L€Ṣ.ị®ạ€⁶ẋj"FZj⁷ Main link. Argument: n (integer)
R Range; yield [1, ..., n].
D Decimal; yield A =: [[1], ..., [1, 0], ...].
µ Begin a new, monadic chain. Argument: A
Ḍ Undecimal; convert back to falt range.
’ Decrement to yield [0, ..., n-1].
½Ċ Take the square root and round up (ceil).
-* Elevate -1 to each rounded square root.
_\ Cumulatively reduce by subtraction.
This yields [1, 2, 1, 0, -1, 0, ...], i.e., the
vertical positions of the digits in A.
L€ Compute the length of each list in A.
x Repeat the nth position l times, where l is the
nth length.
© Copy the result to the register.
Ṣ Sort.
.ị At-index 0.5; yield the last and first element,
which correspond to the highest and lowest position.
ạ€® Take the absolute difference of each position in the
register and the extrema.
This yields the number of spaces above and below
the integers in r as a list of pairs.
⁶ẋ Replace each difference with that many spaces.
F Flatten the list A.
j" Join the nth pair of strings of spacing, separating
by the nth digit in flat A.
Z Zip/transpose the result.
j⁷ Join, separating by linefeeds.
```
[Answer]
# PHP, ~~211~~ ~~177~~ ~~164~~ 163 bytes
Predict the peaks with `$n` and increase the array dynamically in either direction, using `($x, $y)` output cursor.
Numbers are aligned with `str_pad()` and the final output is the `implode()` of that array of strings (`$g`).
```
for($x=0,$d=-1,$h=$n=2,$y=$a=1;$a<=$argv[1];$y+=$d){$g[$y]=str_pad($g[$y],$x).$a;$x+=strlen($a);if($a++==$n){$h+=2;$n+=$h-1;$d*=-1;}}ksort($g);echo implode(~õ,$g);
```
## [Test it online!](http://sandbox.onlinephpfunctions.com/code/a8ca8a253713c3e241570f710f8ed8f76f75d507)
Update: removed 34 bytes by getting rid of the unneeded array\_pad().
Update2: followed @insertusernamehere's advice to shorten it a bit more.
Update3: followed @Lynn's advice to save one more byte with ~õ which imposes the use of LATIN-1 charset. (not available in online PHP emulator so not included there)
[Answer]
# Pyth, ~~60~~ ~~53~~ ~~52~~ ~~46~~ ~~42~~ ~~39~~ ~~38~~ ~~36~~ ~~34~~ ~~32~~ 31 bytes
39: It is now on par with [the bug-fixed version of Jelly](https://codegolf.stackexchange.com/a/82866/48934), and I have out-golfed Dennis' competing version!
38: I have out-golfed Dennis!
36: I have out-golfed Dennis again!
34: Even lower than his bug-fixed version!
31: 32 -> 31 thanks to Dennis.
```
~~[[email protected]](/cdn-cgi/l/email-protection)++\*]\*dl`hkabhSK`hk\*]\*dl`hkabeSKKd~~
~~[[email protected]](/cdn-cgi/l/email-protection)\*]\*dl`hkhaeSKhSKabhSKhkKd~~
~~J1K.u+N=J\_WsI@Y2JtQZ=-RhSKKjsM.t.eX\*]\*dl`hkheSKbhkKd~~
~~J1K.u+N=J\_WsI@Y2JtQQj-#dsMC.eX\*]\*dl`hkheSKbhkK~~
~~J1j-#dsMC.eX\*]\*dl`hkyQ+Qbhkm=+Z=J\_WsI@td2J~~
~~J1j-#dsMCmX\*]\*;l`hdyQ+Q=+Z=J\_WsI@td2Jhd~~
~~J1j-#dsMCmX\*]\*;l`hdyQ+Q=+Z=J\_WsI@td2Jh~~
~~J1j-#dsMCmX\*]\*;l`hdyQ+Q=+Z=@\_BJsI@td2h~~
~~j-#dsMCmX\*]\*;l`hdyQ+Q=+Zsty%s@td2 2h~~
~~j-#dsMCmX\*]\*;l`hdyQ+Q=+Z@\_B1.E@d2h~~
~~JQj-#dsMCmX\*]\*;l`hdyQ=+J@\_B1.E@d2h~~
~~JyQj-#dsMCmX\*]\*;l`hdJ=+Q@\_B1.E@d2h~~
~~j-#dsMCmX\*]\*;l`hdyQ=+Q@\_B1.E@d2h~~
j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2h
```
[Try it online!](http://pyth.herokuapp.com/?code=j-%23dsMCmX%2a%5D%2a%3Bl%60hdyQ%3D%2BQ%40_B1.E%40d2h&input=44&debug=0)
## How it works
```
j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2h input: Q
j-#dsMCmX*]*;l`hdyQ=+Q^_1.E@d2hdQ implicit filling arguments
m Q for each number d from 0 to Q-1:
@d2 yield the square root of d.
.E yield its ceiling.
^_1 raise -1 to that power. this
yields the desired direction.
=+Q increment Q by this amount.
hd yield d+1.
` yield its string representation.
l yield its length.
*; repeat " " for that number of times
] yield a list containing the string above.
* yQ repeat the list for Q*2 times.
the Q has changed, but Q*2 is
an overshoot that is high
enough, so we don't have to
worry about it.
X in that list, replace the
element with index being the
number generated above
hd with d+1.
C transpose the resulting array.
sM flatten each element.
-#d remove lines containing only spaces.
(filter on truthiness of set difference with space)
j join by newlines.
```
[Answer]
# MATLAB, 148 bytes
```
n=input('');k=fix(n^.5);m=0;w=1;d=-1;for l=1:n;s=num2str(l);m(k+1,w:w+nnz(s)-1)=s;w=w+nnz(s);k=k+d;d=d*(-1)^(l^.5==fix(l^.5));end;[m(any(m,2),:),'']
```
Note that the spaces are missing in Octave, as MATLAB prints the the character indexed with `0` as a space, while octave does just omit that character.
Explanation:
```
n=input('');
k=fix(n^.5); %caculate starting height
m=0;w=1;d=-1; %initialize counters and output matrix
for l=1:n;
s=num2str(l);
m(k+1,w:w+nnz(s)-1)=s; %insert current index as a string
w=w+nnz(s); %current horizontal position
k=k+d; %current vertical position
d=d*(-1)^(l^.5==fix(l^.5)); %if we reached a square number, change direction
end
[m(any(m,2),:),''] %delete all zero rows
```
[Answer]
## Haskell, ~~144~~ 142 bytes
```
g n|k<-take n$scanl(+)0$[1..]>>= \x->(-1)^x<$[2..2*x]=unlines[[1..n]>>= \x->show x#(k!!(x-1)==y)|y<-[minimum k..maximum k]]
s#g|g=s|1<2=' '<$s
```
Usage example:
```
*Main> putStr $ g 19
10
9 11
2 8 12
1 3 7 13
4 6 14
5 15 19
16 18
17
```
How it works:
```
s#g|g=s|1<2=' '<$s -- # is a helper function that expects a string s
-- and a boolean g. It returns s if g is True, else
-- as many spaces as there a characters in s
k<-take n$ -- bind k to the first n elements of
[1..]>>= \x->(-1)^x<$[2..2*x] -- 2*x-1 copies of (-1)^x for each x in [1,2,3,...]
-- i.e. [-1, 1,1,1, -1,-1,-1,-1,-1, 1,1,1,1,1,1,1..]
scanl(+)0 -- build partial sums, starting with 0
-- i.e. [0,-1,0,1,2,1,0,-1,-2,-3,-2,-1...]
-- -> k is the list of y coordinates for the
-- numbers 1,2,3,...
[ |y<-[minimum k..maximum k]] -- for all y coordinates in k
\x->show x#(k!!(x-1)==y) -- map the # function
[1..n]>>= -- over [1..n] (the x coordinates)
-- where # is called with
-- s -> a string representation of x
-- g -> True if k at index x equals the current y
unlines -- join with newlines
```
Edit: Thanks @Lynn for two bytes!
[Answer]
## JavaScript (ES6), 213 bytes
```
with(Math)n=>(a=[...Array(n)].map((_,i)=>n-=1+sqrt(--i)&1||-1).map((e,_,a)=>e-min(...a))).map((e,i)=>r[e][i]=++i,r=[...Array(1+max(...a))].map(_=>a.map((_,i)=>` `.repeat(1+log10(++i)))))&&r.map(a=>a.join``).join`\n`
```
Where `\n` represents a literal newline character. Explanation:
```
with(Math) Bring functions into scope
n=> Accepts one parameter
(a= Intermediate result variable
[...Array(n)].map( For each number 0..n-1
(_,i)=>n-= Accumulate index for each number
1+sqrt(--i)&1||-1 Calculate the direction
).map((e,_,a)=>e-min(...a)) Scale the smallest index to zero
).map((e,i)=>r[e][i]=++i, Overwrite the padding with 1..n
r=[...Array(1+max(...a))].map( Calculate number of lines
_=>a.map((_,i)=> For each number 1..n
` `.repeat(1+log10(++i))))) Calculate the padding needed
&&r.map(a=>a.join``).join`\n` Join everything together
```
To shorten `pow(-1,ceil(sqrt(i)))` I rewrite it as `sqrt(i-1)&1||-1` however this doesn't work for `i=0` so to fix that I add 1 but this then flips the sign of the result which is why I end up with `n-=`.
[Answer]
# Python 2, 137 bytes
```
l={}
i=x=y=n=v=0
exec"v+=1;l[y]=l.get(y,'').ljust(x)+`v`;x+=len(`v`);i=-~i%-~n;y+=n%4-1;n+=2>>i*2;"*input()
for k in sorted(l):print l[k]
```
View the output on [ideone](http://ideone.com/6kjoAR).
] |
[Question]
[
Growing up, my first console game system was an Atari 2600 and I will always have a love for some of those games I so enjoyed as a child. Many of the graphics are still memorable, perhaps even iconic.
It turns out that these sprites are very simplistic bitmaps, 8 pixels wide with variable height where the binary representation is the arrangement of the pixels.
For example, the hex bytes 0x18, 0x24, 0x18 would draw a crude circle like so:
```
0x18: 00011000
0x24: 00100100
0x18: 00011000
```
As 8 pixels wide creates fairly small graphics (even by Atari 2600 standards) it was common to double or quadruple either the height, width or both to create a larger (though more blocky and distorted) version of the same image. They would commonly also be flipped vertically or horizontal for both player sprites and playfields. The game *Combat* is a good example of this.
The challenge is, to write code to display these sprites as "graphics" in ASCII form including the ability to stretch or flip them vertically, horizontally or both. This must be in the form of either a full program, or callable function.
## Input:
* An array of bytes, each representing the horizontal bits for that line.
* A non-zero integer value for each direction, horizontal and vertical representing the scaling factor for that dimension.
* A negative value indicates that the dimension should also be flipped along it's axis.
## Output:
* ASCII representation to STDOUT or a newline-separated string, using a space character for black (0) pixels and any printable, non-space character of your choice for white (1) pixels.
## Test data:
```
bmp1 = [ 0x06, 0x0F, 0xF3, 0xFE, 0x0E, 0x04, 0x04, 0x1E, 0x3F, 0x7F, 0xE3, 0xC3, 0xC3, 0xC7, 0xFF, 0x3C, 0x08, 0x8F, 0xE1, 0x3F ]
bmp2 = [ 0x07, 0xFD, 0xA7 ]
bmp3 = [ 0x00, 0x8E, 0x84, 0xFF, 0xFF, 0x04, 0x0E, 0x00 ]
bmp4 = [ 0x00, 0xFC, 0xFC, 0x38, 0x3F, 0x38, 0xFC, 0xFC]
```
Note: Above example input arrays of bytes are provided as hex. If your platform does not accept hex literals for byte representation you may convert them to a native byte-equivalent literal.
## Example Output:
```
f( bmp1, 1, 1 ) =>
--------
XX
XXXX
XXXX XX
XXXXXXX
XXX
X
X
XXXX
XXXXXX
XXXXXXX
XXX XX
XX XX
XX XX
XX XXX
XXXXXXXX
XXXX
X
X XXXX
XXX X
XXXXXX
--------
f( bmp1, -2, 1 ) =>
----------------
XXXX
XXXXXXXX
XXXX XXXXXXXX
XXXXXXXXXXXXXX
XXXXXX
XX
XX
XXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXXXX
XXXX XXXXXX
XXXX XXXX
XXXX XXXX
XXXXXX XXXX
XXXXXXXXXXXXXXXX
XXXXXXXX
XX
XXXXXXXX XX
XX XXXXXX
XXXXXXXXXXXX
----------------
f( bmp2, 1, 2 ) =>
--------
XXX
XXX
XXXXXX X
XXXXXX X
X X XXX
X X XXX
--------
f( bmp2, 2, 1 ) =>
----------------
XXXXXX
XXXXXXXXXXXX XX
XX XX XXXXXX
----------------
f( bmp2, -2, -2 ) =>
----------------
XXXXXX XX XX
XXXXXX XX XX
XX XXXXXXXXXXXX
XX XXXXXXXXXXXX
XXXXXX
XXXXXX
----------------
f( bmp3, 1, -1 ) =>
--------
XXX
X
XXXXXXXX
XXXXXXXX
X X
X XXX
--------
f( bmp3, 3, 3 ) =>
------------------------
XXX XXXXXXXXX
XXX XXXXXXXXX
XXX XXXXXXXXX
XXX XXX
XXX XXX
XXX XXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXX
XXX
XXX
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
------------------------
f( bmp4, -1, -1 ) =>
--------
XXXXXX
XXXXXX
XXX
XXXXXX
XXX
XXXXXX
XXXXXX
--------
f( bmp4, 4, 2 ) =>
--------------------------------
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
--------------------------------
```
Note: the horizontal lines above and below are to show the beginning and end of the output. They are not required in the output, however empty lines (represented by all zeros/spaces) at the beginning and/or end are required, as shown.
Note 2: these test bitmaps were inspired by and re-drawn/coded based on game screenshots tagged as "fair use" on Wikipedia.
## Winning Criteria
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes per language wins.
* Standard [loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
[Answer]
# [Python 2](https://docs.python.org/2/), 117 bytes
```
def f(m,w,h):
for r in m[::cmp(h,0)]:print(''.join(' X'[1<<i&r>0]*abs(w)for i in range(8)[::cmp(0,w)])+'\n')*abs(h),
```
[Try it online!](https://tio.run/##bZBRa4MwFIXf8yvu05JscUQTpkg3GK7@hoHLQ7vVasEoruD2611zU7GrhfgRzj3nekj3e6xaG43j166EkjViEBVPCZRtDz3UFpoiTT@bjlVCcpN2fW2PjNLHQ1tbRuGdFuFqVd/1L9Lcb7bfbOAuWbtkv7H7HUv4eYEUAzf8gX5YytFacTFumy6EZyhA/sgn4Zg75gq5RsVTzwxRUeiMkWv0Z5eMcQNOVYbZxDHx/tBvAENODaKpgc@8Ob7GfqammcQ0/jnR827PczvfVPqk/pfMs5kqmfv7@zQ1hJQM3KMIcAc4wRef1SBayhGao6V62xvgd6Ur3BGES9mdK1U75w33SdcXRcY/ "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~27~~ 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εS²Ä×J³Äи²0‹ií]³0‹iR}˜0ð:»
```
Takes the input as a list of 8-bit binary-strings, and outputs with `1` as non-space character.
-1 byte thanks to *@MagicOctopusUrn*.
[Try it online](https://tio.run/##yy9OTMpM/f//3NbgQ5sOtxye7nVo8@GWCzsObTJ41LAz8/Da2EObwayg2tNzDA5vsDq0@///aCUDEDA0NFDSUVCCMA0NQWwQDeLB2IaoauBsA6AqLGwk9RDNYLYhgg02Hm6@AW62IYobDBFmIuwFKQOrQXU/WArFDbFcusZcukYA) or [verify all test cases](https://tio.run/##yy9OTMpM/W9o5ubpGeoZ9v/c1uCIwy2Hp3tFHm65sCPC4FHDzszDa2trI8GsoNrTcwwOb7A6tPu/jrquqcHh6Ye26R3eofM/WskABAwNDZR0FJQgTENDEBtEg3gwtiGqGjjbAKgKCxtJPUQzmG2IYIONh5tvgJttiOIGQ4SZCHtBysBqUN0PlkJxQyyXIRCOOE/rGiH7GslkiEpDA0OIOCh4jIhTSLSJQLt14WaiOhnOhgWhIWpQIXkdNchRogJkJsjhuoa0t8UYCNEsMUTECjIbot0AMzUgiWPVGwvyCKZfqG@NCbFRbchlTmRUm8MdDrVcCRyghlAmVBQpE@JXZgRzIX5lpkBIlKVEKdM1BXoCAA).
**Explanation:**
```
ε # Map the (implicit) input-list to:
S # Convert the binary-String to a list of characters
²Ä # Take the absolute value of the second input
× # And repeat each character that many times
J # And then join it back together to a single string again
³Ä # Take the absolute value of the third input
и # Repeat that string as a list that many times
²0‹i # If the second input is negative:
í # Reverse each string in the list
] # Close both the if-statement and (outer) map
³0‹i } # If the third input is negative:
R # Reverse the list of lists
˜ # Flatten the list of lists to a list of strings
0ð: # Replace all 0s with spaces " "
» # And join the strings by newlines (which is output implicitly)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~24~~ 19 bytes
```
B,!i|1&Y"2M0<?XP]Zc
```
Inputs are an array of decimal numbers, horizontal scale, vertical scale.
[Try it online!](https://tio.run/##y00syfn/30lHMbPGUC1SycjXwMY@IiA2Kvn//2gzBSAwNAUSRibGINLUBCwCJhWQSGMDEGkGUmNoZA5SCSYNLU2RSEuwCaZglWD1ChZgw8AmG0HEjWO5dI24DAE)
### Explanation
```
B % Implicit input: array of numbers. Convert to binary. Gives a zero-one
% matrix, each row containing the binary expansion of a number
, % Do twice
! % Transpose
i % Input: number
| % Absolute value
1&Y" % Repeat each row that many times
2M % Push the latest input again
0< % Is it negative?
? % If so:
XP % Flip vertically
] % End
Zc % Convert each nonzero into '#'. Zeros are displayed as space
% Implicit end. Implicit display
```
[Answer]
# Dyalog APL, ~~46~~ ~~42~~ 33 bytes
```
' #'[⍉⊃{⊖⍣(0>⍺)⍉⍵/⍨|⍺}/⎕,⊂⎕⊤⍨8/2]
```
[Try it online!](https://tio.run/##fY/BSsNAEIbv@xQLHraFluxmQ7MnoaQJPoIgHirSIlTaq9ReFLQurHhRvKuQmwfx4jGPMi8SZ6YuloIG8m1m//@fmYwXs/7pxXg2n7Zw/3g2h5sHLWB9KyetknvqCMId@Osl@CcILx29D@GrS3fhM4FQX2K5SjDYA3@FB/hXvHVJetxiD3FQHkpsKJdmAP6tqTtoGfUQwy6snyF8NDU2WomT84VhIwWUHihEhagsoaSSkUUYKi1ZckJJvuIXOcVIsAUlHMKxz2xiNDDdGsj@EWKYs2a3NE1hGuey2JWxWYbX0hzKdkJVEWFd3Ja/otBO@MeFkUao/s6jxI/avKf/6Cnr@P7psMJK@w0 "APL (Dyalog Unicode) – Try It Online")
-9 thanks to ngn!
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), 252 bytes
```
N+E+R:-N<1,R=[];N-1+E+S,R=[E|S].
N*E*R:-R=E,E=[];N<0,reverse(E,F),-N*F*R;[H|T]=E,N+H+S,N*T*U,append(S,U,R).
N/E/R:-N<1,R=[];(E<N,D=E,F=32;D=E-N,F=35),N/2/D/C,R=[F|C].
[H|T]^X^Y^R:-128/H/A,X*A*B,Y*[[10|B]]*C,append(C,D),(T=[],R=D;T^X^Y^S,append(D,S,R)).
```
[Try it online!](https://tio.run/##XZLdasJAEIXvfQrvzK4T82drqEqJmw1etKsmEZQ0AaG2FFoVLW0vpK9uZ2crSlg47M53zswEsttv37ev9uH77XRSbdlO72w18CAdFmVf2R5WMv2Qx6zsNBSXHA3pUIIkw8CF/fprvT@sLQkJA1vxhKf9YnzMSzSp9hjjiud8Dqvdbr15tjKYQ8qwlSOd61mWHCiIMZMMA7@PF1vp6w0D5fhO7AhtS44Ct6Du1aJaVtjA80Nn7ESw4BEfwZIXheceR2XJxXmigJiBleMQbBH3c0pmZxoDfh9jndO9HQ2Lpvvj3oLWRGsSkEqqGO1e1KNKQM4eqSS/uNYedSAaCMqGWkPj90yHZgmNkZlu/LHWqKfrwtRdStHEsHvpafR/K7Ohq1PxVSoRFw3Cy87mfqY6FVUengd42e4/Vp9W6/fwtGlB8VAyzSzbZ4gf6/hR4xESv1J1pgzzkU7qbGIYtSWZ1h1T7RCYtWyPVbM6nhkc4EnrLNUsNkGSrO7IjKOLy@V1lpf4R/wB "Prolog (SWI) – Try It Online")
### Explanation
```
N+E+R:-N<1,R=[];N-1+E+S,R=[E|S]. Make `R` a list containing `E` repeated `N` times
N<1,R=[] If `N<1`, let `R` be the empty list
N-1+E+S Else recurse with `N-1`, `E` and `S`
R=[E|S] Let `R` be a new list with `E` as head and `S` as tail
N*E*R:-R=E,E=[];N<0,reverse(E,F),-N*F*R;[H|T]=E,N+H+S,N*T*U,append(S,U,R).
Let `R` be a list
with each element in `E` repeated `N` times
e.g. 2*[3, 6] -> [3, 3, 6, 6]
R=E,E=[] Let `R` be `E` if `E` is the empty list
N<0,reverse(E,F) Else if `N<0`, let `F` be the reverse of `E`
-N*F*R Recurse with `-N`, `F` and `R`
[H|T]=E Else let `H` be the head and `T` be the tail of `E`
N+H+S Let `S` be `N+H+S` (our function, not addition)
N*T*U Recurse with `N`, `T` and `U`
append(S,U,R) let `R` be the concatenation of `S` and `U`
N/E/R:-N<1,R=[];(E<N,D=E,F=32;D=E-N,F=35),N/2/D/C,R=[F|C].
Make `R` the binary representation of `E`
with `N` as the value of the current bit
where 0 and 1 are space and hash respectively
N<1,R=[] If `N<1` let `R` be the empty list
(
E<N,D=E,F=32 If `E<N` the bit isn't set, so `D=E`, `F=space`
D=E-N,F=35 Else `D=E-N`, `F=hash`
)
N/2/D/C Recurse with `N/2`, `D` and `C`
R=[F|C] Let `R` be a new list with `F` as head and `C` as tail
[H|T]^X^Y^R:-128/H/A,X*A*B,Y*[[10|B]]*C,append(C,D),(T=[],R=D;T^X^Y^S,append(D,S,R)).
Make `R` the result,
with inputs being the list `[H|T]`
and the scales `X` and `Y`
128/H/A Let `A` be the binary representation of `H` (8 bits)
X*A*B Let `B` be `A` with each element repeated `X` times
Y*[[10|B]]*C Let `C` be `B` with a newline prepended,
repeated `Y` times
append(C,D) Let `D` be `C` flattened by one level (joining lines)
(
T=[],R=D If `T` is empty, let `R` be `D`
T^X^Y^S Else recurse with `T`, `X`, `Y` and `S`
append(D,S,R) Let `R` be the concatenation of `D` and `S`
)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
FθE↔ζ⭆⮌↨ι²×§ Xμ↔ηF›η⁰‖F‹ζ⁰‖↓
```
[Try it online!](https://tio.run/##VY1Ni8IwFEX38yseXb1AhNbKVOzK8WMYUBCdxYB0ETtPW6itpkFl/nxMXhGdLM7i3Ptu8kLpvFGVtftGA54FrHRZG1yqE453Lf4JCRvj1MGbNV1It4QfyqGU0Bcu/i6P1OLYfNW/dMMAfgIJR@f9eSH8S994/FOTMqSxkBAKAWvaV5QbfMQLat1//7PRtLnWIrV2u4XwFr5Lz7nnPGbO2HQcPBmxibmZMGfcn7wy4QVO4wnfDj2HXT/qFiCT0OtLiDLbu1R3 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Fθ
```
Loop over the list of bytes.
```
E↔ζ
```
Map over the vertical scaling factor, thus multiplying the output lines.
```
⭆⮌↨ι²×§ Xμ↔η
```
Convert the input to base 2, reverse it, map the digits to space and `X`, then multiply each character by the horizontal scaling factor.
```
F›η⁰‖
```
If the horizontal scaling factor was positive, reflect to get the image the correct way around again.
```
F‹ζ⁰‖↓
```
Reflect vertically if the vertical scaling factor was negative.
[Answer]
# [C (clang)](http://clang.llvm.org/), 120 bytes
```
k,w,l,_;f(*o,z,x,y){for(w=z*y;w;)for(k=w>0?z*y-w--:++w,_=l=8*x;_;putchar(_?o[k/y]>>(l>0?--l/x:7-++l/x)&1?88:46:10))_=l;}
```
[Try it online!](https://tio.run/##bVDdboIwGL3vUzReLK20sVCiDQ2axelLMEOcG5sRwRAdqPHZWfuhotNeHOA7P98pC75I59l3Xa9YyVIW64R0c3ZgFdvTY5IXpAwP3b0uNbUfq7AcipEZ8JLzwHFKFodpqLqVjvVmt138zAsSj/Jo1dvPhkOSGjHnaa8KBtxxzJO@uCOlAr8fuIJS49WnGi2zLf5Yb9zIEzMc4iMWlegzi1OLUwk4gUmDfosuTCQoB4AT0I9vcQAJwMoxeJVF1ejdJgGf9KWKF8kZPldpvG8WXwc3Ghmpq0YIiIMqym@XNXiu21QXNxG@jQjxTcR03KJU7c2a9wtrIxD6zZefOI4JPW4KE5iQDr@e96xD9QnBovV8mRGKjwglBP4z88wuc2kXU41sgL5juAcUvuc8JsHk/TcB4T1JA8KG8QePZArCuPuUMT75UMC3DH9qAso/d7MHm1N8bXdFhoVGJ1T/AQ "C (clang) – Try It Online")
[Answer]
# [Common Lisp](http://www.clisp.org/), 157 bytes
```
(lambda(l x y)(dolist(i(if(< y 0)(reverse l)l))(dotimes(j(abs y))(dotimes(n 8)(dotimes(k(abs x))(princ(if(logbitp(if(< x 0)n(- 7 n))i)"#"" "))))(princ"
"))))
```
[Try it online!](https://tio.run/##bVDNboMwDL73KSx6mHNAggYNDrtMrLwH0FBlDYEBm@jTMzsMWNkun/D3Z4fS6L6dsFfDB1wnNHldXHI0MMJd4KUhdUCNusIXuEMgsFNfqusVGGEEGwZdqx7fMS96SmyMhWQbbk4eSW47bUuuM8210EM7N4/UbNGHGKwQWnhHzwNPiMXvHdwwUaGqPi1Uy300lLkxcIWZEPM7zBMex@AZCDKCTDKceXQQLRDyKNkSM5zZl24Qc4wFmXIiIUicL3QxIQ7zutqtc@43gtd4VaxTAg7yqiRaGh3Mh7iTgjXSrJEsXUAmy53u60fgSEUPDyH89Z8c5Z/2XE220576x0VJf@ezFPXDPSdBPlINmf74Goge1k7f "Common Lisp – Try It Online")
### Explanation
```
(lambda(l x y) ; Lambda with parameters `l`, `x`, `y`
(dolist
(i ; For `i` in the list
(if(< y 0)(reverse l)l) ; The reverse of `l` if `y<0` else `l`
)
(dotimes(j(abs y))(dotimes(n 8)(dotimes(k(abs x))
; Do `y` times, for `n` from 0 to 7, do `x` times
(princ(if(logbitp(if(< x 0)n(- 7 n))i)"#"" "))))
; If `x<0` and the `n`th bit is 1
; or `x>0` and the `7-n`th bit is 1
; print "#", else print " "
(princ"
") ; After every `y` loop, print a newline
)
)
)
```
[Answer]
# [Tcl](http://tcl.tk/), 192 bytes
```
proc f {l x y} {lmap i [if $y<0 {lreverse $l} {lindex $l}] {time {lmap n {0 1 2 3 4 5 6 7} {time {puts -nonewline [expr $i&1<<($x<0?$n:7-$n)?{#}:{ }]} [expr abs($x)]};puts {}} [expr abs($y)]}}
```
[Try it online!](https://tio.run/##ZZBRa4MwFIXf@ysOXRjrg2ASo2sn9IcUH7ouBUGjqNuUkN/ubqIbcyPcKOd85ya5w62a57ZrbrjDVhgxOfrW1xYlLuUdbMpjEjr9obteg1XeLs2bHv1/ATuUtV4TBjYGh4BEAoUUmfv22/ehR2Qaoz8prXHRY9uBlY88z5/YmMdnZk5ZxMzhbB/cycIVboWurz0Rh8K9hCbWbYyJDDf3ekAFm4IriERCqAQ8gV8yRirBRQZBxY9qrSNBdMcYz0TKYKbS7XynGpZoRak0W5TlZYkAlyLkfIUj4gVoPCCUCKVSfyTtq@B2NMeKJsN34Qn7/SJEYqvUfnhb4R9BmWjDGApFfKtIyN9CQ8AfpqHb/7SZvwA "Tcl – Try It Online")
```
proc f {l x y} Define a function `f` with arguments `l`, `x`, `y`
{lmap i For each `i` in
[if $y<0 {lreverse $l} {lindex $l}] The reverse of `l` if `y<0` else `l`
{
time { Do `abs(y)` times
lmap n {0 1 2 3 4 5 6 7} { For `n` from 0 to 7
time { Do `abs(x)` times
puts -nonewline Print without newline
[expr $i&1<<($x<0?$n:7-$n)?{#}:{ }]
If `x<0` and the `n`th bit is 1 or
`x>0` and the `7-n`th bit is 1
then return "#" else return " "
} [expr abs($x)]
};
puts {} Print a newline
} [expr abs($y)]
}
}
```
[Answer]
# 8088 machine code, IBM PC DOS, ~~77~~ 71 bytes
**Assembled:**
```
B402 84FF 7906 FD03 F14E F6DF 518A CFAC 5051 B108 8AF3 84F6 7902 F6DE
518A CEB2 2384 DB79 04D0 C8EB 02D0 C072 02B2 2050 CD21 58E2 FA59 E2E4
B20D CD21 B20A CD21 5958 E2CC 59E2 C5
```
**Listing:**
```
PR_BMP MACRO BMP, SZBMP, ZX, ZY
LOCAL LOOP_Y, LOOP_Y2, LOOP_X, LOOP_X2, X_POS, X_NEG
B4 02 MOV AH, 2 ; DOS display char function
84 FF TEST ZY, ZY ; is Y scale negative?
79 06 JNS LOOP_Y ; if positive, start Y LOOP
FD STD ; direction flag start from end
03 F1 ADD BMP, CX ; advance input byte array to end
4E DEC BMP ; zero adjust index
F6 DF NEG ZY ; make counter positive
LOOP_Y:
51 PUSH CX ; save outer byte loop counter
8A CF MOV CL, ZY ; set up repeat counter (Y scale factor)
AC LODSB ; load byte into AL
LOOP_Y2:
50 PUSH AX ; save original AL
51 PUSH CX ; save outer loop
B1 08 MOV CL, 8 ; loop 8 bits
8A F3 MOV DH, ZX ; DH is positive X scale used as counter
84 F6 TEST ZX, ZX ; is X scale negative?
79 02 JNS LOOP_X ; if so, make counter positive
F6 DE NEG DH ; compliment X counter
LOOP_X:
51 PUSH CX ; save bit counter
8A CE MOV CL, DH ; set repeat counter (X scale factor)
B2 23 MOV DL, '#' ; by default, display a #
84 DB TEST ZX, ZX ; is X scale negative?
79 04 JNS X_POS ; if so, rotate left 1 bit
D0 C8 ROR AL, 1 ; else rotate right LSB into CF
EB 02 JMP X_NEG ; jump to examine CF
X_POS:
D0 C0 ROL AL, 1 ; rotate left MSB into CF
X_NEG:
72 02 JC LOOP_X2 ; is a 1?
B2 20 MOV DL, ' ' ; if not, display a space
LOOP_X2:
50 PUSH AX ; save AL (since silly DOS overwrites it)
CD 21 INT 21H ; display char
58 POP AX ; restore AL
E2 FA LOOP LOOP_X2 ; loop repeat counter
59 POP CX ; restore bit counter
E2 E4 LOOP LOOP_X ; loop bit counter
B2 0D MOV DL, 0DH ; display CRLF
CD 21 INT 21H
B2 0A MOV DL, 0AH
CD 21 INT 21H
59 POP CX ; restore outer loop
58 POP AX ; restore original AL
E2 CC LOOP LOOP_Y2 ; loop row display
59 POP CX ; restore byte counter
E2 C5 LOOP LOOP_Y ; loop byte counter
ENDM
```
This turned out to be more of a doozy in ASM than I originally thought. Multiple concurrent loops and lots of if/else branching can certainly give you headaches.
This is implemented as a MACRO since it allows function-like parameter passing for testing.
**Output**
Here is a test program for DOS that prompts for the X and Y scaling factor and draws to the screen. Note, scaling the dragon too much will scroll past the top since default DOS window is only 24 rows.
[](https://i.stack.imgur.com/GKLKc.png)
And here's our little dragon (duck):
[](https://i.stack.imgur.com/wrz9q.png)
**Try it Online!**
You can test in a DOS VM using [DOSBox](https://www.dosbox.com/) or [VirtualConsoles.com](https://virtualconsoles.com/online-emulators/DOS/) with the following steps:
1. Download [VCS.ZIP](https://stage.stonedrop.com/ppcg/VCS.ZIP) (contains all four executables)
2. Go to <https://virtualconsoles.com/online-emulators/DOS/>
3. Upload the ZIP file you just downloaded, click Start
4. Type `PLANE`, `KEY`, `TANK` or `DRAGON`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~146~~ 132 bytes
```
param($x,$y,$b)&($t={$b|%({$r+=,$_*$y},{$r=,$_*-$y+$r})[$y-lt0]
$r-ne$e})|%{$b=,$_*8|%{''+' X'[($_-shr$i++%8)%2]}
$y=-$x;-join(&$t)}
```
[Try it online!](https://tio.run/##bVPtasJAEPx/T7GEjblrLhCN1EARLFafIVBEantFW1ttTGmC5tnt3V6@tF3IMLc7OzchZL/7UelhrbbbM77CGI7n/VP69MExl1hIXIkex2x8xNXJ5UdM/bHE5Q0WpdQH4gEWPqaleMQi2GbhgmEafCpUpTi5eo00saae53uQeI8cl8FhneLG991YuINFybAYB5jfBW@7zSfvYSbKc8kYrj72fZ1owiHMw1tpcG5wHhHOqGNx2GKfOhEpR4Qz0k@7OCIHmkZT2o0Nxlbftw4gKMOgyWC3Hgzej6pp1ExDcqDb42Hrb7FKaNOG1e7wcnc@bTGK27ewvJ4KxtiEMyY5UDoJOu4AJPPAVJIk3hVPqOAvh6TV1Fx0nY1541xbXrhWflD3DOvoLtwCeqBNAVZ9kfKqVzt17/2vV@/a@renswg4gQtHZs4mlATM3zUUBlS@V8@ZetEfBZdWkqrD9zbTjZ7@N7TUKGmRxg5yp5I4gfpyGgdH1GKn60Pc81h5/gU "PowerShell – Try It Online")
Unrolled:
```
param($x,$y,$bitmap)
$transform={
$bitmap|%({$r+=,$_*$y},{$r=,$_*-$y+$r})[$y-lt0]
$r -ne $empty
}
&$transform|%{ # $bitmap is an array of lines
$bitmap=,$_*8|%{''+' X'[($_-shr$i++%8)%2]} # $bitmap is an array of line pixels now
$y=-$x # reuse $y
-join(&$transform)
}
```
[Answer]
# Perl 5, 105 bytes
```
($_,$h,$v)=@F;say for map{$_=reverse if$h<0;y/0/ /;s/./$&x abs$h/eg;($_)x abs$v}$v<0?reverse/\d+/g:/\d+/g
```
[TIO](https://tio.run/##fYzNCsIwEITvPkUoi1hsu5tCL6ZFT958A6FETJuCtiWRYBFf3dgfz36X3dnZmV6ZW@b9BsoIdAQuLA5HYeXAqs6wu@xfUBZGOWWsYk0FOicxICFDYTFBWD@ZvFjQqGoxdoSLdG9wOe1/OTxft1jvluGn8iDwNME5j/gMjQvx@cJiztLVHz8dPz5d/2i61vpYtj4@ZQnxLw)
If input must be hex
[126 bytes](https://tio.run/##Rc3RCoIwGAXg@55ijBVJ022CGE2pILzrDQKZMJ1QOjYxJXr1lmHU1c934JxfS3ONnFujHCOFUe@lh4xbMYKyNeAm9APlqdWmbroSLum2gFjJgU@hkb00VoK6RCqhfCSUAMItCQhaDUAUFikiKz4NezP7J@oTuv/2yOW@IdVuPu7zEUJHY5yd8DEGDLDFDz4D4V/h5Feru7ptrPNF4/xzFFD2Bg)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
⁴²+BḊ€⁸m€Ṡ}¥xA}ZʋƒYo⁶
```
[Try it online!](https://tio.run/##y0rNyan8//9R45ZDm7SdHu7oetS05lHjjlwg9XDngtpDSysca6NOdR@bFJn/qHHb/8PL9f//j@biitY10lHQNYrVUVBW8ElNK1FILEovzU3NKwFKKRhUGJjrAEk3FxDpaK4QC1QVlJmeUaLgCFcWCwA "Jelly – Try It Online")
Assumes there is at most one command-line argument.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 23 [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")
[dzaima's method](https://codegolf.stackexchange.com/a/179229/43319)
Anonymous tacit prefix function. Takes \$(v,h,B)\$ as argument, where \$v\$ is the vertical scaling factor, \$h\$ is the horizontal scaling factor, and \$B\$ is the byte array as an 8-column packed bit-Boolean matrix (this is the normal and most compact way to represent raw bytes in APL). Requires `⎕IO←0` (zero based indexing).
```
' x'⊇⍨∘⊃{⊖⍣(>⍺)⍉⍵/⍨|⍺}/
```
[Try it online!](https://tio.run/##fVBNT8JAEL3zKzYcXIg27EeFnky0QMCDJC2erAdIixcUEjGWiCcS1CYlesB49@KNkxeP/Sn7R@p@1GwhxGz6dufNmzcz7Y2Hhj/tDUdXRhBOghs/8FO2XLU7bPGKCq0g7I5OppPglocY80TdSdaYWPvksDoTN3v@4Oy57YrH4k2Fp27nDKIQAujde33IGQcWPe8OIU7tFWEKQQhZ9MTiL1EQzR9Y9M7iz9IRi3/KLH5h8XeFJ2c8fKykA96cxUs1VjRP1lR0Wq5cx@bYbbXdtH89xoDLgJ4YwAuAQlQ9ENgU2KQSG5JRaGrEkqFSWZPYkHo7jzXpILPUlrWWQEvpsXIAl7DAByK7B1IWdYHHtUxKd0uR9JZzWaburDCbXe2BMiPzH6OmrZFaeln1/ssKI8MwCoMSwPzIH1vWTLImWxxRKpJXkS1GVGWVG2zWgWqO8rPJCJX45Ha5rmaO@QU "APL (Dyalog Extended) – Try It Online")
`{`…`}/` reduce right-to-left using the following anonymous lambda:
`|⍺` the magnitude of the left argument (the scaling factor)
`⍵/⍨` use that to replicate the right argument horizontally
`⍉` transpose
`⊖⍣(`…`)` flip if:
`>⍺` the scaling factor is less than zero
`⊃` disclose (since reduction enclosed to reduce tensor rank from 1 to 0)
`' x'⊇⍨` select elements from the string " x" using that matrix
[Answer]
# [Ruby](https://www.ruby-lang.org/), 89 bytes
```
->b,w,h{y=h>0?-1:0;(b*h.abs).map{y+=1;[*1+8*w..0,*0...8*w].map{|x|' X'[b[y/h][x/w]]}*''}}
```
[Try it online!](https://tio.run/##fZDRasMgFIbv8xTeuaVqNcoiK@kYWfMMA/GiXpTcFMK6koQ2z57pcSHrhcPwIec7//GQr6sb51M1070jPWlvY9Xu@RsVr3z35PKWHd3lmZ2P3W3cVGJncrHRec8YJzlnjPm7BXsf7hh9YuPMuG2tGba9tVOO8TTN7twJVCGD@MBfSGAT2EjgASqRaqWAioTOEniA/vovS5gAVtaQ1YE69os4AdnMb1AsG8TMR@B7GZ1cHIc0vKzVOjvyd7u4KY9J9ZBs6pVSr/vH@2JtlnXX7ws6mfBjiD82FjClFD84WiSlN6RIuv9yNHwJK/1UKpLSn4RTPpZOKqL8svMP "Ruby – Try It Online")
[Answer]
# T-SQL, 216 bytes
Before executing this MS-SQL Studio Management, press CRTL-t to show data as text. The height cannot be adjusted to exceed the number of elements in the input.
Because of the horrible implementation of [STRING\_AGG](https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017), the height variable will only work in MSSM. MS should have made a third optional parameter to include the order of the elements being concatenated.
The online version can only support adjustment of the width. Height will result in a funky result with multiple stacking shapes.
```
USE master
DECLARE @ table(v int,i int identity)
INSERT @ values
(0x06),(0x0F),(0xF3),(0xFE),(0x0E),(0x04),
(0x04),(0x1E),(0x3F),(0x7F),(0xE3),(0xC3),
(0xC3),(0xC7),(0xFF),(0x3C),(0x08),(0x8F),
(0xE1),(0x3F)
-- @ = width
-- @h = height
DECLARE @s INT=1,@h INT=1
SELECT iif(@s>0,reverse(x),x)FROM(SELECT
string_agg(replicate(iif(v&n=0,' ','X'),abs(@s)),'')x,i,j
FROM(values(1),(2),(4),(8),(16),(32),(64),(128))x(n)
,@,(SELECT top(abs(@h))i j FROM @)g GROUP BY i,j)f
ORDER BY i*@h
```
This script will not show the correct shapes in the online version, so I made some minor adjustments to compensate.
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1025973/classic-vcs-ascii-adventure)**
] |
[Question]
[
Your challenge is to take input as a line of text and output it like this.
[](https://i.stack.imgur.com/JzZCj.png)
## Input / output
The input will be a string that contains only printable ASCII characters. The first or last characters will never be spaces, and there will never be two spaces in a row. It will always be at least two characters long.
Your output should be the same string, converted to rainbow colors as will be described below. The output may be in image form (saved to a file or somehow otherwise made available), or it may simply display the result on the screen (as the reference implementation below does).
## Conversion
To determine what color each letter in the string should become, use the following algorithm. Note that *each letter is its own individual color*. **This is not a gradient!**
* If this character is a space:
+ ... it doesn't matter, because spaces can't really... have a color anyway. Simply output a space.
* Otherwise:
+ Let `i` = the index of this character in the string (0-based, so for the very first letter, this is `0`), not counting spaces. For example, in the string `foo bar`, this value would be `4` for the `a`. In other words, this is how many non-spaces have been encountered so far.
+ Let `n` = the number of non-spaces in the string.
+ The color of this letter can now be expressed, in the [HSL cylindrical-coordinate system](https://en.wikipedia.org/wiki/HSL_and_HSV), as [hue=(`i`/`n`)\*360°, saturation=100%, lightness=50%].
Note that these directions imply that the output for `foo` and `f oo` should be exactly the same, except for an added space after the `f`. That is, all the letters should retain the same colors.
Further rules for the conversion process are described below, in the **Rules** section.
## Reference implementation
This is written in JavaScript, and you can try it by pressing the "Run code snippet" button.
```
window.addEventListener('load', function() {
addRainbow('Your challenge is to take input as a line of text and ' +
'output it like this.');
});
// append this text rainbow-ified to the argument (document.body by default)
function addRainbow(text, el) {
(el || document.body).appendChild(makeRainbow(text));
}
// returns a <div> that contains the text in a rainbow font
function makeRainbow(text) {
var div = document.createElement('div');
var letterCount = text.replace(/ /g, '').length, spaceCount = 0;
text.split('').forEach(function(letter, idx) {
if (letter == ' ') ++spaceCount;
div.appendChild(makeLetter(letter, (idx - spaceCount) / letterCount));
});
return div;
}
// returns a <span> that contains the letter in the specified color
function makeLetter(letter, hue) {
hue = Math.floor(hue * 360);
var span = document.createElement('span');
span.appendChild(document.createTextNode(letter));
span.style.color = 'hsl(' + hue + ', 100%, 50%)';
return span;
}
```
## Rules
* When computing the Hue value of a letter, you will almost certainly get a decimal (non-integer) number. You may round this to the nearest integer, floor it, take the ceiling, or simply not round at all.
* The font size must be readable. Here, this is defined as a 10pt size font or greater.
* You may use a fixed-width canvas or "drawing area" to output the text, but it *must* be able to fit the example given in the very first sentence of this post.
* Scoring is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will win.
[Answer]
# [Perl 5.28.1 (webperl)](https://www.perl.org/) + `-p`, 88 bytes
```
@c=unpack C35,"..........vR../012.3-'!..9]........";s|\S|.[38;5;$c[@c*$i++/y/!-~//]m$&|g
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiMDAwMDAwMDA6IDQwNjMgM2Q3NSA2ZTcwIDYxNjMgNmIyMCA0MzMzIDM1MmMgMjIwOSAgQGM9dW5wYWNrIEMzNSxcIi5cbjAwMDAwMDEwOiBjNGNhIGQwZDYgZGMwYiBlMmJlIDlhNzYgNTIwYSAyZTJmIDMwMzEgIC4uLi4uLi4uLnZSLi4vMDFcbjAwMDAwMDIwOiAzMjBlIDMzMmQgMjcyMSAxYjE1IDM5NWQgODFhNSBhYWM5IGM4YzcgIDIuMy0nIS4uOV0uLi4uLi5cbjAwMDAwMDMwOiBjNmM1IDIyM2IgNzM3YyA1YzUzIDdjMWIgNWIzMyAzODNiIDM1M2IgIC4uXCI7c3xcXFN8LlszODs1O1xuMDAwMDAwNDA6IDI0NjMgNWI0MCA2MzJhIDI0NjkgMmIyYiAyZjc5IDJmMjEgMmQ3ZSAgJGNbQGMqJGkrKy95LyEtflxuMDAwMDAwNTA6IDJmMmYgNWQ2ZCAyNDI2IDdjNjcgICAgICAgICAgICAgICAgICAgICAgLy9dbSQmfGciLCJhcmdzIjoiLXAiLCJpbnB1dCI6IllvdXIgY2hhbGxlbmdlIGlzIHRvIHRha2UgaW5wdXQgYXMgYSBsaW5lIG9mIHRleHQgYW5kIG91dHB1dCBpdCBsaWtlIHRoaXMuIn0=)
## Explanation
This script uses an approximation of the colours available to terminal (256 maximum) currently only including a few colour points selected from [this list](https://gist.github.com/dom111/1d3f73081a9a3c8d1d16), so it is likely not to spec, but this was fun anyway! I filtered the list to only show colours with `S` and `L` values of `100%` and `50%` respectively, then sorted by hue, packed the numbers into a string and select the colours from that list.
This implementation includes non-printable characters! Stole [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)'s idea of only replacing `\S` instead of `.`, simple, but clever!
[Answer]
# Python 2: 240 using PIL and colorsys lib
```
import PIL,colorsys as c
s=input()
u,a=len(s),255
g=Image.new('RGB',(u*6,13),(a,)*3)
[ImageDraw.Draw(g).text((j*6,0),s[j],fill=tuple(int(h*a)for h in c.hls_to_rgb(1.*(j-s[:j].count(' '))/(u-s.count(' ')),.5,1)))for j in range(u)]
g.show()
```
Example output:
[](https://i.stack.imgur.com/1yzlz.png)
[](https://i.stack.imgur.com/iqwiL.png)
Thanks to @agtoever and @Trang Oul for some golfing tips, and for @Mauris for pointing out the spaces requirement.
To add a true type fonts, font size control, including horizontal offset and color change based on length.
```
import PIL as P,colorsys as c
s=input()
u=len(s)
a=255
fs=25
f=P.ImageFont.truetype("a.ttf",fs)
sza=f.getsize(s)
oa=f.getoffset(s)
g=P.Image.new('RGB',(sza[0]+fs,2*sza[1]+oa[1]),(a,)*3)
r=fs/4
P.ImageDraw.Draw(g).text((r,0),s,fill=(0,0,0),font=f)
for j in range(u):
o=f.getoffset(s[j])
sz=f.getsize(s[j])
r+=o[0]
P.ImageDraw.Draw(g).text((r,0+fs),s[j],fill=tuple([int(h*a)for h in c.hls_to_rgb(1.*r/sza[0],.5,1)]),font=f)
r+=sz[0]
g.save('a.png')
g.show()
```
The font I used is available from [here](http://www.fontsquirrel.com/fonts/MomsTypewriter?filter%5Bclassifications%5D%5B0%5D=typewriter&sort=popular):
The result is (the top is just printing the string, the one below is printing per letter):
[](https://i.stack.imgur.com/T1QYQ.png)
[Answer]
# Python 3, 131 bytes
Simular to Dom Hastings' answer but implemented in python.
The string `'|\x82\x88\x8ejF"#$%\x1f\x19\x137[\x7f~}'` was built form the list `[124,130,136,142,106,70,34,35,36,37,31,25,19,55,91,127,126,125]` is the terminal colour codes to display in order. They have been filtered so they only include colours with saturation 100% and value 50%. The list was then sorted so the correct hues were displayed first.
Takes input from stdin and returns it to stdout.
### Your terminal you are using MUST support ANSI escape codes to run this properly.
```
x=input();u=u'|\82\88\8ejF"#$%\1f\19\137[\7f~}';j=0
for i in x:print('\033[38;5;%dm%s'%(ord(u[j*18//len(x.replace(" ", ""))]),i),end="");j+=i!=" "
```
Or shortened version with literal byte characters (Didn't paste properly):
```
x=input();u='|<82><88><8E>jF"#$%^_^Y^S7[^?~}';j=0
for i in x:print('ESC[38;5;%dm%s'%(ord(u[(j*18)//len(x.replace(" ", ""))]),i),end="");j+=i!=" "
```
Literal hexdump:
```
783d696e70757428293b753d277c82888e6a46222324251f1913375b7f7e7d273b6a3d300a666f72206920696e20783a7072696e7428271b5b33383b353b25646d25732725286f726428755b286a2a3138292f2f6c656e28782e7265706c616365282220222c20222229295d292c69292c656e643d2222293b6a2b3d69213d2220220a
```
Thanks @swstephe for saving 9 bytes (and also making me notice my byte counting was ever so slightly very wrong)!
[Answer]
# JavaScript (ES6), 114 ~~117 125~~
*Edit2* 3 bytes saved thx @Dom Hastings
*Edit* Invalid HTML, but working anyway.
Usual note: test running the snippet on an EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox)
```
F=s=>document.write(s.replace(/\S/g,c=>`<b style=color:hsl(${i++/s.replace(/ /g,'').length*360},100%,50%>`+c,i=0))
```
```
<input value='Your challenge is to take input as a line of text and output it like this.' id=I size=100>
<button onclick='F(I.value)'>-></button>
```
[Answer]
# PHP, 165 bytes
Run with input as the parameter "s"
The HTML is invalid but it should render in all major browsers (tested in Chrome and Firefox)
```
<?php $n=preg_match_all("/[^ ]/",$q=$_GET['s']);for($i=$j=0;$j<strlen($q);$j++){if(" "!=$s=$q[$j])$i+=360;echo"<a style='color:hsl(".floor($i/$n).",100%,50%)'>".$s;}
```
[Answer]
# PHP 4.1, ~~112~~ ~~103~~ 102 bytes
I've used [@DankMemes' answer](https://codegolf.stackexchange.com/a/55134/14732) as a starting point. From there on, I've implemented a **ton** of changes, to the point that the code is different.
The implementation is similar, the code is totally different.
```
foreach(str_split($s)as$c)echo"<a style=color:hsl(",((" "^$c?$i+=360:$i)/strlen($s))|0,",100%,50%>$c";
```
To use it, simply set a value on a SESSION/GET/POST/COOKIE with the name `s`.
Result of running this function, on the test sentence:
```
<a style=color:hsl(4,100%,50%>Y<a style=color:hsl(9,100%,50%>o<a style=color:hsl(14,100%,50%>u<a style=color:hsl(19,100%,50%>r<a style=color:hsl(24,100%,50%> <a style=color:hsl(29,100%,50%>c<a style=color:hsl(34,100%,50%>h<a style=color:hsl(38,100%,50%>a<a style=color:hsl(43,100%,50%>l<a style=color:hsl(48,100%,50%>l<a style=color:hsl(53,100%,50%>e<a style=color:hsl(58,100%,50%>n<a style=color:hsl(63,100%,50%>g<a style=color:hsl(68,100%,50%>e<a style=color:hsl(72,100%,50%> <a style=color:hsl(77,100%,50%>i<a style=color:hsl(82,100%,50%>s<a style=color:hsl(87,100%,50%> <a style=color:hsl(92,100%,50%>t<a style=color:hsl(97,100%,50%>o<a style=color:hsl(102,100%,50%> <a style=color:hsl(107,100%,50%>t<a style=color:hsl(111,100%,50%>a<a style=color:hsl(116,100%,50%>k<a style=color:hsl(121,100%,50%>e<a style=color:hsl(126,100%,50%> <a style=color:hsl(131,100%,50%>i<a style=color:hsl(136,100%,50%>n<a style=color:hsl(141,100%,50%>p<a style=color:hsl(145,100%,50%>u<a style=color:hsl(150,100%,50%>t<a style=color:hsl(155,100%,50%> <a style=color:hsl(160,100%,50%>a<a style=color:hsl(165,100%,50%>s<a style=color:hsl(170,100%,50%> <a style=color:hsl(175,100%,50%>a<a style=color:hsl(180,100%,50%> <a style=color:hsl(184,100%,50%>l<a style=color:hsl(189,100%,50%>i<a style=color:hsl(194,100%,50%>n<a style=color:hsl(199,100%,50%>e<a style=color:hsl(204,100%,50%> <a style=color:hsl(209,100%,50%>o<a style=color:hsl(214,100%,50%>f<a style=color:hsl(218,100%,50%> <a style=color:hsl(223,100%,50%>t<a style=color:hsl(228,100%,50%>e<a style=color:hsl(233,100%,50%>x<a style=color:hsl(238,100%,50%>t<a style=color:hsl(243,100%,50%> <a style=color:hsl(248,100%,50%>a<a style=color:hsl(252,100%,50%>n<a style=color:hsl(257,100%,50%>d<a style=color:hsl(262,100%,50%> <a style=color:hsl(267,100%,50%>o<a style=color:hsl(272,100%,50%>u<a style=color:hsl(277,100%,50%>t<a style=color:hsl(282,100%,50%>p<a style=color:hsl(287,100%,50%>u<a style=color:hsl(291,100%,50%>t<a style=color:hsl(296,100%,50%> <a style=color:hsl(301,100%,50%>i<a style=color:hsl(306,100%,50%>t<a style=color:hsl(311,100%,50%> <a style=color:hsl(316,100%,50%>l<a style=color:hsl(321,100%,50%>i<a style=color:hsl(325,100%,50%>k<a style=color:hsl(330,100%,50%>e<a style=color:hsl(335,100%,50%> <a style=color:hsl(340,100%,50%>t<a style=color:hsl(345,100%,50%>h<a style=color:hsl(350,100%,50%>i<a style=color:hsl(355,100%,50%>s<a style=color:hsl(360,100%,50%>.
```
] |
[Question]
[
You're a mouse. Your mouse friends have all been captured, and are unconscious and trapped in a maze that has only one entrance/exit. You happen to have a perfect map of the maze, so you can plot a solution to rush in and carry them all to safety. However, the maze is guarded with a security system that will trigger an alert if a threshold of `1000` is reached, causing you to be captured and fail your rescue mission.
From your previous investigations of the maze, each square you step (i.e., each horizontal or vertical movement -- *mice can't move diagonally*) adds `1` to the security system's counter. However, if you're carrying a weight (either a block of dynamite or an unconscious mouse friend), it instead adds `2` since it detects the additional pressure. The entrance/exit square doesn't have this security system, and so doesn't add to the counter.
You have an unlimited supply of dynamite that you've brought to the entrance, so you can simply [blow up all the walls](http://dobrador.com/wp-content/uploads/2012/06/1204343772648.jpg.roflposters.com_.myspace.jpg) to free your friends. But you need to be cautious with doing so, since each explosion adds `50` to the counter from the concussive pressure. Additionally, you can only carry one thing at a time, either one mouse or one block of dynamite. Since each block of dynamite can only detonate one wall space, this means that if there are multiple walls in a row, you need to make an empty-handed trip back to the entrance to grab more.
### Worked-through example
Suppose our maze looks like the following:
```
######
#M# E#
######
```
I'll use `c` for the counter. We start at the `E`ntrance, move one square left while carrying dynamite, `c=2`. We detonate the dynamite to explode the wall, `c=52`. We move two squares left, empty-handed, to get `c=54`, and we're now standing on the mouse's square. We pick our friend up, and move 3 squares back to the `E`xit, but the last square doesn't count since it doesn't have any sensors, so that's only 2 squares with something on our back. That means that when we reach the exit with the final mouse, `c=58`, which is less than `1000`, and therefore the mission succeeds.
### Challenge
Given an input maze, output whether you, the mouse hero, can successfully rescue all trapped mice within the constraints outlined above, or whether the mission is a failure.
### Input
* A 2D maze in [any acceptable format](http://meta.codegolf.stackexchange.com/q/2447/42963) (multiline string, array of strings, etc.).
* For this challenge, I will be using `#` for both the interior and exterior walls, `M` for the mouse friends, and `E` for the entrance.
* The entrance will never be immediately adjacent to an interior wall (there will always be at least one space in which to move freely).
* You can substitute any [printable ASCII characters](http://meta.codegolf.stackexchange.com/a/5869/42963) you wish so long as it's consistent. This *does* allow you to use two different symbols for interior walls vs. exterior walls, so long as you maintain consistency (e.g., if you choose to use `@` for interior walls instead, and leave `#` for exterior, *every* interior wall must be `@` and *every* exterior wall `#`).
* The maze will always be completely bounded by walls, but is not necessarily rectangular. If desired, you can assume that the maze is padded with spaces to make rectangular input (optional).
* The maze may have sections that are unreachable without dynamite.
* You cannot dynamite the exterior walls of the maze.
### Output
A [truthy/falsey](http://meta.codegolf.stackexchange.com/a/2194/42963) value. Truthy for "Yes, the mouse can rescue every other mouse" or Falsey for "No, the alarm system will be tripped."
### The Rules
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Examples
Truthy examples, separated by blank lines.
```
#####
#M E#
#####
######
#M# E#
######
########
#E # M#
# # #
# # #
# #
########
#############################
# ## # # #
# M ## M # # #
# ## # M # E #
#M ## # # #
#############################
###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMM MM#
#MMMMMMMMMMMME#
###############
```
Falsey examples, separated by blank lines
```
#############################
#M ## ## ## #
# M ## M ## ## #
# ## ## M ## E #
#M ## ## ## #
#############################
#############################
########
########
# # #
# M # M#
########
#####
# M #
#####
#####
#####
#####
###################
# # # ## ## # # #
#M#M#M## E ##M#M#M#
# # # ## ## # # #
###################
#######
######
#####
####
# M#
####
###############
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMMM#
#MMMMMMMMMMMME#
###############
```
[Answer]
# Perl, ~~216~~ 215 bytes
Includes +2 for `-0p`
Give input on STDIN. Use `%` for external walls, `#` for internal walls, `0` for empty spaces, `8` for mice and `r` for the starting position. The whole boards must be padded so it forms a rectangle. You can transform and run the examples as:
```
cat dynamite.txt | perl -p0e 's/.+/$a^=$&/egr;s//sprintf"%-*s",length$a,$&/eg;1while/\n/,s/^ *\K#|#(?= *$)|^ *.{@{-}}\K#|\A[^\n]*\K#|#(?=[^\n]*\n\z)|#(?=.{@{-}} *$)/%/sm;y/ EM/0x2/' | dynamite.pl
```
`dynamite.pl`:
```
#!/usr/bin/perl -0p
sub f{@a{@_}||=push@{$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)},@_}f$_;for(@{$%}){f y/xr|/ytx/r;{f s/\pL\d/$&^(E&$&)x2/er}{f s/(q|s|y)#/$&^"\x01\x13"/er}my$o;{$\|=/x/>/2/;$o.="
"while s/.$/$o.=$&,""/meg}f$o}$%++>999|$\||redo}{
```
Replace the `\xhh` escapes for the claimed score.
The program can't realistically handle complex cases. In particular it can't handle any of the failure cases. This is because there are just too many different ways of blowing up the internal walls or picking up mice so the search becomes too wide and uses too much memory even though it's at least smart enough to never process the same state multiple times. The pressure limit has to be lowered to `100` or so for somewhat bearable runtimes and memory usage.
## Explanation
I use the bit pattern of a character to represent the state of a field:
```
contains victim: 0000 0010
has hero: 0100 0000
carry dynamite 0000 0001
carry mouse 0000 0100
home 0000 1000
walkable 0001 0000 (not really needed but results in shorter regexes)
make printable 0010 0000
wall 0010 xxxx (bit patterns not very important,
permawall 0010 xxxx just avoid letters and digits)
```
For example the hero (`01000000`) carrying dynamite (`00000001`) must be on a place he can walk (`00010000`) and we want all values to be printable ASCII (`00100000`). Taking the bitwise `or` of all these bitmasks gives `01110001` which is the ASCII code for `q`. In total this becomes::
```
p: hero r hero on victim
q: hero carrying dynamite s hero carrying dynamite on victim
t: hero carrying mouse v hero carrying mouse on victim
x : hero at home
y : hero at home carrying dynamite
| : hero at home carrying mouse
0: empty without hero
8: home without hero
2: victim without hero
%: permanent wall
#: normal wall
```
The program will only consider the hero moving to the right (the rotation explained later will take care of the other directions). The bitmasks were carefully chosen such that the hero is always represented by a letter and a place he can move to by a digit (except the hero at home carrying a victim, but again this is intentional so that the hero's only move will be to drop the victim). So a hero that can move forward is matched by `/\pL\d/`. The matched substring has to be modified so that the hero and what he is carrying is removed from the first character and added to the second one, which can be done with a bitwise `xor` with the same value for both characters. The xor value consists of the hero bit (`01000000`), the dynamite bit (`00000001`) and the carry mouse bit (`00000100`). Together they `or` to `01000101` which is ASCII `E`. So moving the hero becomes:
```
s/\pL\d/$&^(E&$&)x2/e
```
The hero can blow up a wall if he is standing right in front of it and is carrying dynamite (`q`, `s` or `y`). The hero will lose his dynamite (`xor` with `00000001`) and the wall `#` will change to a passage `0` (xor with `00010011`), so
```
s/(q|s|y)#/$&^"\x01\x13"/e
```
To handle the other directions the whole board is rotated (rotated board ends up in `$o`):
```
my$o;$o.="\n"while s/.$/$o.=$&,""/meg
```
Apart from moving the hero also has a number of other choices he can make:
```
When at home, pick up dynamite: x -> y
When on victim not carrying anything pick him up: r -> t
When at home carrying a victim, drop him off: | -> x
```
This is done by
```
y/xr|/ytx/
```
The board is finished if the hero is at home carrying nothing (`x`) and there are no more victims to rescue (no `2`). This can be conveniently tested using
```
/x/>/2/
```
Once the board is solved I want to remember this state and at the end print it. For that I carry the "is solved" flag in `$\` and print that at the end of the program without printing `$_`, so
```
$\|=/x/>/2/ ... }{
```
The states to be processed at pressure 0 are kept in `@0`, at pressure 1 on `@1` etc. The current pressure is kept in `$%`. Using `$n` or something like it would be shorter but the code doesn't work if the variable isn't initialized to something because autovivification will otherwise change `$n` to an ARRAY reference.Looping over the states at a certain pressure is done using a `for` and not a `map` because with a `for` you can extend the array while it is still being looped over and will pick up the new elements. This is needed because the rotations and single field choices of the hero happen in 0 time and end up in the same pressure array. So the loop for a given pressure is done by
```
for(@{$%}){...}
```
This is repeated until the pressure reaches 1000 or a solution is found:
```
$%++>999|$\||redo
```
All that is left is adding newly discovered states to their respective pressure arrays. That will be done by subroutine `f`. We only want to add a state if it has not been seen yet. States that have been seen before are kept in `%a` so:
```
sub f{@a{@_}||=push@$n, @_}
```
`$n` represents the new pressure for a state. I will derive that from the state that the regex variables still have as a result of the hero's action leading to this call:
```
if $1 is set it was from s/(q|s|y)#/$&^"\x01\x13"/e which blows a wall -> 50
else if $& is set it was from s/\pL\d/$&^(E&$&)x2/e, so the hero moves.
if $& contains 8 the hero went home -> 0
else if the hero has carry bits (5) -> 2
else 1
else ($& was not set) it was from y/xr|/ytx/r -> 0
```
This leads to the following formula for `$n`:
```
$%+($&?$1?50:$&=~8?0:$&&"5"?2:1:0)
```
All the substitutions get an `r` modifier so they return the changed state and leave the current state in `$_` alone. `f` is then called on this changed state, so you get code like
```
f y/xr|/ytx/r;
```
Because the calculation of `$n` needs the regex variables they must default to unset in case the substitutions changes nothing (because the condition to trigger them is not fulfilled). I must also not pick up any regex variables from a previous loop. Therefore the substitutions are wrapped in `{}` blocks to save and restore the regex state. That's how you get statements like
```
{f s/\pL\d/$&^(E&$&)x2/er}
```
In particular the rotation is so wrapped so it calls `f` without regex variables and gets a pressure contribution of 0.
The only thing still to do is to prime `@0` with the initial state at the start
```
f$_
```
This is in the main loop so it also tries to add `$_` to later pressure arrays, but since the initial state will already be in `%a` nothing will happen.
Together all this basically finds the shortest solution using [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm). There is a potential problem though. The current code won't add a state if it is rediscovered with a lower pressure than the first discovery. I've not been able to construct a board that would trigger this, but have also been unable to prove it is impossible.
[Answer]
# JavaScript, ~~863~~ ~~834~~ ~~785~~ 781 bytes
Saved 29 bytes thanks to ETHproductions
Saved 53 bytes thanks to Jordan
```
L=[]
f=(S,r="",R="",p=0,s=S.replace(RegExp(r),R),l=`((.|\n){${s.split`
`[0].length}})`,q=p+1,o=p+2,n=p+50)=>s in L|p>999?1e3:!/M/.test(s,L[s]=0)&/E/.test(s)?p:Math.min(...[[/ E/,"me",q],[/ E/,"de",o],[/ME/,"ce",q],[/E /,"em",q],[/E /,"ed",o],[/EM/,"ec",q],[`E${l} `,"e$1m",q],[`E${l} `,"e$1d",o],[`E${l}M`,"e$1c",q],[` ${l}E`,"m$1e",q],[` ${l}E`,"d$1e",o],[`M${l}E`,"c$1e",q],[/ m/,"m ",q],[/m /," m",q],[`m${l} `," $1m",q],[` ${l}m`,"m$1 ",q],[/ (d|c)/,"$1 ",o],[/(d|c) /," $1",o],[`(d|c)${l} `," $2$1",o],[` ${l}(d|c)`,"$3$1 ",o],[/d#/,"m ",n],[/#d/," m",n],[`#${l}d`," $1m",n],[`d${l}#`,"m$1 ",n],[/mM/," c",q],[/Mm/,"c ",q],[`M${l}m`,"c$1 ",q],[`m${l}M`," $1c",q],[/[mc]e/," E",p],[/e[mc]/,"E ",p],[`e${l}[mc]`,"E$1 ",p],[`[mc]${l}e`," $1E",p]].map(a=>f(s,...a)))
F=s=>f(s)<1e3
```
Takes input as a multiline string.
This defines an anonymous function that uses a recursive function `f` to determine if you trip off the alarm before retrieving all the mice. `f` returns `1000` if the pressure is above 1000 (to avoid endless recursion), returns the pressure if there are no more mice to rescue and the mouse in the exit, and returns the minimum pressure of all possible moves from the current state otherwise. It uses an array `L` to keep track of already visited positions where `L[pos]==0` if it is visited, and undefined if it isn't. This may not be necessary, but it prevents the mouse from doing useless moves and throwing recursion errors at the very least. (This does mean you should redefine `L` if you are testing this multiple times)
This uses the format in the question other than that it requires you to use a different character for the external walls. (Anything other than `# MEmecd`)
More readable version:
```
stateList = []
f=(s,regex="",replacement="",pressure=0,state=s.replace(regexp(regex),replacement),line=`((.|\n){${state.split("\n")[0].length}})`)=>{
if (state in stateList || pressure > 999) return 1e3
if (!/M/.test(state) && /E/.test(state)) return pressure
stateList[state] = 0
return [
[/ E/,"me",pressure+1],
[/ E/,"de",pressure+2],
[/ME/,"ce",pressure+1],
[/E /,"em",pressure+1],
[/E /,"ed",pressure+2],
[/EM/,"ec",pressure+1],
[`E${line} `,"e$1m",pressure+1],
[`E${line} `,"e$1d",pressure+2],
[`E${line}M`,"e$1c",pressure+1],
[` ${line}E`,"m$1e",pressure+1],
[` ${line}E`,"d$1e",pressure+2],
[`M${line}E`,"c$1e",pressure+1],
[/ m/,"m ",pressure+1],
[/m /," m",pressure+1],
[`m${line} `," $1m",pressure+1],
[` ${line}m`,"m$1 ",pressure+1],
[/ ([dc])/,"$1 ",pressure+2],
[/([dc]) /," $1",pressure+2],
[`([dc])${line} `," $2$1",pressure+2],
[` ${line}([dc])`,"$3$1 ",pressure+2],
[/d#/,"m ",pressure+50],
[/#d/," m",pressure+50],
[`#${line}d`," $1m",pressure+50],
[`d${line}#`,"m$1 ",pressure+50],
[/mM/," c",pressure+1],
[/Mm/,"c ",pressure+1],
[`M${line}m`,"c$1 ",pressure+1],
[`m${line}M`," $1c",pressure+1],
[/[mc]e/," E",pressure],
[/e[mc]/,"E ",pressure],
[`e${line}[mc]`,"E$1 ",pressure],
[`[mc]${line}e`," $1E",pressure]
].map(a=>f(state,...a)).reduce((a,b)=>a-b<0?a:b) //reduce used for support in more browsers.
}
s=>f(s)>1e3
```
] |
[Question]
[
The *Tangram* is a dissection puzzle made from seven shapes: Five differently sized triangles, a parallelogram and a square. Given a shape, the goal is recreating the shape using all the pieces and without overlapping. There are obviously infinitely many ways to arrange this set of pieces in the plane. An interesting subset are the
### Grid Tangrams
We can draw the "standard" Tangram square into a bigger square which is subdivided by a *grid* into 16 smaller squares. Grid tangrams are just shapes made up of the tangram pieces, such that all vertices of the pieces are on the grid points.

These are the kinds of Tangram puzzles we want to consider in this challenge, as they are probably easier to handle than the more general ones.
As a side note: The Chinese mathematicians Chuan-Chin Hsiung and Fu Traing Wang proved in 1942 that there are only 13 convex tangrams. They first showed that the problem can be reduced to grid tangrams, and then used some combinatorial and geometric arguments. These are all of those 13:

### Challenge
Given a solvable grid tangram, output a dissection of the grid tangram into the seven tangram pieces.
### IO
A tangram is given as a black and white image (the shape is in black, background in white), with both sides multiples of 50px. The grid has a width of exactly 50px. The grid lines are parallel to the sides of the image.
**EDIT: The image can be accepted as input and returned as output in any convenient raster image format like PNG,TIFF,PBM etc. but a representation as a binary 2d array or string or matrix is acceptable.**
The output should again have the same size and should have again the same shape, but with each piece a different colour, or alternatively with white lines separating all the pieces. It is worth noting that the non rectangular quadrangle can be flipped.
The pixels on the border of the pieces do not exactly have to match the one on the shape, also if there are aliasing effects or other fuzz this is still ok.
Example Input and Output:

Examples:


Possible solutions:

[Answer]
# BBC BASIC, ~~570 514~~ 490 bytes ASCII
Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html>
**435 bytes tokenised**
Full program displays an input from `L.bmp` on the screen, then modifies it to find a solution.
```
*DISPLAY L
t=PI/8q=FNa(1)
DEFFNa(n)IFn=7END
LOCALz,j,p,i,c,s,x,y,m,u,v
F.z=0TO99u=z MOD10*100v=z DIV10*100ORIGINu,v
F.j=0TO12S.4p=0F.i=j+3TOj+9S.2c=9*COS(i*t)s=9*SIN(i*t)p=p*4-(POINT(c,s)<>0)*2-(POINT(9*c,9*s)<>0)N.
m=n:IFn=5A.(43A.p)=0p=0m=7
IF(ASCM."??O|(C",n)-64A.p)=0THEN
F.i=-1TO0GCOL0,-i*n:c=99*COS(j*t)s=99*SIN(j*t)y=402/3^m MOD3-1MOVE-c-s*y,c*y-s:x=n<3MOVEc*x-s*x,s*x+c*x:x=2778/3^m MOD3-1y=5775/3^m MOD3-1PLOT85-32*(n MOD6>3),c*x-s*y,s*x+c*y:IFi q=FNa(n+1)ORIGINu,v
N.
ENDIF
N.N.=0
```
**Explanation**
Note that in BBC basic a distance of 1 pixel = 2 units, so the 50x50 pixel grid becomes a 100x100 grid.
We use a recursive function to place the 2 large triangles, medium triangle, square and parallelogram into the shape. The earlier shape in the list is drawn before the next recursive call is made. if a recursive call returns without finding a solution, the earlier shape is overdrawn in black and a new position of the earlier shape is tried.
Once these five shapes are drawn, placing the two small triangles is just a formality. It is necessary to draw one of them though, in order to distiguish them if they share a common edge. We only colour one of the two small triangles. The other is left in natural black.
Placing of each shape is attempted at different x,y coordinates and in 4 different rotations. To test if there is free space to draw a shape we use the template below, with 45 degree angles. The rotations are made about the `*` and the 8 pixels tested are in 2 semicircles of radius 9 and 81 units and fall on radiating lines at odd multiples of 22.5 degrees to the x and y axes.
For a large triangle all 8 spaces are required to be clear. For other shapes only some of the cells must be clear so a mask is applied.
```
+----+---- Shape Mask HGFEDCBA Mask decimal
|\ E/|\G /
| \/F|H\/ 1,2. Large triangle 11111111 -1
|C/\ | / 3. Med triangle 00001111 15
|/ D\|/ 4. Square 00111100 60
+----* 5. Parallelogram 11101000 -24
|\ B/ 6. Small triangle 00000011 3
|A\/ 7. Parallogr reversed 00101011 43
| / Note: reversed parallelogram is checked/drawn at recursion depth n=5
|/ with a special check, but the coordinates are encoded as m=7.
```
Once it is established that a shape will fit, it must be drawn. If it is a triangle it is plotted with `PLOT 85`, if it is a parallelogram, the number is 32 higher (note that for `PLOT` purposes we consider a square a special parallelogram). In either case 3 consecutive vertices must be given. The second vertex is the origin of the shape (marked `*` in the above table) except in the case of the large triangle, where (prior to rotation) it is `-1,-1.` The other 2 vertices can have x and y coordinates of `-1,0 or 1` which are extracted from base 3 encoded numbers, then scaled by 99 and rotated as necessary by transformation with `c` and `s`.
**Ungolfed code**
```
*DISPLAY L
t=PI/8 :REM Constant 22.5 degrees.
q=FNa(1) :REM Call function, return dummy value to q
END :REM End the program gracefully if no solution. Absent in golfed version.
DEFFNa(n) :REM Recursive function to place shapes.
IFn=7END :REM If n=7 solution found, end program.
LOCALk,z,j,p,i,c,s,x,y,m,u,v :REM declare local variables for function.
k=ASCMID$("??O|(C",n)-64 :REM Bitmasks for big tri, big tri, med tri, sq, normal paralellogram, small tri.
FORz=0TO99 :REM For each point on the grid
u=z MOD10*100:v=z DIV10*100 :REM calculate its x and y coordinates relative to bottom left of screen
ORIGINu,v :REM and set the origin to this point.
FORj=0TO12STEP4 :REM For each rotation 0,90,180,270deg
p=0 :REM assume no non-black pixels found
FORi=j+3TOj+9STEP2 :REM test angles of 3,5,7,9 times 22.5 deg anticlockwise from right x axis.
c=9*COS(i*t) :REM Coords of test points at radius ll
s=9*SIN(i*t)
p*=4 :REM Leftshift any existing data in p
p-=(POINT(c,s)<>0)*2+(POINT(9*c,9*s)<>0) :REM and check pixels at radius 11 and 99.
NEXT
m=n :REM The index of the shape to plot normally corresponds with recursion depth n.
IF n=5 AND (43ANDp)=0 p=0:m=7 :REM If n=5 check if a reverse parallelogram is possible (mask 43). If so, clear p and change m to 7.
REM :REM Check p against mask k, if the shape fits then...
IF (k ANDp)=0 THEN
FOR i=-1 TO 0 :REM draw the shape in colour, and if deeper recursions prove unsuccesful, redraw it in black.
GCOL0,-i*n :REM Colour is equal to n.
c=99*COS(j*t) :REM Set parameters c and s for scaling by 99
s=99*SIN(j*t) :REM and rotation by 0,90,180 or 270 as appropriate.
x=-1 :REM For vertex 1, x=-1 always.
y=402/3^m MOD3-1 :REM Lookup y value for vertex 1.
MOVEc*x-s*y,s*x+c*y :REM Use c and s to transform the vertex and move to it.
x=n<3 :REM For vertex 2, coords are 0,0 except for large triangle where they are -1,-1
y=x :REM in BBC BASIC, TRUE=-1
MOVEc*x-s*y,s*x+c*y :REM Use c and s to transform the vertex and move to it.
x=2778/3^m MOD3-1 :REM Lookup x and y value for vertex 3.
y=5775/3^m MOD3-1 :REM PLOT85 uses last 2 points + specified point to make triangle, PLOT85+32 makes paralelogram (or square.)
PLOT85-32*(n MOD6>3),c*x-s*y,s*x+c*y :REM Use c and s to transform the vertex and draw shape.
IFi q=FNa(n+1):ORIGINu,v :REM If i=-1 recurse to next level. If it fails, reset the origin before replotting this level's shape in black.
NEXT
ENDIF
NEXT
NEXT
=0 :REM Dummy value to return from function
```
**Output**
This is a montage of the solutions found by the program for the test cases. Use of 99 instead of 100 for golfing reasons leaves some small black gaps. As the shapes are redrawn during the searches, it can take a few seconds to run for some cases, and is quite fascinating to watch.
[](https://i.stack.imgur.com/cv193.png)
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/59997/edit).
Closed 8 years ago.
[Improve this question](/posts/59997/edit)
Pyth is in ongoing development, meaning that new features are being added all the time.
I want to make Pyth a better langauge, so I'd like to know what features people are looking for.
This is the place the post ideas you have for making Pyth better.
In your answer, please state:
* What you'd like to see changed/added.
* An example usage of the change.
I'll comment if I'm planning to implement the suggestion.
Please check if the idea you want to suggest has already been suggested. Upvote ideas you'd like implemented.
---
Implemented suggestions:
* [Eval string in Pyth](https://codegolf.stackexchange.com/a/60037/20080), as `.v`
* [More Regex operations](https://codegolf.stackexchange.com/a/60001/20080)
* [Apply While](https://codegolf.stackexchange.com/a/60036/20080) as `.W`
* [Nested Loops](https://codegolf.stackexchange.com/a/60025/20080) and [More Lambdas](https://codegolf.stackexchange.com/a/61066/20080) (They use the same mechanism underneath)
* [Flatten nested lists](https://codegolf.stackexchange.com/a/60036/20080) as `.n`
---
This was on topic as per [this meta question](http://meta.codegolf.stackexchange.com/questions/6905/can-i-ask-a-question-about-improving-a-golfing-language) when I posted the question, it is no longer clear.
[Answer]
## Nested loops
If you want to nest `for` loops, you currently have to waste a byte for using `F<var><seq>` inside a `V<seq>` or vice versa. I'd love to have the same thing as with lambdas, where the variable used for the loop would change when nesting loops.
[Answer]
# Turt
Pyth equivalent of [turtle graphics](https://en.wikipedia.org/wiki/Turtle_graphics), as per [`import turtle`](https://docs.python.org/2/library/turtle.html).
[Answer]
## Easier Module Importing
So far, every time I have used `$` it has been something like:
```
$from <module> import <function> as <pyth-function-with-same-arity>$
for example:
$from unicodedata import name as neg$
```
There could be a new function that summarized this for example `.$`:
```
.$"unicodedata""name""neg"
.$"unicodedata name neg"
```
Or using the newer syntax like `_M` which may not be easy/possible to do:
```
_$unicodedata name$
```
In addition, one function with each arity could be given a single letter macro name so that these calls could be shorter (except for the `_$` option).
[Answer]
# Sleeping
This caused trouble [here](https://codegolf.stackexchange.com/a/60219/21009), and [@mbomb007 suggested to put it as an improvement to Pyth](https://codegolf.stackexchange.com/questions/60188/time-sensitive-echo/60219?noredirect=1#comment144849_60219). Basically, right now, in order to sleep for the given number of seconds, I need to do something like:
```
Q$__import__('time').sleep(Q)$
```
Which is annoying and long as heck.
[Answer]
# More lambdas
*This is really [FryAmTheEggman's idea](https://codegolf.stackexchange.com/questions/59997/how-can-pyth-be-improved/60036#comment144323_60025), but I'm posting it to get it out there.*
Sometimes I find that using two different one-argument lambdas would shorten the code, while having to use a two-argument lambda for one wouldn't.
It would be nice to have `L`, `M` and friends redefine a different function every time used; for example, this code:
```
L*b2L*b3y5'5
```
could compile to:
```
@memoized
def subsets(b):
return times(b,2)
@memoized
def read_file(b):
return times(b,3)
imp_print(subsets(5))
imp_print(read_file(5))
```
The exact choice of functions could be changed, of course.
[Answer]
## Improved multi-dimensional arrays
Using multi-dimensional arrays is rather hard to do currently. For example, the C code `A[B][C][D]` would translate to `@@@ABCD` in Pyth. Something like `@A[BCD)` would be much nicer (albeit not any shorter here). The same also goes for `X`; `A[B][C][D] = E` is currently `X@@ABCDE`, when it could be `XA[BCD)E`.
[Answer]
## Some minor ideas
* Absolute difference, i.e. `abs(val1 - val2)`. Currently it's `.a-<val1><val2>`.
* `min`/`max` for values. Currently it's `hS,<val1><val2>`/`eS,<val1><val2>` or the same thing with more values. (`hS<seq>`/`eS<seq>` for sequences is short enough.)
[Answer]
Not a Pyth feature, but nevertheless...
## Modularize the Pyth code
This only affects Pyth under the hood. Some parts of the Pyth implementation are quite messy. Lots of global variables and other hacky things.
I really got frustrated a few days ago, when I tried using a few functions of the Pyth implementation (like executing a string of Pyth commands) from another Python script.
Something like the following would be nice:
```
from pyth import execute_pyth
print(execute_pyth(code='sQ', input='[1, 2, 3]'))
```
Well, I guess this is just a help call for Pyth5.
[Answer]
# Unique elements
Pyth currently has no short way of getting unique elements of a sequence. You can *test* if it's unique, but you can't get the items that are actually unique. Currently, [the shortest way is](https://codegolf.stackexchange.com/a/60649/21009):
```
{.-Q{Q
```
6 bytes! Compare that to K, where getting the unique elements is a one-byte operation: `=x`.
Maybe `.}` would work here?
] |
[Question]
[
## Overview
**Given a number of hexagons, arrange them into a connected shape within the confines of a 50 by 50 ASCII art image. The shape you choose can be arbitrary - whatever you find most amenable to golfing - as long as it is connected. It may have holes provided they are larger than one hexagon (otherwise the number of hexagons will be ambiguous).**
---
## Layout
All hexagons must be in the following form (only this size and orientation is valid):
```
__
/ \
\__/ Note there are 2 underscores per horizontal edge.
```
Two hexagons are ***directly connected*** if they share an edge:
```
__ __
/ \__ / \
\__/ \ \__/
\__/ or / \
\__/
```
Two hexagons are not connected if they only share a vertex:
```
__ __
/ \/ \
\__/\__/
```
Sharing half an edge also does not count as connected:
```
__
/ \
\__/
/ \
\__/
```
A collection of hexagons is ***connected*** if there exists a path from any hexagon to any other using only *directly connected* hexagons.
## Holes
A hexagon sized hole in a connected collection of hexagons counts as a hexagon, so that any given piece of ASCII art has an unambiguous hexagon count.
This does *not* count as a hole since the prospective hole is a single hexagon:
```
__
__/ \__
/ \__/ \
\__/ \__/
/ \__/ \
\__/ \__/
\__/ 7 hexagons (not 6 with a hole)
```
This *does* count as a hole since it does not correspond to a single hexagon:
```
__
__/ \__
/ \__/ \__
\__/ \__/ \
/ \__ \__/
\__/ \__/ \
\__/ \__/
\__/ 8 hexagons with a hole
```
# Input and output
### Input
An integer from 1 to 255.
### Output
An ASCII art string representing the input number of connected hexagons as described above.
* The number of rows (newline separated substrings) is at most 50, plus an additional optional trailing newline.
* The rows need not be the same length, but each must be of length at most 50.
* Zero length rows can exist above or below the connected shape provided the total number of rows does not exceed 50.
* Space-only rows can exist above or below the connected shape provided the total number of rows does not exceed 50.
* Spaces can appear to the left of the shape provided the row lengths do not exceed 50 (the shape does not need to be aligned to the left).
* Spaces can appear to the right of the shape provided the row lengths do not exceed 50.
* Any characters that do not form part of the connected shape must be either spaces or newlines.
Provided the output is correct, it is not required to be consistent from one run to the next.
## Examples
Input: `6`
Valid Outputs:
```
__ __ __
/ \__/ \__/ \__
\__/ \__/ \__/ \
\__/ \__/ \__/
```
---
```
__ __
/ \__/ \
\__/ \__/
/ \__/ \
\__/ \__/
\__/
```
---
```
__
__ / \
/ \__ \__/
\__/ \__/ \
\__/ \__/
\__/
/ \
\__/
```
Invalid Outputs:
```
__
__/ \__
/ \__/ \
\__/ \__/
/ \__/ \
\__/ \__/
\__/ Invalid for 6 as the centre hole counts as a 7th hexagon.
```
---
```
__ __ __ __
/ \__/ \__/ \ / \
\__/ \__/ \__/ \__/
\__/ \__/ Invalid as the 6 hexagons are not connected.
```
---
```
__ __ __ __
/ \__/ \__/ \/ \
\__/ \__/ \__/\__/
\__/ \__/ Invalid as vertex touching does not count as connected.
```
---
```
__ __ __
/ \__/ \ / \
\__/ \__/ \__/
/ \__/ \
\__/ \__/
\__/ Invalid as the 6 connected hexagons are not the only visible characters.
```
## Winning
The shortest valid answer in bytes wins.
---
# Leaderboard
*(using [Martin's leaderboard snippet](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet))*
```
var QUESTION_ID=54277;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```
[Answer]
# CJam, ~~64~~ ~~57~~ 55 bytes
```
" __
/ \
\__/"N/{_SS/\+_47>S3*f{\+}_2>\@?}q~(*]:..e>N*
```
[Test it here.](http://cjam.aditsu.net/#code=%22%20__%0A%2F%20%20%5C%0A%5C__%2F%22N%2F%7B_SS%2F%5C%2B_47%3ES3*f%7B%5C%2B%7D_2%3E%5C%40%3F%7Dq~(*%5D%3A..e%3EN*&input=255)
This will generate the following pattern, *column-wise*:
```
__ __ __ __ __ __
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/
```
## Explanation
This is based on Dennis's [excellent tip](https://codegolf.stackexchange.com/a/52627/8478), using `.e>` to assemble an ASCII art output from several pieces. As he says, `.e>` takes the element-wise maximum of two arrays (or strings), and since spaces have the lowest character code, we can use this to impose any other characters on a string grid. Furthermore, if the two arrays don't have the same length, the extraneous elements of the longer array are simply copied unchanged. This means that the different patterns don't even need to be the same size. To apply this to two-dimensional arrays (because we don't want to insert the newlines until the very end), we apply `.e>` pairwise to lines, which gives `..e>`.
The basic idea of the code is to generate `N` copies of a single hexagon moved to the right position. We "move" the hexagon vertically by prepending empty lines and horizontally by prepending spaces. Once we're done, we fold all of the copies together, using the beautiful `:..e>` (probably the longest operator I've ever used in a CJam program).
Here is the code:
```
" __
/ \
\__/"N/ e# Get a 2D character grid of the hexagon.
{ e# Read input N, repeat this block N-1 times.
_ e# Make a copy, so we leave the last hexagon on the stack.
SS/\+ e# Prepend two empty lines.
_47> e# Make a copy and discard the first 47 lines.
S3*f{\+} e# Prepend 3 spaces to each line. This copy has been moved back to
e# the top and one column to the right.
_2> e# Make a copy and discard another two lines.
\@? e# If any lines were left after that, pick the copy in the next column,
e# otherwise, stay in the same column.
}q~(*
]:..e> e# Wrap all the hexagons in an array and fold them into a single grid.
N* e# Join them with newline characters.
```
[Answer]
## Python 2, 219 207 chars
```
b=bytearray(' ');h=['__ ','/ \\','\\__/'];k=range;x=input();g=[b*50for _ in k(50)]
for i in k(x):
c=i*3%48+1;r=(i*3+1)/48*2+i%2
for m in k(i>15,3):n=m==0;g[r+m][c+n:c+4-n]=h[m]
print"\n".join(map(str,g))
```
Takes input on stdin.
Pretty much just creates a 50x50 grid of spaces of and plops the hexagons in where appropriate. After the 16th hexagon, I don't need the first row of `h` (the hexagon as a 2D array) so I use `i>15` to start the range at 1 instead of 0. `c=i*3%48+1;r=(i*3+1)/48*2+i%2` calculates the **c**olumn and **r**ow I need to start at. `n` is a boolean but is used as an integer to fix up the bounds (since `h[0]` is only 3 characters to avoid overwriting stuff).
I'm pretty happy with this one, I shaved off about 50 bytes since the initial version, especially when I remembered the `a[x:y]=b` syntax.
Output (n=30):
```
__ __ __ __ __ __ __ __
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \
\__/ \__/ \__/ \__/ \__/ \__/ \__/
(plus 44 lines of spaces each 50 wide)
```
Since trailing lines of whitespace are allowed I changed the creation of `g` to just create 50 `bytearray`s instead of `3+(x>1)+x/16*2`, which is the exact number of rows required, shaving off 12 bytes.
[Answer]
# Swift 2.0, ~~601~~ 591 bytes
```
import Cocoa
var a=Int(Process.arguments[1])!,b="/ \\__".join([String](count:9,repeatedValue:""))+"/",c="\\__/ ".join([String](count:9,repeatedValue:""))+"\\",d=c.startIndex,e=c.endIndex,j=[c.stringByReplacingOccurencesOfString("\\",withString:" ").stringByReplacingOccurencesOfString("/",withString:" ").substringToIndex(advance(d,3*a,e)),b.substringToIndex(advance(d,3*a+a%2,advance(e,-1)))]
while a>0{j+=[c.substringToIndex(advance(d,3*a+1,e)),b.substringToIndex(advance(d,3*a+(a+1)%2,e)]
a<=16 ?j+=[" "+j.removeLast().substringFromIndex(advance(d,1))]:()
a-=16}
for l in j{print(l)}
```
To run: `swift hexagons.swift 21`
Output:
```
__ __ __ __ __ __ __ __
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/
\__/ \__/
```
---
Swift's `substringToIndex` and `stringByReplacingOccurencesOfString` take up so many characters...
[Answer]
# C, 238 bytes
```
#define h(A) c[m+A/4][n+A%4]
i,m,n;
f(a)
{
char c[50][51];
for(i=0;i<50;i++)for(m=0;m<51;m++)c[i][m]=m-50?32:0;
for(;a;)
m=a/12*2,n=a%12*3,a--%2?m=a/12*2+1,n=a%12*3+3:0,
h(1)=h(2)=h(9)=h(10)=95,h(4)=h(11)=47,h(7)=h(8)=92;
for(;i;)puts(c-i--+50);
}
```
Only necessary spaces and newlines considered for character count.
It simply creates a matrix of characters, fills them in reverse order, and then prints the whole thing.
[Answer]
# JavaScript (ES6), 265 bytes
```
A=Array;f='forEach';U=x=1;y=0;a=A.from(A(51),_=>A.from(A(51),_=>' '));d=h=>(` __
/ \\
\\__/`.split`
`[f]((l,i)=>[...l][f]((c,j)=>{if('_/\\'.indexOf(a[x+i][y+j])<0)a[x+i][y+j]=c})),(x+=U*-2+1),(U=!U),(C-y<=3?((U=x+=2),y=0):y+=3),--h?d(h):a.map(d=>d.join``).join`
`)
```
Tessellates hexagons in a row, from left to right, alternating up and down—like a honeycomb—until the end of a row is reached.
Ungolfed with description (works in firefox):
```
'use strict';
const CAP = 51;
var a = Array.from(Array(51), () => Array.from(Array(51),() => ' '))
function draw (hexagons, x, y, a, up) {
// x, y (row, col) represents the current position of the cursor
/*
Here's a map of the first three iterations:
01234567
0 __
1 __/ \__
2 / \__/ \
3 \__/ \__/
For the first 17 iterations, the cursor will be at:
# | x | y
----------
1 | 1 | 0
2 | 0 | 3
3 | 1 | 6
4 | 0 | 9
5 | 1 | 12
6 | 0 | 15
7 | 1 | 18
8 | 0 | 21
9 | 1 | 24
10 | 0 | 27
11 | 1 | 30
12 | 0 | 33
13 | 1 | 36
14 | 0 | 39
15 | 1 | 42
16 | 0 | 45
17 | 3 | 0 <- moves back to the first row
*/
` __
/ \\
\\__/`
// split the hexagon into three lines
.split('\n').forEach((line, index) => {
// and for each line
;[...line].forEach((char, j) => {
// if the cursor position (x, y) translated
// by (index, j) is not already part of a hexagon
// then replace it with the current (index, j) piece
// of the hexagon
/*
0123
0 __
1 / \
2 \__/
*/
if ('_/\\'.indexOf(a[x + index][y + j]) < 0)
a[x + index][y + j] = char
})
})
// `up` represents the next hexagon
// if true, the next hexagon will be drawn attached to
// the top right edge of the current hexagon
if (up) {
x -= 1
// otherwise, it'll be drawn attached to the bottom right edge
} else {
x += 1
}
// move three columns to the right
y += 3
// change directions
up = !up
// if within the right boundary of the 51x51 matrix,
// move back to the left edge and down 2 rows
// and draw the next hexagon as an `up` hexagon
if (51 - y <= 3) {
y = 0
x += 2
up = true
}
// if hexagons > 0, then recurse and draw the next hexagon
// otherwise, return the array (join the columns in each row, then join each row
// by a new line)
return --hexagons ?
draw(hexagons, x, y, a, up)
: a.map(d => d.join('')).join('\n')
}
var n = parseInt(prompt('Number to draw:'))
var r = draw(n, 1, 0, a, true)
document.write('<pre>' + r.replace(/\n/g, '<br>') + '</pre>')
```
[Answer]
# Ruby, 120
```
->n{a=(1..50).map{' '*50}
n.times{|i|x=i%16*3
3.times{|j|a[47-i/16*2-x/3+j][x..x+3]=[' __ ','/ \\','\__/'][j]}}
puts a}
```
creates an array of 50 strings of 50 spaces, then substitutes 4 characters in 3 lines to add the hexagons:
```
" __ "
"/ \"
"\__/"
```
As the first line contains spaces, once a hexagon has been plotted we cannot plot another one below it, because the spaces would overwrite the previous hexagons.
Therefore the hexagons are added in the form of a 16x16 rhombus (distorted rectangle) from bottom to top, and slanting from bottom left to top right.
The string `" __ "` will then be overwritten with additional `\` and `/` where neccessary.
**Ungolfed in test program**
```
g=->n{
a=(1..50).map{' '*50} #make an array of 50 strings of 50 spaces
n.times{|i| #loop through all hexagons
x=i%16*3 #x coordinate of top left corner of hexagon, 16 per row
3.times{|j| #loop through 3 lines to print hexagon.
a[47-i/16*2-x/3+j][x..x+3]= #47-i/16*2 : start at the bottom and work up. each row is 2 lines high and contains 16 hexagons. x/3 : slant upwards as the row moves right.
[' __ ','/ \\','\__/'][j] #These are the symbols for each of the 3 lines required for a hexagon. [x..x+3] defines which characters have to be replaced in each string.
}
}
puts a #print to stdout
}
N=gets.to_i
g.call(N)
```
**Typical output (n=250)**
There should be a few more rows of whitespace at the top here, to make a total of 50, but I don't know if there is a way to get Stackexchange to format to include them.
```
__
__/ \
__/ \__/
__/ \__/ \
__ __/ \__/ \__/
__/ \__/ \__/ \__/ \
__/ \__/ \__/ \__/ \__/
__/ \__/ \__/ \__/ \__/ \
__/ \__/ \__/ \__/ \__/ \__/
__/ \__/ \__/ \__/ \__/ \__/ \
__/ \__/ \__/ \__/ \__/ \__/ \__/
__/ \__/ \__/ \__/ \__/ \__/ \__/ \
__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/ \__/
/ \__/ \__/ \__/ \__/
\__/ \__/ \__/ \__/
/ \__/ \__/ \__/
\__/ \__/ \__/
/ \__/ \__/
\__/ \__/
/ \__/
\__/
```
] |
[Question]
[
To check whether a list of non-negative integers is *balanced*, one can imagine putting respective weights on a board and then try to balance the board on a pivot such that the summarized *relative* weights left and right of the pivot are the same. The relative weight is given by multiplying the weight with its distance to the pivot (see [law of the lever](https://en.wikipedia.org/wiki/Lever#Force_and_levers)).
[](https://i.stack.imgur.com/DcuPO.jpg)
(Source: [wikipedia](https://en.wikipedia.org/wiki/File:Palanca-ejemplo.jpg))
This image corresponds to a list `[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]`. This list is balanced because the `5` has a distance of 20 to the pivot, the `100` a distance of 1 and `5*20 = 100 = 100*1`.
## Examples
```
3 1 5 7
#########
^
```
In this case the pivot is directly under the `5`, the `3` has distance 2 and the `1` and `7` have distance 1. So both sides left and right of the pivot sum up to `7` (`3*2 + 1*1` on the left and `7*1` on the right) and therefore the list `[3, 1, 5, 7]` is balanced.
Note, however, that the pivot does not have to be placed under one of the list elements, but might also be placed in-between two list elements:
```
6 3 1
#######
^
```
In this case the distances become `0.5, 1.5, 2.5, ...` and so on. This list is also balanced because `6*0.5 = 3 = 3*0.5 + 1*1.5`.
The pivot can only be placed exactly below one number or exactly in the middle between two numbers, and **not** e.g. at two-thirds between two numbers.
## Task
Given a list of non-negative integers in any reasonable format, output a `truthy` value if the list can be *balanced* and a `falsy` value otherwise.
You can assume that the input list contains at least two elements and that at least one element is non-zero.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the answer with the fewest amount of bytes in each language wins.
## Truthy Testcases
```
[1, 0]
[3, 1, 5, 7]
[6, 3, 1]
[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]
[10, 4, 3, 0, 2, 0, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[7, 7, 7, 7]
```
## Falsy Testcases
```
[1, 2]
[3, 6, 5, 1, 12]
[0, 0, 2, 0, 1, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[6, 3, 2, 4, 0, 1, 2, 3]
[4, 0, 0, 2, 3, 5, 2, 0, 1, 2, 3, 0, 0, 1, 2, 4, 3, 1, 3, 0, 0, 2]
[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]
```
---
A lot of related challenges where found while this challenge was [sand-boxed](https://codegolf.meta.stackexchange.com/a/10521/56433):
[Is it a balanced number?](https://codegolf.stackexchange.com/questions/94291/is-it-a-balanced-number), [Equilibrium index of a sequence](https://codegolf.stackexchange.com/questions/2438/equilibrium-index-of-a-sequence), [Balance a set of weights on a seesaw](http://codegolf.stackexchange.com/questions/54311/balance-a-set-of-weights-on-a-seesaw), [Balancing Words](https://codegolf.stackexchange.com/questions/52754/balancing-words), [Will I tip over?](https://codegolf.stackexchange.com/questions/129693/will-i-tip-over) and [Where does the pivot belong?](https://codegolf.stackexchange.com/questions/132512/where-does-the-pivot-belong)
[Answer]
# Pyth, ~~12~~ 10 bytes
```
!%ys*VQUQs
```
[Try it online](http://pyth.herokuapp.com/?code=%21%25ys%2aVQUQs&input=%5B100%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+5%5D&debug=0)
Saved 2 bytes thanks to Mr. Xcoder and Erik the Outgolfer.
### Explanation
```
!%ys*VQUQs
*VQUQ Multiply each input by its index.
ys Take twice the sum (to handle half-integer positions).
!% sQ Check if that's a multiple of the total weight.
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 36 bytes
```
IntegerQ[2#.Range[t=Tr[1^#]]/(t-1)]&
```
This is a center of mass problem in a coordinate system with the origin at one of the points and then you determine if the CM falls on a lattice point where the lattice width = 1/2.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zOvJDU9tSgw2khZLygxLz01usQ2pCjaME45NlZfo0TXUDNW7X9AUWZeiUOaQ7WhgYGOAiXItJYLyTAdBRMdBWOwhBGmNFjQGKzGVEfBTEfBXEfBQkfBEkmNCcxciEpTmDlwvQZIXIhdhkjiRrX/AQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ƶO·IOÖ
```
[Try it online!](https://tio.run/##MzBNTDJM/f//2Db/Q9s9/Q9P@/8/2tDAQEeBEmQaCwA "05AB1E – Try It Online")
### How?
```
ƶO·IOÖ ~ Full program. I = input.
ƶ ~ Lift I. Multiply each element with its 1-based index.
O ~ Sum.
· ~ Double.
Ö ~ Is a multiple of?
IO ~ The sum of I.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
×JSḤọS
```
[Try it online!](https://tio.run/##y0rNyan8///wdK/ghzuWPNzdG/z///9oEx0FAzAy0lEw1lEwBTOAXEOYiAES1wQsYogkbhQLAA "Jelly – Try It Online")
Well, looks like [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) pointed the pointless out.
Using Mnemonic's Pyth approach.
Returns a positive integer (truthy) or zero (falsy).
[Answer]
# [R](https://www.r-project.org/), 34 bytes
```
function(n)!(n%*%seq(n)*2)%%sum(n)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPU1EjT1VLtTi1EMjWMtJUVS0uzQUy/6dpJGuY6CgYgJGRjoKxjoIpmAHkGsJEDJC4JmARQyRxI01NLpAxhgYGMCHykKmm5n8A "R – Try It Online")
Takes input as a vector. Ports [mnemonic's answer](https://codegolf.stackexchange.com/a/151322/67312). Returns a `1x1` matrix.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 bytes
```
í* x*2 vUx
```
[Try it online!](https://tio.run/##y0osKPn///BaLYUKLSOFstCK//@jjXUUDHUUTHUUzGMB "Japt – Try It Online")
## Explanation:
```
í* x*2 vUx
U // Implicit Input [3, 1, 5, 7]
í // Pair the input with its index [[3,0],[1,1],[5,2],[7,3]]
* // Multiply each item [0,1,10,21]
x // Sum 32
*2 // Double 64
v // Divisible by:
Ux // Sum of Input 16
// Explicit Output 1
```
Returns `1` for truthy, `0` for falsy.
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
S=s=0
for n in input():S-=s;s-=n
1>>2*S%s
```
Output is via exit code, so **0** is truthy and **1** is falsy.
[Try it online!](https://tio.run/##pVCxboMwEJ3hK26paCtHsp0QWiqy0bUDVZcoA6KuYik1yDYqfD092w2hUjtFstC9e@/evaMb7bFVfPo6ypOAV92LPI6sHvEbiUE0kCTJVBWmoPFHq0GBdK/r7e1dXq0K82RWhYrZbsfvqxszoRoHOy2VhaQcpIWmfRc5UGyLoRGdhbf61ItS61bnf0rZRVqNytbDb@1Mli/PM6NraQTKjRWfziqKpj0jQA/xfk0Aq5RAhmBLwGGsGKXIX/FSb0Jg4y2x4Je2B2vP4WJcmhF4IPCIq12kzDcyHymoQ86tlyNmrkEXrj@3/Gs8n8Y9FyacFInNOXEYTRee/Jx9huEatujz635WevgG "Python 2 – Try It Online")
[Answer]
# [Julia](http://julialang.org/), ~~31~~ 27 bytes
*4 bytes saved thanks to @Dennis*
```
!n=2n[i=1:end]⋅i%sum(n)<1
```
[Try it online!](https://tio.run/##pVFBDsIgELzzivVg0iYcgJaixr6EcDBRE0xFU23SD3jyl34EF7DKxVMJh93Z3dkZOA2d3TXeL1wrnLYt3xzc3ryeD7u8DefClVvuj5ceRmhBE80pMEOJrihgKCmokDUUAhBCzhi2zLgysVCoIykGIsNjVsUiLse9isKKwhq3R10qIirpSv0fuU2cQIBHhGXUk6m/7D@PIhbTTOgNlXqSnoZlRismD980ueIZLmY@mzTEEMBz7a27d65YjCXBT/Rv "Julia 0.6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
*Saved 2 bytes thanks to Mr. Xcoder*
```
->k{(k.map.with_index{|x,i|x*i*2}.sum%k.sum)<1}
```
[Try it online!](https://tio.run/##pVDLboMwEDzDV2wOFRAZB5MQWqn0RwBFeTjB4hFUQKECvp2uTZNyaE@RLGtnZj0768/m8DWKomxqCODC64oek2te6rdEZByUsAgMmxm6lomCY5Pi6KVqDgtzFUZhFMcrAoZh0arMRG0aBMt8X0IHfdtDS@vrTsCga@cgGu2PtDNTKdObqJOdKE687fqWiL5diqU70KrJX1J5W@9sGDWcVcGZHvdZZsoAlq79kZYXpzFkBJxYD9cEsPII@Ai2BCTGijkO6k8cT5kQ2ChLLNxfWoG10nAwDvUJvBJ4w9Eykq8If4okm6eYW9WNmEnCmZn@rPKv72MzV2nTC9mKwuYeeHrqzTzde/QHnJZhM9597q/wO2z2DQ "Ruby – Try It Online")
[Answer]
# C, ~~140~~ 137 bytes
```
float l,r;i,j,t;f(L,n)int*L;{for(i=t=-1;++i<2*n;t*=l-r)for(l=r=j=0;j<n;++j)l+=j<i/2.?L[j]*(i/2.-j):0,r+=j>i/2.?L[j]*(j-i/2.):0;return!t;}
```
[Try it online!](https://tio.run/##pZPfbsIgFMbvfQpmsqStdAP61yHbC/gGzgvj7FLS1YWxK@OzdweqrgZDL2x6AXycH@ccPrbx53bbdVWz32jUYMVrLLHmVbDEbVi3OlryQ7VXQS20iCmfzeoFi1quI9HEKjRKI5SQgnC5aEGWYTMTclE/s6e35Uquo8AMYxm@EKxAeR0oMjYTULja6V/VPmh@7OBM9LWp2yCcHCYIPrOgdz@artZIoAPFiBy5Vb4VaFUwffx4b6cYVYHdhhELQz65imV9bIIRyBlGhY/AMEodQtITcowMxBcOeuKEp6fkCYH07/gz38kplO7Wnp2PhrJs9jBg4zDTJYeVX@6AWVRquwlNKTAqMZpDa7yXk5sNDrXoqYXFFCO3U9y6nfI/L19secsb84s3clsNQKiXAlVmDoWSHkMG/R21KuzJXRIdabIXCVFzF8mG7mUW2ednTvDyYEPp8k6vIT3bsk80GxTOzla7THvz0cG6t8s0uelmev9L8tqemkdkLXrs/gA)
[Answer]
# [Python 3](https://docs.python.org/3/), 51 bytes
```
lambda k:sum(i*e*2for i,e in enumerate(k))%sum(k)<1
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHbqrg0VyNTK1XLKC2/SCFTJ1UhM08hNa80N7UosSRVI1tTUxWkIlvTxvB/QVFmXolGmka0oYGBjgIlyDRWU/M/AA "Python 3 – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 23 bytes
```
{sum(1..*Z*$_)*2%%.sum}
```
[Test it](https://tio.run/##pVJRS8MwEH7Pr7gHJ23NQpOtrVImffIX7EmRUWeEQjdLswoy9tvrJZfOKAjCIA@57758d9/lOt23@TgYDR@52JZs9wnXjZm/1G293@pXWI1HM@wiKUTymFxt4kTNZgKR04jMat0PGlYQMYAnySF95va24IBBxqGgOOdgIQpkmiLxgpNNOhyWThgv6kfGxQuXxiawesHhlsMd9uA7LBxWUIexc1091K0JzaizmdzpICQ9lgZFv23/WTecgnJpemfZlFtO5kggC8TV5PEckmsZ4Ori0WY0B7sHa20OJevw//3/3vjZlOztvffY/B6qZt8NBzhi5cZAsDMRZWIOlso9UXS4aSU7kQgN@38qjvtbZvwC "Perl 6 – Try It Online")
Uses the algorithm from various other entries.
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
sum(
1 .. * # Range starting from 1
Z* # Zip using &infix:«*»
$_ # the input
) * 2
%% # is divisible by
.sum # the sum of the input (implicit method call on 「$_」)
}
```
[Answer]
# Japt, ~~11~~ ~~10~~ 8 bytes
Originally inspired by [Mnemonic's solution](https://codegolf.stackexchange.com/a/151322/58974)
```
x* vUx*½
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=eCogdlV4Kr0=&input=WzMsMSw1LDdd)
~~1~~ 3 bytes saved thanks to ETHproductions.
---
## Explanation
Implicit input of array `U`. Reduce by addition (`x`), multiplying each element by its 0-based index (`*`) in the process. Check if the result is evenly divisible (`v`) by the sum of the original input (`Ux`) with each element being multiplied by 0.5 (`*½`).
[Answer]
## [C#](http://csharppad.com/gist/449df3f2fc21811edf4541d6d44654c5), 71 bytes
---
**Golfed**
```
a=>{int i,s,S=s=i=0;while(i<a.Length){S-=s;s-=a[i++];}return 2*S%s<1;};
```
---
**Ungolfed**
```
a => {
int
i, s, S = s = i = 0;
while( i < a.Length ) {
S -= s;
s -= a[ i++ ];
}
return 2 * S % s < 1;
};
```
---
**Full code**
```
using System;
namespace Namespace {
class Program {
static void Main( String[] args ) {
Func<Int32[], Boolean> f = a => {
int
i, s, S = s = i = 0;
while( i < a.Length ) {
S -= s;
s -= a[ i++ ];
}
return 2 * S % s < 1;
};
List<Int32[]>
testCases = new List<Int32[]>() {
new Int32[] {1, 0},
new Int32[] {3, 1, 5, 7},
new Int32[] {6, 3, 1},
new Int32[] {100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5},
new Int32[] {10, 4, 3, 0, 2, 0, 5},
new Int32[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
new Int32[] {7, 7, 7, 7},
new Int32[] {1, 2},
new Int32[] {3, 6, 5, 1, 12},
new Int32[] {0, 0, 2, 0, 1, 0},
new Int32[] {1, 2, 3, 4, 5, 6, 7, 8, 9},
new Int32[] {6, 3, 2, 4, 0, 1, 2, 3},
new Int32[] {4, 0, 0, 2, 3, 5, 2, 0, 1, 2, 3, 0, 0, 1, 2, 4, 3, 1, 3, 0, 0, 2},
new Int32[] {100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5},
};
foreach( Int32[] testCase in testCases ) {
Console.WriteLine( $"{{ {String.Join(", ", testCase)} }}\n{f( testCase )}" );
}
Console.ReadLine();
}
}
}
```
---
**Releases**
* **v1.0** - `71 bytes` - Initial solution.
---
**Notes**
I might have, or might have not, blatantly "borrowed" [Dennis Python 2 solution](https://codegolf.stackexchange.com/a/151355/52814)...
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ż*∑d?∑Ḋ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqE6xpsiLCLFvCriiJFkP+KIkeG4iiIsIjtaxpvDtyRgLCBgasO4QlwiYCA8PSBgajvigYsiLCJbMSwgMF1cblszLCAxLCA1LCA3XVxuWzYsIDMsIDFdXG5bMTAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCAwLCA1XVxuWzEwLCA0LCAzLCAwLCAyLCAwLCA1XVxuWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwXVxuWzcsIDcsIDcsIDddXG5bMSwgMl1cblszLCA2LCA1LCAxLCAxMl1cblswLCAwLCAyLCAwLCAxLCAwXVxuWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDldXG5bNiwgMywgMiwgNCwgMCwgMSwgMiwgM11cbls0LCAwLCAwLCAyLCAzLCA1LCAyLCAwLCAxLCAyLCAzLCAwLCAwLCAxLCAyLCA0LCAzLCAxLCAzLCAwLCAwLCAyXVxuWzEwMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgMCwgNV0iXQ==)
## How?
```
ż*∑d?∑Ḋ
ż* # Multiply each by its 1-based index
∑ # Sum this
d # Double
Ḋ # Is it divisible by...
?∑ # ...the sum of the input?
```
[Answer]
# [Haskell](https://www.haskell.org/), 39 bytes
```
f l=2*sum(zipWith(*)l[0..])`mod`sum l<1
```
[Try it online!](https://tio.run/##rVDLDoIwELz7FXME0pC2vDSRT/DsgZBAogRiQSJ48edxKQEqiSdteujMdnZntsy721WpYSigYul0z9p6Ve256kvLsVXCXTe1s/p@yagCdRRDnVcNYtR5e4LVPqqmh4vC3oFOgkQw8FQDhsRjIBwwRAsVMozsggXnpPjhBkYrBl@3p4fcFjXl6R9kiGxEDHuGA5lZDUeajkzDo9AMFGo9sWKluTHyYwFfp272IfWPST0KlrI/x5zaBMYUOUdd4BReGLz8x56DFOnwBg "Haskell – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 15 bytes
```
0≡+⌿|(+⌿+⍨×⍳∘≢)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wSDR50LtR/17K/RAJHaj3pXHJ7@qHfzo44ZjzoXaf7//6h3rkJIUWlJRqVCSWpxiUJyYnFqMRdXmoKhggGQNAbSpgrmQJYZiA0SNzBQIBaagtUrmAC1GigYwQSALGOgmCnQSHMFCwVLoBKgsDkEcnE96psKdLe6OpAFdJtbYk4xptOMwE4zA5phqGAI4hhALYC4GsMKqPuNgGIGEFmgiAlUlzFQnRFMHCxmCFYJ8juEb0SCv00B "APL (Dyalog Unicode) – Try It Online")
Looks very ungolfy to me...
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ 75 bytes
thanks to [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) for -3 bytes
```
lambda l:0in[sum(v*(i-y*2)for y,v in enumerate(l))for i in range(len(l)*2)]
```
[Try it online!](https://tio.run/##pZDBDoIwDIbvPEWPYGoypoia@CTIASPoEhgGBwlPj20RRRNPJju039/1379b76611UNxOA5lVp3OGZR7ZWxybyu/W/hm2S90UNQN9NiBsZDbtsqbzOV@GQg3TJvMXojklijNpwMrjpUkRFApQrJCoDJCiLnbIDDgMlSKRv440bgFYS1LqdAzLt1KRDIn3xhhi7Ajd3lXLIRPuvcAbo2xDgrfBZ6U3kcS/UyykWUEQiFq5jrl/Wn8jq9FHO/wLCvrKdV4OZqt1VO8VzsGDmdc//mj0dcnDA8 "Python 2 – Try It Online")
[Answer]
# [Julia 0.6](http://julialang.org/), 25 bytes
```
~=sum
!x=~cumsum(2x)%~x<1
```
[Try it online!](https://tio.run/##pVHLCsIwEDwnX7EKQgt7aKJpFdTvEKQH8QGVtopayEH663GzsSUXT0IOs7Ovmey1q6tD7ly/eXaNnNhNf@wagom26ay3a@UutwfsoGohSaTYK4SsRAJzBMIGoeAwR/AMY5VlVPXHM98xCAseS0DHCQ7nnCUBtLpAWCKsSEAQVzDlXylT/OrWg@6c24hRgcqiDaO/n0siu5qzocsXc2oxuAjtJpqsBzdjGPypiNf/fqEhy6kU/mzWn20nhZhYeG/h/qjaV91KcW5PUorpNCaJcx8 "Julia 0.6 – Try It Online")
[Answer]
# [PHP](https://php.net/), 139 128 bytes
```
<?php $a=explode(',',fgets(STDIN));for($i=0;$i<count($a)-.5;$i+=.5){$z=0;foreach($a as $k=>$v)$z+=($k-$i)*$v;if($z==0)die(1);}?>
```
[Try it online!](https://tio.run/##DcpNDoIwEEDhq8xiEjoyEFDxJ6WwcePGjV6AQJEGI40gMRjPXrt8@Z7trHN5aTsLWCn9sY@h0SLggNu7nkZxvZ3OFyLZDi@BRiUSTV4P7@cksKIoznyHKs7oi4tHf@mq7rxBNQL2qsCZcAmVwD5CQyucpWmFf1VCjdEiJfkrC@dShjXDhmHLkDHsGPYMB4YjQ5r8AQ "PHP – Try It Online")
* -2 bytes for removing quotes around `die` thanks to manassehkatz
* -9 bytes thanks to [Learning the community standard](https://codegolf.meta.stackexchange.com/a/5330/72477)
[Answer]
# [Swift](https://swift.org), 76 bytes
```
{var i=0,t=0;print($0.reduce(0){$0+($1*i,t+=$1,i+=1).0}*2%t<1)}as([Int])->()
```
[Try it online!](https://tio.run/##pVAxDsIwDNx5hYciJdQgJ7QUBGHnDYgBQStFQhUqAQbE24ub0FIGJqQMvnN8vvPlbguX1KfcQQEG6sdtX4E1hM7Q8lzZ0omIJlV@vB5yQfIRUSwiNbLoYhMptLFRckLPkR66lZLP/UVsN6XbyfFayLoQW4VAOzngaorAIEXIAp4hNFQAiog//vHSVgch8cJc6K@Ox1PfZhO8PUOYIyzYw9th5rmsc9iMdN5nfowp9eaot@OT8ueafmjt22Gu@R16SZslCKQ9cd1G6mAIqXq8/vuSfKn6BQ)
[Answer]
# [Perl 5](https://www.perl.org/), 55 + 1 (`a`) = 56 bytes
```
$.=0;map$.+=$p++*$_,@F;$#F+($p=$i-=.5)&&$.&&redo;say!$.
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQqxR9pDIHC1yJ0KpdZwihFkHlkG26fNN7vN2HEwEF68/IIB3AWrdYunHyqCZdgwN2E8g1SoGUurc1@RzfEiTSF8OX@NnTlcXMjmxvxcQf "Perl 5 – Try It Online")
] |
[Question]
[
[Hilbert numbers](https://en.wikipedia.org/wiki/Hilbert_number) are defined as positive integers of the form `4n + 1` for `n >= 0`. The first few Hilbert numbers are:
```
1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97
```
The Hilbert number sequence is given by [OEIS sequence A016813](https://oeis.org/A016813).
A related number sequence, the Hilbert primes, are defined as the Hilbert numbers `H > 1` that are not divisible by any Hilbert number `k` such that `1 < k < H`. The first few Hilbert primes are:
```
5, 9, 13, 17, 21, 29, 33, 37, 41, 49, 53, 57, 61, 69, 73, 77, 89, 93, 97, 101, 109, 113, 121, 129, 133, 137, 141, 149, 157, 161, 173, 177, 181, 193, 197
```
Naturally, [OEIS has this sequence too](https://oeis.org/A057948).
Given a integer `n` such that `0 <= n <= 2^16` as input, output the `n`th Hilbert prime.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so standard rules apply, and the shortest code in bytes wins.
# Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 65895; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```
[Answer]
## Haskell, 46 bytes
```
(foldr(\a b->a:[x|x<-b,mod x a>0])[][5,9..]!!)
```
An anonymous function.
The core is `foldr(\a b->a:[x|x<-b,mod x a>0])[][5,9..]`, which iterates through the arithmetic progression `5,9,13,...`, removing multiples of each one from the list to its right. This produces the infinite list of Hilbert primes. Then, `!!` takes the `n`th element.
I has tried making `(\a b->a:[x|x<-b,mod x a>0])` pointfree but didn't find a shorter way.
[Answer]
# Pyth, 21 bytes
```
Lh*4bye.fqZf!%yZyT1hQ
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&input=6&code=Lh%2A4bye.fqZf%21%25yZyT1hQ&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7&input=6&code=Lh%2A4bye.fqZf%21%25yZyT1hQ&test_suite=1)
### Explanation:
```
Lh*4bye.fqZf!%yZyT1Q implicit: Q = input number
L define a function y(b), which returns
h*4b 4*b + 1
this converts a index to its Hilbert number
.f hQ find the first (Q+1) numbers Z >= 1, which satisfy:
f 1 find the first number T >= 1, which satisfies:
!%yZyT y(Z) mod y(T) == 0
qZ test if the result is equal to Z
this gives a list of indices of the first Q Hilbert Primes
e take the last index
y apply y and print
```
[Answer]
# CJam, ~~36~~ ~~33~~ ~~32~~ 23 bytes
```
5ri{_L+:L;{4+_Lf%0&}g}*
```
[Try it online](http://cjam.aditsu.net/#code=5ri%7B_L%2B%3AL%3B%7B4%2B_Lf%250%26%7Dg%7D*&input=20)
The latest version is actually much more @MartinBüttner's than mine. The key idea in his suggested solution is to use two nested loops to find the n-th value that meets the condition. I thought I was being clever by using only a single loop in my original solution, but it turns out that the added logic cost more than I saved by not using a second loop.
Explanation
```
5 Push first Hilbert prime.
ri Get input n and convert to integer.
{ Loop n times.
_ Push a copy of current Hilbert prime.
L Push list of Hilbert primes found so far (L defaults to empty list).
+ Prepend current Hilbert prime to list.
:L Store new list of Hilbert primes in variable L.
; Pop list off stack.
{ Start while loop for finding next Hilbert prime.
4+ Add 4 to get next Hilbert number.
_ Copy candidate Hilbert number.
L Push list of Hilbert primes found so far.
f% Element wise modulo of Hilbert number with smaller Hilbert primes.
0& Check for 0 in list of modulo values.
}g End while loop.
}* End loop n times.
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
!ü¦¡+4 5
```
[Try it online!](https://tio.run/##yygtzv7/X/HwnkPLDi3UNlEw/f//v4kZAA "Husk – Try It Online")
Uses 1-based indexing.
## Explanation
```
!ü¦¡+4 5 Implicit input n.
¡ Iterate
+4 addition of 4
5 starting from 5: [5,9,13,17,..]
ü Uniquify by
¦ divisibility.
! Get nth element.
```
Most of the work is done by `ü¦`.
The function `ü`, when given a binary function `f` and a list, greedily constructs a subsequence where `f x y` is falsy for every (not necessarily adjacent) pair of elements `x, y`.
In this case it picks a number if it's not divisible by any earlier pick.
Then we just index into the resulting infinite list.
[Answer]
## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), ~~46~~ ~~37~~ 32 bytes
I didn't realize that the gosub was totally unnecessary... >\_>
```
n$z(xxi4*5+d(4-$d%)1=,z+$ziz-)N.
```
[Try it here](http://play.starmaninnovations.com/minkolang/?code=n%24z%28xxi4*5%2Bd%284-%24d%25%291%3D%2Cz%2B%24ziz-%29N%2E&input=9) and [check all test cases here](http://play.starmaninnovations.com/minkolang/?code=57*%5Bi%24z%28xxi4*5%2Bd(4-%24d%25%291%3D%2Cz%2B%24ziz-)6Z%22Mine%3A%20%22%24Oln6Z%22%2C%20Mego%3A%20%22%24O%5D%2E&input=5%2C%209%2C%2013%2C%2017%2C%2021%2C%2029%2C%2033%2C%2037%2C%2041%2C%2049%2C%2053%2C%2057%2C%2061%2C%2069%2C%2073%2C%2077%2C%2089%2C%2093%2C%2097%2C%20101%2C%20109%2C%20113%2C%20121%2C%20129%2C%20133%2C%20137%2C%20141%2C%20149%2C%20157%2C%20161%2C%20173%2C%20177%2C%20181%2C%20193%2C%20197).
### Explanation
```
n$z Take number from input and store it in the register
( Open while loop
xx Dump the stack
i4*5+ Loop counter times 4 plus 5 (Hilbert number)
d Duplicate
( Open while loop
4- Subtract 4
$d Duplicate stack
% Modulo
) Exit while loop when top of stack is 0
1=, 0 if 1, 1 otherwise
z Push register value
+ Add
$z Pop and store in register
iz- Subtract z from loop counter
) Exit while loop when top of stack is 0
N. Output as number and stop.
```
The register is used to store the target index. The outer while loop calculates each Hilbert number and does some bookkeeping. The inner while loop checks each Hilbert number for primality. If a Hilbert number is *not* a Hilbert prime, then the target is incremented so that the outer while loop has to repeat (at least) one more time, effectively skipping Hilbert composites.
[Answer]
## Mathematica, 65 bytes
```
Select[4Range[4^9]+1,Divisors[#][[2;;-2]]~Mod~4~FreeQ~1&][[#+1]]&
```
Generates the entire list and selects the element from it.
[Answer]
# [Raku](https://raku.org/), 35 bytes
```
grep {$_%%none 5,9...^$_},(5,9...*)
```
[Try it online!](https://tio.run/##K0gtyjH7n1up4JChYPs/vSi1QKFaJV5VNS8/L1XBVMdST08vTiW@VkcDwtbS/G@tUJwIUh4dZ2wa@x8A "Perl 6 – Try It Online")
This is an expression for the lazy, infinite list of Hilbert primes.
* `5, 9 ... *` is the infinite list of Hilbert numbers. (Raku infers that it's an arithmetic sequence from the first two elements.)
* `grep { $_ %% none 5, 9 ...^ $_ }` filters that list to those which are divisible (`%%`) by `none` of the Hilbert numbers up to, but not including (`...^`), the number being tested.
[Answer]
# Ruby, 60 bytes
```
h=->i{n=[];x=5;n.any?{|r|x%r<1}?x+=4: n<<x until e=n[i-1];e}
```
Only checks Hilbert prime factors.
[Answer]
# JavaScript (ES6), 73 bytes
```
n=>{for(i=0,t=2;i<=n;)i+=!/^(.(....)+)\1+$/.test(Array(t+=4));return t-1}
```
Just check Hilbert numbers one by one until we reach the nth Hilbert prime. Divisibility by Hilbert number is handled by regex.
[Answer]
# Matlab, 74 ~~83~~ bytes
```
function t=H(n)
x=5;t=x;while nnz(x)<n
t=t+4;x=[x t(1:+all(mod(t,x)))];end
```
Thanks to Tom Carpenter for removing 9 bytes!
Example use:
```
>> H(20)
ans =
101
```
[Answer]
# Julia, 73 bytes
```
n->(a=[x=5];while length(a)<n;x+=4;all(k->mod(x,k)>0,a)&&push!(a,x)end;x)
```
Thanks Alex A. for saving 11 bytes! This uses the same algorithm as the Matlab and Ruby answers. Since Julia arrays are one-indexed, this starts with `f(1) == 5`.
My first attempt, using the Lazy package, is **106 bytes**. If you plan to run this in the REPL, make sure to add semicolons to the ends of the lines to suppress the infinite output. And call `Pkg.Add("Lazy")` if you don't already have it installed.
```
using Lazy
r=range
h=r(1,Inf,4)
p=@>>r() filter(n->n!=1&&all(map(x->mod(h[n],h[x])<1,2:n-1)))
f=n->h[p[n]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 15 bytes
```
ŻḤḤ‘ḍḍiɗċ1=2µ#Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8H/RwxxIgetQwI/Pw9Ic7eo@1nwRSrYaHtiqbGgTpHG5XedS05uikhztncAHVgFQ2rYGoT3WIB6o/Of1It4EtSPnDnav@H90NNw4oB0SZIHlDWyOo/H9DAwA "Jelly – Try It Online")
Uses 1-indexing (e.g. `1 -> 5, 2 -> 9, etc.`), allowed by default on [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") challenges.
## How it works
```
ŻḤḤ‘ḍḍiɗċ1=2µ#Ṫ - Main link. Takes n via STDIN
µ# - Execute the following on integers k = 1, 2, 3, ... until n integers return True:
Ż - Yield [0, 1, 2, ..., k]
Ḥ - Unhalve; [0, 2, 4, ..., 2k]
Ḥ - Unhalve; [0, 4, 8, ..., 4k]
‘ - Increment; [1, 5, 9, ..., 4k+1]
ɗ - Group the previous three links into a dyad.
Use l = [1, 5, ..., 4k+1] on the left and k on the right:
ḍ - Each element in l is divisible by k?
i - Index of k in l or 0?
ḍ - 1 or 0 is divisible by the index?
This yields a list with 2 1s for Hilbert primes
ċ1 - Count 1s
=2 - Equals 2?
Ṫ - Take the last one i.e. the nth Hilbert prime
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 56 bytes
```
$k=$.+=4;1while($k-=4)>1&&$.%$k;($k>1||--$_)&&redo;$_=$.
```
[Try it online!](https://tio.run/##K0gtyjH9/18l21ZFT9vWxNqwPCMzJ1VDJVvX1kTTzlBNTUVPVSXbGihgZ1hTo6urEq@pplaUmpJvrRIP1PL/v9m//IKSzPy84v@6BQA "Perl 5 – Try It Online")
[Answer]
# JavaScript, ~~59~~ ~~58~~ 54 bytes
0-indexed and based on the (possibly erroneous?) observation that, just as all composite numbers are divisible by at least one prime, all *Hilbert* composites are also divisible by at least one Hilbert prime.
Here's [a limited proof](https://tio.run/##ZY9PT4QwEMXvfIrxsEkr2mU3HryUBLRqE/5soG6yMR4Qa1IXWNKyJHx67AqGg3OZ5M3M7735LvrClFq13W1/P47rNTyzhGWBYPDEs1zA1jvCC49ClglIXmPbc/A3TnOuP6Q29I0QEmhdDGjr2cLkKAeD8DupixYp6t9du65yN9hxftECdhmPWe60WtXS0BlDvlTVSY1Qc6Mw9f9UU6lSIs9qRPZSDyixs1WCF9pDGu/SnAtLLE91ezKq@09tqH81@RHVlNX5UxrUzBB7KYDtWXZYWMBzeOR7nvMwYhAeIBAQscAupgmbHrjkbzq0eM4By8VqElrql6sWYzyOPw) of that using the first 20000 Hilbert numbers.
We handle the edge case of `1` being neither prime nor composite below by hardcoding `5` as our stating point.
```
a=[x=5];f=n=>a[a.every(y=>x%y,x+=4)?a.push(x):n]||f(n)
```
[Try it online!](https://tio.run/##DcNRCsIwDADQ0wgJan62gSjZ8BylH0FanGIp6SwN7O7VB@8lVcpD17yd66VH7sKu8eRvkRPP4oRCDWpgPLeDndqRR1yE8rc8oeE1@X2PkLBnXdMGROT@76piMExI72AF0NNHMkTE/gM)
## Explanation
We initialise an array `a=[5]`, which will hold the Hilbert primes, and an integer `x=5`, which we'll use as a temporary variable for the Hilbert numbers, outside the main function. Usually this wouldn't be possible because our rules require that everything be reusable by successive function calls, but here on each successive call of the function `a[n]` will either exist and be immediately returned or we'll resume building the array of primes from where we left off on the last call and continue until it does exist.
`f`, then, is our recursive function taking input via parameter `n`. On each iteration we increment `x` by `4` and then check that, for each existing prime `y` in `a`, `x%y>0`.
If it is then we `push` the new value of `x` to `a`, which returns the updated length of `a`. We use that to index into `a` but, as JavaScript uses 0-based indexing, `a[a.length]` will always return `undefined`, which is falsey, so we fall through the logical `OR` to execute a recursive call to `f(n)` and continue to do so until we encounter a Hilbert composite (i.e., for at least one `y` in `a`, `x%y===0`).
When we do encounter a composite we instead index `n` into `a` and, if it exists, return that value, or continue recursing until the next composite if it doesn't.
[Answer]
# [Python](https://www.python.org), 80 bytes
```
f=lambda I,i=0,H=[2]:(i>I)*H[0]or f(I,i+all((p:=4*len(H)+1)%h for h in H),[p]+H)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3A9JscxJzk1ISFTx1Mm0NdDxso41irTQy7Tw1tTyiDWLzixTSNIBS2ok5ORoaBVa2Jlo5qXkaHprahpqqGQppQPkMhcw8BQ9NneiCWG0PTYi5-0ASmSCJosS89FQNUwNNq4KizLwSjTSNTE2oIpgjAA)
0-indexed (but it would be trivial to change to be 1-indexed). Stores the previous Hilbert numbers in `H`, and stores how many Hilbert primes have been found so far in `i`.
] |
[Question]
[
If we take the natural numbers and roll them up counter clock-wise into a spiral we end up with the following infinite spiral:
```
....--57--56
|
36--35--34--33--32--31--30 55
| | |
37 16--15--14--13--12 29 54
| | | | |
38 17 4---3---2 11 28 53
| | | | | | |
39 18 5 0---1 10 27 52
| | | | | |
40 19 6---7---8---9 26 51
| | | |
41 20--21--22--23--24--25 50
| |
42--43--44--45--46--47--48--49
```
Given some number in that spiral your task is to determine its neighbours - meaning the element above, left, right and below it.
### Example
If we have a look at `27` we can see that it has the following neighbours:
* above: `28`
* left: `10`
* right: `52`
* below: `26`
So the output would be: `[28,10,52,26]`
### Rules
* Input will be a number \$n \geq 0\$ in any [default I/O format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* Output will be a list/matrix/.. of that numbers' 4 neighbours in any (consistent!) order
* You may work with a spiral that starts with 1 instead of 0, however you should specify that in your answer
### Examples
The output is in the format `[above,left,right,below]` and uses a 0-based spiral:
```
0 -> [3,5,1,7]
1 -> [2,0,10,8]
2 -> [13,3,11,1]
3 -> [14,4,2,0]
6 -> [5,19,7,21]
16 -> [35,37,15,17]
25 -> [26,24,50,48]
27 -> [28,10,52,26]
73 -> [42,72,74,112]
101 -> [100,146,64,102]
2000 -> [1825,1999,2001,2183]
1000000 -> [1004003,1004005,999999,1000001]
```
[Answer]
# [R](https://www.r-project.org/), 156 bytes
```
function(n){g=function(h)c(0,cumsum(h((4*(0:(n+2)^2)+1)^.5%%4%/%1/2)))
x=g(sinpi)
y=g(cospi)
a=x[n]
b=y[n]
which(x==a&(y==b+1|y==b-1)|y==b&(x==a+1|x==a-1))}
```
[Try it online!](https://tio.run/##bZNtc5swDMff8ym09tKzF6W1DYSkNz5JL70DYgJrgjswedjTV89kZ23Dho87Gfknyfoj2nOZnsu@KWxtGtbwH5v0/a3iBRNY9Luu37GKsegzE4@smSr@rPhU8uf7eDKJJg8T@aA458Ex3bCubl5rHpxoW5jObbP0@NSsgjw9OXOo6qJixzTN7tgpTfOp/OnMTHJv7/wROZ0hJ/91voW3C4E1UJhmr1vrtmKWZ51eQ92Aade69ceVLl7gUNsKbKXB6s5CQVQXfNet8XwJX2bvKdkLL9kL9TKTwRXCBIfLugV9fNWF1etHeAoxRonJ6pqUo6RCgVLgYoCqUVSGGKKUKAdsOM5GGCHlHqDzUZRuusQE1TCtfIOHfcUYJigpZNibisdoNUcVYSww@qe9ZJReOCFihWo@oJNwjI4UJvREJIgaXlz8FXqohyCZoznOKUAMA5QQl484DFgoJ8xyiXQuSZ1FuAqCW@ib0rS2bzKrtyc/OtuMRsfPT6u/9XWrOzdf2XZrCoIggz3lNDR0VWahdocG8noDpfdp6HRLgwrsd3IfwyYHU0Kb7T5xKpbrIus77fJ1FZXVjY8ozFrDQX/U2JlWwz7b9q52lTXQaL3W63tKQaH@braqO4SvvRtzIjb6I1NeW7i5@mFvXNDFQT/uNPI@1/tAZb/4fypHQtCQehvj0i@8wHJ1/gM "R – Try It Online")
* posted another R answer since it's a slightly different approach than @ngn
* 1-indexed
* neighbours are always sorted by ascending value
* saved 6 bytes removing `round` and using `cospi(x)/sinpi(x)` which are more precise than `cos(x*pi)/sin(x*pi)` in case of half numbers (`0.5`, `1.5` etc...)
* saved another byte removing the minus on y coordinates since the result is the same (just up/down neighbours are reversed)
---
## **Explanation :**
If we look at the matrix coordinates of the values, considering the first value `0` placed at `x=0, y=0`, they are :
```
x = [0, 1, 1, 0, -1, -1, -1, 0, 1, 2, 2, 2, 2, 1, 0, ...]
y = [0, 0, 1, 1, 1, 0, -1, -1, -1, -1, 0, 1, 2, 2, 2, ...]
```
The `x` coordinates follow the [A174344 OEIS sequence](https://oeis.org/A174344) with the recursive formula :
```
a(1) = 0, a(n) = a(n-1) + sin(mod(floor(sqrt(4*(n-2)+1)),4)*pi/2)
```
The same formula holds for `y` matrix coordinates, but with `cos` instead of `sin` and negated :
```
a(1) = 0, a(n) = a(n-1) - cos(mod(floor(sqrt(4*(n-2)+1)),4)*pi/2)
```
So, in R we can translate the formula to this function, taking `sinpi/cospi` as parameter :
```
g=function(h)c(0,cumsum(h((4*(0:(n+2)^2)+1)^.5%%4%/%1/2)))
```
and we generate the two coordinates vectors (we don't negate the y coords since we'll get the same result, just with up/down neighbours reversed) :
```
x=g(sinpi)
y=g(cospi)
```
Note that we have generated `(n+2)^2` coordinates, which are more than the minimum necessary coordinates containing both `n` and their neighbours (a tighter bound would be `(floor(sqrt(n))+2)^2` but unfortunately is less "golfy").
Therefore, now that we have all the coordinates, we first search the coordinates `a,b` corresponding to our `n` :
```
a=x[n]
b=y[n]
```
finally we select the positions of their neighbours, i.e. :
* the up/down neighbours `where x == a and y == b+1 or b-1`
* the right/left neighbours `where y == b and x == a+1 or a-1`
using :
```
which(x==a&(y==b+1|y==b-1)|y==b&(x==a+1|x==a-1))
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 238 bytes
```
((){[()]<((({}[((()))]<>)<<>{((([{}]({}))([{}]{})())[()]){({}[()])<>}{}}>)<<>({}<(((({}{})()){}<>({}))()())<>>)<>>()())<>{{}((()()()[({})]){}<>({}<{}>))(<>)}>}{}){<>((((())()())()())()())(<>)}{}{({}[()]<<>({}<>)<>({}<({}<({}<>)>)>)<>>)}<>
```
[Try it online!](https://tio.run/##TU7BCkIxDPud5iAMz6M/MnZ4HgRRPHgt/faZ9E2Q0i1p06a3z/F4X@6v47mWGWIYZjezyMEXIHP07kE2IicbQCEC9qVHlJyge0ZmDbCkPfxOIamfw2LdXblxRMpMMaSZP3UPLoPxhNRmBKtWd9Xk3yMJrfYh218edcdOh0LexGtdW2tf "Brain-Flak – Try It Online")
Output is in the order left, up, right, down.
### Explanation
```
# If n is nonzero:
((){[()]<
((
# Push 1 twice, and push n-1 onto other stack.
({}[((()))]<>)
# Determine how many times spiral turns up to n, and whether we are on a corner.
# This is like the standard modulus algorithm, but the "modulus" used
# increases as 1, 1, 2, 2, 3, 3, ...
<<>{((([{}]({}))([{}]{})())[()]){({}[()])<>}{}}>
# Push n-1: this is the number behind n in the spiral.
)<
# While maintaining the "modulus" part of the result:
<>({}<
# Push n+2k+1 and n+2k+3 on top of n-1, where k is 3 more than the number of turns.
# n+2k+1 is always the number to the right in the direction travelled.
# If we are on a corner, n+2k+3 is the number straight ahead.
(((({}{})()){}<>({}))()())<>
>)<>
# Push n+1. If we are on a corner, we now have left, front, right, and back
# on the stack (from top to bottom)
>()())
# If not on a corner:
<>{{}
# Remove n+2k+3 from the stack entirely, and push 6-2k+(n+1) on top of the stack.
((()()()[({})]){}<>({}<{}>))
(<>)}
>}{})
# If n was zero instead:
{
# Push 1, 3, 5, 7 on right stack, and implicitly use 1 (from if/else code) as k.
<>((((())()())()())()())
(<>)}{}
# Roll stack k times to move to an absolute reference frame
# (switching which stack we're on each time for convenience)
{({}[()]<<>({}<>)<>({}<({}<({}<>)>)>)<>>)}<>
```
[Answer]
# [~~Perl 6~~Raku](http://raku.org/), ~~94~~ ~~83~~ 78 bytes
~~{my \s=0,|[+] flat((1,*i...*)Zxx flat(1..Inf Z 1..Inf));map {first :k,s[$\_]+$^d,s},i,-1,1,-i}~~
~~{my \s=0,|[+] flat((1,*i...*)Zxx(1,1.5...\*));map {first :k,s[$\_]+$^d,s},i,-1,1,-i}~~
```
{my \s=0,|[\+] flat (1,*i...*)Zxx(1,3/2...*);(grep :k,1==(s[$_]-*).abs,s)[^4]}
```
[Try it online!](https://tio.run/##HYnhCoIwGEVf5SIjpn2tbZZCsR4kNTFwERmJ64diPvta/Thwzr19O3SZf05YWRg/BymdkfQpynUF2zVvcEXJXQiRxOdxDJFu9b@O/Da0PQ4PUsZwV7C62iSxaK6OXFxcdtXiXTMhYjXMCbMFq5cI9jVAEhRBE1JCFjyg94GckIdJyd8rpfRf "Perl 6 – Try It Online")
`s` is a lazy, infinite list of spiral coordinates, represented as complex numbers. It's constructed from two other infinite lists: `1, *i ... *` makes the list `1, i, -1, -i ...`. `1, 1.5 ... *` makes the list `1, 1.5, 2, 2.5, 3, 3.5 ...`. Zipping these two lists together with list replication produces the list of steps from each spiral coordinate to the next: `1, i, -1, -1, -i, -i, 1, 1, 1, i, i, i ...`. (The fractional parts of the right-hand arguments to the list replication operator are discarded.) Doing a triangular addition reduction (`[\+]`) on this list (and pasting 0 onto the front) produces the list of spiral coordinates.
~~Finally, starting from the complex number `s[$_]` (`$_` being the sole argument to the function), we look up the indexes (`first :k`) in the spiral of the complex numbers which are offset from that number by `i`, `-1`, `1`, and `-i`.~~
I shaved a few bytes off by searching for the matching elements in index order, and by testing that the absolute value of the complex difference between the coordinates is 1, rather than testing for 1, -1, i, and -1 explicitly.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
2+1YLtG=1Y6Z+g)
```
Input and output are 1-based.
The output gives the left, down, up and right neighbours in that order.
[Try it online!](https://tio.run/##y00syfn/30jbMNKnxN3WMNIsSjtd8/9/QwA) Or [verify all test cases](https://tio.run/##FY1NC4JAFEX371fcFi3CiGYSbdMuCKRlQbbqqWMOqDPMR@GvN9veczh34NDPr0cBYA09tnrUQaE3xu5w9wp1r21l2DUoFuyDU9zAtLjMMhHlNRQnUWbP5L2ZP6vz7R9RXHcwMdgYoD18Z74j2KM10WGMQ6XcsirLjoNqUE3wlmvVbBfDLX/sdJhmQZIOlFJOIieZkTxSnpLYyx8) except the last two, which time out on TIO.
```
2+ % Implicit input: n. Add 2. This is needed so that
% the spiral is big enough
1YL % Spiral with side n+2. Gives a square matrix
t % Duplicate
G= % Compare with n, element-wise. Gives 1 for entry containing n
1Y6 % Push 3×3 mask with 4-neighbourhood
Z+ % 2D convolution, keeping size. Gives 1 for neighbours of the
% entry that contained n
g % Convert to logical, to be used as an index
) % Index into copy of the spiral. Implicit display
```
[Answer]
# [R](https://www.r-project.org/), 172 bytes
```
function(x,n=2*x+3,i=cumsum(rep(rep(c(1,n,-1,-n),l=2*n-1),n-seq(2*n-1)%/%2))){F[i]=n^2-1:n^2
m=matrix(F,n,n,T)
j=which(m==x,T)
c(m[j[1],j[2]+c(-1,1)],m[j[1]+c(-1,1),j[2]])}
```
[Try it online!](https://tio.run/##NY3LCsIwEEX3/Qo3hRk7QZOiCzHbfoG7EEFCS1PMqH1gQfz22Acu5sCZuZdpY7U5i1gN7Hr/YBiJtdqOWU5euyF0Q4C2fC7jQBKTkCQY6T6lWEgkFl35glXSXaoQ8VMYbzVflZCniUnQ4da3foRi6jNdMGn0u/auhqD1OLuDYBojLTVG2czB9ESipXX59@Vo8Rsr2GNSgZyhZuSLHhc/YPwB "R – Try It Online")
This is R, so obviously the answer is 0-indexed.
Most of the work is creating the matrix. Code inspired by: <https://rosettacode.org/wiki/Spiral_matrix#R>
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~165 162~~ 151 bytes
Prints the indices.
```
f=(n,x=w=y=n+2)=>y+w&&[-1,0,1,2].map(d=>(g=(x,y)=>(k=2*Math.max(x,-x,y,-y))*k+(k+x+y)*(y>=x||-1))(x+d%2,y+~-d%2)-n||print(g(x,y)))|f(n,x+w?x-1:(y--,w))
```
[Try it online!](https://tio.run/##TY5NT8MwDIbv/ApfWO3GqZYgPrQp5cSRXzDtUHW0Gx1p1VVrIgJ/vRhOHF5/PH5l@726Vpd6PA2Tvj4tS@PQc3Czi84rS66Mal6tdtrwmg3bffFRDXhwJbYOA0cxYOds/lpNRxkFYVow60iUdwo7FVSkHGPpQkraEGFQh1vLUX1ryaR9SsN48hO2f/uIUvP7gZqfgzYbjFrzTLRsd2sGw2AZ7hgepBbZe9Hj/qZo@vGlqo/owZXwCXXvL/35rTj3LWbCIAMFXpRtMtqCHJD43yTtFy0/ "JavaScript (V8) – Try It Online")
### How?
For \$x, y \in \mathbb{Z}\$, we compute the 0-based index \$I\_{x,y}\$ of the spiral with:
$$A\_{x,y}=2\cdot\max(|x|,|y|)$$
$$S\_{x,y}=\begin{cases}1,&\text{if }y\ge x\\-1,&\text{if }y<x\end{cases}$$
$$I\_{x,y}=A\_{x,y}^2+(A\_{x,y}+x+y)\times S\_{x,y}$$
*Adapted from [this answer](https://math.stackexchange.com/a/2639611) from math.stackexchange.*
*Also used in [Can you make your way through the Ulam spiral?](https://codegolf.stackexchange.com/a/216328/58563)*
*Saved 1 byte thanks to [@att](https://codegolf.stackexchange.com/users/81203/att).*
[Answer]
# [Python 2](https://docs.python.org/2/), ~~177~~ ~~164~~ 1~~46~~ 144 bytes
```
def f(n):N=int(n**.5);S=N*N;K=S+N;F=4*N;return[n+[F+3,[-1,1-F][n>K]][n>S],n+[F+5,-1][n>K],n+[[1,3-F][n<K],-1][0<n==S],n+[F+7,1][n<K]][::1-N%2*2]
```
[Try it online!](https://tio.run/##NZFNb8IwDIbP41dkh6kfuFOdprQUypELUi89RrmNalwCqhjSLvz17nXCosSyn9ex3eb2e/@@er0sX@dJTanPuqG/@Hvq8/yzznZjP@TD7tSP62F37A38@Xz/mb31a3tcV2QLJi6OzvrDyYkdHQWppoIjldgyVSFrj1iEcu/7/j@3IY6Ss13HxfChc@2W6TorTw918crakpStSNWkmFTjHEI4VpOCwjhtYFo48rAZOgdYCTSksCU/sA2OFNuiGnBMZKEVcAXGIsdOuhYDUaNEjWbm1a0R08YBatTWm8Ab6WgQN3KMzKJjg5KDlZkN6m1EK6OmS8GWWx3m2mIyIJbh2up1O6zombKUjwwOLmzDCgALn@O61dttxkviHybFISF5W0qez2eSp4/3XsJsFTOm1GTLHw "Python 2 – Try It Online")
Calculates `u,l,r,d` directly from `n`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~66~~ 60 bytes
```
{(⊃⍸⍵=s)⌷{⊢/4 2⍴⍵}⌺3 3⊢s←{⌽⍉⍵⍪⍨⌽(⍳(⌈/⍴⍵)+⌈/,⍵)~,⍵}⍣(⍵+4)⊢⍪1}
```
[Try it online!](https://tio.run/##JY29DgFxEMR7T7HlXe7E/@NQqTS0zgtcIqeRkKjkQiMR5FYolBoaEYkCIRKNR5kXOetssZmdzG82GvSKnVHU63ezLHGwnIKf4Htt6CJ9JFjuSwEZ8E28MdKXJSveELN1gvQNXogPPoGPcjrgq4N0XvrnXe@n/Z@a@DnPB4ncvcCVDqH0OIulCbzK/54F@1wsZhustmGrLrvdaIaZJOPPUXuKNBmyVCFdIVMmU6WqJa10AbyLySil/kqrfL4 "APL (Dyalog Unicode) – Try It Online")
1-indexed.
I'd been wanting to solve spiral challenges in APL for a while, so I figured I'd make a spiral creating function for this. I've used simple array magic to make it(and ngn will probably find an insane math relation to calculate it, most likely).
[-6 bytes](https://chat.stackexchange.com/transcript/message/56428225#56428225) from Adám.
## Explanation
```
{(⊃⍸⍵=s)⌷{⊢/4 2⍴⍵}⌺3 3⊢s←{⌽⍉⍵⍪⍨⌽(⍳(⌈/⍴⍵)+⌈/,⍵)~,⍵}⍣(⍵+4)⊢⍪1} input → n
⍪1 to [[1]],
⍣(⍵+4)⊢ apply the following n+4 times:
(⍳(⌈/⍴⍵)+⌈/,⍵) range 1..max(i)+max(shape(i))
~,⍵ without i
⍵⍪⍨ add that as a row
⌽⍉ rotate 90 degrees clockwise
s← assign the spiral to s
{ }⌺3 3⊢ to the 3x3 paritions of the spiral:
⊢/4 2⍴⍵ get every 2nd element
⊃⍸⍵=s find indices of n in the spiral
( )⌷ and index into the matrix of neighbours
```
[Answer]
# [PHP](http://www.php.net/) (>=5.4), 208 bytes
```
<?$n=$argv[1];for(;$i++<($c=ceil(sqrt($n))+($c%2?2:3))**2;$i!=$n?:$x=-$v,$i!=$n?:$y=+$h,${hv[$m&1]}+=$m&2?-1:1,$k++<$p?:$p+=$m++%2+$k=0)$r[-$v][+$h]=$i;foreach([0,1,0,-1]as$k=>$i)echo$r[$x+$i][$y+~-$k%2].' ';
```
To run it:
```
php -n -d error_reporting=0 <filename> <n>
```
Example:
```
php -n -d error_reporting=0 spiral_neighbourhoods.php 2001
```
Or [Try it online!](https://tio.run/##PY5Ra8MgAIT/SgeXNVYdat@S2vwQkRGyrJFsak0ILWP76XP2ZU/HHd8dF6eY86mD1@jTZTPStu8h1S0cpacagx5G91Ev17TW8ITQElWqU82RkMNBFexJw3cNbppjY//2rikmhq9pM/h8lvab6qKq47KRDHPZRixYfMSUVopi1oIgmbJiTelaDfd4MvbDVBvBJBOMS9svBTzDkXGYQsFxo3DW4E5/OOZK2Zf9bt/mnJUQ8jfE1QW/ZO4zf9uNKYX0msYY0ur8RYs/ "PHP – Try It Online")
**Notes:**
* The `-d error_reporting=0` option is used to not output notices/warnings.
* This spiral starts with 1.
---
# How?
I'm generating the spiral with a modified version of [this answer](https://codegolf.stackexchange.com/a/126122/81663) in a 2 dimensional array.
I decide on the size of the spiral based on the input `n` with a formula to always get an extra round of numbers in the spiral (guarantee for existence of above/below/left/right). An extra round of numbers means `+2` in height and `+2` in width of the 2 dimensional array.
So if `n` will be located in a spiral with maximum size of `3*3`, then generated spiral will be `5*5`.
Spiral size is `c*c` where `c = ceil(sqrt(n)) + k`, if `ceil(sqrt(n))` is odd, then `k` is 2 and if `ceil(sqrt(n))` is even, then `k` is 3.
For example, the above formula will result in this:
* If `n = 1` then `c = 3` and spiral size will be `3*3`
* If `n <= 9` then `c = 5` and spiral size will be `5*5`
* If `n <= 25` then `c = 7` and spiral size will be `7*7`
* If `n <= 49` then `c = 9` and spiral size will be `9*9`
* And so on ...
While generating the spiral, I store the `x` and `y` of `n` and after generation, I output the elements above/below/left/right of it.
] |
[Question]
[
The idea of this is mainly from [BIO 2017 q1](http://www.olympiad.org.uk/papers/2017/bio/bio17-exam.pdf). I got the idea for posting this challenge from my [Binary Sequences challenge](https://codegolf.stackexchange.com/questions/150650/binary-sequences), since lots of people seemed to like it.
Also, this is the first challenge I've posted without posting on the sandbox. I'll delete it if no one likes it.
### Rules
Take in a sequence of digits in ternary (base 3); this could be as a string, an array or the numerical value along with the number of preceding zeros.
For each row in the triangle, a row below is generated until there is only one digit in the last row. To find a digit below two other digits, the digit will be the same as two above it if these two other digits above are equal. Otherwise, it will be the digit that is not equal to either of them. Here is an example:
```
0 0 1 2 0 1 2 2
0 2 0 1 2 0 2
1 1 2 0 1 1
1 0 1 2 1
2 2 0 0
2 1 0
0 2
1
```
*You are only expected to return the last row.*
Make your code short.
### Test Cases
```
0 -> 0
11 -> 1
10 -> 2
000 -> 0
012 -> 1
21102 -> 2
201021 -> 1
111111 -> 1
1020202020 -> 2
0212121210 -> 0
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 9 bytes
```
%3←ΩεẊo_+
```
[Try it online!](https://tio.run/##yygtzv7/X9X4UduEcyvPbX24qys/Xvv////RBjpGOoYo2CAWAA "Husk – Try It Online")
### Explanation
The main idea is to compute the mapping of two digits to one as **f(a,b) = (-a-b) % 3**. For golfing purposes we can delay the modulo until the very end.
```
Ωε Apply the following function until the list is only one
element in length.
Ẋo Apply the following function to pairs of adjacent values.
_+ Add the two values and negate the result.
‚Üê Take the first (and only) element of this list.
%3 Take it modulo 3.
```
In principle, it's also possible to compute the result directly by multiplying each element by the corresponding binomial coefficient and multiplying the sum by **-1** for even-length lists, but I don't know of a way to do that in fewer bytes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
td"HYCEsI\
```
[Try it online!](https://tio.run/##y00syfn/vyRFySPS2bXYM@b//2gDBQMFQwUjKGkUCwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L8kRckj0tm12DPmf6xLyP9og1iuaEMFQzAJYhsoGEBpQwUjIG0EpIEyULYBhA1VD4cQ3QpGqBhsCkg/MjaIBQA).
### Explanation
For each pair of digits, the code computes twice the sum modulo 3. The process is repeated as many times as the length of the input minus 1.
```
t % Implicit input: array of length n. Duplicate
d % Consecutive differences. Gives an array of length n-1
" % For each (that is, do n-1 times)
HYC % 2-column matrix where each column is a sliding block of length 2
E % Times 2, element-wise
s % Sum of each column
I\ % Modulo 3
% Implicit end. Implicit display
```
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
f=lambda a,*l:-(f(*l)+f(a,*l[:-1]))%3if l else a
```
[Try it online!](https://tio.run/##LU67CsMwDNzzFcJQsFMHLHcL@A@yZTQeXBrTgPIgztKvd2O1OriTdDfc/jnf22pLSY7i8nxFiLqlvpNJtqTuSdbT9x0GpW6POQHBRHmCWEbnhRFaIFaqmzHMaC@2iIbVXMoJHo7aP2rY4g9GhGZwfom7nNdTZwVpOyDDvMIYmv24nuC5ExtUjSGULw "Python 2 – Try It Online")
Recurses on the sublists deleting the first and last elements respectively.
This would be cleaner in Python 3 if it could actually unpack `f=lambda a,*b,c:...`.
[Answer]
# [Emojicode](http://www.emojicode.org/), 242 bytes
```
üêãüç®üçáüêñüû°Ô∏èüöÇüçáüîÇi‚è©‚ûñüêîüêï1 0üçáüîÇj‚è©0iüçáüçä‚ùéüòõüç∫üî≤üêΩüêïjüöÇüç∫üî≤üêΩüêï‚ûï1jüöÇüçáüê∑üêïj‚ûñ‚ûñ3üç∫üî≤üêΩüêïjüöÇüç∫üî≤üêΩüêï‚ûï1jüöÇüçâüçâüçâüçéüç∫üî≤üêΩüêï0üöÇüçâüçâ
```
Uses the same algorithm as [my C answer.](https://codegolf.stackexchange.com/a/152105/56721) [Try it online!](https://tio.run/##S83Nz8pMzk9J/f//w/wJ3R/m964A4nYge9qH@VMWPZq38P2O/g/zZzVBRKc0ZT7qX/loHlBywhQgnmqoYACTyQLKGGRCeL1dj@b2fZg/YzaQuQsouQmodi9IfRbULBTBR/OmGmYhLJmwHawSaAsQGZNsQicS7kNXaICsCOjl/kYFkKUKXApAekYDkJiyEEQsAgmvUDAAQkMFIyhpBBJsUzA04ALrBgA "Emojicode – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
+2\N$Ḋ¿%3
```
[Try it online!](https://tio.run/##y0rNyan8/1/bKMZP5eGOrkP7VY3///8fbaCjAESGOgpGSAyjWAA "Jelly – Try It Online")
Using Martin Ender's Husk algorithm.
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
f[a]=a
f(h:t)=mod(-f t-f(h:init t))3
```
[Try it online!](https://tio.run/##RYtNCsMgEIX3nmKQLhKooHYX6gF6BpEiiRJpYn6c7np3G21L58F7M7xvRpsebppy9toaZYlvxg5bNS9DwzwgK3eIAQHb9pJRacrpmQpRrGycVxfycCkEr8mPrESdisqvCizFR5wagst9CgkhgQK9Ozvo3rz6K0uGJLc9XexdqWa7wg9F6DrQ@hbRGDLbEI9@3UNEOFXOw/8zvwE "Haskell – Try It Online")
Saves 1 byte over the more symmetrical:
```
f[a]=a
f l=mod(-f(tail l)-f(init l))3
```
[Try it online!](https://tio.run/##RYtBCsMgFET3nuIjXSTQgNpdqAfoGUSKJEqlxqTxd9e7W7Ut/QMzA/P@zaS7DSFnp4yWhjgIclnnbnAdGh8g9KX56LG0/pRRKsrokXJerTbGmnNRXHDOWrKSjWjXUPFVhQX/iFFNcL0GnxASSFC7NbOa9Gs6D0mTZB9PGydbp8Vs8EMRxhGUukTUmizGx7Jvu48Ih8Y5@H/mNw "Haskell – Try It Online")
The idea is simple: recursively compute the function on the sublists deleting the first and last element respectively, and combine them with `\a b -> mod(-a-b)3`. This seems shorter than `zipWith`'ing this fuction .
**[Haskell](https://www.haskell.org/), 44 bytes**
```
f[a]=mod a 3
f l=f$zipWith((-).(0-))l$tail l
```
[Try it online!](https://tio.run/##RYtBCsIwFET3OcWndNGClSTuxBzAE7gIQUKb0GCa1ua7Ee8em6j4B2Y@zJtRx5vxPiUrtRLTPICGA7Hgha2fbrk4HJuma/cN7drW16idB59QyIpWu4qxbPmjtDjjm3PGaEm6ZSHKFZR/lWHOPqKVIjhfvYsIEQTI1ehB9urVn7qoSDT3hwm9ydWkF/ihCMcjSHkOqBSZtAtbv6wuINSFs/Bfpjc "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~91~~ ~~88~~ 84 bytes
*-1 byte thanks to @Mr.Xcoder!*
```
j;f(a,l)int*a;{for(;l-->1;)for(j=0;j<l;)a[j++]=a[j]^a[j+1]?3-a[j]-a[j+1]:a[j];a=*a;}
```
Gets the array and the length. [Try it online!](https://tio.run/##LY3BCsIwEER/RQpC1m4gqRdxjX5IibBEIg1pleIt9NtjFr3svGHYmaCfIdSaKCrGDNPyOTCV@FoVZa2vlkA4OUPpkgl4TH3vXRN/F7b@dtTi9M@dhYldK9nqzNOioLTOHY/eFYMGLQ7/O2z0XlsWVbd/dCj7J4D29gU "C (gcc) – Try It Online")
[Answer]
# J, ~~23~~ 15 Bytes
```
3&(|2+/\-)~<:@#
```
Thanks to @miles
### Old Solution:
```
3|2&(-@+/\)^:(#>1:)^:_]
```
Inspired by Martin Ender's solution:
### Explanation
```
3|2&(-@+/\)^:(#>1:)^:_] | Whole program
] | Seperates the argument from the _ (infinity)
^:(#>1:)^:_ | Do while the length is greater than one
2&(-@+/\) | Inverse of the sum of adjacent elements
3| | Modulo 3
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 17 bytes
```
{3|3-2+/⍵}⍣{1=≢⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Rq4xpjXSNt/Ue9W2sf9S6uNrR91LnoUe@uWqC0ggEQGioYQUkjrjQgbQDmI2EA "APL (Dyalog Unicode) – Try It Online")
**How?**
`2+/‚çµ` - sum each two adjacent items
`3-` - vectorized subtract from three
`3|` - vectorized modulo by three
`⍣` - repeat until...
`1=≢⍺` - only one item is left
[Answer]
# Javascript (ES6), 58 bytes
```
f=s=>s[1]?f(s.replace(/.(?=(.?))/g,(a,b)=>b&&(6-a-b)%3)):s
```
[Answer]
## Batch, 122 bytes
```
@set/an=2,s=i=l=0
@for %%e in (%*)do @set/al+=1,n^^=3
@for %%e in (%*)do @set/as+=%%e*n,s%%=3,n*=l-=1,n/=i+=1
@echo %s%
```
Uses binomial expansion. As @MartinEnder points out, the sum has to be negated (modulo 3) if the number of values (which are counted in the first loop) is even, so `n` is set to either `1` or `2` accordingly. The second loop then computes the sum via the binomial coefficients.
[Answer]
# APL+WIN, ~~30~~ 28 bytes
2 bytes saved courtesy of Uriel.
```
n←⎕⋄¯1↑∊⍎¨(⍴n)⍴⊂'n←3|3-2+/n'
```
Explanation:
```
n←⎕ Prompt for screen input of the form: 0 0 1 2 0 1 2 2
'n‚Üê3|3-2+/n' Successive rows are 3 mod 3 minus successive digit pairs.
(⍴n)⍴⊂ Create a nested vector of the row code, one element per row.
¯1↑∊⍎¨ Execute each element of row code, flatten result and take final value.
```
This is one way of writing looping code in APL on a single line.
] |
[Question]
[
Thanks to your help in the [Mark My Mail](https://codegolf.stackexchange.com/questions/149672/mark-my-mail-ascii-barcodes) challenge, PPCG-Post has successfully stamped all of its parcels with the generated barcodes!
Now, it's time to decode them.
In this challenge your program will, given a barcode generated from the [Mark My Mail](https://codegolf.stackexchange.com/questions/149672/mark-my-mail-ascii-barcodes) challenge, decode it and return the encoded integer.
But watch out! The barcode might be upside down...
---
## 4-state barcodes
In the case you missed the encoding challenge you'll need to know what kind of barcodes we're talking about. A 4-state barcode is a row of bars with four possible states, each representing a base-4 integer:
```
| |
Bar: | | | |
| |
Digit: 0 1 2 3
```
Rendered in ASCII, the barcodes will take up three lines of text, using the pipe (`|`) character to represent part of a bar, and a space () to represent an empty section. There will be a single space in between each bar. An example barcode may look like this:
```
| | | | | | | | | |
| | | | | | | | | | | | | | | | |
| | | | | | | |
```
To convert a barcode back to the integer it encodes, map each bar to its corresponding base-4 digit, concatenate these, and convert it to decimal.
As each barcode will also represent a different barcode when upside down, we implement a start/stop sequence so the orienation can be calculated. For the purpose of this challenge, we will be using the start/stop sequence specified by Australia Post: **each barcode begins and ends with a `1 0` sequence.**
---
# The Challenge
Your task is to, given an ASCII 4-state barcode, parse it and return the integer it encodes - essentially the reverse of [Mark My Mail](https://codegolf.stackexchange.com/questions/149672/mark-my-mail-ascii-barcodes).
But to spice things up, there's a catch - **the barcode may be given upside down.** As in the real world, it will be left to the barcode reader (your program) to **determine the correct orientation** using the start/stop sequence.
### Example:
Given the following barcode:
```
| | | |
| | | | | | | | | | |
| | | | |
```
We can clearly see that the first and last pairs of digits are `0, 2` and not `1, 0`. This means that the barcode is upside down - so we must **rotate it by 180 degrees** (not just flip each bar) to achieve the correct orientation:
```
| | | | |
| | | | | | | | | | |
| | | |
```
Now, we can begin the decoding. We map each bar to its corresponding base-4 digit, ignoring the start/stop sequences as they do not encode the data.
```
| | | | |
| | | | | | | | | | |
| | | |
- - 2 1 0 3 0 2 3 - -
```
We concatenate this to the base-4 integer `2103023`, then convert it to its decimal representation `9419` for the final result.
---
# Rules
* The input will always be a valid, 4-state barcode, rendered in ASCII as set out above, with the described start/stop sequence.
+ You may request trailing spaces, or stripped lines, as well as a trailing newline - whichever format suits your golfing.
+ It may or may not be in the correct orientation - your program must determine whether to read it upside down, by using the start/stop sequence.
+ It will not encode leading zero-digits in the base-4 integer.
* You may take the input as a list of lines, or a string with newlines.
* The output should be an integer in your language's standard integer base, representing the data that was encoded by the barcode.
* As postage stamps are small and can fit very little code on them, your code will need to be as short as possible: this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") - so the shortest program (in bytes) wins!
---
# Test Cases
```
| | | | | | | | | | |
| | |
```
**= 4096** (flipped)
```
| | | | | | | |
| | | | | | | | | | | | | | | |
| | | | | | | | | |
```
**= 7313145** (flipped)
```
| | | |
| | | | | | | | | | |
| | | | |
```
**= 9419** (flipped)
```
| | | | | |
| | | | | | | | |
| | | |
```
**= 990** (not flipped)
```
| | | | |
| | | | | | | | | | |
| | |
```
**= 12345** (not flipped)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
>⁶m2Zm2UFUi¡1ṫ4Ḅ:⁴
```
[Try it online!](https://tio.run/##y0rNyan8/9/uUeO2XKOoXKNQt9DMQwsNH@5cbfJwR4vVo8Yt////j@ZSUgCDGihEZyso6XAp1SjghSAlClAd2EggVuKKBQA "Jelly – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 16 bytes
```
ḋṁẊ=hhttĊ2T§▼↔m↔
```
[Try it online!](https://tio.run/##yygtzv6v8Kip8dC2/w93dD/c2fhwV5dtRkZJyZEuo5BDyx9N2/OobUouEP///18BDGqgEJ2twFWjgBdyKUDVYiOBGAA "Husk – Try It Online")
Input is a list of lines (the TIO link uses a multiline string for clarity).
The lines must have equal lengths, and there must not be extra trailing spaces.
## Explanation
```
ḋṁẊ=hhttĊ2T§▼↔m↔ Input is a list of strings x.
§▼ Lexicographic minimum of
↔ x reversed and
m↔ x with each line reversed.
T Transpose. Now we have a list of columns.
Ċ2 Get every second column, removing the blank ones.
hhtt Remove first 2 and last 2 (the orientation markers).
ṁ Map and concatenate
Ẋ= equality of adjacent pairs.
This turns a column like "|| " into [1,0], and these pairs are concatenated.
ḋ Convert from binary to integer.
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~40~~ 32 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
K@=«I⁷G@Κ¹;⌡I2n{j_{@≠}«+}¹jkjk4│
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=S0AlM0QlQUJJJXUyMDc3R0AldTAzOUElQjklM0IldTIzMjFJMm4lN0JqXyU3QkAldTIyNjAlN0QlQUIrJTdEJUI5amtqazQldTI1MDI_,inputs=JTdDJTIwJTIwJTIwJTdDJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTdDJTIwJTIwJTIwJTdDJTIwJTdDJTIwJTIwJTIwJTBBJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTdDJTIwJTBBJTIwJTIwJTIwJTIwJTdDJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTdDJTIwJTdDJTIwJTIwJTIwJTIwJTIwJTIwJTIw,v=0.12)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~113~~ 105 bytes
```
lambda x:int(''.join([`2*(c>'#')+(a>'#')`for a,b,c in zip(*x[::1-2*(x[-1]>'#')].split('\n'))][4:-4:2]),4)
```
[Try it online!](https://tio.run/##fZLhboMgEID/@xSX7AfQYVOUdZHEvQiS1HY1Y7Fo1CVu8d0daI22sYXkuIPju@OO8rf5KkzQZ3HS5@nl@JlCK7RpMELb70IbLA/BBp8@0Asirzgd1kNWVJDSIz2BNvCnS7xppRDMt56t9JkavNS2LnNtQYlBhCjJhc9FoAjlpG/OdVPHUiJYG4npYGUmBuyyHM7qEOW7aK9o4k246ca9/gh8H6KDdTkEew9ZyPjbHG8@vcqn6c9@Vw3RiLNoxHU3CXerKIe5TQwsItotCYvqPKAsSXPRYKSxILQPVJ5rs@sUhepc/@SN6/bQOeFBWdlPMliTnmFnkTgenem04fX/ "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 96 bytes
```
lambda a:int(`[2*(r==q)+(p==q)for p,q,r in zip(*a[::(a>'|')*2-1].split('\n'))[4:-4:2]]`[1::3],4)
```
[Try it online!](https://tio.run/##fUzLCsIwEPyVvWVTU6Exp4X2R5JAI1IM1G0ae1H677FKTyLOMI/DMOmxXCfWZWhdGcPtfAkQKPKCvdUV5rad5QHTO4YpQ1KzyhAZnjFhFSwRhk6sQla6bvzxnsa4oHAspLSGakPa@942RCevjCwpb88woIAP1p3fHRyv8JeOYV//8k1Clhc "Python 2 – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~46~~ ~~43~~ 42 bytes
```
IsQ@@gg:RV*RVgY^gR'|1(J@UW2*y@2+@y)TM2FB:4
```
Takes the lines of the barcode as three command-line arguments. The first and third lines must be padded to the length of the second line with spaces. [Try it online!](https://tio.run/##K8gs@P/fszjQwSE93SooTCsoLD0yLj1IvcZQw8shNNxIq9LBSNuhUjPE18jNycrk////CmBQA4XobIX/NQp44X8FqFpsJBADAA "Pip – Try It Online")
### Explanation
First some prepwork:
```
IsQ@@gg:RV*RVg Y^gR'|1
g is cmdline args; s is space (implicit)
IsQ If space equals
@@g the first character of the first line, then:
RVg Reverse the order of the rows in g
RV* then reverse the characters in each row
g: and assign the result back to g
gR'|1 In g, replace pipe character with 1
^ Split each row into a list of characters
Y Yank the result into y
```
Now observe that if we ignore the middle row and treat `|` as 1 and as 0, each bar is just a 2-bit binary number:
```
(J@UW2*y@2+@y)TM2FB:4
y@2 Third row
2* Multiply by 2, turning 1 into 2 and space into 0
@y First row
+ Add
UW Unweave: creates a list of two lists, the first containing all
even-indexed elements (in our case, the actual data), the second
containing all odd-indexed elements (the space separators)
@ First item of that list
J Join the list of digits into a string
( )TM2 Trim 2 characters from the beginning and end
FB:4 Convert from base 4 (: makes the precedence lower than TM)
Autoprint
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 71 bytes
```
(.).
$1
sO$^`^\|.*|.
^..|..¶.*¶..|..$
¶
\|
|
+`\|
||||
.*¶$
$&$&
\|
```
[Try it online!](https://tio.run/##hU0xDsIwDNzvFR5MVYpkiTmP4ANRFAYGFgZg9Lv6gH4s2GpKOgRxkeOzzr573t73x7UsMwJCgPXDmL2XUY4CPuN14ZRTVJlUgCSiIsssk5VT9puoIMUpRyUjBrjO4IEHE0uhHqDUeSD79/BJgZUqbbL@sWhblQFaLb426J22mDUCzYOa8DN5v1vZBw "Retina – Try It Online") Link includes smaller test cases. Requires the first and last lines to be space-padded to the length of the middle line. Explanation:
```
(.).
$1
```
Delete the unnecessary spaces.
```
sO$^`^\|.*|.
```
Reverse the characters in the code, but if the bar code begins with a `|`, then select the entire code, otherwise split it in to characters. Then, reverse them. This flips the code if it begins with a `0`.
```
^..|..¶.*¶..|..$
¶
```
Delete the start/stop sequence and the middle row (which is of no use to us).
```
\|
|
+`\|
||||
```
Convert the spaces and `|`s from base 4 to unary.
```
.*¶$
$&$&
```
Double the last line.
```
\|
```
Convert to decimal.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 181 160 bytes
Not too shabby for a java solution, I'm sure there are optimisations I can make, but I've already been staring at this for too long.
Cut down a few bytes by shortening the loop rather than using substring.
Golfed
```
c->{String r="";Integer i,j,l=c[0].length;for(i=4;i<l-4;i+=2){j=c[0][0]>32?i:l-1-i;r+=c[0][j]%8/4*(j==i?1:2)+c[2][j]%8/4*(j==i?2:1)+"";}return l.parseInt(r,4);}
```
[Try it online!](https://tio.run/##bY9fT8MgFMWf209xs8QE7B9t3YNZZYvxyQf34mPTB2Sso1LaUDazdP3sFTY1cSkQyD335ncOFT3QqGm5qjafI5O06@CNCtX7nlCG6y1lHNa9D56roURsR3Ve5AUwnPne4Pteu/@QgkFnqLHPoREbqC0BvRstVGknKbY0z1GhBgKKf50tkAN4fzyqy852e5rfF7FpXqz@rDU9IhwCzZMJLb3SBsd7P3aG13GzN3Fr/Y1UqI5VXCLHx7@Zf8KuQVnLkUXL/pIWNJnNslf785JrEGEVSsJcIMlVaXbZttFIkHkmnmRk74CkuK/OE/YsH9KVWMgoiUSmg4taFTePd/NbVBEiVskixQGzuf/L6SLBgbUdNDd7rUDGLdUdtymQDuc4G0Yv84dxhKk1nmBqTwzCleyq0zc "Java (OpenJDK 8) – Try It Online")
Ungolfed
```
String r = "";
Integer i, j, l = c[0].length;
for(i=4; i<l-4; i+=2){
j = c[0][0]>32 ? i : l-1-i;
r += c[0][j]%8/4 * (j==i?1:2) + c[2][j]%8/4 * (j==i?2:1) + "";
}
return l.parseInt(r, 4);
```
[Answer]
# [Java 8](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html), ~~208~~ ~~166~~ ~~157~~ 151 bytes
Trying it, probably can be better, reduced 42 due unnecessary checks, -9 removing variables, -6 thanks to Luke Stevens
Input is a `char[][3]`
```
(a)->{int i=2,c,s=0;c=(a[0][0]>32)?1:-1;for(;i<a.length-2;i++){s+=((a[i][1-c]>32?1:0)+(a[i][1+c]>32?2:0))*Math.pow(4,c==1?a.length-i-3:i-2);}return s;}
```
ungolfed:
```
int b(char[][] a) {
int i=2,c,s=0; //i for looping, c to check if it's reversed, s is the sum, n the number
c=(a[0][0]>32)?1:-1; //Check if must be reversed
for(;i<a.length-2;i++){ //Looping elements
//(Checking value for 1 + Checking value for 2) * Power, if reversed increasing, else decreasing
s+=((a[i][1-c]>32?1:0)+(a[i][1+c]>32?2:0))*Math.pow(4,c==1?a.length-i-3:i-2);
}
return s;
}
```
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~191~~ ... ~~161~~ 144 bytes
```
import StdEnv
?' '=0;?_=1
r=reverse
$a b|hd a<'|'= $(r b)(r a)=[?(b!!n)*2+ ?(a!!n)\\n<-[4,6..length b-4]]
@[a,_,b]=sum[d*4^p\\d<- $a b&p<-[0..]]
```
[Try it online!](https://tio.run/##fY9NT8MwDIbP5Fd4YqLbaLsPJi4s6iTggMRtxzZMaRO2SGlSJekAqb@dLhmDA0LYkj9kPa/tSnKq@lqzVnKoqVC9qBttHGwce1QHlEUQ4dldtsVzZLDhB24sR0MKZbdnQFdRF2EYjgyUYx/oGOfZqBwM1HiyuIZsRENZFGqV5Mv4Nk0lVzu3hzJZEoLWOY23cUmwbeucTZYvTVGwVQJB/arxyCxNCek3jvp7plNwe2GBSqnfLFhdc604CMXfG24EVxVnvoP78BA4DY5bBwdqhG6tHzSts@jylAFDji7yCE7Wnf13DRGJw9a5l5F@TSA6@NfPxEKxHwLOen9FCAQE4sZ8EwRhWH@d239Wr5LubJ88PfcPH4rWorJH "Clean – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~39~~ 38 bytes
```
B4ththmȯ%4+3%5f≠192Ḟz+zṀ·*cN?↔m↔(='|←←
```
Takes input as a list of strings: [Try it online](https://tio.run/##yygtzv7/38mkJKMkI/fEelUTbWNV07RHnQsMLY0e7phXpV31cGfDoe1ayX72j9qm5AKxhq16zaO2CUD0////aKUaBQUFEFaA0jVgUklHqUYBGwRKKKDogLGUYgE "Husk – Try It Online") or [try the test-suite!](https://tio.run/##yygtzv6f@6ip8b@TSUlGSUbuifWqJtrGqqZpjzoXGFoaPdwxr0q76uHOhkPbtZL97B@1TckFYg1b9ZpHbROA6P///9HRSgrYgJKOUo0CFggUVwDSyADEq1GK1YGZBFOLzsZpJobpNQrYSWR7EGJQkoCLESqhLLBJNShurMFlDNgMVNcAVSIMQAoI3IagGIQIKmjYxMYCAA "Husk – Try It Online")
### Explanation
```
B4ththm(%4+3%5)f≠192Ḟz+zṀ·*cN?↔m↔(='|←←)
? (='|←←) -- if the very first character == '|'
↔ -- reverse the lines
-- else
m↔ -- reverse each line
zṀ·*cN -- zip the lines with [1,2,3..] under..
Ṁ·*c -- convert each character to its codepoint and multiply by one of [1,2,3]
Ḟz+ -- reduce the lines under zipWith(+) (this sums the columns)
f≠192 -- only keep elements ≠ 192 (gets rid of the separating lines)
-- for the example from the challenge we would now have:
-- [652,376,468,652,376,744,376,468,744,652,376]
m( ) -- map the following function
%4+3%5 -- λx . ((x % 5) + 3) % 4
-- this gives us: [1,0,2,1,0,3,0,2,3,1,0]
th -- remove first & last element
th -- remove first & last element
B4 -- interpret as base4 number
```
[Answer]
# [Perl 5](https://www.perl.org/), 152 + 2 (`-F`) bytes
```
push@a,[@F]}{for$i(0..$#{$a[1]}){$_.=($a[0][$i]eq'|')+2*($a[2][$i]eq'|')}$_=reverse y/12/21/r if/^0/;s/^0*1000|10*$//g;s/.\K0//g;$\=$_+$\*4for/./g;say$\
```
[Try it online!](https://tio.run/##bY3NDoIwEITvPgWJm/An7ZbIyZBw4mJ8AoqEQ9EmRrBVE0J5dWvxxMGd7GT228MMQt0ya4eXvhbtrirKep66XoEMkBDYTtBWrJ7DCRqSB@7AugJZi4dv/DBOowWlKzRDkyvxFkoLb6QspSmjypMdPSM9aOcRQ0TDMAJKL44QfsQlAc@hiYFHe9dOyfJrR@DWboz3RxvP@XrMbz/98JT9XdvklBFkaJPyCw "Perl 5 – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~80~~ ~~75~~ 68 bytes
```
@(b)bi2de({rot90(t=~~(b-32)([3,1],[1:2:end]),2),t}{2-t(2)}(5:end-4))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI0kzKdMoJVWjuii/xNJAo8S2rk4jSdfYSFMj2ljHMFYn2tDKyCo1LyVWU8dIU6ekttpIt0TDSLNWwxQkqmuiqfk/TSNaXQEIaoBQAYyhpLo1F4isUcACoXIwXQrIetVjNbm4QKYixGDyNSBTFYgwFlkjlAU09j8A "Octave – Try It Online")
Curiously, `bi2de` is default MSB on the right rather than the left, leading to some headaches while I made this... I think I should have the optimal way of flipping the array before indexing it, but there are *extremely* many ways to do it (either in the first indexing, or with `flipud`, `fliplr`, `rot90`, `'` (transpose), the final indexing...). Takes a rectangular array with spaces and `|`s (so, trailing spaces required)
```
@(b) % Define anonymous function taking input b
t= % Inline-define t,
~~(b-32) % which is the input, converted to 1's and 0's,
([3 1],[1:2:end]) % but only keep the relevant rows (1 and 3 flipped vertically) and columns (only odd)
{rot90(t,2),t} % Flip 180 degrees
{2-t(2) % depending on whether the second element of t is 1 or 0.}
(5:end-4) % Flatten array, discarding control bits
bi2de( ... ) % and convert from binary to decimal,
```
[Answer]
# JavaScript (ES6), ~~184~~ 181 bytes
I'm not an experienced golfer - I'm sure this can be improved, but I loved this challenge! I've always wondered about those marks.
Function `f` takes a list of strings with required trailing spaces. Newlines added to the code below for clarity (not included in byte count).
```
f=t=>((o=[[...t[0]],[...t[2]]])[0][0]=='|'?o:(z=a=>a.reverse())(o.map(z)))
.map((a,r)=>a.filter((_,i)=>~i%2).map(e=>(1+r)*(e=='|')).slice(2,-2))
.reduce((a,b)=>a+parseInt(b.join``,4),0)
```
## Usage
```
t=[' ','| | | | | | | | | | |',' | | |']
console.log(f(t)) // 4096
```
## Ungolfed version with explanation
```
// take list of strings, t, as input:
f = t => (
// create output variable o, discard middle row, turn other rows into lists:
( o = [ [...t[0]], [...t[2]] ] )
// if top-left position isn't a pipe, rotate 180 degrees.
// Alias [].reverse to save 3 bytes :D
[0][0] == '|' ? o : ( z = a=> a.reverse() )( o.map(z) )
).map( (a,r) =>
// remove even-numbered positions (non-encoding spaces):
a.filter( (_,i) => ~i%2 )
// convert non-pipes into zeros, and pipes into 1 or 2;
// top row becomes the base4 1-component, bottom row is 2:
.map( e => (1+r) * (e=='|') ).slice(2,-2)
// convert rows to base4 component strings, then decimal, then sum them:
).reduce( (a,b) => a + parseInt(b.join``,4),0)
```
] |
[Question]
[
Your objective: Given a string of brackets, output the minimum [Damerau-Levenshtein Distance](http://www.wikiwand.com/en/Damerau%E2%80%93Levenshtein_distance) required to turn the input string into a string where the brackets are balanced.
## Input
The input string will only contain brackets and no other characters. That is, it is a combination of any of the characters in `(){}[]<>`. You may take input as either a string or an array of characters. You may not make any other assumptions about the input string; it may be arbitrarily long (up to the maximum size supported by your language), it may be empty, the brackets may already be balanced, etc.
## Damerau-Levenshtein Distance
The Damerau-Levenshtein Distance between two strings is the minimum number of insertions, deletions, single-character substitutions, and transpositions (swapping) of two adjacent characters.
## Output
The output should be the minimum Damerau-Levenshtein Distance between the input string and a string in which the brackets are matched. Output should be a *number*, not the resulting balanced string.
A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
```
()
[]{}
```
Or if every sub-element inside of it is also matched.
```
[()()()()]
{<[]>}
(()())
```
Sub-elements can also be nested several layers deep.
```
[(){<><>[()]}<>()]
<[{((()))}]>
```
(Thanks to @DJMcMayhem for the definition)
## Test Cases
```
Input Possible Balanced Output
Empty Empty 0
[](){}<> [](){}<> 0
[(){}<> [(){}<>] 1
[(]) []() 1
[[[[[[[[ [][][][] 4
(](<>}[>(}>><(>(({}] ()(<>)[(<><>){}] 7
>]{])< []{()} 3
([)}}>[ (){}<> 4
{<((<<][{{}>[<) <>(<<[]>{}>[]) 5
{><({((})>}}}{(}} {<><({()})>}{}{()} 4
(](<)>}[>(}>>{]<<(]] (<()<><<>()>>[])<()> 9
}})( {}() 2
```
(Thanks to @WheatWizard for solving half of the test cases)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
Your submissions should be testable, meaning it should output a result for each test case in no more than an hour.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 1350 bytes
```
{({}(())(<>))<>({(()()()())<{({}[()])<>}{}>}{}<>({<({}[()])>{()(<{}>)}}{}{}<>))<>}<>([[]]){([[]({}()<>)]<>)<>{(({}())<<>(({})<(({}(<()>))<>({}))([(())()()]){<>({}())}{}{<>{}<>({}()){(((({}<(({}<>)<{({}()<([(){}])>)}{}>)<>(({}(<>))<{({}()<([(){}])>)}{}<>>)><>({}))(<(((({}({})[()])[()()]<>({}))<>[({})({}){}]({}<>))<>[(({}<>)<>({}<>)<>)])<>>)))[()](<()>)<<>(({})<({}{}()){({}()<({}<>)<>>)}{}<>(({})<<>(({}<>))>)<>(())>){({}[()()]<(<([({[{}]<(({})()<>[({})]<>)>{()(<{}>)}}{}<(({})<>[()({}<(({}<<>({}<>)<>(({})<>)>)<>[(){}])<>>)]<>)>{()(<{}>)}{}(){[()](<{}>)}<<>{({}<>)<>}{}>)]({}{}))>)<>{({}<>)<>}>)}{}{}<>{}{}{({}<>)<>}{}{}(<>)<>{({}<>)<>}{}{(<{}>)<>{({}<>)<>}<>({}<{}>){({}<>)<>}}{}((({}<({}({})({})<{{}<>{}(<>)}{}(((({}<({}<>)>)<>)))<>>)<>>)<><({}<({}<<>(()())>)>)>)<<>({}<{}{({}<>)([()()()]){((({}()()<>))[()]<(({()(<{}>)}{})<>({}<(({}<<>({}[()()](()[({})({})]({[()](<{}>)}{}<>{}<(({})<>)>)<>))>)<>)>)<>)<>({}<({}<({}<({}<>)>)>)>)>)}{}{}<>}<>{}{}{}{}{}{}{}{}>)>)>)}{}({}<({}<{({}<(({}){({}())}{}{}<(({}){({}())}{}{}<>)>)>)<>}<>{((({}(()()){([{}](<({}(<()>)<>){({}<({}<>)>(())<>)}{}>({})<<>{{}({}<>)<>}{}>))([{}()]{})}{})))<>(({}))<>{<>({}[()])}{}({}<<>{}{}{<>}>)<>{}}<>(({}<>){[()](<{}>)}{})(<>)>)>)<>(<({}<>)>)<>}<>{}({}<(({}){({}())}{}{}){({}<({}<>)>(())<>)}{}{}>)<>{{}({}<>)<>}{}>)<>>)}{}<>([[]{}])}{}(([]){<{}{}>([])}{}<>){({}[()]<{}>)}{}({}<>)
```
[Try it online!](https://tio.run/##dVRBbsQwCPyOOewPkD9i5bA9VKpa9dAr8ttThgHHu90qchwbMwwDztvP/eP79v51/zxPazZbE2naRbQ38wUfUdhGk8P3p00MHNDa7ebH1A0y3QQjEHBmjOMQwwR035TDh7pDrEX9jH@JxlqbZOzpPEawEQSw2PMl4N171tpx4BnuADaGcV@x6cTggHiE7/L6hPYuvcIqIbGI5EZQSKv2gRnDvVulOip@rzm0cltgMLErV2gU5EklXZIKz3AGOuljziqATUMCNpxDpC6tmEHex3LwAMyylLp4pjGipCRg8gQDnsZMYq2oYCKEwkfkRLKXJTyxwHt3YDEeQYzY@yZpYvfagy9LzhoFf2MQgNKeBzIxkUiKQ8sWsoawPasTwTJUG62aj/0QGrOeEHHTJst@KcsiOfpqFtdnk49sddee0vGVcNvoUk8KWppuz7KXkxWpbLT0/buTAgQocw1d/Nqix3XdTM06JCM0JQXv2bLG4KsrBAietlujO6rfUOQS6ijKmVG0Db7nugKP0sUPioTbVmM2wKv8/iGdzfZE@bqG/s/CbYh@GvgFhQs@qVn9E9cNid3zbMOvXR/n7f4L "Brain-Flak – Try It Online")
With constant-speed comparisons and pointer dereferencing, this algorithm is O(n3). Unfortunately, Brain-Flak has neither of these, so this program runs in O(n5) time instead. The longest test case takes about 15 minutes.
## Simplifying results
To see that my algorithm works, we need to show some results that reduce the search space considerably. These results rely on the fact that the target is an entire language instead of just one specific string.
* No insertions are needed. Instead, you can just remove the bracket that the inserted character would eventually match.
* You will never need to remove a bracket, then swap its two neighbors. To see this, assume wlog that the removed bracket is `(`, so we are transforming `a(c` to `ca` in two steps. By changing `c` and inserting a copy, we can reach `ca()` in two steps without a swap. (This insertion can then be removed by the above rule.)
* The same bracket will never need to be swapped twice. This is a standard fact about the Damerau-Levenshtein distance in general.
Another simplifying result that I didn't use, because accounting for them would cost bytes:
* If two brackets are swapped, and they don't match each other, the eventual match to each of those brackets will never be changed or swapped.
## The algorithm
When any string is reduced to a balanced string, one of the following will be true:
* The first bracket is deleted.
* The first bracket stays where it is and matches the bracket at some position `k` (possibly after changing one or both of them).
* The first bracket is swapped with the second, which in turn matches the bracket at position `k`.
In the second case, the bracket at position `k` may have swapped with one of its neighbors. In either of the latter two cases, the string between the (possibly newly) first bracket and the bracket that started in position `k` must be edited to a balanced string, as does the string consisting of everything after `k`.
This means that a dynamic programming approach may be used. Since a swapped bracket need not be swapped again, we only need to consider contiguous substrings, as well as subsequences formed by removing the second character and/or the penultimate character from such a substring. Hence, there are only O(n2) subsequences we need to look at. Each of those has O(n) possible ways to match (or delete) the first bracket, so the algorithm would be O(n3) under the conditions above.
## The data structure
The right stack includes the brackets from the original string, with two bytes per bracket. The first entry determines the entire bracket, and is chosen such that matched brackets have a difference of exactly 1. The second entry only determines whether it is an opening bracket or a closing bracket: this determines how many changes it takes for two brackets to match each other. No implicit zeros below this are ever made explicit, so that we can use `[]` to get the total length of this string.
Each substring under consideration is represented by two numbers in the range 0 to 2n: one for the beginning position, and one for the end. The interpretation is as follows:
* A substring starting at `2k` will start at position `k` (0-indexed), and the second character is not removed.
* A substring starting at `2k+1` will start at position `k`, and the second character is removed due to having been swapped left.
* A substring ending at `2k` will end just before position `k` (i.e., the range is left-inclusive and right-exclusive.)
* A substring ending at `2k-1` will end just before position `k`, and the penultimate character is removed due to having been swapped right.
Some ranges (`k` to `k+1`, `2k+1` to `2k+1`, `2k+1` to `2k+3`, and `2k+1` to `2k+5`) make no physical sense. Some of those show up as intermediate values anyway, because it's easier than adding additional checks to avoid them.
The left stack stores the number of edits needed to convert each substring into a balanced string. The edit distance for the interval `(x,y)` is stored at depth `x + y(y-1)/2`.
During the inner loop, entries are added above the left stack to denote which moves are possible. These entries are 5 bytes long. Counting from the top, the numbers are `d+1`, `y1`, `x1`, `y2`, `x2`, where the move costs `d` edit steps and divides the substring into `(x1,y1)` and `(x2,y2)`.
## The code
Description to come. For now, here's my working copy of the code. Some comments may be inconsistent with terminology.
```
# Determine bracket type for each byte of input
{({}(())(<>))<>({(()()()())<{({}[()])<>}{}>}{}<>({<({}[()])>{()(<{}>)}}{}{}<>))<>}
# For every possible interval length:
<>([[]]){
# Compute actual length
([[]({}()<>)]<>)
# Note: switching stacks in this loop costs only 2 bytes.
# For each starting position:
# Update/save position and length
<>{(({}())<<>(({})<
# Get endpoints
(({}(<()>))<>({}))
# If length more than 3:
([(())()()]){<>({}())}{}{
# Clean up length-3 left over from comparison
<>{}<>
# Initialize counter at 2
# This counter will be 1 in the loop if we're using a swap at the beginning, 0 otherwise
({}())
# For each counter value:
{
# Decrement counter and put on third stack
(((({}<
# Do mod 2 for end position
(({}<>)<{({}()<([(){}])>)}{}>)<>
# Do mod 2 for start position
(({}(<>))<{({}()<([(){}])>)}{}<>>)
# Subtract 1 from counter if swap already happened
><>({}))(<
# Compute start position of substrings to consider
(((({}({})[()])[()()]<>({}))
# Compute start position of matches to consider
<>[({})({}){}]({}<>))<>
# Compute end position of matches to consider
[(({}<>)<>({}<>)<>)]
# Push total distance of matches
)
# Push counter as base cost of moves
# Also push additional copy to deal with length 5 intervals starting with an even number
<>>)))[()](<()>)<
# With match distance on stack
<>(({})<
# Move to location in input data
({}{}()){({}()<({}<>)<>>)}{}
# Make copy of opening bracket to match
<>(({})<<>(({}<>))>)
# Mark as first comparison (swap allowed)
<>(())>)
# For each bracket to match with:
{({}[()()]<
(<([(
# If swap is allowed in this position:
{
# Subtract 1 from cost
[{}]
# Add 1 back if swap doesn't perfectly match
<(({})()<>[({})]<>)>{()(<{}>)}
}{}
# Shift copy of first bracket over, while computing differences
<(({})<>[()({}<(({}<<>({}<>)<>(({})<>)>)<>[(){}])<>>)]<>)>
# Add 1 if not perfectly matched
{()(<{}>)}{}
# Add 1 if neither bracket faces the other
# Keep 0 on stack to return here
(){[()](<{}>)}
# Return to start of brackets
<<>{({}<>)<>}{}>
# Add to base cost and place under base cost
)]({}{}))>)
# Return to spot in brackets
# Zero here means swap not allowed for next bracket
<>{({}<>)<>}
>)}
# Cleanup and move everything to right stack
{}{}<>{}{}{({}<>)<>}{}
# Remove one copy of base cost, and move list of costs to right stack
{}(<>)<>{({}<>)<>}{}
# If swap at end of substring, remove second-last match
{(<{}>)<>{({}<>)<>}<>({}<{}>){({}<>)<>}}{}
# Put end of substring on third stack
((({}<({}({})({})<
# If swap at beginning of substring, remove first match
{{}<>{}(<>)}{}
# Move start of substring to other stack for safekeeping
(((({}<({}<>)>)<>)))
# Create "deletion" record, excluding cost
<>>)<>>)<>
# Move data to left stack
<({}<({}<<>
# Add cost to deletion record
(()())
>)>)>)
# Put start position on third stack under end position
<<>({}<
# For each matching bracket cost:
{}{
# Move cost to left stack
({}<>)
# Make three configurations
([()()()]){
# Increment counter
((({}()()<>))[()]<
# Increment cost in first and third configurations
(({()(<{}>)}{})<>({}<
# Keep last position constant
(({}<
# Beginning of second interval: 1, 2, 1 past end of first
<>({}[()()]
# End of first interval: -3, -1, 1 plus current position
(()[({})({})]
# Move current position in first and third configurations
({[()](<{}>)}{}<>{}<
(({})<>)
>)
<>)
)
>)<>)
>)<>)
# Move data back to left stack
<>({}<({}<({}<({}<>)>)>)>)
>)
}{}
{}<>}
# Eliminate last entry
# NOTE: This could remove the deletion record if no possible matches. This is no loss (probably).
<>{}{}{}{}{}{}{}{}
# Restore loop variables
>)>)>)
}{}
# With current endpoints on third stack:
({}<({}<
# For all entries
{
# Compute locations and move to right stack
({}<(({}){({}())}{}{}<(({}){({}())}{}{}<>)>)>)<>
}
# For all entries (now on right stack):
<>{
# Cost of match
((({}
# Do twice:
(()()){([{}](
# Add cost of resulting substrings
<({}(<()>)<>){({}<({}<>)>(())<>)}{}>({})<<>{{}({}<>)<>}{}>
# Evaluate as sum of two runs
))([{}()]{})}{}
)))
# Find smaller of cost and current minimum
<>(({}))<>{<>({}[()])}{}
# Push new minimum in place of old minimum
({}<<>{}{}{<>}>)
<>{}
}
# Subtract 1 if nonzero
<>(({}<>){[()](<{}>)}{})(<>)
>)>)
<>(<({}<>)>)<>
# Otherwise (length 3 or less), use 1 from earlier as cost.
# Note that length 0-1 is impossible here.
}<>{}
# With cost on third stack:
({}<
# Find slot number to store cost of interval
(({}){({}())}{}{})
# Move to slot
{({}<({}<>)>(())<>)}{}
# Store new cost
{}>)
# Move other slots back where they should be
<>{{}({}<>)<>}{}
Restore length/position for next iteration
>)<>>)}
# Clear length/position from inner loop
{}<>([[]{}])
}{}
(([]){<{}{}>([])}{}<>){({}[()]<{}>)}{}({}<>)
```
[Answer]
# Retina, ~~254~~ ~~252~~ ~~264~~ ~~248~~ ~~240~~ ~~232~~ 267 bytes
*Thank you to @AnthonyPham, @officialaimm, and @MistahFiggins for pointing out bugs*
```
T`[]()`:;'"
+`'-*"|:-*;|{-*}|<-*>
-
+`'(\W+)"|:(\W+);|{(\W+)}|<(\W+)>
A$1$2$3$+B
+`'(\D+)"|:(\D+);|{(\D+)}|<(\D+)>
6$1$2$3$+9
(.*)(}{|"'|;:|><)
1$1
-
A6B9|6A9B
1
A6+B9+|A6+.B9+.|A+6.B+9
11
T`':{";}`<<<>
(.*)(<\W|\W>)
1$1
+`<(.*A.*B.*)?\W|\W(.*A.*B.*)?>
1$1$2
\W|6B|1
```
[Try it Online!](https://tio.run/nexus/retina#dVTNitswEL7rKZbgkpFNTJTdpiQZptik9AUWclAEhtJjoYe9FGmePR3JdpK1Zekw0jff/Hg04y/ws7u9d9aB7o6n9UpV3XpTrsJxU56C35QccFOS2kQcrpdKiypJ0SYphCRJNYUpdsVrUbU9@TyQzwP5PJDPkbwfyQcFdamBfVitw@kYCLUyhZGIqtm3h7BvDq0ycq7aQxVE1CLr0FT7uhVjY9R7tz761Yk7RKTeG14v4Xqh3lPVoYBNXbai@p40T3eKnGKnBN@3wdxuKtbCs7iyd@m0ssNS4ACJLQETIRCAZ6fIeadRgdXMZJVHAERnvZebfJAXpgdgTczsgTl50aMb7xDBOcWsQVkveVvvrGPFkoGckZDSHb11xMpbceUUClVAkKhyExB5lCQHkeIqErx9aCIgB7IDwn0wFv/Wusd2dmHffvz5@/HvZb6W8O29olPNEr59Oo@vMHM74G6Km8/GTmdSSpFz@GfjYc2N@z3F37K9ETUgLUlayi8PqQcsrm9D4@QS9KB5jr@OPTbTLJRJspp0413jGUCjdFQ0fCrH13m/jhaYFDoqPD8yfMv2c8pKSFISbWOM2Mnc42abuj33BpJW9m12aTSyr/lU0qlFnJtsebO4SSOX85XPqY8xzufkO2weN8MYz31FnCmXVT/xL7khWPjy/ueQiRGLRTmLer5@f/yql9d/)
Non-brute force solution! It works for all test cases, and even found an error in one.
*-2 bytes thanks to @MartinEnder (`${4}` to `$+`)*
*+12 bytes to account for additional swapping cases*
*-16 bytes by making better use of character classes*
*-8 bytes by removing an unnecessary restriction on swapping. This also fixed a bug :)*
*-10 bytes by combining the swapping logic into a single regex*
*+2 bytes to account for consecutive swaps*
*+many for various bug fixes\*\**
**Explanation:**
`T`[]()`:;'"` is used to replace special bracket types for convenience.
First, we recursively replace all matched brackets with `-`, `AB` or `69` depending on whether they are adjacent or not.
Then, useful "swapping " is performed by removing newly matched brackets and adding a `1` to the beginning of the string. We also replace `-` with the empty string, as it was just being used for the above swapping.
Next, we try "replacements" by removing pairs of unmatched brackets that don't overlap already-matched brackets and adding a `1` to the string.
Finally, `\W|6B|1` counts any remaining single brackets plus the number of `1`s.
*\*\*I'm currently working on a shorter version that uses Retina's line splitting features, though I ran into a considerable problem so it might take quite awhile.*
[Answer]
# [Haskell](https://www.haskell.org/), 797 bytes
```
import Data.Array;import Data.Function;import Data.List;
e=length;f=fst;o=map;s=listArray;u=minimum;b p=let{m=e p;x=s(1,m)p;
v=s(1,m)(listArray('(','}')[0,0..]:[v!i//[(x!i,i)]|i<-[1..m-1]]);
d q=let{n=e q;y=s(1,n)q;t(a,b)=listArray((a,b),(m,n));
c=t(1,1)[sum[1|x!i/=y!j]|i<-[1..m],j<-[1..n]];
d=t(-1,-1)[if i<0||j<0then m+n else
if i*j<1then(i+j)else u[1+d!(i-1,j),1+d!(i,j-1),c!(i,j)+d!(i-1,j-1),
let{k=v!i!(y!j)-1;l=w!(i,j-1)-1}in-3+i+j-k-l+d!(k,l)]|i<-[-1..m],j<-[-1..n]];
w=t(1,0)[if j>0&&c!(i,j)>0then w!(i,j-1)else j|i<-[1..m],j<-[0..n]]}in d!(m,n);
a=s(0,div m 2)([(m,"")]:[(concat.take 2.groupBy(on(==)f).sort.o(\q->(d q,q)))(
[b:c++[d]|[b,d]<-words"() <> [] {}",(_,c)<-a!(l-1)]++
concat[[b++d,d++b]|k<-[1..div l 2],(_,b)<-a!k,(_,d)<-a!(l-k)])|l<-[1..div m 2]]);
}in u(o(f.head)(elems a))
```
[Try it online!](https://tio.run/nexus/haskell#XVPbbptAEH3nK9aoSmbKQiB9CwtSq6pSpfYLtquKm5PF3GxwUgvvt6cD2LETnmbPzDlzZnd41XXX7gb2PRkS7@tulxzCa@THvskG3TbvwF@6H0KriKqieRyewnW0pnMb1UkX9lFFyUVnH9W60fW@DlPWUfEw1lHBuvBf1EPAa@xC6/kUwhsLbuGW35pblD73PU89yOeVvruT8G@luUZ11MKVgefVbqAUhlbOtrN0Q9Lb8DDrNbgNB0h4ihc3MJ851JQlWhYNVBig7Pe1DI4kfhcdVuVFXvFyiRqlqAuVuwF3iaDXTAv/eCyFPzwVDaudhhVVXzBrynwuRTDBoJ0SZ3gvAydfgSZ6iXyJeUlKPJsjfMtOmDXNsolo5hWQH3SDsIpezhQ3MLpxvzgk7m7camJueHW6FPdi2z37fpnH9GfXZezf3Jx6xov3N@HZaflheH8WoY6M@kz3FloJ3a/Pc/3ManaPIAm2baRHgqxtsmTwhmRTsHvvcdfuu28HaBuIIlyj19PyeC382box0JPxLSKCJdOHzHFkro4y5bkS7ku7y3sbkImYScVGY3P4yzMUbrKCiowqx7GWVlKmjpPz3HFSddwsxidjFbtXEymdSZspzM/8DSo8VpdaGmJeomnGPbSw9p6KJEcoqqLuWYL4Wie6mfaLDboufg5Rt9PNwKiclv03LKCX4qdpvmXerK27ZFfg8nOgtNjps21uSwU4GhHb/ALLM0SRwuuMMQjX51iNCsU77ukjMkg0Jp6iMRYwAhiMjTEjGHPNGAWAEEqOIxWLd@1AgYiNjMHEpBADjEZ9zOO5YFRCgFK2ev0P "Haskell – TIO Nexus")
] |
[Question]
[
Given a polynomial \$p(x)\$ with integral coefficients and a constant term of \$p(0) = \pm 1\$, and a non-negative integer \$N\$, return the \$N\$-th coefficient of the power series (sometimes called "Taylor series") of \$f(x) = \frac{1}{p(x)}\$ developed at \$x\_0 = 0\$, i.e., the coefficient of the monomial of degree \$N\$.
The given conditions ensure that the power series exist and that the its coefficients are integers.
### Details
As always the polynomial can be accepted in any convenient format, e.g. a list of coefficients, for instance \$p(x) = x^3-2x+5\$ could be represented as `[1,0,-2,5]`.
The power series of a function \$f(x)\$ developed at \$0\$ is given by
$$f(x) = \sum\_{k=0}^\infty{\frac{f^{(n)}(0)}{n!}x^n}$$
and the \$N\$-th coefficient (the coefficient of \$x^N\$) is given by
$$\frac{f^{(N)}}{N!}$$
where \$f^{(n)}\$ denotes the \$n\$-th derivative of \$f\$
### Examples
* The polynomial \$p(x) = 1-x\$ results in the geometric series \$f(x) = 1 + x + x^2 + ...\$ so the output should be \$1\$ for all \$N\$.
* \$p(x) = (1-x)^2 = x^2 - 2x + 1\$ results in the derivative of the geometric series \$f(x) = 1 + 2x + 3x^2 + 4x^3 + ...\$, so the output for \$N\$ is \$N+1\$.
* \$p(x) = 1 - x - x^2\$ results in the generating function of the Fibonacci sequence \$f(x) = 1 + x + 2x^2 + 3x^3 + 5x^4 + 8x^5 + 13x^6 + ...\$
* \$p(x) = 1 - x^2\$ results in the generating function of \$1,0,1,0,...\$ i.e. \$f(x) = 1 + x^2 + x^4 + x^6 + ...\$
* \$p(x) = (1 - x)^3 = 1 -3x + 3x^2 - x^3\$ results in the generating function of the triangular numbers \$f(x) = 1 + 3x + 6x^6 + 10x^3 + 15x^4 + 21x^5 + ...\$ that means the \$N\$-th coefficient is the binomial coefficient \$\binom{N+2}{N}\$
* \$p(x) = (x - 3)^2 + (x - 2)^3 = 1 + 6x - 5x^2 + x^3\$ results in \$f(x) = 1 - 6x + 41x^2 - 277x^3 + 1873x4 - 12664x^5 + 85626x^6 - 57849x^7 + \dots\$
[Answer]
## Mathematica, 24 23 bytes
*Saved 1 byte thanks to Greg Martin*
```
D[1/#2,{x,#}]/#!/.x->0&
```
Pure function with two arguments `#` and `#2`. Assumes the polynomial `#2` satisfies `PolynomialQ[#2,x]`. Of course there's a built-in for this:
```
SeriesCoefficient[1/#2,{x,0,#}]&
```
[Answer]
# Matlab, ~~81 79~~ 75 bytes
Unlike the previous two answers this doesn't make use of symbolic calculations. The idea is that you can iteratively calculate the coefficients:
```
function C=f(p,N);s=p(end);for k=1:N;q=conv(p,s);s=[-q(end-k),s];end;C=s(1)
```
[Try it online!](https://tio.run/nexus/octave#PY0xD4IwEIV3fsUtJDSBoYuDTScnF1jcDAOWa9IAd8Vrjf56rIsv3/CG7@XVmTw/U6Yp4fqB23WAmVGAOIEgbpAYJMdYHPCZXApM4MOKUvX2ZOCfKtp7p9uCHg3UPjyYJucC4Hva4oqH2NggzcqUP1isPvdmt47p1cRWlJEy339Ct6hWRlOauVhptDqOLw "Octave – TIO Nexus")
### Explanation
```
function C=f(p,N);
s=p(end); % get the first (constant coefficient)
for k=1:N;
q=conv(p,s); % multiply the known coefficients with the polynomial
s=[-q(end-k),s]; % determine the new coefficient to make the the product get "closer"
end;
C=s(1) % output the N-th coefficient
```
[Answer]
# [GeoGebra](https://www.geogebra.org/), 28 bytes
```
Derivative[1/A1,B1]/B1!
f(0)
```
Input is taken from the spreadsheet cells A1 and B1 of a polynomial and an integer respectively, and each line is entered separately into the input bar. Output is via assignment to the variable `a`.
Here is a gif showing the execution:
[](https://i.stack.imgur.com/eOwv7.gif)
Using builtins is much longer, at 48 bytes:
```
First[Coefficients[TaylorPolynomial[1/A1,0,B1]]]
```
[Answer]
## Haskell, 44 bytes
```
p%n=(0^n-sum[p!!i*p%(n-i)|i<-[1..n]])/head p
```
A direct computation without algebraic built-ins. Takes input as an infinite list of power series coefficients, like `p = [1,-2,3,0,0,0,0...]` (i.e. `p = [1,-2,3] ++ repeat 0`) for `1-2*x+x^2`. Call it like `p%3`, which gives `-4.0`.
The idea is if **p** is a polynomial and **q=1/p** is it inverse, then we can express the equality **p·q=1** term-by-term. The coefficient of **xn** in **p·q** is given by the convolution of the coefficients in **p** and **q**:
**p0· qn + p1· qn-1 + ... + pn· q0**
For **p·q=1** to hold, the above must equal zero for all **n>0**. For here, we can express **qn** recursively in terms of **q0, ..., qn-1** and the coefficients of **p**.
**qn = - 1/p0 · (p1· qn-1 + ... + pn· q0)**
This is exactly what's calculated in the expression `sum[p!!i*p%(n-i)|i<-[1..n]]/head p`, with `head p` the leading coefficient **p0**. The initial coefficient **q0 = 1/p0** is handled arithmetically in the same expression using `0^n` as an indicator for `n==0`.
[Answer]
# J, 12 bytes
```
1 :'(1%u)t.'
```
Uses the adverb `t.` which takes a polynomial `p` in the form of a verb on the LHS and a nonnegative integer `k` on the RHS and computes the `k`th coefficient of the Taylor series of `p` at `x = 0`. In order to get the power series, the reciprocal of `p` is taken before applying it.
[Try it online!](https://tio.run/nexus/j#@5@mYGulYKhgpa5hqFqqWaKnzpWanJGvoKunkKaQqadgaADha@jqaenqaWII6mpZoQsaYhHT1YszxhDU0FUzjjOy0tTWVTNClv7/HwA "J – TIO Nexus")
[Answer]
# Maple, ~~58~~ 26 bytes
This is an unnamed function that accepts a polynomial in `x` and an integer `N`.
EDIT: I just noticed that there is a builtin:
```
(p,N)->coeftayl(1/p,x=0,N)
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
0)i:"1GY+@_)_8Mh]1)
```
Translation of [@flawr's great Matlab answer](https://codegolf.stackexchange.com/a/105286/36398).
[Try it online!](https://tio.run/nexus/matl#@2@gmWmlZOgeqe0Qrxlv4ZsRa6j5/3@0rqEOEBnGcpkBAA "MATL – TIO Nexus")
### How it works
```
0) % Implicitly input vector of polynomial coefficients and get last entry
i % Input N
:" % For k in [1 2 ... N]
1G % Push vector of polynomial coefficients
Y+ % Convolution, full size
@ % Push k
_ % Negate
) % Index. This produces the end-k coefficient
_ % Negate
8M % Push first input of the latest convolution
h % Concatenate horizontally
] % End
1) % Get first entry. Implicitly display
```
[Answer]
## JavaScript (ES6), 57 bytes
```
(a,n)=>a.reduce((s,p,i)=>!i|i>n?s:s-p*f(a,n-i),!n)/a[0]
```
Port of @xnor's Haskell answer. I originally tried an iterative version but it turned out to be 98 bytes, however it will be much faster for large N, as I'm effectively memoising the recursive calls:
```
(a,n)=>[...Array(n+1)].fill(0).map((_,i,r)=>r[i]=r.reduce((s,p,j)=>s-p*(a[i-j]||0),!i)/a[0]).pop()
```
`n+1` terms are required, which are saved in the array `r`. It is initially zeros which allows reducing over the entire array `r` at once, as the zeros will not affect the result. The last calculated coefficient is the final result.
[Answer]
# PARI/GP, ~~31~~ 27 bytes
```
f->n->Pol(Ser(1/f,,n+1))\x^n
```
[Answer]
# [Maxima](http://maxima.sourceforge.net/), ~~31~~ 25 bytes
Saved 6 bytes thanks to the comment of [@alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)
```
f(e,R):=taylor(1/e,x,0,R)
```
[Try it online!](https://tio.run/##Xcm7CoAgFADQ3a@4o8YVey5JPxHNwaUUgqJIB/16sy1azzkobAelZLnBUfSDp7ifN6@UwYBlpqSZKmAyzsNCzjgoFFs3d@0UueWVDAidEBo@@KqYa4T2F9lleKPJkR4)
] |
[Question]
[
## Challenge
Given a string as input, golf down the [Fourier program](http://esolangs.org/wiki/Fourier) which outputs that string.
In Fourier there is no easy way to output a string: you have to go through each character code and output that as a character.
## Fourier
The language is based upon an accumulator, a global variable which is initialised to 0 at the start of the program. This is used by almost every operator in the language. Only some do not change the value of the accumulator.
### Character out
```
a
```
Takes the value of the accumulator as the ASCII code and outputs the character. Does not change the value of the accumulator.
If the accumulator is greater than 255, the program will return an error. Likewise if the accumulator is less than 0.
### Number out
```
o
```
Outputs the value of the accumulator. Does not change the value of the accumulator.
### Increase
```
^
```
Increase the accumulator by one.
### Decrease
```
v
```
Decrease the accumulator by one.
### Add
```
+x
```
Sets the accumulator to the value of the accumulator plus the value of x.
### Subtract
```
-x
```
Sets the accumulator to the value of the accumulator minus the value of x.
### Multiply
```
*x
```
Sets the accumulator to the value of the accumulator multiplied by the value of x.
### Divide
```
/x
```
Sets the accumulator to the value of the accumulator divided by the value of x. (Note that this is integer division, so `1/6` results in `0`)
### Number
```
n
```
Set the accumulator to the integer n.
### Note
Here, `x` and `n` can be any integer from `0` to `2^32-1` inclusive.
## More information
You must only use the operators described above. Therefore your outputted Fourier program is invalid if it uses any of the following (note that the following operators are allowed for the bounty):
* Repeat loops
* If statements
* Variables
* Random
* Modulo
* User Input
* Greater/Less than operators
* Equality operators
* Clear screen
* Time delay
* Date functions
Your program can either be a full program or a function, taking in input via STDIN, a file or function arguments. You may also take input straight from the Internet.
Note that if there is a `vv` in your code, you should replace it with `-2`. The same goes for `^^`, replacing it with `+2`.
## Examples
If the input is `7n`, then the expected program is:
```
55a110a
```
But you can save one byte with
```
55a*2a
```
Another way is
```
7o110a
```
Using number out.
---
Similarly if the input is `Hello`, then the expected program is:
```
72a101a108a108a111a
```
You can golf it down by 3 bytes (because outputting doesn't change the accumulator):
```
72a101a108aa111a
```
But wait, we can use the addition operator, saving 2 bytes:
```
72a101a+7aa+3a
```
## Formatting
Because I'll be using Martin Büttner's Stack Snippet leaderboard, please could you format the title like so:
```
# <Language name>, <length of total output> bytes
```
Then, you can put anything you wish below the title.
## Winning
You should post the length of Fourier programs (produced by your code) to output [this text file](https://ia802707.us.archive.org/16/items/hamlet01524gut/2ws2610.txt) and [this text file](http://janelwashere.com/files/bible_daily.txt). Your score is the combined length of both Fourier programs in bytes (non-ASCII characters aren't used in Fourier so it doesn't really make a difference).
The person with the lowest scores wins. If there is a tie, the shortest program in bytes wins.
## Bounty
This 500 rep bounty is for a *new* answer which golfs the strings using any of Fourier's functions. That includes variables, loops and if statements etc. This new answer will not be accepted.
## Leaderboard
Refer to formatting section above:
```
var QUESTION_ID=55384;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div> <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>
```
[Answer]
# ><>, 14310665 bytes
## 601398 for hamlet + 13709267 for genesis
This is still a work in progress and takes a lot of time to complete.
```
v
0
>i:0(?;:r-:?!v:0a-)?v v
>~:v ~ >:a(?v>
:1+?v~'v'o v o'^'~\:0)?v
>n vno'+' ^?=1:<
^ o'a'<
```
[Answer]
# Python, 14307118 bytes
### 601216 for Hamlet + 13705902 for Genesis = 14307118
There are definitely some senarios under which this solution is not optimal, such as for `1111`, where it will output `1111o` as opposed to `11oo`. However, I think it is nearly optimal.
Edit: Saved a few bytes by improving `0o0o` to `0oo`.
The name of the file containing the input is received on STDIN, output to STDOUT.
Results verified with the official interpreter.
```
def opt_str(char, acc):
opts = []
char_num = ord(char)
opts.append(str(char_num))
if 0 < char_num - acc < 10:
opts.append('+' + str(char_num - acc))
if 0 < acc - char_num < 10:
opts.append('-' + str(acc - char_num))
if char_num - acc == 1:
opts.append('^')
if acc - char_num == 1:
opts.append('v')
if acc == char_num:
opts.append('')
if acc and char_num % acc == 0:
opts.append('*' + str(char_num//acc))
try:
if acc // (acc // char_num) == char_num:
opts.append('/' + str(acc // char_num))
except:
pass
return [opt for opt in opts if len(opt) == len(min(opts, key=len))]
acc = 0
result = []
pos = 0
with open(input(), "r") as myfile:
in_str = myfile.read()
while pos < len(in_str):
i = in_str[pos]
pos += 1
if i in '0123456789':
if i != '0':
while pos < len(in_str) and in_str[pos] in '0123456789':
i += in_str[pos]
pos += 1
if i == str(acc):
result.append('o')
else:
result.append(i + 'o')
acc = int(i)
else:
opts = opt_str(i, acc)
result.append(opts[0] + 'a')
acc = ord(i)
print(''.join(result))
```
[Answer]
# Java, 14307140 bytes
### Hamlet - 601,218
### Genesis - 13,705,922
The idea here is to do all the work upfront, by making a character->character map. Then you can just loop through and grab the shortest strings.
A bit of an exception has to be made for numerals, so I check for them in the main loop. It's still fast, though, and handles the larger test case in a few seconds. I *may* be able to tweak this section for a couple more bytes, but I'm fairly sure it's close to optimum.
Input is a filename as argument. Output is written to a file `inputFilename_out.4`, and the character count is sent to STDOUT.
This is 1737 bytes for the tiebreaker, completely ungolfed. I can golf it a lot if needed, but it's still going to be a bit big.
```
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.text.NumberFormat;
public class FourierMapper {
public static void main(String[] args) throws Exception {
FourierMapper fm = new FourierMapper();
fm.createMap();
String filename = args.length>0? args[0]:"bible.txt";
String out = fm.fourierize(filename);
System.out.println(out.length());
Files.write(Paths.get(filename + "_out.4"), out.getBytes(), new OpenOption[]{});
}
String[][] map = new String[9999][256];
void createMap(){
for(int from=0;from<9999;from++){
for(int to=0;to<256;to++){
if(to<10||from<1){
map[from][to] = ""+to;
} else if(to==from){
map[from][to] = "";
} else if(to-from==1){
map[from][to] = "^";
} else if(to-from==-1){
map[from][to] = "v";
} else if(to>99){
if(to%from<1){
map[from][to] = "*"+(to/from);
} else if(to>from&&to-from<10){
map[from][to] = "+"+(to-from);
} else if(from>to&&from-to<10){
map[from][to] = "-"+(from-to);
} else {
map[from][to] = ""+to;
}
} else {
map[from][to] = ""+to;
}
}
}
}
String fourierize(String filename) throws Exception{
StringBuilder out = new StringBuilder();
byte[] in = Files.readAllBytes(Paths.get(filename));
String whole = new String(in);
out.append(in[0] + "a");
int number = -1;
for(int i=1;i<in.length;){
if(in[i]<58&&in[i]>47){
number = in[i]==48?0:((Number)NumberFormat.getInstance().parse(whole.substring(i,i+4))).intValue();
out.append(""+number+"o");
i += (""+number).length();
} else {
if(number<0)
out.append(map[in[i-1]][in[i]]+"a");
else
out.append(map[number][in[i]]+"a");
number = -1;
i++;
}
}
return out.toString();
}
}
```
[Answer]
# PHP, 14307118 bytes
## 601,216 (Hamlet) + 13,705,902 (Bible)
```
function f($file) {
$text = file_get_contents($file);
$a = 0;
for ($i = 0; $i < strlen($text); $i++) {
$chr = $text[$i];
if (ctype_digit($chr)) {
while ($chr && isset($text[$i + 1]) && ctype_digit($text[$i + 1])) {
$chr .= $text[$i + 1];
$i++;
}
if ($a == (int)$chr) {
print "o";
}
else {
$a = (int)$chr;
print $chr . "o";
}
continue;
}
$ord = ord($chr);
$mapping = array(
'' => $a,
'^' => $a + 1,
'v' => $a - 1
);
for ($j = 2; $j <= 9; $j++) {
$mapping["+$j"] = $a + $j;
$mapping["-$j"] = $a - $j;
$mapping["*$j"] = $a * $j;
$mapping["/$j"] = $a / $j;
}
foreach ($mapping as $op => $value) {
if ($value === $ord) {
$a = $value;
print $op . "a";
continue 2;
}
else if ($value . '' === $chr) {
$a = $value;
print $op . "o";
continue 2;
}
}
$a = $ord;
print $ord . "a";
}
}
```
[Fourier output for Hamlet](https://paste.ee/p/b0H9k)
It works as follows:
1. Iterates over each character in the input;
2. If there is a sequence of non 0 leading digits it will set the accumulator to that number and output it as number. It also checks for similar digits;
3. Otherwise, checks if there is shorter way of outputting the current character (rather than the ASCII code + "a" symbol = 4 characters) by performing a basic operation (+-\*/) on the accumulator with a number between 2 and 9; obviously, it also tries to compare/increment/decrement;
] |
[Question]
[
You all know the Newton method to approximate the roots of a function, don't you? My goal in this task is to introduce you into an interesting aspect of this algorithm.
Newton's algorithm converges only for certain, but most of all complex input values. If you picture the convergence of the method for all input values over the complex plane, you usually get a beautiful fractal like this:
[ *Image from Wikimedia commons*](https://en.wikipedia.org/wiki/File:Julia-set_N_z3-1.png)
## Specifications
The goal of this task is, to generate such fractals. This means, that you get a polynomial as the input and have to print out the corresponding fractal as an image in a format of your choice as the output.
### Input
The input is a whitespace-separated list of complex numbers. They are written down in the style `<Real part><iImaginary part>`, like this number: `5.32i3.05`. You may assume, that the input number has no more than 4 decimal places and is smaller than 1000. The first of them must not be zero. For example, this could be an input to your program:
```
1 -2i7.5 23.0004i-3.8 i12 0 5.1233i0.1
```
The numbers are interpreted as the coefficients of a polynomial, beginning with the highest power. Throughout the rest of this specification, the input polynomial is called **P**. The above input is equal to this polynomial:
```
f(x) = x5 + (-2 + 7.5*i*)x4 + (23.0004 - 3.8*i*)x3 + 12*i*x2 + 5.1233 + 0.1*i*
```
The input may come to you either from stdin, from an argument passed to the program or from a prompt displayed to your program. You may assume, that the input does not contain any leading or trailing whitespace characters.
### Rendering
You have to render the fractal in the following way:
* Choose as many colors as roots of **P** plus an extra color for divergence
* For each number in the visible plane, determine whether the method converges and if yes to which root. Color the point according to the result.
* Do not print rulers or other fancy things
* Print a black point at the points, that are the polynomials roots for orientation. You may print up to four pixels around each root.
* Find a way to choose the visible plane in a way, that all roots are distinguishable and spread widely across it, if possible. Although a perfect placement of the output frame is not required, I reserve the right to refuse to accept an answer that chooses the frame in an unacceptable way, eg. always at the same coordinates, all roots are in one point, etc.
* The output image should have a size of 1024\*1024 pixels.
* Rendering time is 10 minutes maximum
* Using single precision floating-point values is enough
### Output
The output should be a raster graphics image in a file format of your choice, readable by standard software for a brand X operating system. If you want to use a rare format, consider adding a link to a website where one can download a viewer for it.
Output the file to stdout. If your language does not support putting something to stdout or if you find this option less convenient, find another way. In any way, it must be possible to save the generated image.
### Restrictions
* No image processing libraries
* No fractal generating libraries
* The shortest code wins
### Extensions
If you like this task, you could try to color the points according to the speed of convergence or some other criteria. I'd like to see some interesting results.
[Answer]
## Python, 827 777 chars
```
import re,random
N=1024
M=N*N
R=range
P=map(lambda x:eval(re.sub('i','+',x)+'j'if 'i'in x else x),raw_input().split())[::-1]
Q=[i*P[i]for i in R(len(P))][1:]
E=lambda p,x:sum(x**k*p[k]for k in R(len(p)))
def Z(x):
for j in R(99):
f=E(P,x);g=E(Q,x)
if abs(f)<1e-9:return x,1
if abs(x)>1e5or g==0:break
x-=f/g
return x,0
T=[]
a=9e9
b=-a
for i in R(999):
x,f=Z((random.randrange(-9999,9999)+1j*random.randrange(-9999,9999))/99)
if f:a=min(a,x.real,x.imag);b=max(b,x.real,x.imag);T+=[x]
s=b-a
a,b=a-s/2,b+s/2
s=b-a
C=[[255]*3]*M
H=lambda x,k:int(x.real*k)+87*int(x.imag*k)&255
for i in R(M):
x,f=Z(a+i%N*s/N+(a+i/N*s/N)*1j)
if f:C[i]=H(x,99),H(x,57),H(x,76)
for r in T:C[N*int(N*(r.imag-a)/s)+int(N*(r.real-a)/s)]=0,0,0
print'P3',N,N,255
for c in C:print'%d %d %d'%c
```
Finds display bounds (and roots) by finding convergence points for a bunch of random samples. It then draws the graph by computing the convergence points for each starting point and using a hash function to get randomish colors for each convergence point. Look very closely and you can see the roots marked.
Here's the result for the example polynomial.

[Answer]
## Java, 1093 1058 1099 1077 chars
```
public class F{double r,i,a,b;F(double R,double I){r=R;i=I;}F a(F c){return
new F(r+c.r,i+c.i);}F m(F c){return new F(r*c.r-i*c.i,r*c.i+i*c.r);}F
r(){a=r*r+i*i;return new F(-r/a,i/a);}double l(F c){a=r-c.r;b=i-c.i;return
Math.sqrt(a*a+b*b);}public static void main(String[]a){int
n=a.length,i=0,j,x,K=1024,r[]=new int[n];String o="P3\n"+K+" "+K+"\n255 ",s[];F z=new
F(0,0),P[]=new F[n],R[]=new F[n],c,d,e,p,q;for(;i<n;)P[i]=new
F((s=a[i++].split("i"))[0].isEmpty()?0:Float.parseFloat(s[0]),s.length==1?0:Float.parseFloat(s[1]));double
B=Math.pow(P[n-1].m(P[0].r()).l(z)/2,1./n),b,S;for(i=1;i<n;){b=Math.pow(P[i].m(P[i-1].r()).l(z),1./i++);B=b>B?b:B;}S=6*B/K;for(x=0;x<K*K;){e=d=c=new
F(x%K*S-3*B,x++/K*S-3*B);for(j=51;j-->1;){p=P[0];q=p.m(new
F(n-1,0));for(i=1;i<n;){if(i<n-1)q=q.m(c).a(P[i].m(new
F(n-1-i,0)));p=p.m(c).a(P[i++]);}c=c.a(d=q.r().m(p));if(d.l(z)<S/2)break;}i=j>0?0:n;for(;i<n;i++){if(R[i]==null)R[i]=c;if(R[i].l(c)<S)break;}i=java.awt.Color.HSBtoRGB(i*1f/n,j<1||e.l(c)<S&&r[i]++<1?0:1,j*.02f);for(j=0;j++<3;){o+=(i&255)+" ";i>>=8;}System.out.println(o);o="";}}}
```
Input is command-line arguments - e.g. run `java F 1 0 0 -1`. Output is to stdout in PPM format (ASCII pixmap).
The scale is chosen using the Fujiwara bound on the absolute value of the complex roots of a polynomial; I then multiply that bound by 1.5. I do adjust brightness by convergence rate, so the roots will be in the brightest patches. Therefore it's logical to use white rather than black to mark the approximate locations of the roots (which is costing me 41 chars for something which can't even be done "correctly". If I label all points which converge to within 0.5 pixels of themselves then some roots come out unlabelled; if I label all points which converge to within 0.6 pixels of themselves then some roots come out labelled over more than one pixel; so for each root I label the first point encountered to converge to within 1 pixel of itself).
Image for the example polynomial (converted to png with the GIMP):

[Answer]
# Python, 339 char/bytes
```
import numpy as n;import matplotlib.pyplot as p;from colorsys import hls_to_rgb as h
a,d=1,2001j;x,y=n.ogrid[-a:a:d,-a:a:d];z=x+1j*y
for i in range(3): z-=(z**3-1)/3/z**2
z[n.isnan(z)]=0
z=n.array(n.vectorize(h)((n.angle(z)+n.pi)/3/n.pi,1.-1/(1.+n.abs(z)**.1),.8)).swapaxes(0,2)
p.figure();p.imshow(z,interpolation='nearest');p.axis('off')
```
### The plot below is for Newton Fractal of z^3 - 1 function.
[](https://i.stack.imgur.com/Rb4kW.png)
Edit: Thanks to @Khuldraeseth na'Barya now the code is even shorter. Removed the irrelevant code and image.
] |
[Question]
[
The problem statement here is pretty simple, take two real numbers on the range [0,1) as input and output their sum, with probability 1.
The catch here is that there are a lot of real numbers. There are in fact so many real numbers that it is impossible to fit all of them into any finite data type. As such, any way to input real numbers has to be potentially infinite, and any algorithm that handles arbitrary real numbers cannot consume all of the input.
For this challenge you will input (and output) real numbers as lazy sequence (e.g. stream, generator, lazy list, function) of bits, representing their binary expansion. You can assume that the input will be normalized and will not end in an infinite repetition of `1`.
Even with this special input format it isn't possible to add any two real numbers. Any potential algorithm can be tricked into an infinite loop.
So instead we are going to settle for *almost* working. To "work" on a pair of inputs your program needs to be able to output any bit of the output in finite time. For example, if you output a generator I should be able to read to the 5th bit without the program getting stuck in a loop. Your answer needs to work with probability 1, meaning that the measure of the set of inputs which your program does work needs to have measure 1. The behavior for which the program doesn't work is undefined it can loop forever give an incorrect answer etc. so long as these cases themselves have measure zero.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the goal is to minimize the size of your source code as measured in bytes.
## Examples
Here are some examples of rational numbers being added. You do not need to support any of these specific numbers.
```
1/3 = 0.01010101010101010...
+
1/5 = 0.00110011001100110...
=
8/15 = 0.10001000100010001...
```
```
3/8 = 0.011000000000000000...
+
3/16 = 0.001100000000000000...
=
9/16 = 0.100100000000000000...
```
```
17/95 = 0.001011011100111101111110101001110001001011011100111101111110101...
+
3/13 = 0.001110110001001110110001001110110001001110110001001110110001001...
=
506/1235 = 0.011010001110001100101111111000100010011010001110001100101111111...
```
[Answer]
# [Python](https://www.python.org), 75 bytes
```
def f(*I,n=0):
for a,b in zip(*I):yield from[a,*n*[1^a]][:-(n:=1+n*(a^b))]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fVBBasMwELznFXtcqZtiQw_FkAeUPkEoRXYksmCvhKJC3a_0kkv7lP6hv6mcONBT97Yzw-zMfnyluRyjnM-fryVsH3-eDz5AQP1EsmtUt4EQMzjqgQXeOVVCdTP78QAhx8k40qJNu3fWmm6L0u3aO9Ho9r1SdrX8XpTAxecS43gCnlLMBfTmj7XBySUU_1ZomIfRX9bsk3eFsKFW1aF_JatIEQ5Hx4KmApauPDYVv8D3S5aXJYvrq8VK3y7Y2jdlloKaTyMPHgPWgIoeqsG1ze1Rvw)
Takes two iterables and returns one.
## How?
Count bits that differ between the inputs without outputting anything until an equal bit is encountered. Output this bit followed by counter times its complement. Reset counter and start over.
[Answer]
# [Rust](https://www.rust-lang.org), ~~222~~ 199 bytes
```
|a:Box<dyn Iterator<Item=usize>>,b:Box<dyn Iterator<Item=usize>>|a.zip(b).scan(0,|z,(e,f)|Some(if e==f{let q=*z;*z=0;(e..=e).chain((1-e..2-e).cycle().take(q)).collect()}else{*z+=1;vec![]})).flatten()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lY9NTsMwEIX3OYXb1bg4UcMKOXGQ2HWNxKaqKjcdiwjHaRMHaH5OwqYLuEHvwBm4DQ6BihUStjzjmbGe3_fyWtaVPZ6UIbnMDFDSehotUUSQt9oq_-rjvZP8pniOtwdDFhZLaYsydpdc1FXWYJKwzd_zTgZNtoMNDapUGpizrmGATNHutsgRMkVQCNUO3-7FrIlmjZhHgEEgkAbp_WALQt_Vl_7QOKQagQZWPiDsqWsUWmNqgfaoK2xnzYUIo0dMJ8tV78ZKS2vRkX3jnCLP25WZsdpMYNry637KiAKPuOUwODf4BAtjix8Wzt3jYp25EpYhC9n86wxxzG6vKGX_UAh_KYRnBe_Mwnl8h2m8ThKg1PntR-_H45g_AQ)
Just the type declaration of a iterator is already longer than some of the answers here :(
[Answer]
# Javascript, 103 104 105 bytes
```
function*g(a){for(;;){for(i=0;(A=a.next().value)!=a.next().value;)i++;yield*[A,...Array(i).fill(+!A)]}}
```
More nicely formatted:
```
function*g(a){
for(;;){
for(i=0;(A=a.next().value)!=a.next().value;) i++;
yield A;
yield* Array(i).fill(+!A)
}
}
```
Expects a generator function which yields the bits of the numbers to be added, interleaved.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
FN≔⁺NNθNηW⁻ηNNηI﹪⁺θη²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NTwbG4ODM9TyMgp7QYVUpHAVWljkKhpjUXslgGkF@ekZmTqqDhm5kH1J@BrkdTAV19QFFmXomGc2JxiYZvfkppTj7E5kIdhQygDUZALdb//xspGIChIRCCyf@6ZTkA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as `n` (1-indexed) and in interactive mode will prompt for interleaved input bits until it knows what value the `n`th output bit is but on TIO you just have to provide enough bits (if there aren't enough you'll see a prompt but the program will just halt). Explanation:
```
FN≔⁺NNθ
```
Input `n` pairs of bits but only keep the sum of the last pair.
```
NηW⁻ηNNη
```
Input further pairs of bits until two match.
```
I﹪⁺θη²
```
Add the matching bit to the sum from earlier and reduce modulo `2`.
[Answer]
# [R](https://www.r-project.org), ~~62~~ 60 bytes
*Edit: -2 bytes thanks to pajonk*
```
{t=0
\(x,y){u=t
t<<-`if`(x-y,t+1,0)
if(x==y)c(x,rep(!x,u))}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jZFPTsUgEMbjsnOKGjdMpAnsjCknUfNe7StKYnjPliaQpidxUxcewaUH0dMI_ZPQxry4YJiBb358wNt7PXwWh8PuUemidrvKngrdqKMWH62R2c133hnB4J5Y6rBrhQGT59leyT2xmaPmmlOGoCSxQjgsvayuTuTS0hax7yfGz8WXqRojZKtL49GBRX2BHST-MNH1kMhjTVSqdMpvXyr9ZJ6JxbA_CkriY-gg9k49UOcDIiT92A49gG2qV5GmJWGUUT6OJYZ5yXiULRVbKfxd3JrFIx7bqs-vI1xN7lnkiK10LGJs3a3ICOEJSbgoDQ7pX3-G0UvMXW5Tz45m9v-o0y8OwzT_Ag)
Port of [loopy walt's Python approach](https://codegolf.stackexchange.com/a/260289/95126).
Function that accepts sequential pairs of bits from the two numbers to be added as input to successive calls, and gives output when it can, otherwise outputs nothing. So the full output is the concatenated output of successive calls.
Input corresponds to the bits *after* the binary point, output begins with a single bit *before* the binary point, followed by all bits *after* the binary point (since we need to one more bit in case the two input numbers add-up to greater-than one).
Unfortunately my maths isn't good enough to determine when an infinite number of infinitely-small values sum to a finite value [or to zero](https://codegolf.stackexchange.com/questions/260284/add-two-real-numbers-probably#comment573045_260284), so I'm blindly trusting that this approach is valid...
] |
[Question]
[
### Background
Bathroom Etiquette, when pertaining to the available urinals, states that the next urinal to be filled in should be the one that minimizes the total discomfort. The total discomfort equation is given by the following set of equations:
```
**dist(x,y)** = linear distance between person x and person y in Urinal Units
**discomfort(x)** = sum(1/(dist(x,y)*dist(x,y))) for all persons y excluding person x
**total\_Discomfort** = sum(discomfort(x)) for all x
```
A more in depth paper dealing with a similar (not the exact same) problem can be found here: [(Thanks to @Lembik for alerting me to this amazing whitepaper!)](http://people.scs.carleton.ca/~kranakis/Papers/urinal.pdf)
---
### Input/Output
Given an input of a empty and full urinals, output the resulting set of urinals with the addition of one person. If there is a tie for a position the urinals should fill in left to right. The output should be in the same format as the input.
* If given a case with full urinals, return the input.
* The input will always have at least one urinal defined.
---
### Test Cases
```
**INPUT -> OUTPUT**
1000001 -> 1001001
101010101 -> 111010101
100 -> 101
00000 -> 10000
1111111 -> 1111111
0100 -> 0101
101000 -> 101001
```
---
### Rules
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins. Standard loop-holes are forbidden.
[Answer]
# [MATL](http://github.com/lmendo/MATL), ~~19~~ ~~18~~ 17 bytes
```
lyf!Gn:-H_^Xs&X<(
```
[Try it online!](http://matl.tryitonline.net/#code=bHlmIUduOi1IX15YcyZYPCg&input=WzEgMCAwIDAgMCAwIDFd) Or [verify all test cases](http://matl.tryitonline.net/#code=YApseVhLZiFLbjotSF9eWHMmWDwoCkRU&input=WzEgMCAwIDAgMCAwIDFdClsxIDAgMSAwIDEgMCAxIDAgMV0KWzEgMCAwXQpbMCAwIDAgMCAwXQpbMSAxIDEgMSAxIDEgMV0) (slightly modified code).
### Explanation
It suffices to compute the distance from each potential new position to the already occupied ones. The remaining distances are do not depend on the potential new position, and so constitute a constant term, which can be ignored.
Let's take input `[1 0 0 0 0 0 1]` as an example.
```
l % Push 1
% STACK: 1
y % Take input implicitly. Duplicate from below
% STACK: [1 0 0 0 0 0 1], 1, [1 0 0 0 0 0 1]
f! % Indices of nonzero elements, as a column array
% STACK: [1 0 0 0 0 0 1], 1, [1 7]
Gn: % Push [1 2 ... n], where n is input size (array of possible positions)
% STACK: [1 0 0 0 0 0 1], 1, [1; 7], [1 2 3 4 5 6 7]
- % Matrix with all pairs of differences
% STACK: [1 0 0 0 0 0 1], 1, [1; 7], [0 -1 -2 -3 -4 -5 -6;
6 5 4 3 2 1 0]
H_^ % Raise each entry to -2
% STACK: [1 0 0 0 0 0 1], 1, [ Inf 1.0000 0.2500 0.1111 0.0625 0.0400 0.0278;
0.0278 0.0400 0.0625 0.1111 0.2500 1.0000 Inf]
Xs % Sum of each column
% STACK: [1 0 0 0 0 0 1], 1, [Inf 1.04 0.3125 0.2222 0.3125 1.04 Inf]
&X< % Index of minimum. Takes the first if there is a tie
% STACK: [1 0 0 0 0 0 1], 1, 4
( % Assign: write 1 at the position of the minimizer
% STACK: [1 0 0 1 0 0 1]
% Implicitly display
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes
```
J_þTݲSiṂ$Ṭo
```
[Try it online!](http://jelly.tryitonline.net/#code=Sl_DvlTEsMKyU2nhuYIk4bmsbw&input=&args=WzEsIDAsIDEsIDAsIDEsIDAsIDEsIDAsIDFd) or [Verify all test cases.](http://jelly.tryitonline.net/#code=Sl_DvlTEsMKyU2nhuYIk4bmsbwrDh-KCrA&input=&args=W1sxLCAwLCAwLCAwLCAwLCAwLCAxXSwgWzEsIDAsIDEsIDAsIDEsIDAsIDEsIDAsIDFdLCBbMSwgMCwgMF0sIFswLCAwLCAwLCAwLCAwXSwgWzEsIDEsIDEsIDEsIDEsIDEsIDFdXQ)
## Explanation
```
J_þTݲSiṂ$Ṭo Input: boolean array A
J Indices, returns [1, 2, ..., len(A)]
T Truthy indices, returns the indices which have a truthy value
_þ Form the subtraction (_) table (þ) between them
İ Inverse, find the reciprocal of each
² Square each
S Sum the sublists column-wise
$ Monadic chain
Ṃ Minimum
i Find the first index of that
Ṭ Untruth indices, returns a boolean array with 1's at those indices
o Logical OR between that and A, and return
```
[Answer]
## JavaScript (ES6), 89 bytes
```
a=>a[a.map((e,i)=>!e&&(t=0,a.map((e,j)=>t+=(j-=i)&&e/j/j),t<m&&(m=t,k=i)),k=0,m=1/0),k]=1
```
Outputs by modifying the input array.
[Answer]
# R, ~~83~~ ~~76~~ 67 bytes
Just realized that I can save several bytes by not bothering to check if the candidate urinals are empty. Non-empty urinals will always return an `Inf` discomfort value, so they're excluded in the course of the calculation. Also, just using direct indexing rather than `replace`, so it's shorter but less elegant.
```
x=scan()
x[which.min(rowSums(outer(seq(x),which(!!x),`-`)^-2))]=1
x
```
### Explanation
```
x=scan()
```
We read the current state from stdin and call it `x`. We assume that the input is a sequence of `1`s and `0`s separated by spaces or newlines. For the purposes of the explanation, let's say we input `1 0 0 0 0 0 1`.
```
x[which.min(rowSums(outer(seq(x),which(!!x),`-`)^-2))]=1
```
We replace a value of `x` at a particular index with 1. Everything between the `[ ]` is figuring out what the best index is.
Since the existing urinals are immutable, we don't need to consider the distances between them. We only need to consider the distances between the occupied urinals and the possible new one. So we determine the indices of the occupied urinals. We use `which`, a function to return the indices of a logical vector which are `TRUE`. All numbers in R, when coerced to type `logical`, are `TRUE` if nonzero and `FALSE` if zero. Simply doing `which(x)` will result in a type error, `argument to 'which' is not logical`, as `x` is a numeric vector. We therefore have to coerce it to logical. `!` is R's logical negation function, which automatically coerces to logical. Applying it twice, `!!x`, yields a vector of `TRUE` and `FALSE` indicating which urinals are occupied. (Alternative byte-equivalent coercions to logical involve the logical operators `&` and `|` and the builtins `T` and `F`, e.g. `F|x` or `T&x` and so on. `!!x` looks more exclamatory so we'll use that.)
```
which(!!x)
```
This is paired with `seq(x)`, which returns the integer sequence from `1` to the length of `x`, i.e. all urinal locations (and thus all possible locations to consider).
```
seq(x)
```
Now we have the indices of our occupied urinals: `1 7` and our empty urinals `1 2 3 4 5 6 7`. We pass ``-``, the subtraction function, to the `outer` function to get the "outer subtraction", which is the following matrix of distances between all urinals and the occupied urinals:
>
> [,1] [,2]
>
>
> [1,] 0 -6
>
>
> [2,] 1 -5
>
>
> [3,] 2 -4
>
>
> [4,] 3 -3
>
>
> [5,] 4 -2
>
>
> [6,] 5 -1
>
>
> [7,] 6 0
>
>
>
```
outer(seq(x),which(!!x),`-`)
```
We raise this to the `-2`th power. (For those who are a little lost, in the OP, "discomfort" is defined as `1 / (distance(x, y) * distance(x, y))`, which simplifies to `1/d(x,y)^2`, i.e. `d(x,y)^-2`.)
```
outer(seq(x),which(!!x),`-`)^-2
```
Take the sum of each row in the matrix.
```
rowSums(outer(seq(x),which(!!x),`-`)^-2)
```
Get the index of the smallest value, i.e. the optimal urinal. In the case of multiple smallest values, the first (i.e. leftmost) one is returned.
```
which.min(rowSums(outer(seq(x),which(!!x),`-`)^-2))
```
And voilà, we have the index of the optimal urinal. We replace the value at this index in `x` with `1`. In the case of `1111` as input, it doesn't matter which one we replace, we'll still have a valid output.
```
x[which.min(rowSums(outer(seq(x),which(!!x),`-`)^-2))]=1
```
Return the modified input.
```
x
```
[Answer]
## PHP, 135 bytes
```
$a=explode(1,$argv[1]);$b=0;foreach($a as$c=>$d){$l=strlen($d);if($l>$b){$b=$l;$e=$c;}}if($b)$a[$e][intval($b/2)]=1;echo implode(1,$a);
```
I'm sure there's a considerably quicker way of doing it, but I've got a fuzzy head and can't think of one!
### Old code
The code without minification:
```
$a=explode(1,$argv[1]);
$b=0;
foreach($a as $c=>$d){
$l=strlen($d);
if($l>$b){
$b=$l;
$e=$c;
}
}
if($b){
$a[$e][intval($b/2)]=1;
}
echo implode(1,$a);
```
[Answer]
# Python 3 ~~223~~ ~~222~~ 165 Bytes
Okay, I know this isn't the prettiest answer out there, and I'm sure it can be golfed down quite a bit, but I was just messing around and seeing what I could do
Shout out to mbomb007 for the tips on whitespace and comparators
Also, I saw my online character counter was taking all the tabs and turning them into spaces, so the count is a lot less than I originally had
```
def u(a):
m,r,x=9,0,len(a)
for i in range(x):
d=0
if a[i]<'1':
for j in range(x):
if a[j]>'0':d+=float((j-i)**-2)
if d<m:r=i;m=d
return a[:r]+'1'+a[r+1:]
```
Showing revised whitespace:
```
def u(a):
<sp> m,r,x=9,0,len(a)
<sp> for i in range(x):
<tab> d=0
<tab> if a[i]<'1':
<tab><sp> for j in range(x):
<tab><tab> if a[j]>'0':d+=float((j-i)**-2)
<tab><sp> if d<m:r=i;m=d
<sp> return a[:r]+'1'+a[r+1:]
```
Original:
```
def u(a):
m,r,x=9,0,len(a)
for i in range(x):
d=0
if a[i]!='1':
for j in range(x):
if a[j]=='1':d+=float(1/(j-i)**2)
if d<m:r=i;m=d
return a[:r]+'1'+a[r+1:]
```
This expects a string passed to it of 1's and 0's like `"10001"` and returns a string `"10101"`
Edit: Changed `1/float((j-i)**2)` to `float((j-i)**-2)`
[Answer]
# Python 3, ~~574~~ ~~471~~ 347 bytes
I'll probably work on this some more, considering the other Python solution is like a fifth of this one :[.
```
def a(I):
D,l,r={},len(I),range
for i in r(l):
if I[i]<1:
n,t,n[i]=I[:],[],1
for j in r(l):
if n[j]>0:
q,Q=[],0
for k in r(l):
if k!=j and n[k]>0:q.append((k-j,j-k)[k<j])
for i in q:Q+=1/(i**2)
t.append(Q)
T=sum(t)
if T not in D.keys():D[T]=i
if len(D)>0:I[D[min(D.keys())]]=1
print(I)
```
Well that's much better now that I've learned you can use single spaces.
[Answer]
# Python, ~~165~~ ~~163~~ ~~158~~ ~~147~~ ~~141~~ ~~140~~ 139 bytes
```
def u(p):e=enumerate;a=[(sum((i-j)**-2for j,y in e(p)if"0"<y),i)for i,x in e(p)if"1">x];return a and p[:min(a)[1]]+"1"+p[min(a)[1]+1:] or p
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
$āsƶ0Kδ-znD_°+OWkǝ
```
I/O as a list.
Port of [*@miles*' Jelly answer](https://codegolf.stackexchange.com/a/98240/52210), so make sure to upvote that answer as well!
Unfortunately, dividing by 0 won't result in `INF` in 05AB1E like it does in Jelly and MATL, but instead in `0`. So 4 bytes (`D_°+`) are to account for that..
[Try it online](https://tio.run/##yy9OTMpM/f9f5Uhj8bFtBt7ntuhW5bnEH9qg7R@efXzu///RhjoGOig4FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf8PiI43Fx7YZeJ/boluV5xJ/aIO2f3j28bn/df5HRxvqGMChYawOmI@CoWIGQBquEiyGBMFyhnAZKBvIiwUA).
**Explanation:**
```
$ # Push 1 and the input-list
ā # Push a list in the range [1,length] (without popping the list)
s # Swap so the input-list is at the top again
ƶ # Multiply each value by its 1-based index
0K # Remove all 0s
δ- # Pop both lists, and create a subtraction table
z # Convert each inner value to 1/value
n # Square each inner value
D # Duplicate this list
_ # Check for each inner value whether it equals 0 (1 if 0; 0 otherwise)
° # Take 10 to the power this (10 if 0; 1 otherwise)
+ # Add it to each value at the same positions
O # Sum each inner list
W # Push the minimum (without popping the list)
k # Pop both, and push the (first) (0-based) index of this minimum
ǝ # Insert the 1 at this index into the (implicit) input-list
# (after which the result is output implicitly)
```
[Answer]
# [Scala](http://www.scala-lang.org/), 173 bytes
Golfed version. [Try it online!](https://tio.run/##dVDLboMwELzzFatc8AqT2L0V4kj5gJ6qnqoenBgSIx6RgTQt4tupeahKCxlbsrQ7o5lxeZSp7IpDEh0reJE6h8Zx4CpTqAPyWhmdn8RufBFEJ8WuuUpDMmrojSoU5FlRRuW61N8RZQrDuDBEb30GVQE3n6OOiSQahXCZi40SbGAk/xlJz@AuKk9ksjqvL8UnSXxN/ScMLUFtM2yM0GEmVNuG1q8@lEMqwqhBz0q9@6HxOLYdgIpiyGwrIs2pDGBvjPx6H@t8YABvua5A2MpgcbHTKs1JTVac9eArxH6x2UB5LupUjZQA7Lq/c9V0Bt1cxaf1gtvk9MBtphji/WqW8jE2cxnxsNOImdOfcDPVch1@l26pzvh3rdN2Pw)
```
a=>{var(m,r,x,d)=(9d,0,a.size,0d);for(i<-0 to x-1)if(a(i)=='0'){d=0;for(j<-0 to x-1)if(a(j)=='1')d+=math.pow(j-i,-2);if(d<m){r=i;m=d}};a.substring(0,r)+'1'+a.substring(r+1)}
```
Ungolfed version. [Try it online!](https://tio.run/##dVHLboMwELzzFaNcYisJMb01Cod@QE9VT1UPToDEEY/ImD5U8e3Uxg4hMizI9nh3Zne99ZHnvOuqwyU9KrxyUeIvAJI0Q0P4Dm9KivJEbwfEvRv44hKFRs8hG7DU@IZy/GjEwzwtT@rcX2aVBBHYb8DQlEroEOrULD8xfKcHiAyEE0ERx1iy5T3UKV1mlO7ci@VGy0en7g6rGAVX5/BafWuhDcQamyc6CmoD/2RUE@xRPOqZtsUIm2dJPLrd7crDujnU/YMStoakWJky9Tr2SI0jU1MbuIkUejyEy1O9w4uU/PfDDuVTj@e9FGoYzlXfqrwkDVlEzFi0oNQ4tlvU56rJExuyg3ab32e5r@f5rMi5J7K5TDPZPEZf3sCZqo8xL4u12Z6seZkeivNY0@1Eo@qm2rFv1wZt1/0D)
```
object Main {
def u(a: String): String = {
var m = 9.0
var r = 0
val x = a.length
for (i <- 0 until x) {
var d = 0.0
if (a(i) == '0') {
for (j <- 0 until x) {
if (a(j) == '1') {
d += math.pow(j - i, -2)
}
}
if (d < m) {
r = i
m = d
}
}
}
a.substring(0, r) + '1' + a.substring(r + 1)
}
def main(args: Array[String]): Unit = {
println(u("1000001")) // should print: 1001001
println(u("101010101")) // should print: 111010101
println(u("100")) // should print: 101
println(u("00000")) // should print: 10000
println(u("1111111")) // should print: 1111111
println(u("0100")) // should print: 0101
println(u("101000")) // should print: 101001
}
}
```
] |
[Question]
[
Before 1994, Spanish dictionaries used alphabetical order [with a peculiarity](https://en.wikipedia.org/wiki/Spanish_orthography#ref_r): digraphs `ll` and `ch` were considered as if they were single letters. `ch` immediately followed `c` , and `ll` immediately followed `l`. Adding the letter `ñ`, which follows `n` in Spanish, the order was then:
```
a, b, c, ch, d, e, f, g, h, i, j, k, l, ll, m, n, ñ, o, p, q, r, s, t, u, v, w, x, y, z
```
Since 1994 `ll` and `ch` are considered as groups of two letters (`l`,`l` and `c`,`h` respectively), and thus alphabetical order is the same as in English, with the exception of the letter `ñ`.
The old order was definitely more *interesting*.
## The challenge
Input a list of zero or more words and output the list sorted according to the old Spanish alphabetical order. Sorting is between words (not between letters within a word). That is, words are atomic, and the output will contain the same words in a possibly different order.
To simplify, we will not consider letter `ñ`, or accented vowels `á`, `é`, `í`, `ó`, `ú`, or uppercase letters. Each word will be a sequence of one or more characters taken from the inclusive range from ASCII 97 (`a`) through ASCII 122 (`z`).
If there are more than two `l` letters in a row, they should be grouped left to right. That is, `lll` is `ll` and then `l` (not `l` and then `ll`).
Input format can be: words separated by spaces, by newlines, or any convenient character. Words may be surrounded by quotation marks or not, at your choice. A list or array of words is also acceptable. Any reasonable format is valid; just state it in your answer.
In a similar way, output will be any reasonable format (not necessarily the same as the input).
Code golf, shortest wins.
## Test cases
In the following examples words are separated by spaces. First line is input, second is output:
```
llama coche luego cocina caldo callar calma
caldo calma callar cocina coche luego llama
cuchara cuchillo cubiertos cuco cueva
cubiertos cuco cuchara cuchillo cueva
```
"Words" can be single letters too:
```
b c a ch ll m l n
a b c ch l ll m n
```
or unlikely combinations (remember the rule that `l`'s are grouped left to right):
```
lll llc llz llll lllz
llc lll lllz llll llz
```
An empty input should give an empty output:
```
```
Of course, this order can be applied to other languages as well:
```
chiaro diventare cucchiaio
cucchiaio chiaro diventare
all alternative almond at ally a amber
a almond alternative all ally amber at
```
[Answer]
# Pyth, ~~14~~ 13 bytes
**Update:** saw this got accepted and noticed a trivial 1 byte golf. Whoops.
```
:D"ll|ch|."1Q
```
[Try it online.](https://pyth.herokuapp.com/?code=%3AD%22ll%7Cch%7C.%221Q&input=%5B%22llama%22%2C+%22coche%22%2C+%22luego%22%2C+%22cocina%22%2C+%22caldo%22%2C+%22callar%22%2C+%22calma%22%5D&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=%3AD%22ll%7Cch%7C.%221Q&test_suite=1&test_suite_input=%5B%5D%0A%5B%22llama%22%2C+%22coche%22%2C+%22luego%22%2C+%22cocina%22%2C+%22caldo%22%2C+%22callar%22%2C+%22calma%22%5D%0A%5B%22cuchara%22%2C+%22cuchillo%22%2C+%22cubiertos%22%2C+%22cuco%22%2C+%22cueva%22%5D%0A%5B%22b%22%2C+%22c%22%2C+%22a%22%2C+%22ch%22%2C+%22ll%22%2C+%22m%22%2C+%22l%22%2C+%22n%22%5D%0A%5B%22lll%22%2C+%22llc%22%2C+%22llz%22%2C+%22llll%22%2C+%22lllz%22%5D%0A%5B%22chiaro%22%2C+%22diventare%22%2C+%22cucchiaio%22%5D%0A%5B%22all%22%2C+%22alternative%22%2C+%22almond%22%2C+%22at%22%2C+%22ally%22%2C+%22a%22%2C+%22amber%22%5D&debug=0)
For each word, find all non-overlapping matches for the regex `ll|ch|.`. This splits the word into the "letters". Then, just sort the words by the splitted lists.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `a`, 15 bytes
```
µ‛ch‛c~V‛ll‛l~V
```
Takes input as words separated by newlines, outputs a list.
[Try it Online!](http://lyxal.pythonanywhere.com?flags=a&code=%C2%B5%E2%80%9Bch%E2%80%9Bc%7EV%E2%80%9Bll%E2%80%9Bl%7EV&inputs=llama%0Acoche%0Aluego%0Acocina%0Acaldo%0Acallar%0Acalma&header=&footer=)
```
µ‛ch‛c~V‛ll‛l~V # Full program
µ # Sort (implicit) input by key:
V # Replace...
‛ch # `ch`...
‛c~ # with `c~`
V # Replace...
‛ll # `ll`...
‛l~ # with `l~`
```
[Answer]
# PowerShell, ~~46~~ ~~44~~ ~~51~~ 50 bytes
```
$args|sort @{e={$_-replace'(?=ch|ll)(.).','$1Α'}}
```
The `Α` character is the Greek letter alpha which in comes after all Latin letters in PowerShell's default sort order (at least on my machine, I'm not sure if it's different in other locales). It's counted as 2 bytes in UTF8 encoding.
Example usage, assuming this string is saved in a file named `es-sort.ps1`:
```
> es-sort.ps1 'lzego' 'luego' 'llama'
luego
lzego
llama
```
[Answer]
# Mathematica, 81 bytes
```
StringReplace[Sort@StringReplace[#,"ch"->"cZ","ll"->"lZ"],"cZ"->"ch","lZ"->"ll"]&
```
Same approach as TimmyD's answer.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Σ„ch„c~:„ll„l~:
```
I/O as a list of strings.
Very straight-forward approach, but I'm unable to find anything shorter (thus far).
[Try it online](https://tio.run/##yy9OTMpM/f//3OJHDfOSM0BEnRWQzMkBEXVW//9HK@XkJOYmKukoJecnZ6QC6ZzS1PR8CD8zDyyRmJOSD6FzEosgDKCOWAA) or [verify all test cases](https://tio.run/##HY29DcJADIX7m8IKLROkScMizuXEnfSSky4/EhFEVBmAAWjoaNghAzBEFjlsivfZ79myY891cPm6fbb3dDmcqoL29UFFlb@v/f60XrGUQkCxlPl2zAC3TDZa7wijO0ftQycRo4lKcNLSsrGj9ZxkJDUAMh3lYxpir5FaN7GpyZLseAKoJVBnIB1gRbPobzAbucEpUhMm1w2cnN7QLMQf).
**Explanation:**
```
Σ # Sort the (implicit) input-list of strings by:
„ch„c~: # Replace all "ch" with "c~"
„ll„l~: # Replace all "ll" with "l~"
# (and then sort it by default lexicographical order)
# (after which the sorted list is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ ~~15~~ 12 bytes
```
eƬ“ch“ll”µƝÞ
```
[Try it online!](https://tio.run/##y0rNyan8/z/12JpHDXOSM4BETs6jhrmHth6be3je/8Ptkf//q@fkJOYmqusoqCfnJ2ekghg5panp@VCRzDyIXGJOSj6UkZNYBGVB9WUk5qWDNaYk5uapAwA "Jelly – Try It Online")
Previous 12-byter sorted leading digraphs incorrectly, since the index took precedence over the actual character data.
```
Þ Sort the input by:
µƝ for each pair of adjacent characters as a list,
Ƭ apply while unique (collecting all results):
e is it an element of
“ch“ll” ['ch', 'll']?
```
`eƬ2ƤÞ“ch“ll”` also works for 12 bytes, doing precisely the same thing.
[Answer]
# Python 2, ~~128~~ 116 bytes
```
lambda p:map(''.join,sorted([{'!':'ll','?':'ch'}.get(c,c)for c in w.replace('ll','!').replace('ch','?')]for w in p))
```
I still feel like there's definitely room for improvement here.
[Answer]
# Javascript, 95 bytes
```
s=>s.map(a=>a.replace(/ll|ch/g,m=>m[0]+'~')).sort().map(a=>a.replace(/.~/g,m=>m>'d'?'ll':'ch'))
```
[Answer]
# Perl, 40 bytes
Includes +1 for `-p`
Run with the list of words on STDIN:
```
perl -p spanisort.pl <<< "llama coche luego cocina caldo callar calma"
```
`spanisort.pl`
```
s/ll|ch|./\u$&/g;$_="\L@{[sort split]}"
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 42 bytes
```
->a{a.sort_by{_1.gsub(/ll|ch/){$&[0]+?|}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3tXTtEqsT9Yrzi0rikyqr4w310otLkzT0c3JqkjP0NatV1KINYrXta2pra6E6LApKS4oV3KJVy6NzchJzExWS85MzUhVySlPT80HszDygUGJOSj6IzEksAlG5ibGxXBD9CxZAaAA)
] |
[Question]
[
Given an n non-negative integers, how many numbers must be changed so that each number x appears x times? You cannot add or remove elements, only replace them with other numbers.
For example:
```
1 6 23 6 9 23 1 1 6
```
can be turned into:
```
1 6 2 6 6 2 6 6 6
```
with 5 changes, which is optimal.
## Test cases
```
0 => 1
1 2 3 => 1
5 5 5 5 5 => 0
23 7 4 8 => 3
100 100 100 6 => 4
5 5 5 5 5 5 => 1
1 2 2 4 4 4 4 9 9 9 9 => 5
```
Shortest code wins!
[Answer]
# [Vyxal 3](https://github.com/Vyxal/Vyxal/tree/version-3), 16 bytes
```
L:ɾẋΩᵛC₌}ƛ?ÞṅL}g
```
Simple bruteforce, probably can be golfed more.
[Try it Online!](https://vyxal.github.io/latest.html#WyIiLCIiLCJMOsm+4bqLzqnhtZtD4oKMfcabP8Oe4bmFTH1nIiwiIiwiWzIzLDcsNCw4XSIsIjMuNC4xIl0=)
```
L:ɾẋΩᵛC₌}ƛ?ÞṅL}g­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠⁠⁠⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁢‏⁠⁠⁠⁠⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌­
L:ɾẋ # ‎⁡Nth cartesian power of range [1, length]
Ω } # ‎⁢Filter by items where
ᵛC₌ # ‎⁣Count of each item is item
ƛ } # ‎⁤Map through list
?ÞṅL # ‎⁢⁡Length of multiset difference between input and item
g # ‎⁢⁢Push minimum
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [R](https://www.r-project.org), 88 bytes
```
\(x,n=sum(x|1))min(combn(rep(1:n,n),n,\(r)`if`(all(names(t<-table(r))==t),sum(r!=x),n)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY5LCsJADIb3niLiJoEUOm3VIo7ncNFFH7RQ6IzSTqELT-AV3FTBQ3kb-xgpwk9C8iV_8njW_auQ79YUTvg5R9ixlk2rsLsJIlVqzC4q1VjnVxQHzZpYc4Q1xWURY1JVqBOVN2iOjknSKh8ISWmIR496Lbthnois_73ADF2iDcgTiNVYCQaPwf_rbRkWWeJOxPMZ9gwBQ2j7_uziugxL2FkYTDCYFqx-h-aP-n7OXw)
[Answer]
# Haskell + [hgl](https://gitlab.com/wheatwizard/haskell-golfing-library), 28 bytes
```
mMl<df**<fb(jn rl)<<dpS uq<l
```
I didn't want to brute force this, so I didn't. Although brute forcing would probably be shorter.
## Explanation
First we find all the strictly descending integer partitions of the length of the input. We convert these to "perfect lists". This gives us all the perfect lists with the same size as the input. Then we take use the set difference to remove the elements in the input from each perfect list, these represent the number of replacements that need to be done. Then we get the size of the smallest element and output that.
## Reflection
This answer feels *painfully* long. There are a couple things here:
* `dpS uq` is a bad way to get strictly descending integer partitions. It is 6 bytes long and slower than it needs to be. There should be a 3-byte version.
* This isn't the first time I've wanted a function that zips and then concatenates, but I apparently haven't added it. It would be useful here.
* There should be a shorter way to replicate every item in a list its own number of times (currently `fb(jn rl)`). I remember noticing that some obscure combination of functions did this, but I can't remember which. It's really bothering me.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JṗLċⱮ`ƑƇn⁸§Ṃ
```
A monadic Link that accepts a list of integers and yields the minimal number to alter to form a *perfect array*.
**[Try it online!](https://tio.run/##y0rNyan8/9/r4c7pPke6H21cl3Bs4rH2vEeNOw4tf7iz6f///9FGOgpAZKmjYAxGIG4sAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/r4c7pPke6H21cl3Bs4rH2vEeNOw4tf7iz6f/RSQ93ztA53J71qGGOgq2dwqOGuZqR//9HRxvE6nApRBvqKBjpKBiD2aY6CggEFjEy1lEw11Ew0VGwgKg2MNBRQBBmmNogOmMB "Jelly – Try It Online").
### How?
Constructs all lists of the same length as the input using an alphabet of `1` through to that length (with the elements in all possible orders). Filters these down to *perfect arrays*. Counts the differing entries of each with respect to the input (by summing the results of a vectorised not-equal). Returns the minimum.
```
JṗLċⱮ`ƑƇn⁸§Ṃ - Link: list of integers, Array
J - indices {Array} -> [1..length(Array)]
L - length {Array}
·πó - {Indices} Cartesian power {Length}
-> all arrays of length length(Array) formed from 1..length(Array)
Ƈ - keep those for which:
Ƒ - is invariant under?:
Ɱ` - map across itself with:
ċ - count occurrences
n⁸ - {that} not-equal? (vectorises) {Array}
§ - sums
Ṃ - minimum
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 29 bytes
```
{&/+/~x=+{+/x=\:x}/'+!#/2##x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6pW09fWr6uw1a7W1q+wjbGqqNVX11ZU1jdSVq6o5eJKc9AxABKGCkYKxkDaVAEKgWwjYwUTBXMFC5C0gYECDJshKwMAUYQUvg==)
`+!#/2##x` Generate all n-tuples with values in [0,n), where n is the length of the input.
`{...}/'` For each tuple, run until convergence:
`+/x=\:x` ... Replace each value with its count.1
`~x=+` element-wise comparison between the input and each generated tuple.
`&/+/` Find the minimum number of different values.
1 If this converges it must have reached a perfect array. Right now I can't think of a proof that it always converges (or equivalently, there are no cycles of length >1).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ƒÅ¬§√£ í√ꬢQ}‚Ǩ-ƒÄO√ü
```
Port of [*@mathScat*'s Vyxal answer](https://codegolf.stackexchange.com/a/269105/52210).
[Try it online](https://tio.run/##ASwA0/9vc2FiaWX//8SBwqTDo8qSw5DColF94oKsLcSAT8Of//9bNSw1LDEsMiwyXQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PNB5acnjxqUmHJxxaFFh7buuhdbq1Rxr8D8//r/M/OtogVifaUMdIxxhIm@pAIZBtZKxjrmOiYwGSNjDQgWEzZGVghcY6xjqGcFEjHSMo2xDMjgUA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) inpu-length]
¤ # Push its last item (without popping): the length
√£ # Cartesian power, to create all possible lists of this length
í # Filter it by:
Ð # Triplicate the current list
¢ # Pop two, and count how many times each item occurs
Q # Check that this list of counts and current list are still the same
}€ # After the filter: map over each remaining list:
- # Subtract the values at the same positions from the (implicit) input-list
Ā # Check for each difference that it's NOT 0 (0 if 0; 1 otherwise)
O # Sum the checks of each inner list together
ß # Pop and push the minimum
# (which is output implicitly as result)
```
[Answer]
# Python3, 742 bytes
Rather long, but non-brute force solution (for the sake of variety)
```
from itertools import*
D=lambda d,n,K,U:{**{a:b for a in d if(b:=[j for j in d[a]if j not in K])},n:[*K,*U]}
def P(n,d,r,F):
U=d.get(n,[])
d={i:d[i]for i in d if i!=n}
k=[[],[]]
for i in d:
if i<n or len(d[i])!=i:k[i>F]+=d[i]
if len(k[1])>=r:yield D(d,n,K:=k[1][:r],U),K;return
for K in combinations(k[0]+k[1],r):
if[]==k[1]or any(j in K for j in k[1]):yield D(d,n,K,U),K
def f(a):
d,I={},0
for i in a:d[i]=d.get(i,[])+[I];I+=1
q=[(len(a),len(a),d,0)]
M=-1
while q:
n,A,d,C=q.pop(0)
if all(i==len(d[i])for i in d):M=min(M,C)if M!=-1 else C;continue
if n==0:continue;
if len(L:=d.get(n,[]))!=n:
r,F=n-len(L),A-n
for u,i in P(n,d,r,F):
if M==-1 or C+len(i)<M:q+=[(F,A-n,u,C+len(i))]
q+=[(n-1,A,d,C)]
return M
```
[Try it online!](https://tio.run/##lVLRbtowFH3PV1yeahODktIxZupKFRVSlUXaC0@WH0KTrC6JE0LQhBDfznwdGO00qUwWSjj33HPuPU69a18rM5rUzfGYN1UJus2atqqKDeiyrpq27z2JIimXaQIpMyxiC77v9/cJX0JeNZCANpCCzsmSC/nmsDeHyUTp3L6bqsX/kaIHZrjsR6y/UAcvzXL4QQxLWcPmlHuwEOnwZ9ZaSCrqQSr2mqdSK1TUZxfQPWEOHqyElMoSlQeXuhVxlHsDFisyQ7Cf9oTmK6kf5soXCHhIwupKhoo@iIbvdFak8ETcglwgLnmj2IKyaNpk7bYxnU@EPi9VudQmaXVlNlYjUD42sIZ2/lIJp4DhmB1xYUSXXJzpR0fn4wLJSYIqKXsW@wML3i2XuCxOEWmMyJfPavrsi9CDtZAEF0ooOz1SFlC7aCwGtvzrVRcZrHE8wx5tbSbWw7qqSUC7xJKiIFqIP4ldIqU8FqU2JGYzaolxzwpCVmwymE1fKtNqs806DSNEwM/QtMNQ8Dt/f6/2MgzOAfbShRk4AmWPA4MY2m6ZM/7wZYATiwV6W8rMxzZN72O@9u3mc@xnW3bGcXFwFTMIu30R6u4R4mPdaNOSnMh@mdTEvjO4CW6Gm7rQLbHdlHr/ooRwC6PPaV/gdD6n3o7gK9zB5ArvIIDzb/wfM1wzRQhjsJOM4Rs@QnuudJjYc2dPCKO/gjn@Bg) (includes extra/longer test cases)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
I⌊EΦEX²Lθ⌕A⮌⍘⊗ι²1⁼ΣιLθΣEι⌈⟦⁰⁻λ№θλ
```
[Try it online!](https://tio.run/##RU5BCoMwEPxK8LSBFKoFofTU2nqqIPUoHlINGlhjNYnt79OohS4LM8sOM1N3fKoHjs7lk1QGEq4NZFLJ3vaQ8RekEo2YVpoPb88iRu5CtaaDkVJGUqmaMyI8xCwmLeDCtSiM92rhOtgnigakl0WLNgiDBW6j5aih8AnL6@/mj@IXKxnJ@GdtUe49l8pqQEaSwfqWIyNIaUW3OTlXliEjsY85rHDcWLhuXFVuN@MX "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
EX²Lθ⌕A⮌⍘⊗ι²1
```
Generate all subsets of `{1..l}`, where `l` is the length of the input array.
```
Φ....⁼ΣιLθ
```
Filter for those that sum to `l`.
```
I⌊E...ΣEι⌈⟦⁰⁻λ№θλ
```
Calculate the number of changes required for each subset and output the minimum.
[Answer]
# JavaScript (ES7), 122 bytes
Brute force.
```
a=>eval("for(m=s=a.length,n=s**s;n--;)a.map(c=(x,i)=>(c[v=n/s**i%s+1|0]=-~c[v],d+=v!=x,v),d=0).some(v=>c[v]-v)|d>m?m:m=d")
```
[Try it online!](https://tio.run/##fc7fa8IwEAfw9/0VN0FI9NKm1v1Aue4PkT6EJnUdTSJGgg/iv15TkMm6sXDcw92H@@ZLRRWaY3c4Cee1GVoaFFUmqp7NWn9klgKprDduf/pER2GxCFsnxJarzKoDa4idseNUsWYXyeVp383DsrjImsQ1zWrUS4rPdMbIUZPkWfDWsEjVuBSRX3RlP@zGkp7xofEu@N5kvd@zlu1kzTlMXp5D8TRxBcIKofyh/3IvCI@66@Tk1K1KhDeENcL7983kyl@5UiI82uuIk1v/m3uPHv833AA "JavaScript (Node.js) – Try It Online")
### Commented
This is a version without `eval()` for readability.
```
a => { // a[] = input array
for( // main loop:
m = // m = minimum score
s = a.length, // s = size of a[]
n = s ** s; // n = counter, initialized to s ** s
n--; // decrement n down to 0
) //
a.map(c = // c = object to count value occurrences
(x, i) => // for each element x at index i in a[]:
( c[ // increment c[v]
v = // where v is:
n / s ** i // a value in [1 .. s] computed
% s + 1 | 0 // according to n and i
] = -~c[v], //
d += v != x, // increment d if v != x
v // yield v
), //
d = 0 // start with d = 0
) // end of map()
.some(v => // for each value v in the result of map():
c[v] - v // trigger some() if c[v] != v
) | // end of some()
d > m ? // if some() was triggered or d > m:
m // do nothing
: // else:
m = d; // update m to d
return m // return m
} //
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 39 37 bytes
```
{⌊/+/¨⍵∘≠¨{⍵/⍨{⊃∧⌿{⍺=⍴⍵}⌸⍵}¨⍵},⍳⍴⍨⍴⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@/@lFPl762/qEVj3q3PuqY8ahzwaEV1UC2/qNeIN3V/Khj@aOe/UCRXbaPercAJWof9ewAUWAdtTqPejeDxVdAZf@7PWqbQF1DN0PVcD3qmwo03E3BUMFIwRjOM4VBuIiRsYKJgrmCBUKDgQEcm2FqVDD9DwA "APL (Dyalog Classic) – Try It Online")
```
{⌊/+/¨⍵∘≠¨{⍵/⍨{⊃∧⌿{⍺=⍴⍵}⌸⍵}¨⍵},⍳⍴⍨⍴⍵}
{ ,⍳⍴⍨⍴⍵} generate all n-length arrays of numbers 1-n (where n is the input length)
{⍵/⍨ ¨⍵} keep only arrays for which
{⊃∧⌿{⍺=⍴⍵}⌸⍵} all numbers appear a number of times equal to their value (perfect arrays)
⍵∘≠¨ for each, find the number of elements that differ from the input
⌊/+/¨ and return the minimum
```
[Answer]
# [Wolfram Language(Mathematica)](https://www.wolfram.com/wolframscript/), ~~119~~ 88 bytes
Saved 31 bytes thanks to @ZaMoC
---
88 bytes version. [Try it online!](https://tio.run/##fYzLCsIwFET3fsWFQtESsA9fKIUILtwIarsLUS71UgNNkCYuROyv141Q60IYBuYMHI3uShqdKrBtNcfzMt0pI7DZotbKlBtlHZqCGs8f84wqKpw4oilJmDSvRXRCKZv8fqvINoatzYXzDDUdOOc5VtWDe76U7TDIyToo0JINRoN9rYwTWjzDl5SrbkYMYgZJH04ZdOlfccJgzmDCYPEjCkNg8N2zP9KPt30D)
```
m@a_:=Min[a~HammingDistance~#&/@Select[Range[n=Tr[1^a]]~Tuples~n,And@@SameQ@@@Tally@#&]]
```
119 bytes version. [Try it online!](https://tio.run/##fYxBawJBDIXv/opAQaoEuq7WlpaFKfTQQ4ViFzyEIGGJuwMzoTjjoYi/fRUpWHsohIT38t4XJXcaJftG@n7jZP1UvYRQb3dKtYTw7QRviErmqjrdCfOQB/EcW/nc0d6qd7U2d04OuPBGbxKjt/bVpyzWKJ3qPLxznxq0yVTvvoImWoq16gyNccPM/e241pShkaRpPBp8bL1lirQvDszPFzlBKBGm1@Y9wmWuX@UU4QFhhvD4B1QUgPB7z/@B/nD7Iw)
```
f@a_:=AllTrue[Tally@a,#[[2]]==#[[1]]&]
m@a_:=With[{n=Length@a},Min[HammingDistance[a,#]&/@Select[Tuples[Range@n,n],f]]]
```
Ungolfed version. [Try it online!](https://tio.run/##lZBdS8MwFIbv@ysOCENHwK7zC6XgmBcKDob2LgQJ8dgW0nQk6YVs@@319APXXQwrhCQned8n70khfYaF9LmSdf3i1mi/UPmFtfKbS2s/BNzHEAAstE5shTyRWrc3gsEZ55EQEMfNbka73W5wFsJEPASr3CwzaVJ0SXkSvio/K418ayCGVzSpz/oXNmgL1y6/RipVC1yWlfFuzxpAJyR3Um00Ov7WCLghgqEM3f2BQLp31FTynn/cd@cYPkKGZ1kUuUmfcuelUdjkow8QMIHLx2N666a2@ZAgCBqcTxN0HpR06KYXwdrmxvOTH7QN943rL9WMQcRgPkp7zeAwRjmiOYNbBlcM7salCUNgMJxv/p@sD1fXPw)
```
IsPerfectArray[arr_] :=
AllTrue[Tally[arr], #[[2]] == #[[1]] || #[[2]] == 0 &];
MinChangesToPerfectArray[arr_] :=
Module[{n = Length[arr], perms, perfectArrays, changeCounts},
perms = Tuples[Range[n], n];
perfectArrays = Select[perms, IsPerfectArray];
changeCounts = HammingDistance[arr, #] & /@ perfectArrays;
Min[changeCounts]];
(*Test cases*)
Print[MinChangesToPerfectArray[{0}]];
Print[MinChangesToPerfectArray[{1, 2, 3}]];
Print[MinChangesToPerfectArray[{5, 5, 5, 5, 5}]];
Print[MinChangesToPerfectArray[{23, 7, 4, 8}]];
Print[MinChangesToPerfectArray[{100 , 100 , 100 , 6}]];
Print[MinChangesToPerfectArray[{5, 5, 5, 5, 5, 5}]];
```
[Answer]
# [Python 3](https://www.python.org/) - 157 Bytes
This is a brute force solution. It won't always run fast, but it gets the job done nicely.
```
lambda l:(N:=len(l))-max([sum([l[p]==k[p]for p in range(N)])for k in[[i//(N**j)%N+1for j in range(N)]for i in range(N**N)]if all([g==k.count(g)for g in k])])
```
[Try it online!](https://tio.run/##XY1ZDoIwEIav0heTKVbZXAhJr9ALNH2oS7FQSoOQ6OmxFUzUTGb78s8/7jncOpsXrp8mRY1sTxeJTAmspOZqwWC8aeUD@H1sgRvuBKWNr6rrkUPaol7a6goMCxxQ4xHnOo6BRVGNV2ydBlz/KAPRXySKPNQKSWOAV95/e@5GO0D1tqyCshH@weR67TFXwBOBiW8pyUg@j3uyxLxmOTmSHSkWXZKQTx7@9OHCe78A)
**Explanation**
```
(lambda l: #Define a function that takes a list l
(N:=len(l))- #Return N (the length of l) minus the following
max([ #The maximum value in this list
sum([ #Sum the True values in this list
l[p]==k[p] #p-th item in the input equals item in k
for p in range(N) #Where p is the p-th item in the lists
])
for k in #Loop through the items in this list; k equals the item
[
[
i//(N**j)%N+1 #Goes through all possible arrays with max N and length N
for j in range(N) #j is equal to 1,2...N
]
for i in range(N**N) #Do this for i = 1,2...N**N to get all possible lists
]
if all([ #Only include the list if all of these Booleans are true
g==k.count(g) #Is g equal to how many times g occurs?
for g in k #Do this for every item in all possible lists
])
])
)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 112 bytes
```
f=(z,a=[],i=0)=>1/z[i]?Math.min(...z.map((_,j)=>(++j!=z[i])+f(z,t=[...a],i+1,t[j]=-~t[j]))):a.some((v,i)=>v-i)*i
```
[Try it online!](https://tio.run/##fc5LboMwEAbgfU8x3Y3LYMwjD0VycoKewEKVlUJiBDgKiAWLXJ0OUlRUWtUa2Qt/v39XdrDd@e5ufdj6z2IqNQ@OZLXJyWkl9DGORuPy07vtr7JxLUopR9nYG@IHVXyPQVC96tmIoORorw0Ty/Egpt5UuQ4f8yGEOFjZ@aZAHMhxcgideHPT2bedrwtZ@wuWaBRLWK0ogvhl5WKChCD9of9yG4JlnpqdWrskJdgRZAT77zfZpb96lSJYtu2M2WX/9j6r5/9NXw "JavaScript (Node.js) – Try It Online")
Recursive is bit shorter
[Answer]
# [Python](https://www.python.org), 111 bytes
```
f=lambda L,l=0,p=0,s=0:(d:=len(L)-p)and min(f(L,k,p+k,s+max(0,k-L.count(k)))for k in[*range(-~l,-~d//2),d])or s
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU1LboMwEN1zitllhgyJA6FNkZwTsO-i6sItobUwtgVEaje5SDds2jvlNjWCqNXTSPM-M-_rx38O786O4_d5qJPD1dXSqPalUlCykYJ9mF6KAqtCmpPFkhJPylbQaos1ltywXzfcr1v1gYKbpNy8urMdsCGi2nXQgLZPcafs2wmTi-HkUm23KXH1TMHtl9rHKWpCFJwPLYKKCDQ7kGA2vTd6wJU8riiCeFZb5VHbgTHWi0_sKPi-CzJqrlFPyvx-vLYC5BF20Q5SyOY1hxsCFVGawT3s4TCxLNoJAbe5m6T9v3z-9ysNJzMeFgQrn1t_AQ)
### obsolete [Python](https://www.python.org), 128 bytes
```
f=lambda L,*s:[r:=len(L)-sum(s)]and min([f(L,*s,k)for k in range([0,*s][-1]+1,-~r//2)]+[sum(max(0,t-L.count(t))for t in[*s,r])])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU5BboMwELzzir1lTUxiILQpEnkB9x4sH9wmtFbARsZI7aXqP3rh0v4pv6ldiFKNVtqd2Zndr5_-3b0aPU3fo2uS_eWzqVrZPR0l1DQeSm7Lqj1prEkyjB0OREh9hE5p5A2GDXomjbFwBqXBSv1yQs48LXiSinVKkw-73WZErHmwd_INGXVJvXk2o3boyJ_ZeTP3UVYQQZY_HoPQhlTT-_uMlBEoaqCCdjP0rXK4qg4rEkE8s53sUWlHMVaLTqghXu-tp1HRBlVg5vjp0jGoDpBGKWSQz20BV_iRRVkO97CDfZjyKGUMrnUXqN2__eKWlXnLjIcFXirmq78)
## How?
* Creates all strictly increasing partitions of the length of the input.
* For each partition:
+ Counts how many instances of each element are in the list and
+ if there are too few adds the number missing to the tally for that partition
* Takes the minimum over all sums.
[Answer]
# [Desmos](https://desmos.com/calculator), 123 bytes
```
f(l)=[sgn([B[B=j].count-jforj=B]^2.max)L+sgn(B-l)^2.totalfori=[0...L^L]].min
L=l.length
B=l[mod(floor(Li/L^{[1...L]}),L)+1]
```
Brute force. This theoretically works for any list, but in practice it errors out for input lists with greater than 5 elements because of Desmos's 10000 element restriction.
[Try It On Desmos!](https://www.desmos.com/calculator/cmggrtolhp)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/mpfni46tib)
] |
[Question]
[
I live in the UK, where it rains. A lot. I also have the unfortunate necessity to need to wear glasses to see, which means that when it rains (as it is now), I can barely see out of them. This challenge is so that you can all experience the same!
## Task
Output ASCII art glasses with a drop of water added each second.
## Input
None
## Output
A pair of glasses with drops of water on them.
### Glasses
```
________________________
| /__\ |
| / \ |
| / \ |
\_______/ \_______/
```
### Raindrops
A raindrop is denoted by a `.`. A raindrop is randomly placed on the glasses' lenses. So when a raindrop is placed, the glasses might look like this
```
________________________
| /__\ |
| . / \ |
| / \ |
\_______/ \_______/
```
If it is placed on a blank space (), an `.` is placed on the image. If it is placed on a square which already has a raindrop, the drop graduates.
The steps on drops are
* no drops placed:
* 1 drop placed: `.`
* 2 drops placed: `o`
* 3 drops placed: `O`
* 4+ drops placed: `@`
## Rules
* The image should **look** as though it stays in place. This means that you can either clear the screen or print enough newlines to "clear" the screen. You cannot return a list of steps. Sorry about this, but you should be able to work around that.
* When outputting newlines to "clear" the screen, you must have at least 3 newlines between the glasses.
* The code runs until the glasses are full of fully graduated drops i.e. until the output looks like this:
```
________________________
|@@@@@@@@@@/__\@@@@@@@@@@|
|@@@@@@@@@/ \@@@@@@@@@|
|@@@@@@@@/ \@@@@@@@@|
\_______/ \_______/
```
* Shortest code in *bytes* wins.
[Answer]
## JavaScript (ES6), ~~269~~ ~~267~~ 265 bytes
```
document.write('<pre id=o>')
a=[...` _8_8_8
| 9 /__\\ 9|
| 9/ 4\\ 9|
| 8/ 6\\ 8|
\\_7/ 8\\_7/`.replace(/.\d/g,s=>s[0].repeat(s[1]))]
s=" .oO@@"
g=_=>o.innerHTML=a.join``
f=(i=s.indexOf(a[j=Math.random()*a.length|0])+1)=>i?g(a[j]=s[i]):f()
g()
setInterval(f,1e3)
```
Edit: Saved ~~2~~ 4 bytes thanks to @Shaggy.
[Answer]
# Java 8, ~~449~~ ~~421~~ 420 bytes
```
v->{String q="########",g=" ________________________\n|##"+q+"/__\\##"+q+"|\n|#"+q+"/ \\#"+q+"|\n|"+q+"/ \\"+q+"|\n\\_______/ \\_______/\n\n\n";for(int t=0,n,x;g.matches("(?s).*[#\\.oO].*");Thread.sleep(150)){for(;(x=g.charAt(n=(int)(Math.random()*g.length())))!=35&x!=46&x!=111&x!=79;);g=t++>0?g.substring(0,n)+(x<36?".":x<47?"o":x<80?"@":"O")+g.substring(n+1):g;System.out.println(g.replace('#',' '));}}
```
-1 byte thanks to *@ceilingcat*.
**Explanation:**
[Try it here.](https://tio.run/##dZJbT8IwFIDf/RXHkkjLsEJEUGqdPvgIPpj44owpY3TT0c614Azw27GFeUmMp0kv3zltun19EUtxrItEvUxft3EujIGRyNTqACBTNilnIk5g7JcAS51NIcYPflgSsGmp3w3cVnFS2Ewr5oo2B64zVtgshjEo4LBdHl@t7m2ZKQlvHDXqQG3JETz/E5Fau5LgLUAnbhHV87XHe@qv4/g3/qGef@Eoqs@rMz73RVzWNcRmusTuS8HyTlu1KybpXNg4TQxGODSEth4bUUT13RNtIcLIytczXHFJ41SUNxYr7vcTPBI2paVQUz3HpCVpnihpU0xcHPLTs6PqkPf6vu92u34YXDDCJLdBcNUJJTWLidn9JezuQQJcXZ72Q0TRsLrsDUKk/eS8E6JrNER3iAS/d6igS4aS3X8Ym8ypXlhaOG5zhSUtkyJ3DnGz0Ww3oUkI22y2zGsqFpPcaapt7eTOnXq8l/X4BOKv4/1DUDTGapHnZK98s/0E) (`Thread.sleep` is removed so you instantly see the result.)
```
v->(){ // Method without empty unused parameter and no return-type
String q="########",g=" ________________________\n|##"+q+"/__\\##"+q+"|\n|#"+q+"/ \\#"+q+"|\n|"+q+"/ \\"+q+"|\n\\_______/ \\_______/\n\n\n";
// The glasses (with inner spaces replaced by '#')
for(int t=0,n,x; // Index integers
g.matches("(?s).*[#\\.oO].*");
// Loop (1) as long as the glasses still contain "#.oO"
Thread.sleep(150)){ // And sleep 150ms after each iteration to give the animation
for(; // Inner loop (2)
(x=g.charAt(n=(int)(Math.random()*g.length())))!=35&x!=46&x!=111&x!=79;
// To find the next '#', '.', 'o' or 'O' randomly
); // End of inner loop (2)
g=t++>0?? // Flag so it prints the initial glasses without a raindrop
g.substring(0,n)+(x<36?".":x<47?"o":x<80?"@":"O")+g.substring(n+1):g;
// Add a raindrop on this random position
System.out.println(g // And print the glasses
.replace('#',' ')); // After we've replaced '#' with spaces
} // End of loop (1)
} // End of method
```
**Output:**
NOTE: The dots are a bit weird in the gif, but that's a problem in my ScreenToGif.exe..
[](https://i.stack.imgur.com/WHxax.gif)
[Answer]
# Python 2, ~~365~~ 328 bytes
That's a bit better...
```
import time,random
g=' '+'_'*24+r"""
|xxX/__\Xxx|
|xX/ \Xx|
|X/ \X|
\_______/ \_______/""".replace('X','x'*8)
while 1:
print'\n'*3+g.replace('x',' ')
s='x.oO@@'
if all(c not in g for c in s[:-2]):exit()
i,c=random.choice([(i,s[s.index(j)+1])for i,j in enumerate(g)if j in s])
g=g[:i]+c+g[i+1:]
time.sleep(1)
```
[**Try it online**](https://repl.it/IPuU/2)
The above link uses 30 lines instead of 3, but you can see it with 3 if you resize your browser window to be small enough vertically. Change `time.sleep(1)` to `time.sleep(.1)` for 10x speed.
[Answer]
# F#, non-recursive ~~379~~ ~~414~~ 404 bytes
```
open System
let z=String.replicate
let mutable s,d=z 54" ",new Random()
while Seq.exists((<>)'@')s do printfn" %s\n|%s/__\\%s|\n|%s/ \\%s|\n|%s/%7s%s|\n\\_______/%9s_______/\n\n"(z 24"_")(s.[..9])(s.[10..19])(s.[20..28])(s.[29..37])(s.[38..45])"\\"(s.[46..53])"\\";Threading.Thread.Sleep(1000);d.Next54|>fun i->s<-(s.[i]|>function|' '->"."|'.'->"o"|'o'->"O"|_->"@")|>(fun c->s.Remove(i,1).Insert(i,c))
```
[Try it online!](https://tio.run/##Tc9Rb4IwEAfwdz9F04RAEzlBYWpU4utetkT2NgxhcM4m0DJapzN8d1bAJbuX/v7X3CV3Um4lhew6WaMg8Y/SWE1K1OS@i3XDxSc0WJc8zzQO7eqis48SiZoWuzsJA0roVOCVHDJRyMphk@uZm@8YvwBvXGnlONuI2XubKVJIUpuV@iQosVQiWkvN0jRJLNWOgZj6F62lGpwk6Vgza63@aNqCOncyD2hKmaPgHWB9HOB7AP7Dc@P56uE1wGI5erECCMIjo0lC@xw8AYSLMW/ezg1mRX/8KIhLxNrxPc9jmwJe8KbDoI1OF0G4G6mt22/gx6GTay5FaxPbjSjQ1oYe0kD2eKVtap49ZW3k9PO5mYcDVvIbHT71GTwLhY02zhnrul8 "F# (Mono) – Try It Online")
* -7 bytes thanks to @vzwick
+ by aliasing String.replicate
+ by opening System instead of referencing it every time
* -3 bytes by reducing the while loop to one line
I love the premise of this challenge :)
And thanks for the earworm.
# F#, ~~406~~ ~~441~~ ~~438~~ ~~437~~ 423 bytes
```
open System
let z=String.replicate
let s,d=z 54" ",new Random()
let rec(!)s=s="";printfn" %s\n|%s/__\\%s|\n|%s/ \\%s|\n|%s/%7s%s|\n\\_______/%9s_______/\n\n"(z 24"_")(s.[..9])(s.[10..19])(s.[20..28])(s.[29..37])(s.[38..45])"\\"(s.[46..53])"\\";Threading.Thread.Sleep(1000);if Seq.exists((<>)'@')s then d.Next 54|>fun i-> !((s.[i]|>function|' '->"."|'.'->"o"|'o'->"O"|_->"@")|>(fun c->s.Remove(i,1).Insert(i,c)))else()
!s
```
[Try it online!](https://tio.run/##TdBRa4MwEAfw932KNCAmUK/a2rWlU/q6lw3m3maRoucqaHRetnXF7@6idrB7ye9/4QK5nJyqVnXf1w0qFv2QxuquRM2uQaTbQr1Di01ZpCeNY5vmWXBla58zPlf4zV5OKqsrIcfLFlMxkxRQwPm@MdM6V5xZFKvOokWSxLFF3RSYqX/R2tDoOE6mWlg7@qNpKy6ubOnzhEtB8AawO47wXADv5qXxcnvzDmC1mbzaAvjro@RxzIfs3wOsV1Pev55bPGXDPydBVCI2wnNdV@6LnEX4AXgpSJMQD6G0D7Ykps9mVxk84UWbVXRh/qlY4YRsJob3i@PYSXVRq85mthNy4J0NA2qDesAz7xJzHLjsQjHMp05I8IJV/YWimHsSHhVhq41TKSWWhGbJM@r7Xw "F# (Mono) – Try It Online")
* -3 bytes by constraining s to string by comparing it with string
* -1 byte, function name is now "!" saving a single space when calling it
* -7 bytes thanks to @vzwick
+ by aliasing String.replicate
+ by opening System instead of referencing it every time
* -1 byte, no need for parenthesis when calling d.Next
* -6 bytes, function is now one line
# Explanation
```
open System
let z = String.replicate // define alias
let s, d = z 54 " ", new Random() // s holds a flat representation of the glasses.. glasses
let rec(!) s =
s=""; // type s to string
printfn" %s\n|%s/__\\%s|\n|%s/ \\%s|\n|%s/%7s%s|\n\\_______/%9s_______/\n\n"
(z 24 "_") // top of the glasses
(s.[..9]) // slice
(s.[10..19]) // and
(s.[20..28]) // dice
(s.[29..37]) // the
(s.[38..45]) // glasses
"\\" // \ gets prepended with 6 spaces thanks to %7s
(s.[46..53])
"\\"; // same deal, just 8 spaces this time
Threading.Thread.Sleep(1000);
if Seq.exists((<>)'@') s then // if not everything's totally covered
d.Next 54 // get new random int < 54 (string has indices 0-53)
|> fun i-> // passing is shorter than a let binding, saves two spaces and a new line
!( // call the function again with new drop on glasses
(s.[i] // get part of the glasses drop fell on
|>function
|' '->"." // promote drop
|'.'->"o"
|'o'->"O"
|_->"@")
|>(fun c-> s.Remove(i,1).Insert(i,c))) // and insert this in the string
else ()
!s
```
[Answer]
# C, ~~313~~ ~~309~~ ~~305~~ 304 bytes
Needs to be golfed down quite a bit;
```
c;f(r,q){for(char*m=" ________________________\n|**********/__\\**********|\n|*********/ \\*********|\n|********/ \\********|\n\\_______/ \\_______/\n";c<216;r=rand()%144,m-=135)for(system("clear");*m++;putchar(*m^42?*m:32))q=--r?*m:*m^42?*m^46?*m^111?*m^79?*m:64:79:111:46,c+=q!=*m,*m=q;}
```
I run it with the following test stub
```
main()
{
srand(time(0));
f();
}
```
[](https://i.stack.imgur.com/vDQjS.gif)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 237 224 228 218 206 198 197 bytes
```
g=" #{?_*24}
|x##/__ax##|
|x#/ ax#|
|x/ ax|
a#{u=?_*7}/xa#{u}/
".gsub ?x,?#*8;217.times{|t|puts g.tr('#a',' \\');()while t<216&&g[x=rand*106]!~/[#.oO]/;g[x]=g[x].tr '#.oO','.oO@';sleep 1}
```
[Try it online!](https://tio.run/nexus/ruby#HYzRCoIwGIXv9xTLgVMx1yQ0MLE36AFUZNlQwVR0kuDsrbu2rf/i/Oc7cM5exQZEa1I4/nkDckGIFAVTT2ogUJ0iDX@vSQKG1jlWlXAji/YbAQAYXjXND5gsboKcS@TT0BPNi0@rFHKYxQQrT4wWRgy7GGYZtiPLftdNy6G4@jQwzSpd4pF1T4eegvzwISny@ntOIpXnsRbVh1iHakHpDUdTy/kA6bbv364/lqys@Q8 "Ruby – TIO Nexus")
Previous answer was wrong, it did not take into account a raindrop falling on a @. Apparently not a requirement. Some bytes saved.
This terminates with an error thrown, but this definitely terminates as soon as the full glasses are printed.
* Saved 13 bytes by putting the printing into a lambda, and changing the assignment to use tr (duh)
* 8 bytes loss with the 1 second requirement.
* 10 bytes gain by using the gsub trick instead of interpolation (seen & adapted from [mbomb007's Python answer](https://codegolf.stackexchange.com/questions/122284/raindrops-are-falling-on-my-glasses/122557#122557)).
* 12 bytes gain by removing the lambda printing now that the print is written only once >.>
* 1 byte gain by making all the `\\` be `a`, then changing back inside the tr
* 7 byte gain by putting the changing the spaces on the last line with another `x` (duh). In case some of you guys are wondering why this doesn't affect the main loop : the main loop doesn't consider the last line to determine its `x`.
* 1 byte gain by removing the at the end of the top of the glasses
Yay < 200 bytes :D
Gif :
[](https://i.stack.imgur.com/Xj3kB.gif)
[Answer]
## Mathematica, 438 bytes
```
f=Flatten;p=Print;z=32;q=95;l=124;t=Table;v=z~t~8;s={f@{z,q~t~24,z},f@{124,z~t~10,47,q,q,92,z~t~10,l},f@{l,z~t~9,47,z~t~4,92,z~t~9,l},f@{l,v,47,z~t~6,92,v,l},f@{92,q~t~7,47,v,92,q~t~7,47}};c=0;Monitor[While[c<54,a=s[[i=RandomInteger@{2,4},j=RandomChoice[Range[2,13-i]~Join~Range[14+i,25]]]];If[a==z,s[[i,j]]=46,If[a==46,s[[i,j]]=111,If[a==111,s[[i,j]]=48,If[a==48,s[[i,j]]=64]]]];c=Count[Flatten@s,64];Pause@1],Column@FromCharacterCode@s]
```
here is a 10x speed result gif
[](https://i.stack.imgur.com/BjXYp.gif)
[Answer]
# Bash, ~~576~~ ~~510~~ ~~429~~ 416 Bytes
```
j()(IFS=
printf "$*")
for i in {53..0};{ a[$i]=
b[$i]=@;}
while(($i == 0));do clear
echo " ________________________
|`j ${a[@]::10}`/__\\`j ${a[@]:10:10}`|
|`j ${a[@]:20:9}`/ \\`j ${a[@]:29:9}`|
|`j ${a[@]:38:8}`/ \\`j ${a[@]:46}`|
\_______/ \_______/"
[ `j ${a[@]}` = `j ${b[@]}` ]&&{
i=1
}
sleep 1
d=`shuf -i0-53 -n1`
c=${a[$d]}
case $c in )a[$d]=.;;.)a[$d]=o;;o)a[$d]=0;;0)a[$d]=@;esac
done
```
Wow, golfed a lot. If anyone have any idea for further golfing, I'm open to suggestions
[Try it yourself!](https://tio.run/##ddDBaoNAEAbg@zzFYJegBe0am5K4LHgq9NyjEV11xQ2iQVt6MAu99EX7IlaNaZND5/TPz8eyTCq6chgOpmW@PL9yOLaqfivQIPeGBUXTokJVY7/xHIdq1qMIiYr49@cXpHMKmIaPUlXSNIlCzpFaFssbzCopWpBZ2SAaGP8zcEoOSHoRBpHvu1QnD3G83/91Lp3b07VbU383Qhznmq53U30jva2/XeStfXya5H75xAJGcikMCPFX6wT5eUvPW7Ra9aC4CxruukrKI7qQ86Qr3wu0FbU3Htq1m0DGpwdIHmnIRCeRZNMpx9NZc8sdxpwlNow1S6SM0SUGTHYig7yp5TD8AA) It has the sleep commented because of the 60 seconds limit
Here is the gif:
[](https://i.stack.imgur.com/snQlG.gif)
[Answer]
## Perl, 167 bytes
**Note that `\x1b` is a literal escape character.**
```
$_="\x1bc 24_
|10X/__\\10X|
|9X/4 \\9X|
|8X/6 \\8X|
\\7_/8 \\7_/
";s/\d+(.)/$1x$&/ge;do{$a[rand 54]++,sleep print s/X/($",".",o,O)[$a[$-++%54]]||"@"/ger}while grep$_<4,@a
```
[See it online!](https://asciinema.org/a/90ybDoChlx5kaznCUGTHKv5ZY)
[Answer]
# PHP, ~~262~~ 254 bytes
```
for($t=" 8_8_8_
|Y9Y/__\Y9Y|
|9Y/4 \9Y|
|8Y/6 \8Y|
\\7_/8 \\7_/";$c=$t[$i++];)$s.=$c<1?$c:str_repeat($t[$i++],$c);for(;$c=$s[++$k];)$c!=Y?:$s[$m[]=$k]=" ";for(;$u<216;print str_pad($s,999,"
",sleep(1)))$u+=($c=".oO@"[$a[$p=rand(0,53)]++])&&$s[$m[$p]]=$c;
```
Run with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/ea6ce8dcc4729cf3bc0781abd2e2cf9c6b085891).
**breakdown**
```
# prep 1: generate template from packed string
for($t=" 8_8_8_\n|Y9Y/__\Y9Y|\n|9Y/4 \9Y|\n|8Y/6 \8Y|\n\\7_/8 \\7_/";
$c=$t[$i++];)$s.=$c<1?$c:str_repeat($t[$i++],$c);
# prep 2: map substituted spaces and replace with real spaces
for(;$c=$s[++$k];)$c!=Y?:$s[$m[]=$k]=" ";
# loop until glasses are fully wet:
for(;$u<216;
# 4. print glasses prepended with 865 newlines
print str_pad($s,999,"\n",
# 3. wait 1 second
sleep(1)))
$u+=($c=".oO@"[
$a[$p=rand(0,53) # 1. pick random position
]++]) # 2. and increment
&&$s[$m[$p]]=$c # if not fully wet, graduate drop
; # and increment drop count ($u+=)
```
] |
[Question]
[
**This is a good beginner challenge and a good time killer.**
*I only said a -natural- log because the title was too short, this has nothing to do with logarithms.*
Given 2 variables:
* The number of ants `n`.
* The width of the log `w`.
Output a log of width `w` with `n` ants (Example shown `w=3`, `n=6`)
```
| |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
| ^ ^ ^ |
| |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
| ^ ^ ^ |
| |
```
A single ant looks like this:
```
\O/ # Upper-case O
-O- # Upper-case O
/o\ # Lower-case o
^
```
***A few ant laws:***
1. Ants may not touch each other nor the edge of the log directly, they
prefer to touch spaces.
2. Each row of ants must be `w` wide, with `n/w` rows of ants.
3. Ants always need a log, the log width is greater than 0, guaranteed.
4. Ants also... well, need ants, the number of ants is greater than 0, guaranteed.
5. Ants are also surprisingly well organized, they will fill a log from left to right, top to bottom; as if they were reading a book.
***Ant-xamples***
**w=3, n=5**
```
| |
| \O/ \O/ \O/ |
| -O- -O- -O- |
| /o\ /o\ /o\ |
| ^ ^ ^ |
| |
| \O/ \O/ |
| -O- -O- |
| /o\ /o\ |
| ^ ^ |
| |
```
**w=1, n=1**
```
| |
| \O/ |
| -O- |
| /o\ |
| ^ |
| |
```
**w=1, n=3**
```
| |
| \O/ |
| -O- |
| /o\ |
| ^ |
| |
| \O/ |
| -O- |
| /o\ |
| ^ |
| |
| \O/ |
| -O- |
| /o\ |
| ^ |
| |
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the person with the smallest bytecount wins.
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~70~~, 68 bytes
```
i \O/
-O-
/o\
^ Àä{ò@bf }C GïpòÇÓ/d
HÄÒ çÞ/ÙÒ
ëI|yê$p
```
[Try it online!](https://tio.run/nexus/v#@5@pEOOvr8CloOuvCyT182OApEKcgoL04YbDS8SqD29ySEpTEKt1VpB2P7y@4PCmw@2HJ@uncHkcbjk8SeHw8sPz9A/PBLK4xA6v9qyRrjy8SqXg////hgb/jQE "V – TIO Nexus")
```
00000000: 6920 5c4f 2f20 0a20 2d4f 2d20 0a20 2f6f i \O/ . -O- . /o
00000010: 5c20 0a20 205e 2020 1bc0 e416 7bf2 4062 \ . ^ ....{.@b
00000020: 6620 167d 4320 1b47 ef70 f2c7 d32f 640a f .}C .G.p.../d.
00000030: 48c4 d220 e7de 2fd9 d220 0a16 eb49 7c1b H.. ../.. ...I|.
00000040: 79ea 2470 y.$p
```
This has never happened to me before, but [a known bug](https://github.com/DJMcMayhem/V/issues/7) has actually saved me bytes!
It's kinda hard to explain exactly what's going on, but unfortunately when you try to duplicate something by columns, V will move one column over before duplicating. Which is why originally I did:
```
h<C-v>{dÀp
```
which doesn't use the duplicate operator. However, because we already needed to move one line over, we can simply do
```
hÀä<C-v>{
```
[Answer]
# PHP>=7.1, 150 Bytes
```
for([,$w,$n]=$argv;$i<ceil($n/$w)*5+1;)echo str_pad("| ".str_repeat(["","\O/ ","-O- ","/o\ "," ^ "][$i%5],$n<$w*ceil($i++/5)?$n%$w:$w),$w*4+2)."|\n";
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/75a0070ae76a9a73d92650599cdcc2f4f91dca4d)
[Answer]
# Python 2, 144 bytes
```
n,w=input()
s=' ';k='|';a=k+s*w*4+s+k;print a
while n>0:
for i in['\\O/','-O-','/o\\',' ^ ']:print k+s+(i+s)*min(w,n)+s*4*(w-n)+k
n-=w;print a
```
[Try it Online!](https://tio.run/nexus/python2#NY07DsIwEER7n2K79VdBIjSxnCvkABikFCBWhk0UB7nh7sYSopmZ5r2pbEsgXt@7VCIHBPQp4Af9HJLJuujeZJP8uhHvMIvyoOcNeDwMAu7LBgTEZ4xx6tCim1zLbomxFVwBL8OPayYjyWSlX8SyWFZN3WtZXFtJALtQ/he1niwcvw)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~44~~ 43 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
*Crossed out 44 is not 44 with use of* ` `
```
⁶ṁ;⁶jЀ“\-/“OOo^ ”;UṖz⁶¤Y
sÇ€⁶;YỴz⁶Zj@€⁾||Y
```
**[Try it online!](https://tio.run/nexus/jelly#@/@ocdvDnY3WQCrr8IRHTWseNcyJ0dUHkv7@@XEKjxrmWoc@3DmtCih/aEkkV/HhdpCaxm3WkQ93bwGJRmU5gEX21dRE/v//39DovykA)**
### How?
```
⁶ṁ;⁶jЀ“\-/“OOo^ ”;UṖz⁶¤Y - Link 1, make a row of ants: list x (could be integer = length)
⁶ - literal ' '
ṁ - mould like x (makes a list of that many spaces)
;⁶ - concatenate one more space
¤ - nilad followed by link(s) as a nilad
“\-/“OOo^ ” - literal ["\-/","OOo^ "] ("..." a list of chars really)
U - reverse each [" ^oOO","/-\"]
; - concatenate ["\-/","OOo^ "," ^oOO","/-\"]
Ṗ - pop ["\-/","OOo^ "," ^oOO"]
⁶ - literal ' '
z - transpose & fill ["\O/","-O-","/o\"," ^ "," "]
jЀ - join left mapped over right
- (join the spaces with each of the ant parts in turn)
Y - join with newlines
sÇ€⁶;YỴz⁶Zj@€⁾||Y - Main link: n, w
s - split n into chunks of length w (implicitly makes a range of length n)
Ç€ - call the last link (1) as a monad for €ach
⁶; - a space concatenated with that
Y - join with newlines
Ỵ - split at newlines (both the ones we just joined with AND the others!)
z⁶ - transpose & fill with space characters (making the shorter rows,
- including the single space as long as the longest one)
Z - transpose it back the right way
⁾|| - literal ['|','|']
j@€ - join with reverse arguments for €ach (put each row between pipes)
Y - join back up with newlines
- implicit print
```
---
I have asked about `w<n` in [a comment](https://codegolf.stackexchange.com/questions/117268/ants-on-a-natural-log#comment286753_117268) since it's slightly ambiguous.
If the log needs to be `w` ants wide rather than just the ants being `w` wide, it costs two bytes:
```
⁶ṁ;⁶jЀ“\-/“OOo^ ”;UṖz⁶¤Y
+RsÇ€YỴz⁶Zj@€⁾||ṫ5Y
```
This does the same as before except rather than prepending a single space to make the first, blank line it creates a whole extra row of ants and chops off all but its trailing blank line.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 47 bytes
```
" \O/-O-/o\ ^ "5äðìI.D)IôvyøJ'|ì})˜¬¸«.B„ |«»
```
[Try it online!](https://tio.run/nexus/05ab1e#AUMAvP//IiAgIFxPLy1PLS9vXCBeICI1w6TDsMOsSS5EKUnDtHZ5w7hKJ3zDrH0py5zCrMK4wqsuQuKAniB8wqvCu///NQoz "05AB1E – TIO Nexus")
**Explanation**
```
" \O/-O-/o\ ^ " # push the ant-string
5ä # split into 5 parts
ðì # prepend a space to each
I.D # copy input-1 number of times
) # wrap in a list
Iô # split into parts each the size of input-2
v # for each row of ants
yø # zip, so body parts are on the same row
J'|ì # join to string and prepend a pipe to each
} # end loop
)˜ # wrap in a flattened list
¬¸« # append a copy of the first row (spaces)
.B # pad rows to equal length with spaces
„ |« # append " |" to each row
» # merge on newlines
```
[Answer]
# [SOGL](https://github.com/dzaima/SOGL), ~~74~~ ~~71~~ 74 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
|pe4*I@*o |o→L:"╔O¦‘2n;"nΤ↕¬┐α┐PΝld‘*┼eG-’⁵@**┼ |4*┼OL→ALbe÷:?{eA}}be%:?A
```
First part: function which outputs an empty log part
```
→L define function L
|p output in a newline "|"
e4* multiply width by 4
I increace that
@* get that many spaces
o append [to current line] that
|o append "|"
```
The second part has a compressed string `"nΤ↕¬┐α┐PΝld‘`, which is the ant. It decompresses to `\-/ OOo^/-\` .
That's the ant (with spacing to the right), but taken top-to-down then to right like
```
159d
26ae
37bf
48cg
```
It's stored like that because the `┼` function appends strings like that (that's because then you can multiply the string to add multiple instances to it).
The part itself: function which asks for a number on stack denoting how many ants to draw.
```
Example input: width 3, on stack 2
: duplicate the input [2,2]
"╔O¦‘ push "| | | | " [2,2,"| | | | "]
2n split into chunks of two [2,2,["| ","| ","| ","| "]]
; put one of the input copies ontop of the stack [2,["| ","| ","| ","| "], 2]
"...‘* multiply that many ants [2,["| ","| ","| ","| "], "\\-/ OOo^/-\\ \\-/ OOo^/-\\ "]
┼ add horizontally the ants ["| \O/ \O/ \O/ ",
"| -O- -O- -O- ",
"| /o\ /o\ /o\ ",
"| ^ ^ ^ "]
e get the width [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "| ^ ^ ^ "], 3]
G- subtract input from it [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "| ^ ^ ^ "], 1]
’⁵@* push 16 spaces [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "| ^ ^ ^ "], 1, " "]
* multiply [the 16 spaces and empty place count] [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "| ^ ^ ^ "], " "]
┼ add that horizontally [["| \\O/ \\O/ \\O/ ", "| -O- -O- -O- ", "| /o\\ /o\\ /o\\ ", "| ^ ^ ^ "]]
|4*┼ add 4 vertical bars to the array [["| \\O/ \\O/ \\O/ |", "| -O- -O- -O- |", "| /o\\ /o\\ /o\\ |", "| ^ ^ ^ |"]]
O output the array []
L call the empty line function []
→A define as A
```
And the main function:
```
L call the empty line drawing function
be÷ push floor(b/e) (the amount of full lines)
:?{eA}} that many times call A with the full width on the stack
be% push b%e (the leftovers)
:? if truthy (aka !=0)
A call A with for the leftovers
```
[Answer]
# [Perl 5](https://www.perl.org/), 159 bytes
```
($w,$n)=@ARGV;
print
$_%$w?"":"| ",
[' \O/-O-/o\\ ^ '=~/.../g]->[($_<5*$w*int$n/$w||$_%$w<$n%$w?$_/$w:0)%5],
($_+1)%$w?" ":" |\n"
for 0..$w*(6+5*int(($n-1)/$w))-1
```
[Try it online!](https://tio.run/nexus/perl5#HUzNCsIwGHuVUgKf03XTKQjW@nPyOPDgqSgdCm7o5xChHvrutTOHhIQkcQSfgzOz2x8PJ43GkKBvCseLySzT6AyckcFykPrpenTFUCgkLkIOtTV4C79KDwWJhP9WDRYuJ2vrknJStUpcvqxNIs6CHF/BysALf28fN/Bmqvt3yx8Z0KBDE2SMsarifPkD "Perl 5 – TIO Nexus")
# [Perl 5](https://www.perl.org/), 152 bytes
Another one based on the Python solution:
```
($w,$n)=@ARGV;
$b=' 'x($w*4+1);$j=$a="|\n|";
map$j.=' '."$_ "x($w<$n?$w:$n).' 'x($w-$n).$a,'\\O/','-O-','/o\\',' ^ 'and$n-=$w
while$n>0;
print"|$b$j$b|"
```
[Try it online!](https://tio.run/nexus/perl5#HUzNCsIwGHuVUgKf03XTKQjW@nPyOPDgqSgdCm7o5xChHvrutTOHhIQkcQSfgzOz2x8PJ43GkKBvCseLySzT6AyckcFykPrpenTFUCgkLkIOtTV4C79KDwWJhP9WDRYuJ2vrknJStUpcvqxNIs6CHF/BysALf28fN/Bmqvt3yx8Z0KBDE2SMsarifPkD "Perl 5 – TIO Nexus")
[Answer]
## Mathematica 210 Bytes
```
StringRiffle[If[#2==c||#2==1,"|",If[r-#1<6&>2+4 (a+w-h w),Table[" ",5,4],Characters@" \\O/ -O- /o\\ ^ "~Partition~4][[1+Mod[#1-1,5],1+Mod[#2+1,4]]]]&~Array~{r=5(h=⌈(a=#)/(w=#2)⌉)+1,c=4w+3},"\n",""]&
```
Thinking I need to make a Mathematica based golfing language.
[Answer]
## Python 2, 166 bytes
```
w,n=input()
print'\n'.join(['|'+' '*w*4+' |']+[' '.join(['|']+[p]*r+[' ']*(w-r)+['|'])for r in[w]*(n/w)+[[],[n%w]][n%w>0] for p in['\O/','-O-','/o\\',' ^ ',' ']])
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 43 bytes
```
NθF⪪× Nθ«←P↓⁶M⊗⊕⊗θ→P↓⁶⸿E⪪\O/-O-/o\ ^ ³⭆ι⁺μκ
```
[Try it online!](https://tio.run/##fY49D4IwEIZn@RWXTm1S4kB0wNWFRJSoIzFBLNjYDywtDsbfXovR6OR29@a55976XJlaV8L7THXOrp08MoOvZBE12gDedYJbvOeS9RgBovBLEULhSgjco0muB4bTFWtsuJzkTljeGa4sTpf6pijMX/EILbU7CnbCmaoNk0zZMH@yIAvKdMvb8z9P8UpQadB3y6vuXRaVm2m8iae6hMPYOAnKnQ1QOzKcQiFcjyWFS/gWBA/vk2jm40E8AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `w`.
```
F⪪× Nθ«
```
Input `n`, then create a string of `n` spaces and split it into rows of length `w` (except the last piece which may be smaller). Loop over those rows.
```
←P↓⁶M⊗⊕⊗θ→P↓⁶⸿
```
Print the sides of the log section.
```
\O/-O-/o\ ^ Literal string
⪪ ³ Split into (4) pieces of length 3
E Map over each piece
⭆ι Map over each row space
⁺μκ Appending the piece
Implicitly print the results on separate lines
```
] |
[Question]
[
[Brachylog](https://github.com/JCumin/Brachylog) is a language that's beginning to rise in prominence in code-golfing recently (and just received a major update with a terser syntax). Like Prolog, it has the advantage that it can often solve a problem (typically via brute force) merely from a sufficiently accurate description of what a problem looks like, a feature that means that on the right sort of challenge, it's often comparable to the top golfing languages (and has been known to beat Jelly from time to time).
What tips do you have for golfing (i.e. writing the shortest possible programs in) Brachylog? This is mostly looking for advice that's specific to Brachylog in particular, rather than advice that's applicable to a wide range of languages. (Tips about golfing in declarative languages in general might potentially be appropriate here, depending on how much application they'll have to languages other than Brachylog, although see also [Tips for golfing in Prolog](https://codegolf.stackexchange.com/q/67023/62131).)
[Answer]
# Exploit nested predicates to create new variables
Brachylog has lots of special syntax cases to make its two special variables, `?` (input / left parameter) and `.` (output / right parameter), terser to use. This means that if you don't need to access your predicate's `?` and `.`, but do need to use variables, you can often save bytes via creating a nested predicate to use *its* `?` and `.`.
As a simple example, consider a program that looks like this:
```
… A … ∧A … B … B …
```
This is a pretty common shape for a longer program; after all, there are lots of gaps that could contain anything. Suppose we have no need for `?` or `.` inside the centre three gaps. Then we could rewrite it like this:
```
… { … & … . … } …
```
Here, the nested predicate's `?` is serving the role of `A`, and its `.` is serving the role of `B`. We can observe that this is a byte shorter than the original code; changing `AABB` to `{?.}` has no change in terms of bytes, but this allowed us to simplify `∧?` to the abbreviation `&`.
A related trick is to change
```
∧. … ?∧
```
to
```
~{ … }
```
(which is one byte shorter), although note that it's nearly always cheaper to get the caller to exchange the arguments instead (unless the predicate is called from at least three different places in the program, which is rare in Brachylog).
[Answer]
# Split up length-2 predicates inside metapredicates
This is best explained by example. To remove the first and last elements of a list, we behead and knife it:
```
bk
```
If we wanted to perform this operation on every element of a list, we can use a map operation:
```
{bk}ᵐ
```
However, it's a byte shorter to split the predicate into two, and map each part separately:
```
bᵐkᵐ
```
The same trick can be used with quite a few metapredicates:
```
{bk}ᵐ → bᵐkᵐ
{bk}ˢ → bˢkˢ
{bk}ᶠ → bᶠkˢ
~{bk} → ~k~b
```
Note that for some metapredicates, like `ᵘ`, there's no general-purpose way to split it into two parts, but it may nonetheless be possible to find a decomposition that works for the specific task you're working on.
[Answer]
# We do have an increment builtin... sometimes!
`+₁` is the only *reliable* way to add 1 to something. However, under many circumstances, `<` does the job for a byte less--its output must be strictly greater than its input, so in the absence of external complications, its output will be the integer strictly greater than its input with the least absolute value.
Of course, this substitution can and will fall apart should further logic be employed, as well as in the case of non-integers (which are ceiled) and negative integers (which produce 0).
[Answer]
# `s` isn't longest first, but `⊇` is
I wanted to title this "(Ab)use all choice orders at your disposal", but I couldn't think of any other cases of note.
Sometimes choice order is pretty important. Sometimes the choice order your program already has is precisely what you need, just as often it's not; in the case of `s` generating substrings in the order of largest-first prefixes of largest-first suffixes, it's not infrequent that you might wish it was simply largest first instead. Fortunately, `⊇` generates its sublists longest first, where every possible substring is included--there's just some other stuff you also don't want. However, `s`'s choice order is no problem at all if you're using it to check substring existence, in a program structured something like `⊇. [...] &s`.
[Answer]
# Casting the empty list to the empty string
Sometimes, when working with strings, the algorithm we use might unify what we want with the empty list `[]`, when we would rather want the empty string `""`.
We can cast the empty list to the empty string using `,Ẹ`, which appends the empty string to its left variable (this is an exploit of the way `,` is implemented).
This also has the benefit that it does not do anything if the left variable is a string. So, if your program is
```
{
some predicate that should always output a string,
but actually outputs [] instead of "" in specific cases
}
```
Then
```
{
some predicate that should always output a string,
but actually outputs [] instead of "" in specific cases
},Ẹ
```
will work the way you want.
[Answer]
# Single-element runs in a list
Consider this snippet:
```
ḅ∋≠
```
If the input is a list or string, the output is unified with a sublist/substring of length 1 that's not part of a longer run of equal elements.
It splits the list into blocks of equal elements and finds a block whose elements are all different.
To get the elements themselves instead of singleton lists, tack `h` to the end.
I used this construct [here](https://codegolf.stackexchange.com/a/149460/32014) with `o` to find a character that occurs only once in the input string.
[Answer]
# Failing on empty lists
Empty lists can come up often, and sometimes you need to fail when you see one. The obvious means to do so may be `¬Ė`, or even `l>0`, but there exist quite a few one-byte alternatives:
* `b`
* `k`
* `h`
* `t`
* `∋`
* `z`
just off the top of my head. What inspired me to write this out is actually the discovery of a less obvious failure on an empty list: the metapredicate `ⁿ`, which one might expect to be vacuously successful on an empty input, [fails instead](https://codegolf.stackexchange.com/a/205397/85334). Metapredicates which produce failure on an empty list:
* `ⁿ`
* `ᵛ`
* `ᵉ`
* `ᵈ` (any list of length other than 2)
* `ʰ`
* `ᵗ`
The general idea to take away from this is that a lot of Brachylog's builtins that seem like they're just to produce an output from an input don't necessarily have an output for every conceivable input, which is more to our advantage than it is detrimental, and is (...usually) easy to think about once you're aware of it.
] |
[Question]
[
A friend of yours has given you directions to the best restaurant in town. It's a series of left and right turns. Unfortunately, they forgot to mention for how long you need to go straight ahead between those turns. Luckily you have a street map with all the restaurants on it. Maybe you can figure out which restaurant they meant?
## Input
The map is given as a rectangular grid of ASCII characters. `.` is a road, `#` is a building, `A` to `Z` are the various restaurants. You start in the top left corner, going east. Example:
```
.....A
.#.###
B....C
##.#.#
D....E
##F###
```
Your friend's instructions will be given as a (potentially empty) string or list of characters containing `L`s and `R`s.
## Output
You can walk any path that corresponds to the left and right turns in the input string, provided that you take at least one step forward before each of them, as well as at the end. In particular this means if the string starts with `R` you cannot go south immediately in the left-most column. It also means you can't turn around 180° on the spot.
You cannot walk through buildings or restaurants except the one you reach at the end. You may assume that the top left corner is a `.`.
You should output all the restaurants that can be reached with your friend's instructions, as a string or list.
You may assume that the instructions will lead to at least one restaurant. E.g. a single `L` would be invalid for the above map.
Some examples for the above map:
```
<empty> A
R F
RR B,D
RL C,E
RLRL E
RLLR C
RLLL B
RLRR D
RLRRRR A,C
RLLLRLL B
```
Note in particular that `R` doesn't reach `B`.
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Additional Test Cases
Here is a larger map, courtesy of [Conor O'Brien](https://codegolf.stackexchange.com/users/31957/c%E1%B4%8F%C9%B4%E1%B4%8F%CA%80-ob%CA%80%C9%AA%E1%B4%87%C9%B4) (which I modified a bit):
```
.......Y..........................######
.####.....#.##....##..######....#.###.##
B.........#.##.#..##....##...##.#.#P...#
.#.#####..#.##..#.##....##.#....#.####.#
.#.#...C..#.##...G##..#.##.#....#.#....#
.#.#.#.#..#.####.###.#..##.#....#.#.NO.#
.#.#A#.#..#.##...F###...##.#.##.#......#
.#.###....#.##....##....##.#....###....#
.#.....##...##....##...D##........###R.#
.#.##..##...##E...##..######....####...#
.....X....#.#.....................##S.T#
###########.###########M############...#
#................................###.#.#
#.#########.########.######.#.######.#.#
#......V#.....######.IJ...........##.#.#
#########.###......ZH############L##.#.#
#########.##########.###############.#.#
####K##...##########.#....#..........#.#
####....########U......##...#######Q.#.#
#####################################W.#
```
And here are a few selected lists of directions and their expected results:
```
<empty> Y
RR B
RLL Y
RLRR B,C,X
RLLLRRR G
RLRLRLRL I,Z
RLLRRRLRRLRR C,D,F,G,Y
RLRRLLRLLLRL B,C,Y
RLLRRLRRRLLLL F,M,N,O,Y
RLRRLLLRRRRLLLL F,M,Y
RLRRLRRRRRRRRRR E,F,Y
RLRRRLLLRLLRRLL M,N,O
RLLRRLRRLRLRLRRLLR E,U
RLRLLRLRRLRRRRRLRL F,G,I,Z
RLLRRLLRLLRRRLRRLLRR W
RLLLRRRLRRLLLLLRLLLLLL D,G,X
RLRLLRLRRLRLRRRLRLLLRR B,C,E,J,X
RLRLRLLLLRLRRRRRRLRLRRLR Y
RLRLRRRLRLLLLRLRRLLLLRLLRRL E,M,X
RLRLLLRRRLLLRLLRLLRLRRLRLRR B,E,F,K
RLRRRLLLLLLLLLLLLLLLRRRRLLL A,B
```
Bonus question: is there an input that results in *only* `I` *or only* `U`? If so, what's the shortest such path?
[Answer]
# Perl, ~~150~~ ~~149~~ ~~146~~ ~~145~~ ~~141~~ ~~140~~ ~~138~~ ~~136~~ ~~135~~ ~~133~~ ~~130~~ ~~126~~ ~~125~~ 124
Added +7 for -F -Xn0i
An initial attempt.
Run with the map on STDIN and the directions after the -i option, e.g.
```
perl -F -Xn0iRL incomplete.pl
.....A
.#.###
B....C
##.#.#
D....E
##F###
```
Close STDIN with `^D` or `^Z` or whatever works on your operating system.
`incomplete.pl`:
```
%P=0;$^I=~s``{%;=!/
/;%P=map{$_|=$F[$^H=$_+=(1,@+,-1,"-@+")[$d&3]]=~/(\w)|#|^$/*~!\$;{$1}}(%P)x@F}$d-=B&$'^u`eg;print%
```
Replace the ^H by the literal control character to get the given score
Bonus question:
* There is no input that results in only `I`
* The shortest input that results in only `U` is `RLLRRLLRLRLRRLRRLRLRLRRLLR`
* The longest input needed to result in a unique set is `RLLRRRLRLRLLLRRLRLLLLLRRRLLRRRLLLLLLLRRLRRRR` which gives `B O R`
[Answer]
# Python 2, ~~180~~ ~~177~~ ~~168~~ ~~163~~ ~~161~~ 158 bytes
```
def a(v,o,c=0,A=0,d='.',O={0}):
while'.'==d:w=v.find('\n');c+=[1,~w,-1,w+1][A%4];d=v[c];o>v<a(v+' '*w,o[1:],c,ord(o[0])-~A,d);d>v>o<O.add(d)
return`O`[9::5]
```
Parameter `v` is the map as a string; `o` is the `LR` string.
Mitch Schwartz saved ~~2~~ ~~3~~ ~~10~~ lots of bytes. Thanks!
I saved two bytes by setting `O={0}` and returning ``O`[9::5]`, which might not be very portable: it assumes that `hash(0) == 0`, I think, because that causes the order of elements in `repr(O)` to be
```
set([0, 'A', 'B', 'C'])
```
and creatively slicing that string gets me the answer.
[Answer]
# C++ 364
**Thanks to @ceilingcat for finding a much better (and shorter) version**
```
#import<bits/stdc++.h>
#define M m[y][x]
using namespace std;vector<string>m;char n[99],j;int r(int x,int y,char*d,int z){for(;z%2?y+=z-2:(x-=z-1),y>=0&y<m.size()&x>=0&&m[y][x]&&!*d|M==46&&(!*d?n[M]+=M>64&M<91,M==46:!r(x,y,d+1,z+(*d-82?*d==76:3)&3)););}main(int c,char**v){for(string l;getline(cin,l);)m.push_back(l);for(r(0,0,v[1],0);j<99;j++)n[j]&&cout<<j<<" ";}
```
[Try it online!](https://tio.run/##LZBdb4IwFIbv@RVMsqaFwkCNG7Zo9nk1brwlZMGCWiaFABpg87ezVncuTvvkPSd5WlZV9p6xcTR4UZV1S7e8bR6aNmWW5RxWmpFmOy4yPdSLqI@jLtZODRd7XSRF1lQJy3Q5S84Za8uaNm0ts1VB2CGpdRH5foxzwkWr11D1DqveYxWb6RUG9LMra0iG@@m6t4LBni5hZ8vTQ7hfBS7oaeE0fMggAp1i8O8BwJ2Z/oZBMF8AAOV9LaIwtoJwtZiDkPoevmbLuxp2uMep5eHBgmZqP03XZhoEj4vlDIEZQgSRS5FwcTVkNzfzfNO6PUg/kn3WHuU3QMYFPsqVwqlOzeFrm7BvKFnN1tDFLj5HXoxdRHLq@yS3LCSiXLqy8tRSmlM60SfkMo6OqmfNMRzDMLQXRa@aYSjW3hS9S/qQ2bj53Mj6Aw "C++ (gcc) – Try It Online")
[Answer]
# Haskell, 257 bytes
```
import Data.List
t=transpose
r=reverse
l=length
f(m,x,y)=[(m,n,y)|n<-[x+1..l(m!!0)-1],notElem '#'[m!!y!!z|z<-[x..n]]]
i!c=[last$(t.r$m,l m-y-1,x):[(r.t$m,y,l(m!!0)-x-1)|c/='L']|(m,x,y)<-i>>=f]
m#i=intersect['A'..'Z'][a!!y!!x|(a,x,y)<-foldl(!)[(m,0,0)]i>>=f]
```
[Try it Online!](https://tio.run/##NY5Rb4MgEMff/RRaTIAMWX1dSpNu7Z588nGEB@LsSgZokCza@N0dWEtyd39@ufvf3eTw22q9LMr0nfPpWXpJKzX4xDPvpB36bmgTx1z717qgNNOt/fG35IoMGcmEGQ/CBjHbQ8HHl5JSjUyW7XFRCmI7f9GtSSGAPMApy@7zPfZRaoUQicoaxrUcfI48dbkhOjXFVJRkxG8cOeoDmsjTcCxKPDevDFZQzNv@Q6GOR3YViQGKKevjlY3n8AQphV9QcLmuHWckt/5rp781ynA8fE/2WDwMFiOVTVnau@CSIyN7hABO@Y7Gd9qRHQUUABDEeyQfQQAQWRDnSC4r@Yw9Ig6Gbx1jTdWatlI9ULXBeiv1E4cIFss/)
Calling `m#i` for a map `m` with a list of instructions `i` outputs the possible restaurants.
[Answer]
# Python3, 333 bytes:
```
m,n={1:{0:3,1:4},2:{0:4,1:3},3:{0:2,1:1},4:{0:1,1:2}},{1:(0,1),2:(0,-1),3:(1,0),4:(-1,0)}
def f(b,p,x,y,d):
try:
if b[x][y]=='.':
x+=n[d][0];y+=n[d][1]
if 64<ord(r:=b[x][y])<91 and not p:yield r
if x>=0and y>=0:yield from f(b,p,x,y,d);yield from f(b,p[1:],x,y,m[d][p[0]=='L'])
except:1
q=lambda b,p:set(f(b,p,0,0,1))
```
[Try it online!](https://tio.run/##lVRrb5swFP3uX2HFHzCbY0ESTRstk7r1sQfrNvYeQ1MyQENKgIInBVX89szGBpwspdqNYo59DsfX1zZFzX7n2fxxUe52G5K5t7ZzazlzYjuLhswEXnA8b8hc4BnHdkMWAtscz5qG8DewRWyTq/lzysHcwTaxTC7DUwEaEMUJTPCKFGRLahKZDoCsrHkLYZrAVbANgzp0XYMa7RjcPnSzIAoDKzypFbTDluHyR4vTvIxw6bjqRfP0iQ2XWQSznMHCqdN4HcGyk2@fupYga/5UXFLmm718Tg7HA9sJW24j5i54Ijw7zwhNAOPtr7hgjg1u3PVys4qWkOudKmZYOlpEVMPcVe5kMgFUxBmgiCKEwDPRew4QEn1wLnoXvHfJOSEWZWL5z1W@5OvjVSpj9qfMYLBOK4ZTM8lLmMI0g0m6ZnGJr/MsJrCiVbFOGTZ@ZIZphgAUZZoxfIN7p8okBqeOE/7dzAjljVCjpDdm6o3a@qOkP27s697G1Hgws0ygbRGl3@idgdoA7VMOUAlEK8luVPzlNg9CRDW5HEDvBFLHonWhQ6s0nSNSQnF0eslVL@@EtHeUve7dPoFeeP1WCc96IWcukZaeUg85Hq5ac0TD1Poiu/Zc1UxK/c6xF178W0eVidyZr9r6juzMB/oRATQE1fAbpBPCEdF7Aqm7qfnQA0B10Dl@RtpJoS9f7VlKoW4jme8v9AS9Y8Ijqxqm5vFaVVEj2nLpJxDohRXxieo71cb7/anH4gsXinvzn98ZT/5Gvw2@uMn33fT2Mkun3V8)
] |
[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 1 year ago.
[Improve this question](/posts/12188/edit)
I hope this kind of "riddle" is ontopic in Programming Puzzles & Code Golf.
Give an example of a situation where the C# method below ***returns `false`***:
```
public class Giraffe : Animal
{
public bool Test()
{
return this is Giraffe;
}
}
```
Rules: The code lines above must not be changed in any way, but you would put the code into an application so that the "project" compiles and the method is called. When run, the method must return `false`. The solution I have in mind, does not emit its own IL at run-time or similar "exotic" things, it's an ordinary instance method call.
[Answer]
Yay, found it!
```
public class Animal
{
public class Giraffe { } // 1
}
public class Giraffe : Animal // 2
{
public bool Test()
{
return this is Giraffe;
}
}
```
Since `Giraffe 1` is a member of `Animal`, and `Giraffe 2` is one level further out, the name `Giraffe` in the `is` test refers to the former (section 7.6.2 in the C# 5 spec).
Visual Studio shows a warning for `this is Giraffe`:
>
> The given expression is never of the provided type
>
>
>
which is obviously true, since it's the whole point :)
You cannot put `Giraffe 1` directly inside `Giraffe 2`, because
>
> member names cannot be the same as their enclosing type
>
>
>
– but such a rule does not exist for derived classes.
Neat problem, took me a while.
] |
[Question]
[
In chess, the queen piece can move arbitrarily far in each cardinal and intercardinal direction. What does this mean? Well, I'll show you with an ASCII drawing:
```
\..|../
.\.|./.
..\|/..
---Q---
../|\..
./.|.\.
/..|..\
```
It means the queen (notated as `Q`) can move along these lines (notated as `\`, `|`, `/`, and `-`), and cannot reach the other spaces (notated as `.`). The `|`s extend from the queen vertically, the `-`s horizontally, and the `\/`s diagonally.
However, I've quickly lost interest in chess and am more fixated on the diagram itself;
How many different symbols are contained within the 3x3 region centered on any given square? One way to visualize this would be to replace the symbols with this value, shown below:
```
2232322
2234322
3356533
2465642
3356533
2234322
2232322
```
Why? Well, for example:
The queen square has value 5 because the 3x3 region centered on the queen looks like this:
```
\|/
-Q-
/|\
```
Where we can see 5 distinct symbols: `\|/-Q`.
The top left square has value 2 because the 3x3 region around that square looks like this:
```
\.
.\
```
Where we can see 2 distinct symbols: `\.`. Anything beyond the board is not a symbol, so those space characters I've included for visualization purposes don't count.
## Challenge:
Given the queen's position on an MxN board, output the number of unique symbols contained within the 3x3 region around each square, based on the queen movement diagram which would be generated. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest wins :)
## Rules:
* Standard I/O rules apply, any format to represent the grid size and the queen's position is fine in whatever order / format, and output can be plain text or a list of strings or whatever.
* Since any given cell can only see up to 6 different symbols, digits on a line do not need to be delimited in any way. Lines, however, must be clearly delimited, as the board is not necessarily square.
* 0 indexing is allowed.
* Input will always be valid; Board will always be at least 1 unit wide and at least 1 unit tall, and the queen's position will always be on the board.
## Examples:
Formatted as
```
(board width, board height) (queen x, queen y)
image of board
output
```
Queen x and queen y given as 1 indexed, x being leftmost and y being topmost, output being 1 indexed as well. Your I/O format may differ from this.
Note that your program does not need to use the symbols `Q\|/-.`, nor does it need to generate an image of the board at all. Only the number grid should be output.
```
(1, 1) (1, 1)
Q
1
(3, 3) (2, 2)
\|/
-Q-
/|\
454
555
454
(6, 3) (2, 2)
\|/...
-Q----
/|\...
455322
556422
455322
(2, 7) (1, 5)
|.
|.
|.
|/
Q-
|\
|.
22
22
33
55
55
55
33
(7, 2) (5, 1)
----Q--
.../|\.
2235553
2235553
(10, 10) (10, 10)
\........|
.\.......|
..\......|
...\.....|
....\....|
.....\...|
......\..|
.......\.|
........\|
---------Q
2221111122
2222111122
2222211122
1222221122
1122222122
1112222222
1111222232
1111122233
2222223355
2222222354
(7, 7) (4, 4)
\..|../
.\.|./.
..\|/..
---Q---
../|\..
./.|.\.
/..|..\
2232322
2234322
3356533
2465642
3356533
2234322
2232322
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~52~~ ~~49~~ ~~48~~ 45 bytes
```
9,i:i-]!=E2M+~+4KGY(3HGZ(3M*+^4Y6Z+9_YA!gsIGe
```
Input order is: board width, queen x, board height, queen y.
[Try it online!](https://tio.run/##y00syfn/31In0ypTN1bR1tXIV7tO28TbPVLD2MM9SsPYV0s7ziTSLErbMj7SUTG92NM99f9/My4jLmMuIwA) Or [verify all test cases](https://tio.run/##y00syfmf8N9SJ9MqUzdW0dbVyFe7TtvE2z1Sw9jDPUrD2FdLO84k0ixK2zI@0lExvdjTPfW/QXKES1ZURch/Qy4I5DLmMgJjLjMYwwgobM5lygUmQBwuQwMEAoqagDEA).
The code first generates the board using the numbers 1, 9, …, 59049 (first six powers of 9) instead of the symbols `.`, `/`, …, `Q`. Then 2-dimensional convolution with a 3×3 matrix containing ones is performed. This gives the sum of the 3×3 block centered in each cell. The desired result is the number of non-zero digits in the base-9 expansion of the sum for each cell.
Base 9 is sufficient (rather than base 10) because if the same character (`.`) appears 9 times in a 3×3 block the base-9 expansion will contain, due to carry, a digit 1 and the rest 0 (instead of a digit 9 and the rest 0 if base 10 were used), but the final result is 1 anyway.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 61 bytes
```
NθNηUOθη.JNNP*⁺θηQJ⁰¦⁰TθηFηFθ«Jκι≔⊞OKMKKδ⊞υΣEδ∧Lλ⁼μ⌕δλ»⎚⪪⪫υωθ
```
[Try it online!](https://tio.run/##VY9BTsMwEEXXzSlGWU2Qi1ohsSCrChWJitCg9gJuYxKrju04NiwQZzfjAFLqjfVmnr@@zx13Z8NVjM/aBv8a@pNwOBRlNueOeH9SRrc4MOgY5Lc5jXaht0eDc7NgcIVkVUF5aZ3UHh9uGNQqjFNK2tXTOH@bpa0YrIiOTva/Wpm9GwfUAaZ7KOArW/zJFwaShMVmHGWrsQ5jt7fCcW8c1kJcKmOcSKUSUBsGTdKTh4HBIfRYcYsNg41u8EXo1neoSNsOgasRewZPkjYkqGI6ZfadPSrB6W//9Q9WSY87I3XK/KTXA3kx3sMdrGEdlx/qBw "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
NθNηUOθη.
```
Input the dimensions of the board and draw it.
```
JNNP*⁺θηQ
```
Draw the Queen's lasers and then the Queen herself.
```
J⁰¦⁰Tθη
```
Trim the lasers to size.
```
FηFθ«
```
Loop over each square.
```
Jκι≔⊞OKMKKδ
```
Get the cell and its eight neighbours.
```
⊞υΣEδ∧Lλ⁼μ⌕δλ
```
Save the count of distinct nontrivial neighbours.
```
»⎚⪪⪫υωθ
```
Clear the canvas and output the counts.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 52 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{2 2↓{≢∪0~⍨,⍵}⌺3 3⊢(-2+⍵)↑2+(≠⍥|⊃×⍥×,2+,⍳=)/¨⍺∘-¨⍳⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=qzZSMHrUNrn6UeeiRx2rDOoe9a7QedS7tfZRzy5jBeNHXYs0dI20gQKaj9omGmlrPOpc8Kh3ac2jrubD04GMw9N1jLSB6jfbauofWvGod9ejjhm6IMZmkBkA&f=SylKLFd41DZBoVpdPzBGt0ZPPdpQu9pWv@ZR71arw9P1D08HMh51txhpGzzq3fyodwWQW3sISO561DFDF8QACm6NreUqSS0uARuk86h36aOuJqBSBR2FFJDxUBGFNK7ijMSC1GKwMg1DBUNNBQ1jBWMwaQYkzRWMgKSRgjmQNDRQMDQAi5lrchXkF2eWZObnoeg0gqoGkaZgEUMFUySdJgommgq6CoZcXBrqSfmJRSnqCuqFpampeUAa5CwQXZRaXJpToq75qHfVo7aJCGtAnjm0QgHiXAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Takes 0-indexed `qy qx` as left argument, and `height width` as the right argument.
Actually drawing the ascii art is a bit simpler (can be seen in the footer).
[Answer]
# [Python 3](https://docs.python.org/3/), 149 bytes
```
lambda w,h,x,y:[[len({(I==J,I==-J,I==0,J==0)for I in[i-1,i,i+1]for J in[j-1,j,j+1]if~x<I<w-x>~y<J<h-y})for i in range(-x,w-x)]for j in range(-y,h-y)]
```
[Try it online!](https://tio.run/##fY1BboMwEEX3nGKUFW7HUiBpK0XQPVyBZkEUuxilDnKQglUlVydjDIrVRRczI733v93ZvjnrzSjzr/FU/xyONVyxwQHtrqpOQse/cZHnJdLi015jSYvJs4EClK4UT1Chek32DpUOtYRabAkpeR@yIrvy4fNuszJruL1NVUU5MLX@FjEfkDyb6m2ALVKa7cejkNCLSx@/1GwXAbiccTm5EIDOKE0Bg3ARXb5asWhhLIqmMiQIfoA/L5vlhoCbdJZpKN//kymBj@DZt1A6kS7wz5/JGsGPl/6GTTfbubn1cnwA "Python 3 – Try It Online")
The position of queen is 0-indexed.
Maybe someone may golf many bytes from it, but I'm not sure how to do that.
[Answer]
# Python3, 468 bytes
```
R=range
U=lambda b,x,y:-1<x<len(b)>-1<y<len(b[0])
def V(b,m,x,y):
if r:=U(b,x,y)==1>b[x][y]:b[x][y]=m
return r
def l(x,y,Q):
b=eval('[0]*y,'*x);b[Q[0]][Q[1]]=5;B=eval(str(b));q=[(6,*Q,1,0),(7,*Q,0,1),(8,*Q,-1,1),(9,*Q,1,1)]
while q:m,x,y,X,Y=q.pop(0);q+=[(m,x+i*X,y+i*Y,X,Y)for i in[-1,1]if V(b,m,x+i*X,y+i*Y)]
return b,B
def f(X,Y,Q):
b,B=l(X,Y,Q)
for x in R(X):
for y in R(Y):B[x][y]=len({b[J][K]for J in R(x-1,x+2)for K in R(y-1,y+2)if U(B,J,K)})
return B
```
[Try it online!](https://tio.run/##pZLNTuswEIXX5Cm8iyedorgFCilmkWW7KlJRq8iLWKRglKap6b031hXPXsZJ@Nkh0Y0znjnz5czItTs876rxdW2Px3tp8@qpCJayzLf6MWcaG3TJUNw2t2VRcQ13FLsuzmIFwWOxYQ9c49YLIQmY2TCbyCVvO0FKcaezRmVOJf1XbgNmi8MfWzHbtpeclLjwzVoWf/OSh4SOHIZRA1OdLeim6BRKyctp2kleD5bcwHQvM36F0QIFxoB84sMYBYXXPhyKNr7pFAJUwP49m7Jg@6R1jCtcy/15vat5TLAB0Sg/MNEKHZ1rX4fNzjLDTJV5mjKfA3/JPLefSWPaTrXh1NpPhaks@2vAPK0hGrvnK19tE65LrCFJ@y35Ff/X2Uxlc@UVs07RkIdmMGo9zbuUo5SjFBlb8hRnOIc3@PSTHj/skyXyjzxGFgP9@ay2pjrwMDx/2ZmKb/PabxUNAAR9aRhGoxiCb4QxjpEwTJxAuDqRMMER8otTphjhpN3Dxa8Jgh5Z7B/WzQljkAna5w@A4zs)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~69~~ 68 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
θDI¹->©н‚ß®W.ý`D¹н‚ß¹н¹ß)vyN4%N8«.Λ}1A0.ΛS¶¡¶δ.ø¬g¶иšĆ2Fø€ü3}εε˜¶KÙg
```
Inputs as two loose pairs, in the order `[queen x,queen y]`, `[board width,board height]`.
[Try it online](https://tio.run/##yy9OTMpM/f//3A4Xz0M7de0Orbyw91HDrMPzD60L1zu8N8Hl0E6YAJBxaOfh@ZpllX4mqn4Wh1brnZtda@hoAKSCD207tPDQtnNb9A7vOLQm/dC2CzuOLjzSZuR2eMejpjWH9xjXntt6buvpOYe2eR@emf7/f7ShjmksV7SRjnksAA) or [verify all test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GpeSZV1BaUmyloGRve25H2IW9LqFcSo7JJaWJOQr5pSVAOaCUjtL/cztcIiN07Q6tvLD3UcOsw/MPrQvXO7w3JsElAioApCMOz9csq/QzUfWzOLRa79zsWkNHAyAVfGjboYWHtp3bond4x6E16Ye2XdhxdOGRNiO3wzseNa05vMe49tzWc1tPzzm0zfvwzPT/SnphtlxKAUWpJSWVugVFmXklqSlITvE6tFvn0DZ7LpDjucozMnNSFYpSE1MUMvO4UvK5FBT08wtK9CF@hFJo3rZRUAGrzUv9Hx1tqGMYqwMmY7mio410jIA8Yx1jJJ4ZlGeoYwrkGemYg3mmYH3mQBVgOQMdQwOQOWAaJGKiYwKWB6kGAA).
**Explanation:**
(let's call the inputs `[x,y]` and `[w,h]` in the explanation below)
*Step 1:* Use the Canvas builtin to draw the shape (with `0123a` instead of `|/-\Q`):
```
θ # Push the last item of the first (implicit) input: y
D # Duplicate it
I # Push the second input [w,h]
¹- # Subtract the first input: [w-x,h-y]
> # Increase each by 1: [w-x+1,h-y+1]
© # Store this in variable `®` (without popping)
н # Pop and push its first item: w-x+1
‚ # Pair it with the duplicated y
ß # Pop the pair, and push its minimum: min(y,w-x+1)
® # Push pair `®` again: [w-x+1,h-y+1]
W # Push its minimum (without popping): min(w-x+1,h-y+1)
.ý # Add it to the middle of the pair: [w-x+1,min(w-x+1,h-y+1),h-y+1]
` # Pop the triplet and push all three separated to the stack
D # Duplicate the top h-y+1
¹н # Push the first item of the first input: x
‚ # Pair them together: [h-y+1,x]
ß # Pop and push the minimum: min(h-y+1,x)
¹н # Push the first item of the first input: x
¹ß # Push the minimum of the first input: min(x,y)
) # Wrap all eight values on the stack into a list
v # For-each over these values:
y # Push the current value
N # Push the 0-based loop-index
4% # Modulo-4
N # Push the 0-based loop-index again
8« # Append an 8
.Λ # Use the (modifiable) Canvas builtin with these three options
} # Close the loop
.Λ # Use the (modifiable) Canvas builtin again with the options:
1A0 # 1,"abcdefghijklmnopqrstuvwxyz",0
```
[See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) But in short, these are the steps it does:
1. Draw \$y\$ amount of `'0'` in direction ↑ (`0`), then reset back to the origin with 'direction' `8`.
2. Draw \$\min(y,w-x+1)\$ amount of `'1'` in direction ↗ (`1`), and reset back to the origin again with `8`.
3. Draw \$w-x+1\$ amount of `'2'` in direction → (`2`), and reset back to the origin again with `8`.
4. Draw \$\min(w-x+1,h-y+1)\$ amount of `'3'` in direction ↘ (`3`), and reset back to the origin again with `8`.
5. Draw \$h-y+1\$ amount of `'0'` in direction ↓ (`4`), and reset back to the origin again with `8`.
6. Draw \$\min(h-y+1,x)\$ amount of `'1'` in direction ↙ (`5`), and reset back to the origin again with `8`.
7. Draw \$x\$ amount of `'2'` in direction ← (`6`), and reset back to the origin again with `8`.
8. Draw \$\min(x,y)\$ amount of `'3'` in direction ↖ (`7`), and reset back to the origin again with `8`.
9. Draw \$1\$ character from string `"abcdefghijklmnopqrstuvwxyz"` (thus `'a'`) in direction ↑ (`0`).
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f//3A4Xz0M7de0Orbyw91HDrMPzD60L1zu8N8Hl0E6YAJBxaOfh@ZpllX4mqn4Wh1brnZtda@hoAKT@/4821DGN5Yo20jGPBQA)
*Step 2:* Add a no-op border (of newline characters) like a painting frame, and then get all overlapping 3x3 blocks:
```
S # Convert it to a list of flattened characters
¶¡ # Split on newlines
δ # Map over each row of characters:
¶ .ø # Surround it with a leading/trailing newline character
¬ # Push the first line (without popping the matrix)
g # Pop and push its length
и # Create a list of that many
¶ # newline characters
š # Prepend it as first row
Ć # Enclose; appending its own head
2F # Loop 2 times:
ø # Zip/transpose; swapping rows/columns
€ # Map over each row:
ü3 # Convert it to a list of overlapping triplets
} # Close the loop
```
[Try just the first two steps online.](https://tio.run/##yy9OTMpM/f//3A4Xz0M7de0Orbyw91HDrMPzD60L1zu8N8Hl0E6YAJBxaOfh@ZpllX4mqn4Wh1brnZtda@hoAKSCD207tPDQtnNb9A7vOLQm/dC2CzuOLjzSZuR2eMejpjWH9xjX/v8fbahjGssVbaRjHgsA)
*Step 3:* Remove all painting-frame newline characters, and count how many unique characters each 3x3 block contains, which is our resulting matrix:
```
εε # Nested map over each 3x3 block:
˜ # Flatten it to a list of characters
¶K # Remove all newline characters
Ù # Uniquify it
g # Pop and push its length
# (after which the resulting matrix is output implicitly as result)
```
[Answer]
# JavaScript (ES10), 153 bytes
The position is 0-indexed. The method is similar to [the one used by @tsh](https://codegolf.stackexchange.com/a/251022/58563).
```
(w,h,x,y)=>(F=X=>Y<h?new Set([-!!X++,0,X<w].flatMap(p=>[-!!Y,0,Y<h-1].map(q=>[(H=X+~x+p)==(q+=Y-y),H==-q]+!H+!q))).size+[`
`[X-w]]+F(X<w?X:!++Y):'')(Y=0)
```
[Try it online!](https://tio.run/##dc0/b8IwEAXwnU@BJ3y6cxQDKgJxYUNZOnWxFVkiok6hCvnTRA106FdP3bGiSDf93tO79/wz744f56ZXVf3qx4JHOdCJrnQDTuSeDSd2e9pVfpi@@F5mSgiDSDGZ7eCiosz757yRDSe/iQ0e2kq76BK0DSpTNvh9xQaYZYts1Q0oZVatQ5GiaAEg6s5fHrPD5JAZNTiHexnWd2YjEC1sZjOQlmMYj3XV1aWPyvpNFlKTDu9igMlfX9AiJPrOnx74nFZhZ3nnK5rT8p99HVO4Na0Bxh8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 109 bytes
```
f(w,h,x,y)=matrix(h,w,i,j,#Set([[k-y==s=l-x,s==t=y-k,!s,!t]|n<-[0..8],(k=i-n%3)>=0&&k<h&&(l=j-n\3)>=0&&l<w]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VZDBasMwDIZfxe1osEEuyVLWjkV9iR09M8xYFjduMIlLEuhj9LZLL2PPtLeZknmHwi_Q90tCQp_f3rT29cNfr1-nUMrdz7HkPVQwwCjwaEJrB15BDxYOcPf8HrhStRwRO3RygA4x4ChrWHSwCPrcFFKl6_VOA6_RymaViz2mSVIXVZJwhwfZvETLFb0WIi69GO_dyA2Te-Zb2wRKlwRL8fTHnr8Z53gJzAgBTKkMGCklacIcWD4b2UQPN3QPbDt3biailIxNnMvInuKRFKvbeTjXOt72_5hf)
A port of [@tsh's Python answer](https://codegolf.stackexchange.com/a/251022/9288). The position is 0-indexed.
] |
[Question]
[
Don't tell anyone, but I've nicked my uncle's time travel machine! My uncle is obsessed with prime numbers, though, and that shows in the machine — he has programmed it so that it can only go to dates that sum up to a prime number.
So it can't go to `1947-08-15` because 1947+8+15 = 1970, which is not a prime number. It *can* go to `1947-07-25`, because 1947+7+25 = 1979, which is prime. So if I want to go back to watch India's independence celebrations, it looks like I'll have to go a few weeks earlier and wait out those 20 days.
I have some other dates that I want to go to, and I'll similarly have to go to a date before (or if I'm lucky, equal to) my target date, that sums up to a prime number. I'm impatient, though, and don't want to wait too much — so I want to find the date I can use that is closest to my target date.
**Can you write me a program that takes my target date and gives me the date I should input into the time machine — the closest date before or equal to the given date whose parts add up to a prime number?**
(For this challenge, we're using the *proleptic* Gregorian calendar — which simply means we use the current Gregorian calendar even for periods when people then were using the older Julian calendar.)
### Input
* A date
+ ideally, any date in the Current Era (AD); practically, whatever subset of that your language can naturally handle
+ in any single human-readable format⁺ you like
### Output
* The date closest to the input date, which is less than or equal to the input and whose date+month+year sums up to a prime number.
+ in any single human-readable format⁺ you like
⁺: "human readable" as in the day, month and year all separately spelt out, in whatever order
### Test cases
```
1947-08-15
=> 1947-07-25
1957-10-04
=> 1957-09-27
1776-07-04
=> 1776-07-04
999-12-12
=> 0999-12-10
2018-06-20
=> 2018-06-15
1999-01-02
=> 1998-12-29
1319-12-29
=> 1319-07-01
```
*(Thanks to @Shaggy, @PeterTaylor, and @Arnauld for help with the question.)*
[Answer]
# [Red](http://www.red-lang.org), 87 bytes
```
func[d][d: d + 1 until[d: d - 1 n: d/2 + d/3 + d/4 i: 1 until[n %(i: i + 1)= 0]i = n]d]
```
[Try it online!](https://tio.run/##TYvRCsIwDEXf9xV5ERQJa2q3roX9hK@lT2aFghQZ2/d3UbEIIeSce7MuXO8Lh9glX9NeHoFjYA8MVyDYy5afX0TBIkevJeH@9tkGsm@1AqezYH5/XmZQMcMMJXKsrzWXDRLQgBOSM7b7GYOkxAz/xiJZOzZBGmWcc81ohSNqRVM9AA "Red – Try It Online")
## More readable:
```
f: func [ d ] [
d: d + 1
until [
d: d - 1
n: d/day + d/month + d/year
i: 1
until [
i: i + 1
n % i = 0
]
i = n
]
d
]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 94 bytes
Takes input as 3 integers in currying syntax `(year)(month)(day)`. Returns a hyphen-separated string with a leading hyphen.
```
y=>m=>g=d=>(P=k=>n%++k?P(k):~k)(n=eval(s='-'+new Date(y,m-1,d).toJSON().split`T`[0]))?g(d-1):s
```
[Try it online!](https://tio.run/##Zc5Ba8JAEAXge3/FXoozxIk728R1hY2XnnpohXorBYOJwSYm0gSLl/71dDdVKOnhXR4fj/eRntN293k4dVQ3Wd7vbX@xydEmhc1sAmtb2qS@D4JytYYSl98lQm3zc1pBayc0Cer8SzymXQ6X6ZF4mmHYNU@vL8@AYXuqDt12s32T74irAjJiXLb9rqnbpsrDqilgD2wijSAWCBwjitlM@IakJhXfjWnsKEvHoxuNHTWk9JhqPXdM/6Gu8asyGlFhjHGrashApWuIFbEcUSXZ/RRuWclf6huSc@L/X/2qYBd1@2oWflWZMX3g6wFlrtQ1w1fufwA "JavaScript (Node.js) – Try It Online")
### How?
We first convert the date to JSON format `yyyy-mm-ddT00:00:00.000Z` ([ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)), split it on the `'T'`, keep only the left part and add a leading hyphen, which gives `-yyyy-mm-dd`.
```
s = '-' + new Date(y, m - 1, d).toJSON().split`T`[0]
```
This expression **s** can now be `eval()`'uated to get the opposite **n** of the sum of **year + month + day**.
```
n = eval(s)
```
We use the helper function **P()** to test whether **-n** is prime (in which case it returns **0**). If it is, we return **s**. Otherwise, we try again with the previous day.
```
(P = k => n % ++k ? P(k) : ~k)(n) ? g(d - 1) : s
```
[Answer]
# [Ruby](https://www.ruby-lang.org/en/), 94 bytes
[Try it online!](https://tio.run/##bclPC4IwHMbxu69iNzf6NTZR5w7VpXcREpMtGuGf5kREfe1LOnRJeODLw8cN1RQUOqFwPGNNZk11Oza@xYzMi10qZ9QLWerbe4/sA2FLtZoOltZt459bJ6McoZ2ztbmsa@TMe7DOxFp5E//el@PQDb5H6nbdjDZmxFymAgrgGSmjf8sEcAYs3UMhchD7JqUEnmzbsYTxAnJIGCnDBw)
Takes a single Date input, and returns a string in the ISO 8601 format (`YYYY-MM-DD`).
```
require'date'
require'prime'
->d{d.downto(0){|i|break i.to_s if (i.day+i.month+i.year).prime?}}
```
It uses Ruby's prime module. If that's not allowed, or frowned upon, then for two bytes more I present this abomination:
---
# [Ruby](https://www.ruby-lang.org/en/), 97 bytes
[Try it online!](https://tio.run/##bcnRCoIwGIbhc69igeCWa@4Xa3lQnnQXpTHZohFprYlI1q0vzxM@ePl4bFcPXqId8qs9VuStmGr7xrWYk/doxtpqeUOGufb8QuaCClhiw5QcYsPubeOuUwctLVl8UVJBEY4VBogLcoI4TD6fwOpnZ6yOlHQ68o/OvZA8HqbDGt1jyDNBtxTWpAz@bS0ocMqzORRiQ8W85XlOIZ02YymHLd3QlJPSe/8D)
It uses a check for a number being prime from [this stackoverflow answer](https://stackoverflow.com/a/19714987/4173627). I have no idea how this works, it looks a bit like witchcraft.
Same input as above, and same output.
```
require'date'
->d{d.downto(0){|i|break i.to_s if ?1*(i.day+i.month+i.year)!~ /^1?$|^(11+?)\1+$/}}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~130~~ 127 bytes
Input is `year, month, day`.
-3 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
```
from datetime import*
def f(a):
while(lambda n:any(n%m<1for m in range(2,n)))(a.year+a.month+a.day):a-=timedelta(1)
print a
```
[Try it online!](https://tio.run/##Tc3BCsIwEATQe79iL0JWV2mCNrbox6wksYFmU0JA@vW1XlQYGHiHmXmpYxazrqHkBI6rrzF5iGnOpe4b5wMExTg0AK8xTl5NnB6OQQaWRcku3XTIBRJEgcLy9MqQIKLi0@K5HPiUstRxa8cLDny8f/adnyorjdvqXKJU4DWoz7nS/dnSlfQFsfnSxZJu6fxH1nZk/6Xve9Jmy49Mq6/UkWkR1zc "Python 2 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 117 bytes
```
function(d){while(!numbers::isPrime(y(d))){d=d-1};d}
`<`=format
y=function(d)sum(as.integer(c(d<"%Y",d<"%m",d<"%d")))
```
[Try it online!](https://tio.run/##ZY3BCoJAEIbvvkVCsEITM1aua3rrAbp209q1FlqFVYkIn93WupTCwA/zzf@NHcpsKLvq0uq6YjJ4PW76rtii6sxZ2SZJdHO02ij2dDAIXjKTQP1e9l6e5llZW1O03jP7MTSdYUWz1lWrrsqyC5Opvzz5qzHMN6TvVEM5nh2KVjGfxJYDxkA7R7w/sONACLidAs4jQD4HQgig0M1kHyLFgBGEOHvhGkiA0wZt6KMKhQPDGw "R – Try It Online")
[Answer]
# Java 8, ~~144~~ 128 bytes
```
d->{for(;;d=d.minusDays(1)){int n=d.getYear()+d.getMonthValue()+d.getDayOfMonth(),i=2;for(;i<n;n=n%i++<1?0:n);if(n>1)return d;}}
```
[Try it online.](https://tio.run/##pZDBTsMwDIbvewpfkBKti5pqo5Ss47IjG4dJSAhxCE06Mlp3atOhaeqzF6/AbachxYr9K/7y2zt90JOd@eyzQjcNrLTD0wjAobd1rjML63MJsKN3wrvSiscq08VSewsZu6Qarqijo6CzBoQUejNZnPKqZkqZ1IjSYdss9bFhkvMTfQVI6tb6F6trxsdDvqrQfzzrorV/CnU85YPMeODSSA1EN0eFKd648XguH8J75MrlDBeS19a3NYJRXderEZnZt@@Fy6Dx2tN1qJyBkuZlG1873L6@geY/w563ACUZR/s1FGyYCWBzbLwtRdV6saceXyArBYqLixBVzmQyjQO4C0DOOL@aMSOGDAMIp9dD4viWAPG/IEmSkJHoHFczolDSOkIyE4W/kG7U9d8)
`java.time.LocalDate` class has been an improvement in comparison to the old `java.util.Date`, but why did they had to make those names longer (`getMonthValue` and `getDayOfMonth` instead of `getMonth` and `getDay`).. >.>
**Explanation:**
```
d->{ // Method with LocalDate as both parameter and return-type
for(;; // Loop indefinitely
d=d.minusDays(1)){ // Going one day back after every iteration
int n=d.getYear()+d.getMonthValue()+d.getDayOfMonth(),
// Set `n` to the sum of year+month+day
i=2;for(;i<n;n=n%i++<1?0:n);if(n>1)
// If `n` is a prime:
return d;}} // Return the now modified input-LocalDate `d`
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~57~~ 53 bytes
```
->d{d-=9until/^(11+)\1+$/!~?1*(d.day+d.year+d.mon);d}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6lOkXX1rI0ryQzRz9Ow9BQWzPGUFtFX7HO3lBLI0UvJbFSO0WvMjWxCEjl5udpWqfU/i9QSIsOycxN1ctLLdcwtDQx17HQMTTVjOVCkzA11zE00DEwwZAxNzfTMcciYWlpqWNoBEToEkYGhhY6ZjpGBpiWgLToYGgwNDYEG2VkqRn7HwA "Ruby – Try It Online")
Not my idea - stolen from the "abomination" by IMP1
---
## Original idea:
# [Ruby](https://www.ruby-lang.org/), 59 bytes
```
->d{d-=9until((2...w=d.day+d.year+d.mon).all?{|x|w%x>0});d}
```
[Try it online!](https://tio.run/##bY3LCoMwFET3/YpuCoZeL7mpGkPR/kR3xYUlCoKPIpUY1G9PbZdaGJjF4cz0w9O6MnF@qiftJ2po31XteQIRTaJR5/as0RZ5v1bTtQzzur5N8zib05jyhV314l7H8nGvmgLbwnikAgkxUMiywwaEEogDD3ZEygjkH6CUAhJrtkBwiiECwfcnXwV2Al3oNyUUy9wH "Ruby – Try It Online")
[Answer]
# F#, 134 133 bytes
```
let rec s(d:System.DateTime)=
let x=d.Year+d.Month+d.Day
if(Seq.tryFind(fun i->x%i=0){2..x-1}).IsNone then d else d.AddDays(-1.)|>s
```
-1 byte thanks to from [sundar](https://codegolf.stackexchange.com/users/8774/sundar).
[Try it online!](https://tio.run/##bZBRS8MwFIXf@ysug0GLbWjqZq3agjAFH@aEiSBzD2G5dYE2nUmmHZu/vaZzc7AZuITk45577sl1MKsUNk2BBhTOQLv8arzSBksyYAafRYle6kCL65STV2TqjJNhJc3c3gO2ckDk7hg/iFGreyG5my8liCCruyINvXVESB3Qb4886MdKIpg5SuCAhUbg5JZzK6HdgBJvk@mmWlj6O96Z3NxJq/lUCWmyqdM6KJmQwNT7p3VkT/vFdyY1pDCR@AV71y5NerEPlz7QvncNR6hvEQ196J2gOL7wIf6HJElie6K2jlEUUjvH9kXh6ai2LaS2TtroOd1JRoll@38yZPULK5Y43W7ZZisMKtgmu98Xggz04bXJYKFsULmETnf0Zrqjzh/0DiFtBcPmBw)
Total the day, month and year and see if it's prime. If it is, return that date. If not, decrement the date by 1 day and try again.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~105~~ 90 bytes
```
for($a=$args[0];'1'*((Date $a -f yyyy+MM+dd)|iex)-match'^(..+)\1+$';$a=$a.AddDays(-1)){}$a
```
[Try it online!](https://tio.run/##HcxNCsIwEEDhq4QSyIxhglNXpbgQCq56An9gMKkVKpUmoEU9e5S@/fce4zNMsQ/DkHM3TqBlq2W6xsP6VBs2K4BGUlBaFHVq/mfb1nqPn1t4Id0lXXpzBucsHtlqUy/e7bxvZI5AjPj@ask5wz4kWl4Fb7giLqmsClQ/ "PowerShell – Try It Online")
*Thanks to sundar for -13 bytes.*
Takes input as a `DateTime` `2018-06-20` and saves it into `$a`. Then we're in a `for` loop. Each iteration, we're taking `$a` `-f`ormatted like `yyyy+MM+dd` (i.e., the current date we're on separated by `+` signs) added together with `|iex` (similar to `eval`), string-multiplying that with `1`s to form a unary number, and using a [prime-checking regex](https://codegolf.stackexchange.com/a/57636/42963) to determine if the current date is prime or not. If it is not prime, we `.AddDays(-1)` to go backwards a day and continue the loop. If it is prime, we break out of the loop and place `$a` onto the pipeline with implicit output.
The resulting output is culture-dependent. On TIO, which uses `en-us`, the output is long-date format, which looks like `Saturday, July 1, 1319 12:00:00 AM`.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~114~~ 108 bytes
```
a=`date +%s -d$1`
while [ "`date +%d+%m+%Y -d@$a|bc|factor|awk NF!=2`" ]
do a=$[a-86400]
done
date +%F -d@$a
```
[Try it online!](https://tio.run/##S0oszvj/P9E2ISWxJFVBW7VYQTdFxTCBqzwjMydVIVpBCSaRoq2aq60aCZR2UEmsSUquSUtMLskvqkksz1bwc1O0NUpQUojlSslXSLRViU7UtTAzMTAA8fNSuaAmuEH0/v//39DSxFzXwELX0BQA "Bash – Try It Online")
My first ever bash golf. Honestly, my first real bash program ever ... primality test taken from [here](https://codegolf.stackexchange.com/questions/57617/is-this-number-a-prime/57674#57674).
This might sometimes fail if there is a timezone change, but TIO uses UTC, so there it should work.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~167~~ 164 bytes
-3 bytes thanks to ceilingcat.
```
r;P(n,i){for(r=0;++i<n;)r|=n%i<1;}f(y,m,d){for(;P(y+m+d,1),r;)d=--d?d:" >8><><>><><>"[!--m?y--,m=12:m]/2+(m==2&y%4<1&y%100|y%400<1);printf("%04d-%02d-%02d",y,m,d);}
```
[Try it online!](https://tio.run/##bVBBboMwEDyHV7iWqIywVdslJY4h@ULvVQ8VBsTBJKJpVZTwdrq2SZtKFdpdz87OrE3F2qqa50E/k552ybk5DGQouU7Truh1MlzKPu4KoaeGjNRSEyZgekxtaqhI6KATUzJm9maL0W6zK@DzCb/cMWb3I2PUlkJu7euDTIktS3k/xlkhIAvOL3DmvBCJPg5df2oIjnlmWMxlSJiGvXqaPw@dQS2BKTRS5IoNxYRSL916adcmic7R6n9fROqvY12dur5Ff5lkizB1G8AGnJ2rcwQ3Ha3cb/CEA8eP0zvBGI5TFPn7vHU98UtbghAS9DdukJO2RKgsB7ShSKwhAoKQ6yu/BiQ4dDPHO4QU8PnC5/lTUHj@BgUeKQXTQoa4QTzwkgvYjUAluYsrEj/7ncLf2KmU2gS9VAv/KNS1A9Ujv9@9b5q/AQ "C (gcc) – Try It Online")
## Rundown
```
r;P(n,i){for(r=0;++i<n;)r|=n%i<1;}
```
The anti-prime-checking function. Since the earliest valid year we need to deal with is 0001-01-01, the lowest number we ever need to worry about is 3, so the special-case checks for n==2 or n < 2 are stripped out. r is set to a truthy value if n is *not* a prime. r is kept global, since not having to return it saves two bytes (`i=n;` to return vs `,r` to check the global). i is set to 1 by the function caller, to save another 2 bytes.
```
f(y,m,d){for(;P(y+m+d,1),r;)
```
We take the date as three separate integers and start the main loop, which goes on until y+m+d is prime. Then we come to the meat of the function:
```
!--d? Decrement day and check if zero, which means we go back to last day of previous month.
d=" >8><><>><><>" The string contains the number of days of each month times 2, to bring them into printable ASCII range.
We begin the string with a space, to avoid having to substract from index later.
[!--m?y--,m=12:m]/2+ Decrement month and check if zero. If so, go back a year and set m to 12. Use m as index in string.
(m==2&!(y%4)&y%100|!(y%400)) If the new month is February, add 1 to day if it's a leap year.
:0; Do nothing if day did not become zero.
```
It might seem iffy to use m and y both in the leap year check and as the index of the string, when the evaluation order is unspecified. Luckily, we only check for leap year if m == 2, which can't happen at the same time as we change m and y, since that only happens going from January to December, so the leap year check is never bothered by the order of evaluation.
Finally, the result is printed to STDOUT:
```
printf("%04d-%02d-%02d",y,m,d);}
```
[Answer]
# C# - ~~281~~ ~~239~~ 232 Char
```
using System;class P{static void Main(){var d=DateTime.Parse(Console.ReadLine());do{int c=d.Year+d.Month+d.Day;if(c%2!=0){int i=3;for(;i<=c;i+=2)if(c%i==0)break;if(i>=c)break;}d=d.AddDays(-1);}while(d>DateTime.MinValue);Console.WriteLine(d);}}
```
ungolfed:
```
using System;
class P
{
static void Main()
{
var d = DateTime.Parse(Console.ReadLine());
do
{
int c = d.Year + d.Month + d.Day;
// minimum datetime in c# is 0001-01-01
// therefore do not need to check for the first two primes
int i = 3;
for (; i < c; i += 2) if (c % i == 0) break;
// check to break the date decrement loop if counter passed the input value
// ie, no factor could be found
if (i >= c) break;
d = d.AddDays(-1);
} while (d > DateTime.MinValue);
Console.WriteLine(d);
}
}
```
Made the code less efficient but smaller. Prime loop will now go up to the integer rather than the square root. It will also process all even numbers.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
`tsZp?.}YOqZOT
```
[Try it online!](https://tio.run/##JYuxDkBAEER7XzFfILvnWFtp9NdokEvoSQitbz/rJFO8yZvZ13tLS1ruazq68hnDOYUhxdgPaWb1ghZcx8K4FjCB/FdEGpD8RVXBzmLsiFtQA0f5YoYY9BmuOM@cxhc "MATL – Try It Online")
Alternately:
### 15 bytes
```
`tsZp~tbYOw-ZOw
```
[Try it online!](https://tio.run/##JYsxCoAwEAR7X7EfEO6i5nK9vY2NSkCtFQQD6fx6TBS2mGV2zy0caU1ruOfrCfs0xHoeYvL9mBbWVuDAna8ydwImUFuKiAXJX1QVbHIyG2IHsjD0XbIhBhXDDX8zo/4F "MATL – Try It Online")
[Answer]
# Scala, 116 bytes
```
d=>LazyList.iterate(d)(_ minusDays 1)find{d=>val s=d.getYear+d.getMonthValue+d.getDayOfMonth
2 to s/2 forall(s%_>0)}
```
Uses `java.time.LocalDate` as input and output.
[Try it in Scastie](https://scastie.scala-lang.org/JgawE0wBTPG4EmI8UcE6JQ)
] |
[Question]
[
Inspired by a discussion from the [Esolangs.org unofficial Discord Server.](https://discord.gg/3UXSK5p)
## Instructions
A chess cycle is an arrangement of a chess board where each piece *must* attack one other piece, and *only* one other piece, and each piece is attacked exactly once.
The effective idea to to "connect" pieces with each other, forming a single cyclic chain. Here is a board example:
[](https://i.stack.imgur.com/rkhKX.png)
**You will only be given boards with Knights, Rooks and Bishops.**
Your submission must take a chess board in any valid format(string, list of strings, 2D array, list of piece positions, FEN, ...) and output a truthy or falsy value for whether the board represents a valid cycle or not.
## Testcases
To create your own testcases, create your board [here](https://lichess.org/editor/), copy the FEN box contents, and use as input [here.](https://staxlang.xyz/#c=%27%2F%22%601%22R%22%5Cd%22%7Be%27+*%7DR%27+%27.R&i=1R4B1%2F3N4%2F3N4%2F3N1B2%2F8%2F2B2N2%2F4R1BB%2FR1N5)
FEN: `8/2B5/8/1N6/5N2/3B4/8/8`, [lichess](https://lichess.org/editor/8/2B5/8/1N6/5N2/3B4/8/8_w_-_-_0_1)
Board:
```
........
..B.....
........
.N......
.....N..
...B....
........
........
```
Output: `True` (In the illustration)
---
FEN: `8/8/8/3R4/8/8/8/8`, [lichess](https://lichess.org/editor/8/8/8/3R4/8/8/8/8_w_-_-_0_1)
Board:
```
........
........
........
...R....
........
........
........
........
```
Output: `False` (Rook cannot attack self)
---
FEN: `1R4B1/3N4/3N4/3N1B2/8/2B2N2/4R1BB/R1N5`, [lichess](https://lichess.org/editor/1R4B1/3N4/3N4/3N1B2/8/2B2N2/4R1BB/R1N5_w_-_-_0_1)
Board:
```
.R....B.
...N....
...N....
...N.B..
........
..B..N..
....R.BB
R.N.....
```
Output: `True`
---
FEN: `6B1/4N2N/5B2/8/8/6B1/4N2N/5B2`, [lichess](https://lichess.org/editor/6B1/4N2N/5B2/8/8/6B1/4N2N/5B2_w_-_-_0_1)
Board:
```
......B.
....N..N
.....B..
........
........
......B.
....N..N
.....B..
```
Output: `False` (Multiple Cycles)
---
FEN: `8/6R1/8/5R1N/3N4/8/5BB1/7N`, [lichess](https://lichess.org/editor/8/6R1/8/5R1N/3N4/8/5BB1/7N_w_-_-_0_1)
Board:
```
........
......R.
........
.....R.N
...N....
........
.....BB.
.......N
```
Output: `False` (Rook on f5 attacks two pieces)
---
FEN: `8/8/8/8/8/8/8/8`, [lichess(tsh)](https://lichess.org/editor/8/8/8/2R2R2/8/8/8/8_w_-_-_0_1)
Board:
```
........
........
........
........
........
........
........
........
```
Output: `False` (No pieces for a cycle)
---
FEN: `8/8/8/2R2R2/8/8/8/8`, [lichess(tsh)](https://lichess.org/editor/8/8/8/2R2R2/8/8/8/8_w_-_-_0_1)
Board:
```
........
........
........
..R..R..
........
........
........
........
```
Output: `True` (Two connected rooks, single cycle)
---
FEN: `8/8/8/1R3B2/8/3R2N1/8/8`, [lichess(Robin Ryder)](https://lichess.org/editor/8/8/8/1R3B2/8/3R2N1/8/8_w_-_-_0_1)
Board:
```
........
........
........
.R...B..
........
...R..N.
........
........
```
Output: `False`
## Other Info
* You may represent the pieces and empty squares as any number or character, as long as it is consistent.
* Given boards will always be 8x8 and valid i.e. not containing any invalid characters.
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/), 259 bytes
```
o=DirectedEdges->True
i|->RelationGraph[(d=Abs[#1[[2]]-#2[[2]]];#1!=#2&&NoneTrue[i,RegionMember[Line[p={#1[[2]],#2[[2]]}]~RegionDifference~Point@p]@*Last]&&Switch[#1[[1]],r,Times@@d==0,b,Equal@@d,n,Sort@d=={1,2}])&,i,o]~IsomorphicGraphQ~CycleGraph[Length@i,o]
```
[Try it online!](https://tio.run/##xVDdbpswGL3nKVij0TZyxMxPgjRRMdZqmpShlvYO@YLAl2At2JkxiyZEHqJvsCfcI2QYUNqo95ssy8f2d853zlemsoAylTRLj0fu31IBmYT8Lt9ANbt5EjVo9M/z7xi2XQ1nX0S6K5Kr3P@0qpIJThKLkNnE6k/ycYLf@RPLMCLOQFETimLYdLRvUK5AJEvKINn5zUhEI7Elh6Hslq7XIIBlcLjnlMlgR4LpMq0kMYzHPZVZ0ffEHVWgJ1pCFQS5739AK3T3o0633Q0x9MiFVM8NRlZLrg1EESeHrxUvudgVNOszPBw@/8q2MORZAtvIIlB1x7X/Xr@a5hwqdin1PRffdcp0WdBKB/aTCs5KYBLpq1rqVOoZr7e5DtsK9kVnfXqtrf3/N7BkR/75xDRNuxeq94VnWqFreiaO5qYbWaYdOt3Nu5jdrJOmYaixkNu2qFmhxkaLETnIVqj7nSOnbVtCXuTUsuNe5JWQUCT3rBTHTohNO3LGjUPLVG6szoUT4zA0Yxy5L3yVc2iPByO9OWdE9gk5A@ptzkc0f2W4f@v0Fqdgi1OwBfLGXw/hkeEprvL9UFOQwVlQ7zzmm0FYcbfejgIP4j3yevHjXw "Wolfram Language (Mathematica) – Try It Online")
(uses [\[Function]](http://reference.wolfram.com/language/ref/character/Function.html) rather than `|->`, as TIO doesn't have the most recent version of the language)
Defines a function that takes in a list of piece positions as input, each in the form `{piece, {row, column}}` where piece is one of `r`, `b`, or `n`.
Un-golfed explanation:
```
i|->
IsomorphicGraphQ[ (*check if the following graphs are equivalent*)
CycleGraph[Length[i], DirectedEdges -> True],
(*cyclic graph with length of input*)
RelationGraph[ (*graph defined by a functional relation*)
(d = Abs[#1[[2]] - #2[[2]]]; (*set `d` to absolute difference in coordinates*)
#1 != #2 && (*no pieces attack themselves*)
NoneTrue[i, (*no other pieces are...*)
RegionMember[RegionDifference[Line[p = {#1[[2]], #2[[2]]}], Point[p]]] @* Last
] && (*between these two pieces*)
Switch[First @ #1, (*switch by attacking piece*)
r, Times @@ d == 0, (*rooks attack when one coordinate offset is zero*)
b, Equal @@ d, (*bishops attack when both offsets are equal*)
n, Sort[d] == {1, 2}] (*knights attack when one offset is 1 and the other is 2*)
)&, i, DirectedEdges->True], (*apply to list of pieces*)
]&
```
[Answer]
# JavaScript (ES6), 241 bytes
Expects a list of triplets `(x,y,p)`, where \$(x,y)\$ are the coordinates of the piece and \$p\$ is its type (\$0\$, \$1\$ or \$2\$ for bishop, knight or rook respectively).
Returns \$0\$ or \$1\$.
```
a=>(g=(i,n,k)=>i>=0?m^(m|=1<<i)?a.map(([X,Y],j)=>(h=([x,y,t]=a[i],X-=x)*X)|(v=(Y-=y)*Y)&&![h-v,h+v-5,h*v][t]&a.every(([p,q])=>(S=Math.sign)(p-=x)-S(X)|S(q-=y)-S(Y)|(p*=p)+(q*=q)<1|[p-q,1][t]|p>=h&q>=v)?k=1/k?-1:j:0)|g(k,-~n):!i&!a[n]:0)(m=0)
```
[Try it online!](https://tio.run/##pZBNb9pAEIbv/hULB2eGrBc49EJZI1lKbnUl0wPIcaWVWfCC8TcWVmn/OrX5SICQKlItSzvzzjvPzs5SlCL3M5UURhTP5H7O94KbsOCgaERXyE1l8t5o/RPWO94fDhWOBFuLBMCd0KlHl7UDAg7ulla08LhwlUcnBt9iZ4I7KDlMDV5hZ4q63nIDo6TBY2l8oUGn9NzC0wWTpcyqGpfQ1GtgY/5NFAHL1SJCSBqSMYaaNYa0IdXJtAYnHZ7gI6QdnuKwv3MTI6X9hrhLTB7oqclLHK14v7saGf3BctDD3QJW1PgT4aCl9JZwI68WYc17uM9kulGZhId5/oAsk2L2rEI5riIfesiKeFxkKloAsjwJVQHtl@glaiObx9mT8APICTfJL42QUBZEEE5c72ud5W/2CzNklFTYdLiMscx7K/iUbA8Fn7Q4abM20XUiWLLJg2a9pKKkbdlOm6loJrff5@Cjh4jNVX4c5XEoWRgvYA6iEX@jpnW75GmbSL@opx@QH9lGUvIswrw@rpLr46K0Z6dPY8w6B2fFZheKfQysG885uCNdBs7HpXegg9c6SPa5dhFY123W62h1o2Vpzmns80RHUCPa2kn4@P675luTc9vmHN32HaJlvSq29qn3f25H/zI5h///Qc6dZTnNM9@b/wI "JavaScript (Node.js) – Try It Online")
## How?
### Algorithm
We recursively walk through the input list of \$N\$ entries by going from a piece \$A\$ to a piece \$B\$ attacked by \$A\$. We test whether we eventually go back to the starting piece in \$N\$ iterations.
Furthermore, we force the search to stop and the test to fail if:
* we reach a piece that was already visited and is not the starting one (e.g. a mutual attack between 2 rooks which would result in an infinite loop)
* we detect than any piece attacks more than one piece
### Attacks
Given two pieces \$A\$ and \$B\$ at positions \$(x\_A,y\_A)\$ and \$(x\_B,y\_B)\$, we compute \$dx=x\_A-x\_B\$ and \$dy=y\_A-y\_B\$.
As illustrated below, the piece \$A\$ attacks \$B\$ if:
* \$A\$ is a rook and we have either \$dx^2=0,\:dy^2>0\$ or \$dx^2>0,\:dy^2=0\$
* \$A\$ is a bishop and \$dx^2=dy^2\$
* \$A\$ is a knight and \$dx^2+dy^2=5\$
[](https://i.stack.imgur.com/8bTEO.png)
For rooks and bishops, we also have to make sure that there is no piece in between on the same ray. This is the weak point in this piece-oriented approach, as the corresponding code (the `a.every()`) is pretty long.
## Commented
```
a => ( // a[] = list of pieces
g = (i, n, k) => // g is a recursive function taking an index i and
// a number of moves n
i >= 0 ? // if i is a non-negative number:
m ^ (m |= 1 << i) ? // set the i-th bit in m; if it was not already set:
a.map(([X, Y], j) => // for each piece (X, Y) at position j in a[]:
( h = ( // load the position (x, y) and the type t
[x, y, t] = a[i], // of the i-th piece
X -= x // set: X = X - x, h = X²
) * X // Y = Y - y, v = Y²
) | (v = (Y -= y) * Y) // abort if both h and v are equal to 0
&& ![ h - v, // bishop: we must have h = v
h + v - 5, // knight: we must have h + v = 5
h * v // rook : we must have either h = 0 or v = 0
][t] & //
a.every(([p, q]) => // make sure that there is no closer piece (p, q)
(S = Math.sign) // that blocks the capture, which is not the case:
(p -= x) - S(X) // if it's not in the same direction
| S(q -= y) - S(Y) //
| (p *= p) + // or it's the capturing piece itself
(q *= q) < 1 //
| [p - q, 1][t] // or the capture types do not match
| p >= h & q >= v // or it's not blocking because it's further
) ? // end of every(); if all tests pass:
k = 1 / k ? -1 : j // update k to j, or -1 if it's already set
: // else:
0 // do nothing
) | // end of map()
g(k, -~n) // do a recursive call with i = k and n + 1
: // else:
!i & !a[n] // this is a full cycle if i = 0 and n = a.length
: // else:
0 // abort
)(m = 0) // initial call to g with i = m = 0
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~343~~ ~~335~~ ~~334~~ 327 bytes
-8 thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs)
A function that takes two inputs: a list of piece types and a list of piece coordinates.
Piece types:
* Rook: `1`
* Bishop: `2`
* Knight: `3`
Coordinates are given in the format:
`21 + y * 10 + x`
Coordinate format inspired by [sunfish](https://github.com/thomasahle/sunfish).
Returns `True` for true and `None` or `False` for false.
I haven't heavily tested it yet, please let me know if it fails on a test case.
```
m={1:[1,10],2:[11,9],3:[19,21,12,8]}
def f(p,c):
x=0
for y in c:
q=p[x];w=m[q]+[-i for i in m[q]];a=[]
for d in w:
for i in range(1,9):
z=c[x]+i*d
if z<20|z>99|z%10%9<1|z in c:a+={*c}&{z};break
if q>2:a=[x+i for i in w if x+i in c]
if len(a)-1|0**x&y-c[0]:return
x=c.index(a[0])
return len(p)>x<1
```
[Try it online!](https://tio.run/##TZDLboMwEEX3fMVsEtlgKuxIVXiYH7G8cHm0VhsHEBUGmm@ntrNodzPn3jszmmGdP@7mchw3vtNCUEIzSZgrKMklubgiJ8xRRq7yEbVdDz0aSIOLCCzPIujvE6ygDTSOwMgHYWW58JsYZSJSHXTtdU9kqbiQzudp6@niU3@mSZn3DrnVOHDYeOPmJTpuQ6t7UGZFYqtYRrY6z8l2otkpryjZwg0SFyrhe9w8zvv2KN@mTn1GITfWrHDLbfLvpMULnoTo0/fVGaRwSn@yOLbnNW1EJoupm78n4wyWNy/atJ1FynEcwVMJqQHXtqLHMGkzox65VwKVBAR7JcCuEuPjFw)
## Explanation
A crucial observation is that if each piece attacks one other and after n moves we are back on the original piece, then there exists a cycle.
```
# A list of move directions for each piece. +-10 is vertical and +-1 is horizontal
# Only positive numbers, to save bytes
m={1:[1,10],2:[11,9],3:[19,21,12,8]}
def f(p,c):
# A variable representing the current piece index
x=0
# It is a cycle if and only if after n moves, we arrive back at the original piece. (n is number of pieces)
for y in c:
# Values used multiple times
q=p[x]
w=m[q]+[-i for i in m[q]]
# List of attacks of current piece
a=[]
# Movement of bishops and rooks: keep going in each direction
for d in w:
for i in range(1,9):
z=c[x]+i*d
# Check for out of bounds or landing on another piece
if any([z<20,z>99,z%10%9<1,z in c]):a+={*c}&{z};break
# Knight moves
if q>2:a=[x+i in c for i in w if x+i in c]
# Does it only attack one piece? Does it end up at the start too early?
if len(a)-1|0**x&y-c[0]:return
# Move to next piece
x=c.index(a[0])
return len(p)>x<1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~55~~ 54 bytes
```
_þ`;"JṖẸ$ƇAṖṢJƑƲƇṭ¬Ẹ$Ƈ,ṖAEƊƇƊƊƲ€ị@"ṠAṂṪƊƙ$€µF0ịƬL’=L×Ẹ
```
[Try it online!](https://tio.run/##XU7LSsNAFN3nK0rJsnIzk4eB4KMDZlHKLGYhuNJNF0o/QHehm0Bc6UItKIoKQombotCx0EWD8x@TH4l3YogPZu7Mueece2ZORuPxWVUdFqujqDvQ8kp/LGyV9g2SjwN1oeYq1fJ1nX8LPRT6eypTKVam5uUk18vz3a6WDzgz0XKG7NRGev0eOyipfFgm061hcY0B1eelljdRmdx2NrY7ZXIXFS9gafmEEPadU5WhJBjH9tgehULLlUl6tnfwwh1jmYhZL9aLe8d8oUitP3mppZdvRYrGg6oKgTIfQiA8AJ9TcJmHXWiF5gRX1F3NEOExAi73miKMgpmmOOUJwhgIwn0rQJPHKQe/1kP4TWBsIAiSPnrrHIQMDZu8ebFdTU8Frn8cEW6d7QrKScv/OFv0BQ "Jelly – Try It Online")
A dyadic link taking two arguments. The left argument is a list of co-ordinates of the pieces. The right argument is a list of the piece types corresponding to those co-ordinates, with 1=rook, 2=bishop, 3=knight. The result is 1 for true and 0 for false.
The TIO link includes a footer that starts with newline-separated FEN notation and for each one, converts them to the desired input format and then calls the main program.
Rewritten to work using co-ordinate arithmetic for bishops and rooks rather than splitting rows, columns and diagonals, and saving 11 bytes in the process.
---
## Original version:
# [Jelly](https://github.com/DennisMitchell/jelly), ~~75~~ 66 bytes
```
fƇ⁹ḟ0ṣṪḢƭ€ʋ€Fḟ0
ŒṬFÄṁ×Ʋ;Z,ŒD;ŒdƊƲçþJ
ạṢ⁼ؽʋþ`T€ṭ"Ç0F?Ʋị@"µF0ịƬL’=L
```
[Try it online!](https://tio.run/##XU49SwNBEO33V4SQMjK3e3fx4NDIIldI2GIRQSsLIyj5AdolIhwkXRojKGIUAiFpgkLWaIos2SL/Yu@PnHNHiB8MMzvz5s3bd1lvNK7T9NzESUvZ6ZNj1YtVQzvtm3FyM1p1sEQZTpZdq0aRvrWqpe/MJDwpL7v74bJ7Ztpmogd6fkDsx7NV/aT1qXuLr1VHz08P8dyqcVHHTlQ1Ezvr7BUX75GDjRnVkub9Ti3NhHth0nwobO0WkuZjqAdA0Aa2cORcmTauJBc4XpTqgbRqjqKL11IVn8wdZiYxLOc@0U1bx@SPXkzs7E3HSDxO0wAY9yEAKirgCwYu93AKSJBVcGU@5QiVHqfgCm@dlDPIrhleeZJyDpIKn1SQ5AkmwM/3AfwGULYiKYI@cnMdbDkStsX6x02sZyYx/mFUurm2K5mgG/yHuem@AQ "Jelly – Try It Online")
## Explanation
### Link 1
* takes a list of lists as its left argument x
* takes an integer as its right argument y
* returns a list of the integers found to the left and right of y in members of x containing y, filtering out zeros
```
Ƈ | Keep those lists which:
f ⁹ | - contain y
ʋ€ | For each of these:
ḟ0 | - Exclude zeros
ṣ | - Split at y
ṪḢƭ€ | - Take the tail of the first part and head of the second (note will return 0 if nothing there)
F | Flatten
ḟ0 | Exclude zeros
```
## Link 2
* takes a list of lists of co-ordinates as its only argument
* returns a list of lists of the attacked pieces for each, first assuming each piece is a rook and then assuming each is a bishop
```
ŒṬ | Multidimensional untruthy (recreate the board as 1s and 0s)
Ʋ | Following as a monad with argument z:
F | - Flatten
Ä | - Cumulative sum
ṁ | - Mould like z
× | - Multiply by z (restoring zeros)
Ʋ | Following as a monad with argument w:
; | - w concatenated to:
Z | - Transpose of w
, Ɗ | - Paired with following as a monad:
ŒD | - Diagonals of w
; | - Concatenated to
Œd | - Antidiagonals of w
çþJ | Call link 1 for each member of this list using each of a sequence of integers from 1 to the length of the original argument of link 2
```
### Main link
* takes a list of the coordinates of pieces on the board as its left argument x
* takes a list of piece types as its right argument y
* returns 1 if there is a chess cycle and 0 if not
```
Ʋ | Following as a monad:
ʋþ` | - Following as a dyad for each possible pairing of co-ordinates:
ạ | - Absolute difference
Ṣ | - Sort
⁼ؽ | - Equals [1,2] (i.e. a knight’s move)
T€ | - Truthy indices of each
ṭ" | - Tag each onto the corresponding list in the following:
F? | - If the original list of coordinates is not empty when flattened:
Ç | - Then call link 2 using the original co-ordinate list as its argument
0 | - Else a literal 0
| By this point we have a list of length-3 lists, one for each original set of co-ordinates. The first member corresponds to attacked pieces as a bishop, the second as a rook and the third as a knight
ị@" | Index into each list using the type of piece
µ | Start a new link as a monad
F | - Flatten
0ịƬ | - Starting with the last member, index into the list of attacks until we reach a piece we’ve seen before, preserving all of the intermediate steps
L | - Length of this
’ | Subtract 1
=L | Is equal to the number of pieces
```
] |
[Question]
[
## Introduction
Consider two arrays of the same length, say `A = [0,1,0,2]` and `B = [-1,1,2,2]`.
Suppose we know that their contents are equivalent in some sense, item by item:
* `0` is equivalent to `-1`,
* `1` is equivalent to `1`,
* `0` is equivalent to `2`, and
* `2` is equivalent to `2`.
Equivalence is transitive: `-1` and `0` are equivalent, and `0` and `2` are equivalent, so `-1` and `2` are also equivalent.
The *unification* of `A` and `B` is the array where each item of `A` (or `B`) has been replaced by the largest number that's equivalent to it.
In this case, the unification would be `[2,1,2,2]`.
## The task
Write a program or function that takes two non-empty integer arrays of equal length, and outputs their unification. You can also modify one of the inputs in place instead of returning.
The lowest byte count wins.
## Test cases
```
[0] [0] -> [0]
[1] [2] -> [2]
[0,-1] [-1,-1] -> [0,0]
[0,1,0] [2,1,0] -> [2,1,2]
[1,2,3] [0,0,1] -> [3,3,3]
[0,1,0,2] [-1,1,2,2] -> [2,1,2,2]
[1,0,1,-4] [-3,-1,-2,2] -> [1,0,1,2]
[1,2,3,-2] [1,0,-3,-2] -> [1,2,3,-2]
[-3,-2,-1,0,1] [-1,-1,-1,-1,-1] -> [1,1,1,1,1]
[-3,-2,-1,0,1] [2,-1,0,1,-3] -> [2,2,2,2,2]
[-3,5,5,3,1] [4,2,3,1,2] -> [4,5,5,5,5]
[4,0,2,-5,0] [0,4,-5,3,5] -> [5,5,3,3,5]
[-2,4,-2,3,2,4,1,1] [-2,4,1,2,2,3,1,-2] -> [1,4,1,4,4,4,1,1]
[-10,-20,-11,12,-18,14,-8,-1,-14,15,-17,18,18,-6,3,1,15,-15,-19,-19] [-13,6,-4,3,19,1,-10,-15,-15,11,6,9,-11,18,6,6,-5,-15,7,-11] -> [-8,14,18,14,19,14,-8,-1,-1,15,14,18,18,18,14,14,15,-1,18,18]
[20,15,2,4,-10,-4,-19,15,-5,2,13,-3,-18,-5,-6,0,3,-6,3,-17] [-18,7,6,19,-8,-4,-16,-1,13,-18,8,8,-16,17,-9,14,-2,-12,7,6] -> [20,15,20,19,-8,-4,20,15,17,20,17,17,20,17,-6,14,15,-6,15,20]
```
[Answer]
## JavaScript (ES6), ~~100~~ ~~90~~ ~~110~~ ~~102~~ 96 bytes
```
a=>b=>a.map(v=>t[v],a.map((_,k)=>a.map((x,i)=>t[x]=t[y=b[i]]=Math.max(k?t[x]:x,k?t[y]:y)),t={}))
```
My initial solution was 90 bytes:
```
a=>b=>a.map(v=>t[v],a.map(_=>a.map((x,i)=>t[x]=t[y=b[i]]=Math.max(t[x]||x,t[y]||y)),t={}))
```
Although it's passing all provided test cases, it fails for something such as:
```
A = [0, -1], B = [-1, -1]
```
### Test cases
```
let f =
a=>b=>a.map(v=>t[v],a.map((_,k)=>a.map((x,i)=>t[x]=t[y=b[i]]=Math.max(k?t[x]:x,k?t[y]:y)),t={}))
console.log(JSON.stringify(f([0])([0]))); // -> [0]
console.log(JSON.stringify(f([1])([2]))); // -> [2]
console.log(JSON.stringify(f([0,1,0])([2,1,0]))); // -> [2,1,2]
console.log(JSON.stringify(f([1,2,3])([0,0,1]))); // -> [3,3,3]
console.log(JSON.stringify(f([0,1,0,2])([-1,1,2,2]))); // -> [2,1,2,2]
console.log(JSON.stringify(f([1,0,1,-4])([-3,-1,-2,2]))); // -> [1,0,1,2]
console.log(JSON.stringify(f([1,2,3,-2])([1,0,-3,-2]))); // -> [1,2,3,-2]
console.log(JSON.stringify(f([-3,-2,-1,0,1])([-1,-1,-1,-1,-1]))); // -> [1,1,1,1,1]
console.log(JSON.stringify(f([-3,-2,-1,0,1])([2,-1,0,1,-3]))); // -> [2,2,2,2,2]
console.log(JSON.stringify(f([-3,5,5,3,1])([4,2,3,1,2]))); // -> [4,5,5,5,5]
console.log(JSON.stringify(f([4,0,2,-5,0])([0,4,-5,3,5]))); // -> [5,5,3,3,5]
console.log(JSON.stringify(f([-2,4,-2,3,2,4,1,1])([-2,4,1,2,2,3,1,-2]))); // -> [1,4,1,4,4,4,1,1]
console.log(JSON.stringify(f([-10,-20,-11,12,-18,14,-8,-1,-14,15,-17,18,18,-6,3,1,15,-15,-19,-19])([-13,6,-4,3,19,1,-10,-15,-15,11,6,9,-11,18,6,6,-5,-15,7,-11]))); // -> [-8,14,18,14,19,14,-8,-1,-1,15,14,18,18,18,14,14,15,-1,18,18]
console.log(JSON.stringify(f([20,15,2,4,-10,-4,-19,15,-5,2,13,-3,-18,-5,-6,0,3,-6,3,-17])([-18,7,6,19,-8,-4,-16,-1,13,-18,8,8,-16,17,-9,14,-2,-12,7,6]))); // -> [20,15,20,19,-8,-4,20,15,17,20,17,17,20,17,-6,14,15,-6,15,20]
console.log(JSON.stringify(f([0,-1])([-1,-1]))); // -> [0,0]
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 27 bytes
```
l~_])\z_,*f{{_2$&,*|}/:e>}p
```
[Try it online!](http://cjam.tryitonline.net/#code=bH5fXSlcel8sKmZ7e18yJCYsKnx9LzplPn1w&input=Wy0xMCAtMjAgLTExIDEyIC0xOCAxNCAtOCAtMSAtMTQgMTUgLTE3IDE4IDE4IC02IDMgMSAxNSAtMTUgLTE5IC0xOV0gWy0xMyA2IC00IDMgMTkgMSAtMTAgLTE1IC0xNSAxMSA2IDkgLTExIDE4IDYgNiAtNSAtMTUgNyAtMTFd) [Test suite.](http://cjam.tryitonline.net/#code=cU4veyItPiIvUyp-OlI7XTpgUyo6TDsKCkx-X10pXHpfLCpme3tfMiQmLCp8fS86ZT59CgpSPW99Lw&input=WzBdIFswXSAtPiBbMF0KWzFdIFsyXSAtPiBbMl0KWzAgMSAwXSBbMiAxIDBdIC0-IFsyIDEgMl0KWzEgMiAzXSBbMCAwIDFdIC0-IFszIDMgM10KWzAgMSAwIDJdIFstMSAxIDIgMl0gLT4gWzIgMSAyIDJdClsxIDAgMSAtNF0gWy0zIC0xIC0yIDJdIC0-IFsxIDAgMSAyXQpbMSAyIDMgLTJdIFsxIDAgLTMgLTJdIC0-IFsxIDIgMyAtMl0KWy0zIC0yIC0xIDAgMV0gWy0xIC0xIC0xIC0xIC0xXSAtPiBbMSAxIDEgMSAxXQpbLTMgLTIgLTEgMCAxXSBbMiAtMSAwIDEgLTNdIC0-IFsyIDIgMiAyIDJdClstMyA1IDUgMyAxXSBbNCAyIDMgMSAyXSAtPiBbNCA1IDUgNSA1XQpbNCAwIDIgLTUgMF0gWzAgNCAtNSAzIDVdIC0-IFs1IDUgMyAzIDVdClstMiA0IC0yIDMgMiA0IDEgMV0gWy0yIDQgMSAyIDIgMyAxIC0yXSAtPiBbMSA0IDEgNCA0IDQgMSAxXQpbLTEwIC0yMCAtMTEgMTIgLTE4IDE0IC04IC0xIC0xNCAxNSAtMTcgMTggMTggLTYgMyAxIDE1IC0xNSAtMTkgLTE5XSBbLTEzIDYgLTQgMyAxOSAxIC0xMCAtMTUgLTE1IDExIDYgOSAtMTEgMTggNiA2IC01IC0xNSA3IC0xMV0gLT4gWy04IDE0IDE4IDE0IDE5IDE0IC04IC0xIC0xIDE1IDE0IDE4IDE4IDE4IDE0IDE0IDE1IC0xIDE4IDE4XQpbMjAgMTUgMiA0IC0xMCAtNCAtMTkgMTUgLTUgMiAxMyAtMyAtMTggLTUgLTYgMCAzIC02IDMgLTE3XSBbLTE4IDcgNiAxOSAtOCAtNCAtMTYgLTEgMTMgLTE4IDggOCAtMTYgMTcgLTkgMTQgLTIgLTEyIDcgNl0gLT4gWzIwIDE1IDIwIDE5IC04IC00IDIwIDE1IDE3IDIwIDE3IDE3IDIwIDE3IC02IDE0IDE1IC02IDE1IDIwXQ)
### Explanation
```
l~ e# Read and evaluate input, dumping arrays A and B on the stack.
_ e# Copy B.
])\ e# Wrap in array, pull off B, swap. Gives B [A B] on the stack.
z e# Transpose the [A B] matrix to get a list of all equivalent pairs.
_,* e# Repeat this list by the number of pairs. This is to ensure that the
e# following procedure is applied often enough to allow transitive
e# equivalences to propagate.
f{ e# Map this block over B, passing in the list of pairs each time...
{ e# For each pair...
_2$ e# Copy both the pair and the current value/list.
&, e# Get the length of their intersection. If this is non-zero,
e# the current pair belongs to the current equivalence class.
* e# Repeat the pair that many times.
| e# Set union between the current value/list and the repeated pair.
e# This adds the pair to the current list iff that list already
e# contains one value from the pair.
}/
:e> e# Get the maximum value of this equivalence class.
}
p e# Pretty print.
```
[Answer]
## Python 2, 91 bytes
```
f=lambda a,b:[a<x>b.update(b&set(x)and x)and b or max(f(zip(a,b)*len(a),{x})[0])for x in a]
```
[Answer]
## Python, 86 bytes
```
f=lambda a,b:a*(a==b)or f(*[map({x:y for x,y in zip(a,b)if x<y}.get,x,x)for x in b,a])
```
Simultaneously updates both lists by replacing each value in the first list by the corresponding element in the second list if it's greater. The replacement is done with [`map` on a dictionary's `get` method](https://codegolf.stackexchange.com/a/51621/20260). Then, swaps the lists, and repeats until they are equal.
[Answer]
# Pyth, 13 bytes
```
eMumS{s@#dGGC
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=eMumS%7Bs%40%23dGGC&input=%5B1%2C0%2C1%2C-4%5D%2C%5B-3%2C-1%2C-2%2C2%5D&debug=0)
### Explanation:
Start with each pair. Iteratively extend each pair (list) with overlapping lists, deduplicate the elements and sort. Stop once this process converges. Print the maximum of each list.
[Answer]
## Php, ~~266~~ ~~241~~ ~~213~~ 200 bytes
Solution:
```
function u($x,$y){foreach($x as$i=>$j){$k[$y[$i]][]=$j;$k[$j][]=$y[$i];}$h=function($c,&$w)use($k,&$h){$w[]=$c;foreach($k[$c]as$u)!in_array($u,$w)&&$h($u,$w);return max($w);};return array_map($h,$x);}
```
Usage: `u([1,2,3], [0,0,1]);` returns the desired array.
Not-so golfed:
```
function unify($x, $y)
{
foreach($x as $i=>$j) {
$k[$y[$i]][] = $j;
$k[$j][] = $y[$i];
}
$h = function ($c, &$w=[]) use ($k, &$h) {
$w[] = $c;
foreach($k[$c] as $u)
!in_array($u, $w) && $h($u, $w);
return max($w);
};
return array_map($h, $x);
}
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~29~~ 28 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
[`⌈/¨({∪¨,/∘.{⍵/⍨≢⍺∩⍵}⍨⍵}⍣≡,¨)`](http://tryapl.org/?a=f%u2190%u2308/%A8%28%7B%u222A%A8%2C/%u2218.%7B%u2375/%u2368%u2262%u237A%u2229%u2375%7D%u2368%u2375%7D%u2363%u2261%2C%A8%29%20%u22C4%200%201%200%202%20f%20%AF1%201%202%202&run)
Same idea as the [Pyth solution](https://codegolf.stackexchange.com/questions/99399/array-unification#answer-99537).
[Answer]
# Mathematica, 56 bytes
```
#/.($|##->Max@##&@@@ConnectedComponents@Thread[#<->#2])&
```
[Answer]
# Java, ~~273~~ 263 bytes
```
interface Z{int z(int x);default Z g(int m,int n){return x->{for(int t;x!=(t=x==m?z(n):z(x));)x=t;return x;};}static void f(int[]a,int[]b){Z y=x->x;int i=0,v;for(int u:a){u=y.z(u);v=y.z(b[i++]);if(u<v)y=y.g(u,v);if(v<u)y=y.g(v,u);}i=0;for(int u:a)a[i++]=y.z(u);}}
```
The method `f(int[]a,int[]b)` solves the challenge.
```
interface Z{
//should return an "equivalent" integer
int z(int x);
//return a Z lambda where the 1st arg is "equivalent" to the 2nd arg
default Z g(int m,int n){
return x->{
for(int t;x!=(t=x==m?z(n):z(x));) //always find the last equivalent number for x
x=t;
return x;
};
}
//solve the challenge
static void f(int[]a,int[]b){
Z y=x->x; //start off with all numbers only equivalent only to themselves
int i=0,v;
for(int u:a){
u=y.z(u); //get a's element's equivalent number
v=y.z(b[i++]); //get b's element's equivalent number
if(u<v)y=y.g(u,v); //if a's was smaller than b's, make a's equivalent to b's
if(v<u)y=y.g(v,u); //if b's was smaller than a's, make b's equivalent to a's
}
i=0;
for(int u:a) //overwrite a with each element's equivalent value
a[i++]=y.z(u);
}
}
```
First go through both arrays and keep track of equivalent numbers.
Then modify every element in the first array to have the equivalent numbers stored.
[Answer]
# Python, 522 bytes
```
a = [-2,4,-2,3,2,4,1,1]
b = [-2,4,1,2,2,3,1,-2]
m = {}
visited = {}
for i in range(len(a)):
if a[i] in m:
if b[i] not in m[a[i]]:
m[a[i]].append(b[i])
else:
l = []
l.append(b[i])
m[a[i]] = l
if b[i] in m:
if a[i] not in m[b[i]]:
m[b[i]].append(a[i])
else:
l = []
l.append(a[i])
m[b[i]] = l
def dfs(v, maximum):
if v > maximum:
maximum = v
visited[v] = True
for n in m[v]:
if not visited[n]:
d = dfs(n, maximum)
if d > v:
maximum = d
return maximum
result = []
for k in range(len(a)):
for q in m:
visited[q] = False
result.append(max(dfs(a[k], a[k]), dfs(b[k], b[k])))
print(result)
```
**Explanation**
Make a table of values corresponding to each unique element in in both arrays (`a` and `b` in this case). For example if
```
a = [0,1,0]
b = [2,1,0]
```
then the table would be:
```
0:[0,2]
1:[1]
2:[0]
```
then apply depth first search, so, for example, assume I pick the leftmost element in `a` the value is then `0` and `0` has the equivalences: `0` and `2`. Since `0` has already been visited, go to `2`. 2 has the equivalences: `0`. So the best result for choosing the leftmost element in `a` is `2`.
Here's the tree:
```
0
/ \
0 2
\
0
```
and you want to take the largest value in there, so the result is `2`.
[Answer]
# PHP, 132 bytes
```
function(&$a,$b){for(;$i<count($a);$i++){$r=$a[$i];$s=$b[$i];$r<$c[$s]?:$c[$s]=$r;$s<$c[$r]?:$c[$r]=$s;}foreach($a as&$v)$v=$c[$v];}
```
Anonymous function that takes two arrays.
This is my take on 'modify one of the arrays in place', as specified in the output of the challenge. This loops through each of the two arrays, records the equivalence if the current one is bigger than the one stored, then loops through the first array and replaces all the values with their largest equivalents. The first array is taken by reference (hence the `&$a`), so the array passed in is modified 'in place'.
[Answer]
# Java, 170 bytes
## Golfed
```
(a,b)->{int[]d=a.clone();for(int i=0,y;i<d.length;i++){y=0;for(int j=0;j<a.length;j++)if(a[j]==d[i]||b[j]==d[i])y=Integer.max(y,Integer.max(a[j],b[j]));d[i]=y;}return d;}
```
## Ungolfed
```
(a, b) -> { // Two argument lambda
int[] d = a.clone(); // We clone our first array for modification
for (int i = 0,y; i < d.length; i++) { // Going through the elements of d...
y = 0; // We initialize our 'highest' equivalent
for (int j = 0; j < a.length; j++) { // Going through each of our arrays (a and b)...
if (a[j] == d[i] || b[j] == d[i]) { // If either of them is the number we're trying to match for equivalence...
y = Integer.max(y, Integer.max(a[j], b[j])); // We see if the new number is bigger than the largest we've found.
}
}
d[i] = y; // We then assign the largest equivalent number for the current position in our output array.
}
return d; // And return!
}
```
Anonymous function that takes two `int[]`s as arguments and returns an `int[]`.
] |
[Question]
[
As a follow-up to this [challenge](https://codegolf.stackexchange.com/questions/87189/how-many-rectangles-in-the-grid), we now want to count the number of rectangles in grid with *r* rows and *c* columns where there is a line crossing through every diagonal of a square in the grid. Now, we are still counting the the same rectangles as before, but this time we must also include rectangles that are tilted by 45 degrees.
Your goal is to create a function or program that given the number of rows *r* and columns *c* outputs the number of rectangles in a diagonal grid with dimensions (*r*, *c*).
As a demonstration, this is an animation that iterates through all 37 rectangles formed by a (2 x 3) diagonal grid.

## Test Cases
```
Each case is [rows, columns] = # of rectangles
[0, 0] = 0
[0, 1] = 0
[1, 0] = 0
[1, 1] = 1
[3, 2] = 37
[2, 3] = 37
[6, 8] = 2183
[7, 11] = 5257
[18, 12] = 40932
[42, 42] = 2889558
[51, 72] = 11708274
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code wins.
* Builtins that solve this are not allowed.
[Answer]
# Ruby, 58 bytes
This is a straightforward implementation of the algorithm in [Releasing Helium Nuclei's C answer](https://codegolf.stackexchange.com/a/87595/47581).
```
g=->m,n{n>m ?g[n,m]:m*~m*n*~n/4+n*((2*m-n)*(4*n*n-1)-3)/6}
```
I have been investigating why this formula works, with limited success. It's easy to confirm that the number of upright rectangles is equal to `(m+1)*m/2 * (n+1)*n/2`, the number of diagonal rectangles is a little more elusive.
Neil has [confirmed](https://codegolf.stackexchange.com/questions/87560/count-the-rectangles-in-a-diagonal-grid/87595?noredirect=1#comment216539_87595) for `m==n` that the number of tilted rectangles in an `n*n` square is `(4*n**4-n*n-3*n)/6` and that [when](https://codegolf.stackexchange.com/questions/87560/count-the-rectangles-in-a-diagonal-grid/87595?noredirect=1#comment216544_87595) `m>n` you need to add an additional `(m-n)(n*(4*n*n-1)/3)` (related to [OEIS A000447](https://oeis.org/A000447)), though this does not explain where those two formulas came from. I have found part of the answer.
For `m==n`, the shape inside the grid is an [Aztec diamond](http://mathworld.wolfram.com/AztecDiamond.html).
[](https://i.stack.imgur.com/4vq6W.gif)
The number of rectangles in an Aztec diamond is the sum of number of large rectangles superimposed to make it (for the fourth diamond, which is found in a `5x5` grid, `2x8`, `4x6`, `6x4`, and `8x2`) minus the number of the rectangles counted twice (the number of rectangles in the **previous** Aztec diamond).
The formula here is (TeX to be added later):
```
# superimposed rectangles, 2x(2n-2), 4*(2n-4), ...
f = lambda n: sum( (2*k)*(2*k+1)/2 * (2*n-2*k)*(2*n-2*k+1)/2 for k in range(1, n) )
aztec_rect = f(n) - f(n-1)
```
According to Wolfram Alpha, the closed form for `f` is `1/30*(n-1)*n*(4*n**3+14*n**2+19*n+9)` and the closed form for `aztec_rect` is, as Neil discovered, `1/6*n*(n-1)*(4*n**2+4*n+3) == 1/6*(4*n**4-n**2-3*n)`.
I have yet to discover why `(m-n)(n*(4*n*n-1)/3)` works, though I suspect that it is because one definition of [A000447](https://oeis.org/A000447) is `binomial(2*n+1, 3)`. I will keep you posted.
**Update:** I have reason to believe that the function of the number of rectangles in an extended Aztec diamond `m>n` is related to the number of superimposed `2k*2(n-k)` rectangles in the diamond minus `F(m-1,n-1)`. More results when I have them.
**Update:** I tried a different route and ended up with another formula for extended Aztec diamonds that is mostly explainable but has one term that I don't yet understand. Huzzah! :D
```
def f(m,n):
if n > m:
return f(n,m)
if n == 0:
return 0
else:
return(m-n+1)*(4*n**4-n*n-3*n)/6-f(m-1,n-1)+(m-n)*2+(m-n)*(n-2)-(m-n-1)*f(n-1,n-1)
```
A quick breakdown of that last formula:
* `(m-n+1)*(4*n**4-n*n-3*n)/6` is the number of superimposed Aztec diamonds of size `n` in the structure, as `f(n,n) = (4*n**4-n*n-3*n)/6`. `f(7,3)` has 5 superimposed Aztec diamonds size `3`, while `f(3,3)` has only 1 diamond.
* `-f(m-1,n-1)` removes some of the duplicate rectangles from the middle of the superimposed diamonds.
* `+(m-n)*2` accounts for 2 extra `2`-by-`(2n-1)` rectangles for each extra diamond.
* `+(m-n)*(n-2)` accounts for an extra `n`-by-`n` square for each extra diamond.
* `-(m-n-1)*f(n-1,n-1)` This is the new puzzling term. Apparently I have not accounted for some extra squares in my counting, but I haven't figured out where they are in the extended diamond.
Note: when `m==n`, `m-n-1 = -1`, meaning that this last term *adds* squares to the counting. I might be missing something in my regular formula. Full disclosure, this was only meant to be a patch to an earlier draft of this formula that just happened to work. Clearly, I still need to dig into what's going on, and it may be that my formula has some bugs in it. I'll keep you posted.
Russell, Gary and Weisstein, Eric W. "Aztec Diamond." From MathWorld--A Wolfram Web Resource. <http://mathworld.wolfram.com/AztecDiamond.html>
[Answer]
# C, ~~71~~ 64 bytes
```
f(m,n){return n>m?f(n,m):m*~m*n*~n/4+n*((2*m-n)*(4*n*n-1)-3)/6;}
```
[Try it on Ideone](https://ideone.com/RaWkKJ)
[Answer]
# Python, ~~73~~ 68 bytes
```
x=lambda m,n:m*~m*n*~n/4+n*((2*m-n)*(4*n*n-1)-3)/6if m>n else x(n,m)
```
And while the following version has a higher bytecount (75), it was a nice exercise in finding places to use `~`:
```
def f(r,c):
if r<c:r,c=c,r
x=(4*c**3-c)/3
return r*c*~r*~c/4+x*r--~x*c/2
```
[Answer]
## Convex, ~~37~~ 36 bytes
```
__:)+×½½\~æ<{\}&:N\¦\-N¦¦N*(*3-N*6/+
```
[Try it online!](http://convex.tryitonline.net/#code=X186KSvDl8K9wr1cfsOmPHtcfSY6TlzCplwtTsKmwqZOKigqMy1OKjYvKw&input=&args=WzMgMl0)
Uses betseg's algorithm modified and optimized for a stack-based language. Explanation to come when I have some more free time. I bet this can be shortened but I'm not going to bother at the moment.
[Answer]
## Batch, 82 bytes
```
@if %2 gtr %1 %0 %2 %1
@cmd/cset/a%1*~%1*%2*~%2/4+((%1+%1-%2)*(%2*%2*4-1)-3)*%2/6
```
] |
[Question]
[
The task is very simple, when given an input, output one of the following spirals:
`Input = 1` gives a spiral with the letter `A` beginning in the top left corner:
```
A B C D E F
T U V W X G
S 5 6 7 Y H
R 4 9 8 Z I
Q 3 2 1 0 J
P O N M L K
```
`Input = 2` gives a spiral with the letter `A` beginning in the top right corner:
```
P Q R S T A
O 3 4 5 U B
N 2 9 6 V C
M 1 8 7 W D
L 0 Z Y X E
K J I H G F
```
`Input = 3` gives a spiral with the letter `A` beginning in the bottom right corner:
```
K L M N O P
J 0 1 2 3 Q
I Z 8 9 4 R
H Y 7 6 5 S
G X W V U T
F E D C B A
```
`Input = 4` gives a spiral with the letter `A` beginning in the bottom left corner:
```
F G H I J K
E X Y Z 0 L
D W 7 8 1 M
C V 6 9 2 N
B U 5 4 3 O
A T S R Q P
```
As you can see, the spiral always goes *clockwise* and moves from the *outside* to the *inside*.
The rules are simple:
* You need to provide a full program using STDIN and STDOUT, or the nearest equivalent if not possible.
* Given an input (`1, 2, 3, 4`), output the related spiral.
* Trailing whitespaces are allowed
* Leading whitespaces are allowed when used *consistently*
* You need to use uppercase letter for the output, lowercase letters are not allowed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the program with the least amount of bytes wins!
[Answer]
# [Japt](https://github.com/ETHproductions/Japt), 53 bytes ~~58 59 60~~
*Saved 5 bytes thanks to @ETHproductions*
```
"FGHIJK EXYZ0L DW781M CV692N BU543O ATSRQP"¸zU ®¬¸} ·
```
This uses the rotate command which I never thought would be so useful
## Explanation && Ungolfed
```
"FGHIJK EXYZ0L DW781M CV692N BU543O ATSRQP"qS zU m_q qS} qR
// Implicit: U = input
"FGH...SRQP" // String, " " represent newlines
qS // Split " "
zU // Rotate
m_ // Loop the lines
q qS} // Insert spaces
qR // Join by newlines
```
[Try it online](http://ethproductions.github.io/japt?v=master&code=IkZHSElKS3pFWFlaMEx6RFc3ODFNekNWNjkyTnpCVTU0M096QVRTUlFQInEneiB6VSCucSBxU30gcVI=&input=MQ==)
[Answer]
## CJam, ~~45~~ ~~43~~ 42 bytes
```
'[,65>A,+W%(s{W%z_,@s/(@.+}A*ri{W%z}*Sf*N*
```
[Test it here.](http://cjam.aditsu.net/#code='%5B%2C65%3EA%2C%2BW%25(s%7BW%25z_%2C%40s%2F(%40.%2B%7DA*ri%7BW%25z%7D*Sf*N*&input=1)
### Explanation
```
'[,65> e# Push the upper-case alphabet.
A,+ e# Append the digits.
W% e# Reverse everything.
(s e# Pull off the 9 and turn it into a string.
{ e# Repeat this 10 times to roll the string up in a spiral...
W%z e# Rotate the existing grid clockwise.
_, e# Duplicate grid so far and get the number of rows.
@s e# Pull up the list of characters and flatten it into one string.
/ e# Split the string into chunks of the size of the number of rows.
( e# Pull off the first chunk.
@.+ e# Pull up the grid so far and prepend the chunk as a new column.
}A* e# We now have the spiral as desired, with the A in the bottom left corner.
ri e# Read input and convert to integer.
{ e# Repeat this code that often..
W%z e# Rotate the spiral clockwise.
}*
Sf* e# Join each line with spaces.
N* e# Join the lines with linefeeds.
```
[Answer]
# Mathematica 156 bytes
Converts initial string of letters, `"ABCDEFTUVWXGS567YHR498ZIQ3210JPONMLK"`, into an array. `Nest` applies `f` to that array `n-1`times, where n is the input number. `f` works by `Transpose`-ing the array followed by `Reverse`applied to each row. `g` converts the final array into a string.
```
s=StringJoin;r=Riffle;f=Nest[Reverse/@Transpose@#&,Partition[Characters@"ABCDEFTUVWXGS567YHR498ZIQ3210JPONMLK",6],#-1]&;
g@n_:=s@r[s/@(r[#," "]&/@f[n]),"\n"]
```
---
**Example**
```
g[4]
```
[](https://i.stack.imgur.com/TszTo.png)
---
If the output could be given as an array, the function `g` would be unnecessary.
```
f[4]
```
>
> {{"F", "G", "H", "I", "J", "K"}, {"E", "X", "Y", "Z", "0", "L"}, {"D",
> "W", "7", "8", "1", "M"}, {"C", "V", "6", "9", "2", "N"}, {"B",
> "U", "5", "4", "3", "O"}, {"A", "T", "S", "R", "Q", "P"}}
>
>
>
[Answer]
# MATLAB, ~~61~~ 89 bytes
```
b=[65:90 48:57];n=zeros(12,6);n(2:2:end)=rot90(b(37-spiral(6)),input('')-2);disp([n' ''])
```
I'll see if I can get it down a bit. Not sure though.
This creates an array of all letters from A to Z followed by 0 to 9, then takes a spiral and uses that to arrange the data in the correct order. The array is then rotated by the amount the user specifies and then printed out.
The output consistently uses leading spaces as allowed by the question (in fact at no extra byte cost, it could do trailing spaces instead). Here is an example:
```
F G H I J K
E X Y Z 0 L
D W 7 8 1 M
C V 6 9 2 N
B U 5 4 3 O
A T S R Q P
```
---
As I saw that spaces are required, this original code (for 61) is not valid because it doesn't add a space between each character. But I will add it here for reference.
```
b=['A':'Z' '0':'9'];disp(rot90(b(37-spiral(6)'),6-input('')))
```
and produces:
```
ABCDEF
TUVWXG
S567YH
R498ZI
Q3210J
PONMLK
```
[Answer]
# JavaScript ES6, 165 ~~172~~
Simple rotation, starting from a hardcoded string
**Note** 1 byte saved thx @user81655
```
p=prompt();alert("ABCDEF TUVWXG S567YH R498ZI Q3210J PONMLK".split` `.map((r,y,a)=>[...r].map((c,x)=>p<2?c:a[p<3?5-x:p<4?5-y:x][p<3?y:p<4?5-x:5-y]).join` `).join`
`)
```
Test snippet:
```
// Test: redefine alert to write inside the snippet
alert=x=>P.innerHTML=x
p=prompt();
alert(
"ABCDEF TUVWXG S567YH R498ZI Q3210J PONMLK"
.split` `
.map(
(r,y,a)=>
[...r].map(
(c,x)=>p<2?c:
a
[p<3?5-x:p<4?5-y:x]
[p<3?y:p<4?5-x:5-y]
).join` `
).join`\n`
)
```
```
<pre id=P></pre>
```
[Answer]
# Pyth - 60 bytes
Hardcodes the string and uses matrix operations to get all the options.
```
jjL\ @[_CKc6"ABCDEFTUVWXGS567YHR498ZIQ3210JPONMLK"KC_K__MK)Q
```
[Test Suite](http://pyth.herokuapp.com/?code=jjL%5C+%40%5B_CKc6%22ABCDEFTUVWXGS567YHR498ZIQ3210JPONMLK%22KC_K__MK%29Q&test_suite=1&test_suite_input=1%0A2%0A3%0A4&debug=1).
[Answer]
# Ruby, 173 bytes
```
->i{_,r,o=->s{s.map{|i|i*' '}},->s{s.transpose.map{|i|i.reverse}},%W(ABCDEF TUVWXG S567YH R498ZI Q3210J PONMLK).map(&:chars);puts i<2?_[o]:i<3?_[t=r[o]]:i<4?_[r[t]]:_[r[r[t]]]}
```
**Ungolfed:**
```
-> i {
_ = -> s { s.map{|i| i*' ' } }
r = -> s { s.transpose.map{|i| i.reverse } }
o = %W(ABCDEF TUVWXG S567YH R498ZI Q3210J PONMLK).map(&:chars)
puts i<2?_[o]:i<3?_[t=r[o]]:i<4?_[r[t]]:_[r[r[t]]]
}
```
**Usage:**
```
->i{_,r,o=->s{s.map{|i|i*' '}},->s{s.transpose.map{|i|i.reverse}},%W(ABCDEF TUVWXG S567YH R498ZI Q3210J PONMLK).map(&:chars);puts i<2?_[o]:i<3?_[t=r[o]]:i<4?_[r[t]]:_[r[r[t]]]}[4]
F G H I J K
E X Y Z 0 L
D W 7 8 1 M
C V 6 9 2 N
B U 5 4 3 O
A T S R Q P
```
[Answer]
## Python, 152 bytes
```
s=[r for r in "ABCDEF TUVWXG S567YH R498ZI Q3210J PONMLK".split(" ")]
for i in range(1,int(input())):s=zip(*list(s)[::-1])
for x in s:print(" ".join(x))
```
] |
[Question]
[
StickStack is a very simple stack-based programming language with only two instructions:
* `|` pushes the length of the stack onto the stack
* `-` pops the top two elements from the stack and pushes back their difference (`second topmost - topmost`)
## Language details
* The stack is empty at the start of the program.
* All instructions are executed sequentially from left to right.
* If there are less than 2 numbers on the stack the `-` instruction is illegal.
* At the end of the execution the stack should contain **exactly one number**.
Any integer can be generated by a StickStack program. For example:
```
|||--||-- generates the number 2 through the following stack states:
[]
[0]
[0, 1]
[0, 1, 2]
[0, -1]
[1]
[1, 1]
[1, 1, 2]
[1, -1]
[2]
```
To evaluate your StickStack code you can use [this online (CJam) evaluator](http://cjam.aditsu.net/#code=q'%7C%2F%22%5D_%2C%2B~%22*~%5DS*&input=%7C%7C%7C--%7C%7C--). (Thanks for @Martin for the code.)
## The task
You should write a program or function which given an integer number as input outputs or returns a string representing a StickStack program which outputs the given number.
## Scoring
* Your primary score is the **total length of the StickStack programs** for the below given test cases. Lower score is better.
* Your submission is valid only if you ran your program on all the test cases and counted your score.
* Your secondary (tiebreaker) score is the length of your generating program or function.
## Input test cases
(Each number is a different test case.)
```
-8607 -6615 -6439 -4596 -4195 -1285 -72 12 254 1331 3366 3956 5075 5518 5971 7184 7639 8630 9201 9730
```
Your program should work for any integers (which your data-type can handle) not just for the given test cases. The solutions for the test numbers should not be hardcoded into your program. If there will be doubt of hardcoding the test numbers will be changed.
[Answer]
# Java, 5208 ~~5240~~ ~~5306~~ ~~6152~~
This is a recursive function that edges closer to the target, with base cases for when it gets within 5 (which is often only one step).
Basically, you can get `(a*b)+(a/2)` for `(a+b)*2` sticks with a simple pattern. If `a` is odd, the result will be negative, so that leads to some weird logic.
This takes a minute or so for 231-1, with a length of 185,367 as the result. It works almost instantly for all test cases, though. It scores `4*(sqrt|n|)` on average. The longest individual test case is `9730`, which results in a 397-length stick stack:
```
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||-|||||||||||||||||||||-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|-|--------------------------------------------------------------------------------------------------|-
```
**Update:**
Found a shorter way to add/subtract from the basic pattern. Back in the lead (for now)!
---
With a harness and test cases:
```
import static java.lang.Math.*;
public class StickStacker {
public static void main(String[] args){
StickStacker stacker = new StickStacker();
int tests[] = {-8607,-6615,-6439,-4596,-4195,-1285,-72,12,254,1331,3366,3956,5075,5518,5971,7184,7639,8630,9201,9730};
int sum = 0;
for(int test : tests){
String sticks = stacker.stickStack3(test);
sum += sticks.length();
System.out.println("In: " + test + "\t\tLength: " + sticks.length());
System.out.println(sticks+"\n");
}
System.out.println("\n\nTotal: "+sum);
}
String stickStack3(int n){return"|"+k(n);}
String k(int n){
String o="";
int q=(int)sqrt(abs(n)),a,b,d=1,e=0,c=1<<30,
z[]={232,170,42,10,2,0,12,210,52,844,212};
a=n>0?q:-q;
a-=n>0?a%2<1?0:1:a%2<0?0:-1;
for(b=0;b<abs(a)+10;b++)
if(abs(n-(a*b+a/2-(n>0?0:1)))<abs(a)&&abs(a)+b<c){
c=abs(a)+b;
d=a;e=b;
}
for(a=0;a++<e;)o+="-|";
for(a=0;a++<abs(d);)o="|"+o+"-";
c=n-(d*e+d/2-(n>0?0:1));
if(c>0&&c<abs(d)){
if(c%2==0)
o=o.substring(0,c)+"-|"+o.substring(c);
else
o=o.substring(0,c+1)+"-|"+o.substring(c+1)+"|-";
c=0;
}else if(c<0&-c<abs(d)){
if(c%2!=0)
o=o.substring(0,-c)+"-|"+o.substring(-c);
else
o=o.substring(0,-c-1)+"-|"+o.substring(-c-1)+"|-";
c=0;
}
return n==0?"":n<6&&n>-6?
Long.toBinaryString(z[n+5])
.replaceAll("0","-")
.replaceAll("1","|"):
o+k(c);
}
}
```
Will golf (more) in the unlikely event of an exact tie.
[Answer]
# Python 2 - 5188
Quite efficient time-wise, and seems to be (probably) the optimal solution. I observed that a pattern such as
`|||||-|||-|-|-|------` (an optimal solution for 25)
can be delineated as
```
0 |
-1 |
+2 | -
-3 | -
+4 | | -
-5 - | -
+6 | | | | -
-7 - - - -
```
where each the total value at the end is the sum of (each level's value times the number of '|'s ). So for example above, we have `-1*1 + 2*1 - 3*1 + 4*2 - 5*1 + 6*4 = 25`. Using this I wrote this solution which produces similar output to other answers, and in a trivial amount of time.
I believe this is the optimal solution, as I test every possible optimal height (I actually test many more than necessary) and I'm pretty sure the solution always involves at most one layer with two '|'s besides the last (I can guarantee this for positive numbers but not 100% sure about negatives).
```
def solution(num):
if num == 0:
return '|'
neg = num<0
num = abs(num)
high = int(num**0.5)
def sub(high):
counts = [1]*high
total = num - (high+neg)/2
if total%high == 0:
counts[-1] += total/high
else:
counts[-1] += total/high
if (total%high)%2==1 and not neg:
counts[-1] += 1
counts[-(total%high)-1] += 1
elif (total%high)%2==0 and neg:
counts[(total%high)-2] += 1
counts[0] += 1
else:
counts[total%high-1] += 1
string = ""
for c in counts[::-1]:
string = '|-'*(c-1)+'|'+string+'-'
return '|'+string
return min((sub(h) for h in range(2-neg,2*high+2,2)), key=lambda s: len(s))
```
Here is the code I used to test it
```
string = "-8607 -6615 -6439 -4596 -4195 -1285 -72 12 254 1331 3366 3956 5075 5518 5971 7184 7639 8630 9201 9730"
total = 0
def string_to_binary(string):
total = 0
for i,char in enumerate(string[::-1]):
total += (char=='|')*(2**i)
return total
def stickstack(bits,length):
stack = []
for i in range(length):
d,bits = divmod(bits,2**(length-i-1))
if d == 1:
stack.append(len(stack))
else:
stack[-2] -= stack[-1]
stack = stack[:-1]
return stack
for num in string.split():
s = solution(int(num))
print '%s:' % num
print s
result = stickstack(string_to_binary(s),len(s))
print 'Result: %s' % result
print 'Length: %s' % len(s)
total += len(s)
print
print 'Total length: %s' % total
```
[Answer]
# JavaScript (ES6) 5296 ~~6572~~
**Edit** As I said in my explanation, I'm not good at solving integer equations. My guess of b value was not so good, so I have widened the range of values to try. ~~And (wow) I'm leading by now.~~
**Edit 2** Bug fix, same results. I have an idea, but cant't nail it down.
Bytes: ~460, quite golfed. It works on 32 bit integers, run time near 0.
The code is the F function (hidden in the snippet) below.
Run the snippet to test (in FireFox).
```
F=n=>{
l=1e8;
v=Math.sqrt(n>0?n:-n)/2|0;
p='|';
if (n)
for(b=v>>2|1;b<=v+v+9;b++)
[w=n>0?(n-b)/(2*b)|0:(-n-b)/(2*b-1)|0,w+1].map(r=>(
t=2*r*b+b, d=n-t, n<0?t=r-t:0,
q=n>0?'|'.repeat(2*b+1)+'-|'.repeat(r)+'-'.repeat(2*b)
:'|'.repeat(2*b)+'-|'.repeat(r)+'-'.repeat(2*b-1),
q+=t<n?'||--'.repeat(n-t):'|-'.repeat(t-n),
m=q.length,m<l&&(l=m,p=q)
))
return p
}
// Test --------------------------------------------
FreeTest=_=>{var n=IN.value|0,s=F(n)
LEN.value=s.length,CK.value=Check(s),ST.innerHTML=s}
Check=t=>{var s=[],a,b;
[...t].forEach(c=>c=='|'? s.push(s.length):(b=s.pop(),a=s.pop(),s.push(a-b)))
return s.pop()}
ot=[];
tot=0;
[-8607,-6615,-6439,-4596,-4195,-1285,-72,
12,254,1331,3366,3956,5075,5518,5971,7184,7639,8630,9201,9730]
.forEach(x=>{
s=F(x), k=Check(s), l=s.length, tot+=l,
ot.push(`<tr><td>${x}</td><td>${l}</td><td>${k}</td><td class='S'>${s}</td></tr>`)
})
ot.push(`<tr><th>Total:</th><th>${tot}</th></tr>`)
TOUT.innerHTML=ot.join("")
```
```
td.S { font-size: 8px; font-family: courier}
pre { font-size: 8px; }
input { width: 6em }
```
```
Free test: <input id="IN" value=1073741824>
<button onclick="FreeTest()">-></button>
Len:<input readonly id="LEN"> Check:<input readonly id="CK">
<pre id=ST></pre>
<table><thead>
<tr><th>Number</th><th>Len</th><th>Check</th><th>Sticks</th></tr>
</thead>
<tbody id=TOUT></tbody>
</table>
```
**Explanation**
Positive numbers, to begin with.
Start with a "base" (try in CJam if you like, spaces allowed)
```
| gives 0
||| -- gives 1
||||| ---- gives 2
||||||| ------ gives 3
```
Summary: 1 stick, then b\*2 sticks, then b\*2 dashes
Then try adding one or more '-|' in the middle split. Each one add a fixed increment that is two time the starting base and can be repeated many times.
So we have a formula, with b=base and r=increment repeat factor
```
v=b+r*2*b
b=1, r=0 to 3, inc=2
| || -- 1
| || -| -- 3
| || -| -| -- 5
| || -| -| -| -- 7
b=3, r=0 to 3, inc=6
| |||||| ------ 3
| |||||| -| ------ 9
| |||||| -| -| ------ 15
| |||||| -| -| -| ------ 21
```
See? The addes value increases quicky and each addition still is only 2 chars. The base increment gives 4 more chars each time.
Given v and our formula v=b+r\*2\*b, we need to find 2 ints b and r. I'not an expert in this kind of equation, but b=int sqrt(v/2) is a good starting guess.
Then we have an r and b that together give a value near v. We reach v exactly with repeated increment (||--) or decrement (|-).
Follow the same reasoning for negative numbers, alas the formula is similar but not equal.
[Answer]
# JavaScript, 398710
## 94 bytes/chars of code
I came up with a solution! ... and then read Sparr's answer and it was exactly the same.
Figured I would post it anyway, as js allows for slightly fewer chars.
Here's an unminified version of the code:
```
function p(a){
s = "";
if(a<=0){
for(i=0; i<-2*a-1;i++)
s="|"+s+"-";
return "|"+s;
}
return "|"+p(0-a)+"-";
}
```
[Answer]
# Python, 398710 (71 bytes)
Simplest possible solution, I think. Uses 4\*n (+/-1) characters of stickstack to represent n.
```
def s(n):return'|'*(n*2+1)+'-'*n*2 if n>=0 else'|'*(n*-2)+'-'*(n*-2-1)
```
] |
[Question]
[
## Background
When searches return many pages of results, GitHub avoids cluttering their UI by eliding page links. Instead, their UI lets you select:
1. Pages at the beginning of the results.
2. Pages near the current page.
3. Pages at the end of the results.
In this way, no more than 11 page links are ever displayed at one time. Before describing the precise logic underlying the pager, a few screenshots will help demonstrate it:
[](https://i.stack.imgur.com/N4S8L.png)
[](https://i.stack.imgur.com/SC1m9.png)
[](https://i.stack.imgur.com/Yx5bw.png)
[![GitHub page buttons 1 2 … 92 93 [94] 95 96 … 99 100](https://i.stack.imgur.com/odr8V.png)](https://i.stack.imgur.com/odr8V.png)
[![GitHub page buttons 1 2 … 93 94 [95] 96 97 98 99 100](https://i.stack.imgur.com/8k05a.png)](https://i.stack.imgur.com/8k05a.png)
[![GitHub page buttons 1 2 … 96 97 98 99 [100]](https://i.stack.imgur.com/PO6dQ.png)](https://i.stack.imgur.com/PO6dQ.png)
## The logic
Assuming a total of `n` results, and a current page of `p`, the pager will always show:
1. The current page.
2. The 4 pages closest in absolute distance to the current page.
* That is, it will show a "window" of length 5, centered on the current page, but shifting as needed if the current page is too close to one of the boundaries (the first or last page).
3. The first 2 pages.
4. The last 2 pages.
5. All other contiguous pages besides these will be elided with a single `...`, with one exception:
* If only 1 page would be elided, simply show that page rather than the `...`, because it's going to take up the same amount of space anyway.
As an aside unrelated to the challenge, it's interesting that [Stack Overflow does not follow the exception to rule 5](https://i.stack.imgur.com/SmNi2.png).
## Task
**Input:** A total number of pages `n` and a current page `p`.
**Output:** A list containing all the pages, in order, to be shown by the GitHub pager, with logic as described above. You may use any value that is not a possible page value to represent the ellipses. For example, -1, infinity or 0 (but 0 is only valid if you are using 1-based indexing).
* You can use 0-based or 1-based indexing.
* You can take input and output in any reasonable format (e.g. output can be an array, 1 number per line, etc.)
This is code golf with standard site rules.
## Test Cases
Format will be `[n, p] => <output list>`, using -1 to represent ellipsis. Test cases use 1-based indexing.
```
[1, 1] => [1]
[2, 1] => [1, 2]
[2, 2] => [1, 2]
[5, 1] => [1, 2, 3, 4, 5]
[5, 5] => [1, 2, 3, 4, 5]
[11, 6] => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[11, 5] => [1, 2, 3, 4, 5, 6, 7, -1, 10, 11]
[12, 6] => [1, 2, 3, 4, 5, 6, 7, 8, -1, 11, 12]
[12, 7] => [1, 2, -1, 5, 6, 7, 8, 9, 10, 11, 12]
[13, 7] => [1, 2, -1, 5, 6, 7, 8, 9, -1, 12, 13]
[100, 1] => [1, 2, 3, 4, 5, -1, 99, 100]
[100, 100] => [1, 2, -1, 96, 97, 98, 99, 100]
[100, 99] => [1, 2, -1, 96, 97, 98, 99, 100]
[100, 98] => [1, 2, -1, 96, 97, 98, 99, 100]
[100, 95] => [1, 2, -1, 93, 94, 95, 96, 97, 98, 99, 100]
[100, 94] => [1, 2, -1, 92, 93, 94, 95, 96, -1, 99, 100]
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 103 bytes
```
lambda n,m:[S&{i+1}and i for i in range(n)if{i}&(S:={0,1,2,*range(min(n-5,m-2),max(6,m+4)),n-2,n-1,n})]
```
[Try it online!](https://tio.run/##nZFBasMwEEX3PcVAIUjNGCTZSqxATpFlmoVK6lRQTYzJosX47K7sUohtmZoIRgv9/@aPpPL79nGlNC@rtti/tp/Wv50tEPrd8bCq3Vo2ls7goLhWYXcElaXLOyPuito1K3bY7WuBEhW@/CreEaNEo08UR2@/2Ab9OuMcKVGhJFLDT21ZObqxgkkECWElknN4hqM8Pf1JaiwhqIGq5lUdYRFShAxBD2x6gU2G882cLUgIW4QcwYRUEUoOUf0fmsgIqJZl9mxXashuJ2znjE47gtOFcJ/cfVJ6BwvRv/zM1B1i@lwxZoSYBpoQZ0KeyecwY@AhLH8M0zEs3M5knbioRRZroaZt7p@q/QE "Python 3.8 (pre-release) – Try It Online")
0-indexed. Use `set()` for ellipsis. And it can be [97 bytes](https://tio.run/##nZHLasMwEEX3/YqBQpCaMehhJVYgX5FlmoVL61RQTYzJIsH4213JpRA/0poIZqN7z9zRqLyeP0@ks7Jqi@1r@5X7t/ccCP1mv1vUbimb4lSBA0dQ5XT8YMRdUbtmwXabbS1QosKXH8U7YpQY9Inm6PMLW6Ffas6REhVKIjX80JaVozMrmESQEA7n8Ax7eXj6FVRfQFA9Td3TzIhD0AgpgumZzL8mGe5X06YgIKwRMgQb8kQo2QfN32AiJzA1J68jY6k@uR6Q0Tc55wDVs9AuNX6JvkGF6HY9OW8EbJcphoQQwzAbomzIstk9yFp4AMoegcwYCq@yaZRmNUjHDdS4ye2C2m8) if we can output each page numbers as a set.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes
```
_2«Ɠ»3,‘ŻạⱮ«4§<11×RŒg§
```
[Try it online!](https://tio.run/##ATQAy/9qZWxsef//XzLCq8aTwrszLOKAmMW74bqh4rGuwqs0wqc8MTHDl1LFkmfCp///OTX/MTAw "Jelly – Try It Online")
Takes page count as a command-line argument and page number from standard input. 1-based, using 0 for elided pages.
## Algorithm
In order to handle the special case of showing five pages at one end if the active page happens to be there, the page number \$p\$ is clamped into the range \$[3, n-2]\$ (this is impossible if there are 4 or fewer pages, but in that case, the algorithm gives the correct result regardless of the page number because the first two and last two pages cover the whole range). The idea is that instead of having a special case, we can just use the "natural" behaviour of showing pages within two spaces of the current page in order to show the five pages at an end.
For each page, its page number is then compared to \$0\$, the clamped value of \$p\$, and \$n+1\$, looking for the absolute distance. If the page is within two pages of any of these anchors, then we want to display its page number. We also want to display a page if it's within three pages of two of the anchors (if the anchors are on the same side of the page, it'll necessarily be within two pages of one of them because no two anchors can be in the same place; if the anchors are on opposite sides, then they're forming a one-page gap which needs to be displayed rather than elided). To accomplish this check, any absolute distance that's 4 or greater is clamped to 4, and then the three absolute distances are added together. If we're within two pages of any anchor, the sum will be at most \$4+4+2=10\$ (but could be lower). If we're within three pages of two anchors, the sum will be at most \$4+3+3=10\$ (again, it could be lower). If neither of these conditions hold, the sum will be at least \$4+4+3=11\$. So we can check whether a page should be displayed by seeing whether the sum is in the range \$[0,10]\$ or not.
Once the list of pages to include has been determined, they're converted into a list of page numbers of the appropriate format (by pointwise-multiplying the "should be included" boolean by the page number, and then collapsing runs of consecutive zeroes). The runs of consecutive zeroes can be detected by looking for runs of consecutive equal elements, because all the included page numbers will be different from each other.
## Explanation
```
_2«Ɠ»3,‘ŻạⱮ«4§<11×RŒg§
Ɠ Read and parse standard input
¬´ Clamp to at most
_2 {the argument} minus 2
»3 Clamp to at least 3
, Form a 2-element list with
‘ {the argument} plus 1
Ż Prepend 0
Ɱ For each number from 1 to {the argument}
·∫° take its absolute difference with {each list element}
¬´4 Clamp to at most 4
§ For each {page}, sum the three clamped differences
<11 1 for sums below 11, 0 for sums at least 11
√ó Multiply
R {pointwise} by a list from 1 to {the argument}
Œg Group consecutive equal elements
§ Replace each {group} with its sum
```
[Answer]
# [Python](https://www.python.org), 98 bytes (@xnor)
```
lambda n,k:[1,2,3*(k<7),*range(max(6,min(k,m:=n-2))-2,min(max(6,m),k+3+2//k)),m*(k+6>n),n-1,n][:n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZLRToMwGIUTL_cUf3bVjh9HC2yUyF4EuWARlACFTGb0WbxZYvSd9GlsYegQ4rKLJuWc75y_bXj9qF-ah0oe3tLg9n3fpKb3uS3icnsXg8TcDxlytBckv1lTXOxieZ-QMn4mKywzSXIs_UCanFKTt8LRopgbtsGXy5xSLFXaWG0kRWkylFHoy6iflFY7KCCTUNWJJBb1Z0DUWIoVBFDGNUme4gKL68e6yBoyh2ADc0pnUO8y2ZAwA5U3GeiaTNekbToKggq7Le0mHb6u9uoqwCJdEbJoFvLfLwTeCXwguAMCwUZwENzOcacdpoTVhKVUhDWChyBUraUWO-JTTT1uslOYn-1ueb34kV-f8tqdPEkfsM8H2gn67WwdsKzpN-o40Q6wfkC1_VMuVLVQ3cIb0UJcAnuXwO4IVscWjnb-DzqjIB-HBzfvfr9v)
### Old [Python](https://www.python.org), 101 bytes
```
lambda n,k:[1,2,3*(k<7),*range(max(4,min(k-2,n-4)),min(max(6,n-2),k+3+2//k)),(n-2)*(k+6>n),n-1,n][:n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZLRToMwFIYTL_cUJ7tqt4OjBTa6yF4EuWARlACFTGb0WbxZYvSd9Gk8hU03IS67aNJz_u__T9v09aN-aR4qvXtLg9v3bZNa_mdSxOX6LgaN-TIUKNGZsPxmwXGyifV9wsr4mblYZprllkRtuZy3lenPqZYc86kzlbNZTgozDQqYzleakypQR-FSR_th67TaQAGZhqpONLP5cgSMJnOsIIAyrlnyFBdYXD_WRdawMQQrGHM-gnqT6YaFGZDfEmBiMhOTtu4oCCrstrybtPu62tJtQEQmIhTRKJS_FYLsGvKk4Z0QCA6Ci-B1ijesCGrMByTqIiwQfARFsTYtsceHkg64JY5heTa75c2Se35xzBt18CQHg3Pe0E4wb-cYg20Pv1HHqXaA_QPS9k-4omhF2crv0UpdAvuXwF4PpmMr1yj_G92eUfbNJzfvvt83)
### Old [Python](https://www.python.org), 110 bytes (@tsh)
```
lambda n,k:range(1,-~n*(n<9))or[1,2,3*(k<7),*range(max(4,min(k-2,n-4)),min(n-2,k+3+2//k)),(n-2)*(k+6>n),n-1,n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZLBToNAEIYTj32KSU-77WDZBVq2KX2RyoHGogRYCFKjF1_ESxOj76RP4yy02gqx6WGTnZnv_2dms68f5XN9X-jdWxzcvG_r2PI_dRbl69sINKbzKtJ3GybQetEjpheK86JaCZTojFi6mHEctUQePTEX80Sz1JKoLZfzJtIUpWNnLCeTlFIm5qQcT5eaEyZQh_uu67ioIINEQ1FuNLP5fACMRuBYQAB5VLLNY5Rhdv1QZknNhhAsYcj5AMoq0TVbJUB6S4CxSYxN3KjDICiwvfK20-7raksrgAiNxUqEg5X8jRBkm5AnCe-EQHAQXASvrXj9FUGJaU-JsggzBB9Bka1NR-zxPqcDboljWJ71bnhz5J6fHfOm2jvJQeCcFzQdzNs5RmDb_W_UcqppYP-AdP1jrshakbfyO7RSl8D-JbDXgWls5ZrK_0K3I5Rd8cnm7ff7Bg)
### Old [Python](https://www.python.org), 112 bytes
```
lambda n,k:range(1,-~n*(n<9))or[1,2,3*(k<7),*range(max(4,k-2--2//(k+~n)),min(n-2,k+3+2//k)),(n-2)*(k+6>n),n-1,n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZLRToMwFIYTL_cUJ7tqx6mjBTa6jL0IcoFxKAEKQWb0Zi_izRKj76RPYwubbkJcdtGk_c_3_-e06etH9dI8lGr3lgQ375smYf5nlcfF7V0MCrNFHav7NeHItmpC1FJSWtYhR4HOhGTLOcVJRxTxM3ExY4IxMZ2SzNoqSrFIFVFMYGY5lpYzLZkz1V5rtlIUFeOoon3f26SsIYdUQVmtFbHpYgRED0GxhACKuCLrpzjH_PqxytOGjCFYwZjSEVR1qhoSpqD9jIOJSU1M0rqjICix29Ku0-7raqMvATwyESGPRqH4PSGIThAngndCIDgILoLXVbzhCtfCbKCkVYQ5go8gdaytF9_jQ0kHnPFjWJzNbnmzxJ6fH_OmOjjJweCcN7QdzNs5xmDbw2_UcbJtYP-AevsnXOpoqbOl36OlvAT2L4G9HqzHlq6p_G90e0bRN5_cvPt-3w)
Thanks to @tsh for spotting typo.
1-based, 0 for ellipsis. Outputs a range object instead of a list if n<9. If that is not acceptable we can add 3 bytes or switch to python 2.
[Answer]
# Python3, 194 bytes:
```
lambda n,p:F([[-1,i][i<3 or p+4-2*(p-2>0)>=i>=p-2-2*(n-p<2)+(n-p==1)or i>n-2]for i in range(1,n+1)])
F=lambda j,l=0:j if[]==j else[[[-1,l+1][l+2 in j],j[0]][j[0]!=-1]]*(j[0]+l!=-2)+F(j[1:],j[0])
```
[Try it online!](https://tio.run/##lZLLbsIwEEXXzVdM2RATp4odUgjCWbLsD7heBJG0joyxkqhSv56OebUUBGJhZx7nznUsu@/@c2PTqWu3tXjfmnK9XJVgqZstQiljRrWSep7CpgUXjWM@Cl3Mi4QUQhcCQ1@xsZtzEvmvEIwgqgsbc1X7CLSFtrQfVciojRhRJFiIg01DjUhmDehaKiEaqExXyZ2riZiSJuJe3SjayEQp6fdnETOlRqGPI4MZGi8wY7M9RbYdCBgMBoFkFJgCUYBkKpD8N6PA9wV@VsjOCAophTGFbN/JrncYFl6vtLBKYUJhSiHHsQkudsCzG3jM/sL87uwd7xc/8JO/vO9ePclRkN4X7Bz83aVekCTX72jP5TuD5ARi@G94jqNznJ1PL@g8fwSePgJnFzAeOx/7zm3h@ELIL8Vnf@4f3unZ19r0VRu@bWxFoXvpnNF9OHy3Q0JmwVNJl/hS16ULq6/SUNBHwHsigkTXVW0PdTgqCQgByyBwrbaI9FXXd@A8sBqS7Q8)
[Answer]
# [Python](https://www.python.org), 151 bytes
```
lambda l,k:re.sub(' +',' . ',' '.join(str(i)if(i<2 or i>l-3or k-3<i<k+3or(i<5and k<6)or(i>l-6and k>l-7))else''for i in range(l))).split(' ')
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nZNLbsIwEIYXXZFTTNk4LibKg1cQ4SIhQgGc1iWEyDZSe4luu-iGRds7taepnRQIgQrRhePxzHz_b1mZt8_8WT6ss-17AsHkYyOT9uDrNY1Xs0UMKVkOObXEZmYigBYiCCzQX2Q9rllmCslNhllispELaw5snLY9tS_b3oiNli0Vq1I3zhawHPWwPqmOXnFWQR9jmgqKUKJZYBnwOLunZooxtkSeMqlsETbYKl9zCZyW1_u-eTE0IamQ03ksKAH6lNO5pIspp2KTSi0VGo0wdAjYERAInSgiOuHuEwTcQ86p57rVPgIegQ6B7qHY-bPoODo-qRLoEegTGBDwlZ-tllMhzujtCGShOuBesigZVXXcCtOrMEXH2VtVIe8yVFrpN_R2lG2ffb3fXr9wsqvNvl838ZWFrzz8wXlgcC3QvxbonACezqrVvQx7J7B7KnD8GtHQaOScZdI8_NfNYDyRTZKYd_scxru2sJi-toOBJcBuAyUHepy0LuwnqjYZkcJjIagapyNVCAL4n6ABUI7ldlvuPw)
Returns a list of strings. Abuses regex to remove duplicate spaces. Elipsed pages are replaced with a `.`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~45~~ ~~ 44 ~~ 38 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
[*Crossed out 44 is no longer 44 :)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44)
```
4ÝÍ+¤I-F<}¬(ƒ>}3LìI2Ý-«ILÃïêD¥Θ2ä1.ý˜*
```
Inputs in the order \$p,n\$. Outputs with 0 for the ellipsis.
[Try it online](https://tio.run/##AUsAtP9vc2FiaWX//zTDncONK8KkSS1GPH3CrCjGkj59M0zDrEkyw50twqvKkjDigLp9ypJAfcOqRMKlzpgyw6QxLsO9y5wq//85NQoxMDA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCqEvYf5PDcw/3ah9aEqHrZlN7aI3GsUl2tcY@h9dEGB2eq3todYTP4ebD6w@vcjm09NwMo8NLDPUO7z09R@u/zv/oaEMdw1gdIGkEJI3ApKGOKZA0BZNmOoaGYA6YAvJACszhlDFYuaGBAYg2MICyLC1hDAsYwxTGMAEzYgE).
**Explanation:**
Step 1: Create list `[1,2,3,p-2,p-1,p,p+1,p+2,n-2,n-1,n]`, while keeping \$p-2\$ and \$p+2\$ in bounds, and remove any overlapping duplicated values:
```
4√ù # Push list [0,1,2,3,4]
Í # Decrease each by 2 to [-2,-1,0,1,2]
+ # Add each to the first (implicit) input p: [p-2,p-1,p,p+1,p+2]
¤ # Push the last value / maximum (without popping the list): p+2
I- # Decrease it by the second input n
F } # (If it's positive) loop that many times:
< # Decrease the values in the list by 1 each iteration
¬ # Push the first value / minimum (without popping the list): p-2
( # Negate it
ƒ } # (If it's now non-negative) loop that + 1 amount of times:
> # Increase the values in the list by 1 each iteration
3Lì # Prepend-merge list [1,2,3]
2√ù # Push list [0,1,2]
I - # Subtract each from the second input n: [n,n-1,n-2]
¬´ # Merge that list
IL # Push a list in the range [1,n]
à # Only keep those values from the list, removing out of bounds values
ï # `Ã` converts the values to strings, so convert them back to integers
ê # Sorted-uniquify the list
```
Step 2: Insert the `0`s where necessary, and output the result:
```
D # Duplicate this list
¥ # Pop the copy, and push its forward differences
Θ # Check for each whether it's equal to 1 (1 if 1; 0 otherwise)
2√§1.√ΩÀú # Insert a 1 in the middle of the list:
2√§ # Split it into two equal-sized parts
1.√Ω # Intersperse with 1
Àú # Flatten it back to a single list
* # Multiply the values at the same positions
# (after which the result is output implicitly)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~34~~ ~~32~~ ~~30~~ ~~29~~ 28 bytes
```
R©ạÞḣ5;⁸’¤;2ḣ⁸Ṭµ+3\Ịݬo×®Œg§
```
[Try it online!](https://tio.run/##AUQAu/9qZWxsef//UsKp4bqhw57huKM1O@KBuOKAmcKkOzLhuKPigbjhuazCtSszXOG7isW7wqxvw5fCrsWSZ8Kn////MTL/Ng "Jelly – Try It Online")
Thanks to Unrelated String for -2 byte.
### Explanation (outdated)
```
R© Range and copy to register.
√û Sort by...
·∫° Absolute difference with p.
·∏£5 First 5 elements.
;⁸’¤;2 Append n-1 and 2.
®œ& Intersection with register, for the special case that n=1.
·π¨ Untruth (boolean array from truthy indices).
µ Chain separator.
·π°3 All slices with length 3.
§ Sum each slice.
2= True if equals to 2.
1; Prepend 1.
| Vectorized OR with the result of the previous chain.
×® Vectorized multiplication by the register.
Œg Group nearby equal elements. Only possible for the zeros.
§ Sum each group.
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 158 bytes
```
.+
$*
\G1
$`1
¶
O`1+
\b(1+) \1\b
<$1>
(?=(1+ ){0,2}<)((1+ |<1+> ){5}).+ 1+( 1+ 1+)
$2...$4
(1+ 1+ )1+ .+(( 1+| <1+>){5})(?<=>( 1+){0,2})
$1...$2
<|>
1+
$.&
```
[Try it online!](https://tio.run/##JU4xDsIwDNzvFR4CSgiK4tAAldIyMjKwdiiVGFgYEBvtt3gAHytOKvnu7HMu8uv@fjxv80pfe5qdhdqgOzNUz4TfF7j0bNENmq2hjrsBSXELfWrEIfPx2zAlo/MwJratWHEyzhJbLZAyUME5pyroMpMROKvzeqScKRF9Sk2bveVPSXFOBaSxBeQG5dbzzMQIBQFRNFIEM@0zSRdyF@gA3mXyXp4U9r5oXS9yXCQuUv0B "Retina 0.8.2 – Try It Online") Takes newline-separated values but link is to test suite that splits on spaces for convenience. Explanation:
```
.+
$*
```
Convert to unary.
```
\G1
$`1
```
Generate all of the page numbers.
```
¶
```
Concatenate the current page.
```
O`1+
```
Sort it into position, so it's now a duplicate.
```
\b(1+) \1\b
<$1>
```
Change the duplicate into a marking.
```
(?=(1+ ){0,2}<)((1+ |<1+> ){5}).+ 1+( 1+ 1+)
$2...$4
```
Elide at least two page links starting from three pages after the current page to two pages before the last page, but also not starting before page 6.
```
(1+ 1+ )1+ .+(( 1+| <1+>){5})(?<=>( 1+){0,2})
$1...$2
```
Elide page links before the current page, using the same rules but mirrored.
```
<|>
```
Remove the marking for the current page.
```
1+
$.&
```
Convert to decimal.
[Answer]
# JavaScript (ES6), 106 bytes
Expects `(n)(p)`. The output is 1-indexed, with `0` for ellipsis.
```
n=>g=(p,b=k=i=[])=>++k>n?b:g(p,k<(p<3?6:3)|k>n-(p+3>n?5:2)|(p-=k)*p<9?[...b,...k>++i?[k+~i?0:i]:[],i=k]:b)
```
[Try it online!](https://tio.run/##pZGxboMwEIb3PsWNdjEEm5hghOFBEENIE0QdAWqqTlFfnR50aQAjqgy@wfd/353h/fh1vJ0@6u7Tbdq3c3/RfaPTSpOOldroWucF1anjmLTJyrjCa5OQLgmyMA7oHW9d0jkBNmUs6J10rjb0tUtUlnueVzIsBuk6y43zXWd@XBdxXrBamyIuaX9qm1t7PXvXtiIXAsDpWCjsdpDz4mXaFw99BsISEasRObUwCBjsGUhLVm7K8nH7cCnLIGRwYBAxUAy4j4dbeLnGu9xOiy3TR8FwhEVweBAM8cXllw3BJsO4A7Z4MDVw37f@ml9OjRv4i@BQpqMVDlY4WUXrLDafYKMnWDln8cUKn6zkfzz7uUfMXX@/Yf8D "JavaScript (Node.js) – Try It Online")
[Answer]
# [Scala 3](https://www.scala-lang.org/), 160 bytes
Port of [@tsh's Python answer](https://codegolf.stackexchange.com/a/249570/110802) in Scala.
---
```
n=>m=>{val S=Set(0,1,2)++(Math.min(n-5,m-2)to Math.max(6,m+4)-1)++Set(n-2,n-1,n);(0 to n-1).toSeq.filter(i=>S.contains(i)).map(i=>if(S.contains(i+1))i else -1)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pZS_TsMwEMYXpj7FCRZbcdo4bdq6KJUYkWCqmKoOpiRglDglMf9U8SQsXWDhicrTcG4ZgMZVKyJFTu6--_m7s-TX92oqM9n-GB_6uniUpT6cLIPi8jaZGjiXSsO80YAHmUE6AHKqDY2HdomHo-RujB8TCjG83ZvU7y8XOh7m8XBu5aN4lBgSMM5C6nnkXJqbZq400X7Ecj-kpoB1TD6RLsu9DvU5Cm2R9kOmfc40PSYBoBB_aNMUuGMzVZlJSqJw_-a00AYdVkRRipyZjaqU_Ex4nFIFSVYlgIyXtc_PgyO4SlLIUUNkeV0N4KQs5fN4ZEqlryd0ABdaGexr3gB8Zhg1mSYp4ZQAtyGEUYBWC85UhV3SP7rQoWPA66ThbtLITWUQMmgz6NTVRHvWcNtmd3sNg4hBl0GPQZ-BwNTGEFaYaDcMnrYDEu7lxXK4TW4MbwXqOUC2rK6lWlB7P9DKkn3DDVIQrE90a2-r0VhDwlEfBC4nAn0INCJ62xFCOJvZGdH_PyJyI3AaAschOnvgOm5cDfL3mF8a33fFYrFevwA)
[Answer]
# [Uiua](https://www.uiua.org/), ~~54~~ ~~52~~ 49 bytes (SBCS)
~~Previous versions:~~
```
↘1⊜(⊂⊙'⊂¯1)[]>0+=2∩'/+⍉⊃=<3≐'⌵-,⊂⊂0↥3↧⊙(⊃'-2'+1⧻.)∶+1⇡
↘1⊜(⊂⊙'⊂¯1)[]>0+=2∩/+⊃=<3∺'⌵-,⊂⊂0↥3↧⊙(⊃'-2'+1⧻.)∶+1⇡
```
Current version:
```
↘1⊜(⊂⊙'⊂¯1)[]>0+=2∩/+⊃=<3⊂⊟⇌.,⌵-,↥3↧⊙(⊃'-2(+1⇡))∶
```
Note: An extra byte can be saved by reversing the input values (i.e. [p, n] rather than [n, p].
[Try it online!](https://www.uiua.org/pad?src=UGFnZXIg4oaQIOKGmDHiipwo4oqC4oqZJ-KKgsKvMSlbXT4wKz0y4oipJy8r4o2J4oqDPTwz4omQJ-KMtS0s4oqC4oqCMOKGpTPihqfiipko4oqDJy0yJysx4qe7LiniiLYrMeKHoQpQYWdlciDihpAg4oaYMeKKnCjiioLiipkn4oqCwq8xKVtdPjArPTLiiKkvK-KKgz08M-KIuifijLUtLOKKguKKgjDihqUz4oan4oqZKOKKgyctMicrMeKnuy4p4oi2KzHih6EKUGFnZXIg4oaQIOKGmDHiipwo4oqC4oqZJ-KKgsKvMSlbXT4wKz0y4oipLyviioM9PDPiioLiip_ih4wuLOKMtS0s4oalM-KGp-KKmSjiioMnLTIoKzHih6EpKeKItgoKUGFnZXIgMSAxICAgICAjIFsxLCAxXSA9PiBbMV0KUGFnZXIgMiAxICAgICAjIFsyLCAxXSA9PiBbMSwgMl0KUGFnZXIgMiAyICAgICAjIFsyLCAyXSA9PiBbMSwgMl0KUGFnZXIgNSAxICAgICAjIFs1LCAxXSA9PiBbMSwgMiwgMywgNCwgNV0KUGFnZXIgNSA1ICAgICAjIFs1LCA1XSA9PiBbMSwgMiwgMywgNCwgNV0KUGFnZXIgMTEgNiAgICAjIFsxMSwgNl0gPT4gWzEsIDIsIDMsIDQsIDUsIDYsIDcsIDgsIDksIDEwLCAxMV0KUGFnZXIgMTEgNSAgICAjIFsxMSwgNV0gPT4gWzEsIDIsIDMsIDQsIDUsIDYsIDcsIC0xLCAxMCwgMTFdClBhZ2VyIDEyIDYgICAgIyBbMTIsIDZdID0-IFsxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCAtMSwgMTEsIDEyXQpQYWdlciAxMiA3ICAgICMgWzEyLCA3XSA9PiBbMSwgMiwgLTEsIDUsIDYsIDcsIDgsIDksIDEwLCAxMSwgMTJdClBhZ2VyIDEzIDcgICAgIyBbMTMsIDddID0-IFsxLCAyLCAtMSwgNSwgNiwgNywgOCwgOSwgLTEsIDEyLCAxM10KUGFnZXIgMTAwIDEgICAjIFsxMDAsIDFdID0-IFsxLCAyLCAzLCA0LCA1LCAtMSwgOTksIDEwMF0KUGFnZXIgMTAwIDEwMCAjIFsxMDAsIDEwMF0gPT4gWzEsIDIsIC0xLCA5NiwgOTcsIDk4LCA5OSwgMTAwXQpQYWdlciAxMDAgOTkgICMgWzEwMCwgOTldID0-IFsxLCAyLCAtMSwgOTYsIDk3LCA5OCwgOTksIDEwMF0KUGFnZXIgMTAwIDk4ICAjIFsxMDAsIDk4XSA9PiBbMSwgMiwgLTEsIDk2LCA5NywgOTgsIDk5LCAxMDBdClBhZ2VyIDEwMCA5NSAgIyBbMTAwLCA5NV0gPT4gWzEsIDIsIC0xLCA5MywgOTQsIDk1LCA5NiwgOTcsIDk4LCA5OSwgMTAwXQpQYWdlciAxMDAgOTQgICMgWzEwMCwgOTRdID0-IFsxLCAyLCAtMSwgOTIsIDkzLCA5NCwgOTUsIDk2LCAtMSwgOTksIDEwMF0K) (contains all three versions)
**Explanation:**
```
‚à∂
# Reverse the top two items on the stack
‚äô( )
# Temporarily pop the top item and:
⊃
# Perform the following two functions on the same values:
(+1‚á°)
# Create an array of numbers from 1 to n
'-2
# Get n - 2
‚Üß
# Get the minimum of p and n - 2
# (This pushes p away from the end, if needed)
↥3
# Get the maximum of 3 and the result
# (This pushes p away from the beginning, if needed)
‚åµ-,
# Copy the 1 to n array and for each item:
# Get the absolute difference between it and the calculated value
# (Creates a n-length array)
⊂⊟⇌.,
# Join the result, the 1 to n array, and its reverse together
# (Creats a 3-by-n matrix)
⊃=<3
# Check if each matrix entry is equal to or less than 3
# (Creates 2 3-by-n matrices)
‚à©/+
# For both matrices, add each column up
# (Results in 2 n-length arrays)
=2
# Convert the counts of =3 to 0s and 1s (1 if there are exactly 2 3s)
+
# Add the result to the counts of <3
>0
# Convert the result to 0s and 1s (1 if the count is >0)
↘1⊜(⊂⊙'⊂¯1)[]
# Use the result to remove the page numbers we shouldn't see and replace them with a -1
```
**Example:**
```
Input: 12 7 Stack (top on left):
# 12 7
: # 7 12
‚äô( # 12
⊃
(
‚á° # [0 1 2 3 4 5 6 7 8 9 10 11]
+1 # [1 2 3 4 5 6 7 8 9 10 11 12]
)
'-2 # 10 [1 2 3 4 5 6 7 8 9 10 11 12]
) # 7 10 [1 2 3 4 5 6 7 8 9 10 11 12]
‚Üß # 7 [1 2 3 4 5 6 7 8 9 10 11 12]
↥3 # 7 [1 2 3 4 5 6 7 8 9 10 11 12]
‚åµ-, # [6 5 4 3 2 1 0 1 2 3 4 5] [1 2 3 4 5 6 7 8 9 10 11 12]
⊂⊟⇌., # [[12 11 10 9 8 7 6 5 4 3 2 1][1 2 3 4 5 6 7 8 9 10 11 12][6 5 4 3 2 1 0 1 2 3 4 5]] [1 2 3 4 5 6 7 8 9 10 11 12]
⊃=<3 # [[0 0 0 0 0 0 0 0 0 1 0 0][0 0 1 0 0 0 0 0 0 0 0 0][0 0 0 1 0 0 0 0 0 1 0 0]] [[0 0 0 0 0 0 0 0 0 0 0 1 1][1 1 0 0 0 0 0 0 0 0 0 0 0][0 0 0 0 1 1 1 1 1 1 0 0 0]] [1 2 3 4 5 6 7 8 9 10 11 12]
‚à©/+ # [0 0 1 1 0 0 0 0 0 2 0 0] [1 1 0 0 1 1 1 1 1 1 0 1 1] [1 2 3 4 5 6 7 8 9 10 11 12]
=2 # [0 0 0 0 0 0 0 0 0 1 0 0] [1 1 0 0 1 1 1 1 1 1 0 1 1] [1 2 3 4 5 6 7 8 9 10 11 12]
+ # [1 1 0 0 1 1 1 1 1 1 1 1] [1 2 3 4 5 6 7 8 9 10 11 12]
>0 # [1 1 0 0 1 1 1 1 1 1 1 1] [1 2 3 4 5 6 7 8 9 10 11 12]
↘1⊜(⊂⊙'⊂¯1)[] # [1 2 -1 5 6 7 8 9 10 11 12]
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 113 bytes
```
n=>p=>[L=0,1,2,p>6?{}:3,p=p>n-2?n-4:p>2?p-2:1,p+1,p+2,p+3,p+4,p<n-7?{}:n-2,n-1,n].filter(v=>v>L&v<=n?(L=v):v>={})
```
[Try it online!](https://tio.run/##pZFNboMwEEb3PcWsKhDjBBsMGMXmAtwgyiJKIUqFjJVEbKKcnRq6afgTVRbjzXzvzdj@PjbH2@l6MXei66@iLWWrpTJS7XPpI0WGRkXZ45kGaKRRmrBMkzA1imWGsJSi8bqyMc8mvBDNTpO4A2wUNaGoD5vyUt2Lq9NI1aj8s9lJnTm5bNy0UfLxdNtTrW91VWyq@uyUDgB1@8OF7Rb29PAx7LOXPgKbibDFCB9aEAKEEIHPZPmqLO23j6ayCBFCjJAgCATq26IzPF/i7avO0mzN9F7QFZsRxC@CLj65/LQhWGXod7AtGgwN1Pdnv@aXE/0G/iTYHcPRwg4WdrJIllnbfINN3mD5mLU3FvbKgv/HE449bOz6@4btDw "JavaScript (Node.js) – Try It Online")
Hardcode
] |
[Question]
[
*This question is a part of the [lean](/questions/tagged/lean "show questions tagged 'lean'") [LotM](https://codegolf.meta.stackexchange.com/questions/23916/).*
A ring is a type of structure that takes the rules of addition and multiplication we are familiar with and abstracts them, so we can reason about them. To do this we state a number of expected properties as axioms and see what we can say about systems that follow these axioms. For example \$a + (b + c) = (a + b) + c\$, is one of the axioms commonly given.
But exactly what the ring axioms are depends on whom you ask. Because, rings can be defined in a number of equivalent ways. Often one of the given axioms is that for any \$a\$ and \$b\$ then \$a + b = b + a\$. We call this *additive commutativity*. However this axiom is not needed! Usually we can prove it from more basic axioms.
In this challenge I will give a minimal axiom set for rings in the Lean programming language and your task is to prove commutativity.
The `ring` class is defined as follows:
```
universe u
class ring (α : Type u) extends has_add α, has_mul α, has_one α, has_zero α, has_neg α :=
( add_assoc : ∀ a b c : α, a + (b + c) = (a + b) + c )
( mul_assoc : ∀ a b c : α, a * (b * c) = (a * b) * c )
( add_left_id : ∀ a : α, 0 + a = a )
( mul_left_id : ∀ a : α, 1 * a = a )
( mul_right_id : ∀ a : α, a * 1 = a )
( add_left_inv : ∀ a : α, (-a) + a = 0 )
( left_distribute : ∀ a b c : α, a * (b + c) = a * b + a * c )
( right_distribute : ∀ a b c : α, (a + b) * c = a * c + b * c)
open ring
```
Your goal is to create an object with the same type as:
```
axiom add_comm {α : Type*} [ring α] : ∀ a b : α, a + b = b + a
```
This is the same as proving the claim.
You may rename things here however you want as long as the underlying type is correct. So the following is a smaller but perfectly valid header for your proof:
```
def k{A:Type*}[ring A]:∀a b:A,a+b=b+a
```
You can't use different but similar looking types. So for example redefining the notation of `=` to make the proof trivial:
```
local notation a `=` b := true
def k{A:Type*}[ring A]:∀a b:A,a+b=b+a := λ x y, trivial
```
is not a valid answer, even though the type *looks* identical. (Thanks to [Eric](https://codegolf.stackexchange.com/users/4341/eric) for pointing this possible exploit out.)
You must actually prove the claim, so you may not use `sorry` or `axiom` in your proof.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal.
*If you want to do this challenge but don't know where to get started just use the links in [the LotM post](https://codegolf.meta.stackexchange.com/questions/23916/). I'll be happy to help anyway I can in chat.*
[Answer]
## Lean, ~~451~~ ~~449~~ ~~445~~ ~~439~~ ~~414~~ 407 bytes
```
def k{A}[ring A](a b:A):a+b=b+a:=let
L:=@add_left_inv A,I:=@add_left_id A,K:=@congr_arg,c:=λx y,K(+y)$L x in
by{let C:=add_assoc,simp[I]at*,let
e:=λb,(λ(a:A)h:a+a=a,(eq.trans(by
rw[<-I a,<-L,<-C,h])$L _:a=0))(b+-b)$by simp[<-C]at*;rw c,let
d:=K(λx,-b+x+-a)(left_distribute(1+1)b
a),simp[c,C,right_distribute,mul_left_id,mul_right_id,λa b,(by
rw[<-C,e,λa:A,(by rw[<-L,C,e,I]:a+0=a)]:b+a+-a=b)]at*,rw
d}
```
Unpacked:
```
def add_comm {A} [ring A] (a b : A) : a + b = b + a :=
let
L := @add_left_inv A,
I := @add_left_id A,
K := @congr_arg,
c := λ x y, K (+ y) (L x)
in begin
have C := add_assoc,
simp [I] at c,
-- c: ∀ (x y : A), -x + x + y = y
have e : ∀ (b : A), b + -b = 0 := λ b,
have ∀ (a : A), a + a = a → a = 0 :=
λ (a : A) (h : a + a = a), show a = 0, from
eq.trans (by rw [← I a, ← L, ← C, h]) (L _),
this (b + -b) (by simp [← C] at c ⊢; rw c),
have d : -b + ((1 + 1) * (b + a)) + -a = -b + ((1 + 1) * b + (1 + 1) * a) + -a :=
K (λ x, -b + x + -a) (left_distribute (1+1) b a),
simp [c, C, right_distribute, mul_left_id, mul_right_id,
have ∀ (a b : A), b + a + -a = b :=
λ a b : A, show b + a + -a = b, by
rw [← C, e,
have ∀ (a : A), a + 0 = a, from
λ a : A, show a + 0 = a, by rw [← L, C, e, I],
this],
this] at d,
-- d : a + b = b + a
rw d
end
```
[Answer]
# Lean, 268 bytes
```
import tactic.cache
def k{A}[r:ring A](a b:A):a+b=b+a:=by{casesI
r with _ _ _ _ _ c _ d _ _ e f,let g:=λa:A,trans(by
simp*:_=-(a+-a)+(a+-a+a+-a))$by
simp[<-c,*],let:=λa,trans(by
rw[<-c,e,g]:a+b+_=a+(-a+a))$by
rw[c,g,d],transitivity-a+(1+1)*(a+b)+-b,rw f,simp*,simp*}
```
[Run with Lean Web Editor](https://leanprover-community.github.io/lean-web-editor/#code=import%20tactic.cache%0A%0Auniverse%20u%0A%0Aclass%20ring%20%28%CE%B1%20%3A%20Type%20u%29%20extends%20has_add%20%CE%B1%2C%20has_mul%20%CE%B1%2C%20has_one%20%CE%B1%2C%20has_zero%20%CE%B1%2C%20has_neg%20%CE%B1%20%3A%3D%0A%20%20%28%20add_assoc%20%3A%20%E2%88%80%20a%20b%20c%20%3A%20%CE%B1%2C%20a%20%2B%20%28b%20%2B%20c%29%20%3D%20%28a%20%2B%20b%29%20%2B%20c%20%29%0A%20%20%28%20mul_assoc%20%3A%20%E2%88%80%20a%20b%20c%20%3A%20%CE%B1%2C%20a%20*%20%28b%20*%20c%29%20%3D%20%28a%20*%20b%29%20*%20c%20%29%0A%20%20%28%20add_left_id%20%3A%20%E2%88%80%20a%20%3A%20%CE%B1%2C%200%20%2B%20a%20%3D%20a%20%29%0A%20%20%28%20mul_left_id%20%3A%20%E2%88%80%20a%20%3A%20%CE%B1%2C%201%20*%20a%20%3D%20a%20%29%0A%20%20%28%20mul_right_id%20%3A%20%E2%88%80%20a%20%3A%20%CE%B1%2C%20a%20*%201%20%3D%20a%20%29%0A%20%20%28%20add_left_inv%20%3A%20%E2%88%80%20a%20%3A%20%CE%B1%2C%20%28-a%29%20%2B%20a%20%3D%200%20%29%0A%20%20%28%20left_distribute%20%3A%20%E2%88%80%20a%20b%20c%20%3A%20%CE%B1%2C%20a%20*%20%28b%20%2B%20c%29%20%3D%20a%20*%20b%20%2B%20a%20*%20c%20%29%0A%20%20%28%20right_distribute%20%3A%20%E2%88%80%20a%20b%20c%20%3A%20%CE%B1%2C%20%28a%20%2B%20b%29%20*%20c%20%3D%20a%20*%20c%20%2B%20b%20*%20c%29%0A%0Aopen%20ring%0A%0Adef%20k%7BA%7D%5Br%3Aring%20A%5D%28a%20b%3AA%29%3Aa%2Bb%3Db%2Ba%3A%3Dby%7BcasesI%0Ar%20with%20_%20_%20_%20_%20_%20c%20_%20d%20_%20_%20e%20f%2Clet%20g%3A%3D%CE%BBa%3AA%2Ctrans%28by%0Asimp*%3A_%3D-%28a%2B-a%29%2B%28a%2B-a%2Ba%2B-a%29%29%24by%0Asimp%5B%3C-c%2C*%5D%2Clet%3A%3D%CE%BBa%2Ctrans%28by%0Arw%5B%3C-c%2Ce%2Cg%5D%3Aa%2Bb%2B_%3Da%2B%28-a%2Ba%29%29%24by%0Arw%5Bc%2Cg%2Cd%5D%2Ctransitivity-a%2B%281%2B1%29*%28a%2Bb%29%2B-b%2Crw%20f%2Csimp*%2Csimp*%7D%0A%0Aexample%20%7B%CE%B1%20%3A%20Type*%7D%20%5Bring%20%CE%B1%5D%20%3A%20%E2%88%80%20a%20b%20%3A%20%CE%B1%2C%20a%20%2B%20b%20%3D%20b%20%2B%20a%20%3A%3D%20k)
] |
[Question]
[
Most tip calculator apps simply take a flat percentage of the meal price. So, for example, if your meal is $23.45, you can leave a 15% tip = $3.52, or a more generous 20% tip = $4.69.
Convenient enough for credit card users. But not so if you prefer to leave cash tips, in which case these oddball cent amounts get in the way. So let's modify the idea to be more convenient for cash users.
## Your assignment
Write, in as few bytes as possible, **[a program or function](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet)** that takes as input:
* Price of the meal
* Minimum tip percentage
* Maximum tip percentage
And output any tip amount within the range [price \* min\_percentage / 100, price \* max\_percentage / 100] that minimizes the number of bills/banknotes and coins required.
Assume the US monetary denominations of 1¢, 5¢, 10¢, 25¢, $1, $5, $10, $20, $50, and $100.
## Example
Here is a non-golfed example program in Python:
```
import math
import sys
# Do the math in cents so we can use integer arithmetic
DENOMINATIONS = [10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1]
def count_bills_and_coins(amount_cents):
# Use the Greedy method, which works on this set of denominations.
result = 0
for denomination in DENOMINATIONS:
num_coins, amount_cents = divmod(amount_cents, denomination)
result += num_coins
return result
def optimize_tip(meal_price, min_tip_percent, max_tip_percent):
min_tip_cents = int(math.ceil(meal_price * min_tip_percent))
max_tip_cents = int(math.floor(meal_price * max_tip_percent))
best_tip_cents = None
best_coins = float('inf')
for tip_cents in range(min_tip_cents, max_tip_cents + 1):
num_coins = count_bills_and_coins(tip_cents)
if num_coins < best_coins:
best_tip_cents = tip_cents
best_coins = num_coins
return best_tip_cents / 100.0
# Get inputs from command-line
meal_price = float(sys.argv[1])
min_tip_percent = float(sys.argv[2])
max_tip_percent = float(sys.argv[3])
print('{:.2f}'.format(optimize_tip(meal_price, min_tip_percent, max_tip_percent)))
```
Some sample input and output:
```
~$ python tipcalc.py 23.45 15 20
4.00
~$ python tipcalc.py 23.45 15 17
3.55
~$ python tipcalc.py 59.99 15 25
10.00
~$ python tipcalc.py 8.00 13 20
1.05
```
[Answer]
# JavaScript (ES6), 93 bytes
```
(x,m,M)=>(g=(t,c=1e4)=>t>x*M?0:t<x*m?[...'1343397439'].some(d=>g(t+(c/=-~d/2)))*r:r=t)(0)/100
```
[Try it online!](https://tio.run/##dcxBDoIwFATQvadg5y@WT0tLsMTCCTiBcUGgEA1QA41h5dUrie6Ii1lMXmYe9atemvn@dNFkW@M77WGlI62ILqDX4GijuZFbc8UaViXL3WUNx/KKiEcupBAqk0Idb7jY0UCrix7cCZpYR@82Tggh4ZzP2hFgJOaM@cZOix0MDraHDhKBMqUB35IwQg5/lWc7TRUq9dumOw3OyNim4vvsPw "JavaScript (Node.js) – Try It Online")
### How?
We recursively compute a sum of bill/coin values until it falls within the acceptable range, always trying the highest value first.
This is guaranteed to use the minimum amount of bills and coins because for any solution \$\{b\_0,\dots,b\_n\}\$ returned by this algorithm:
* all terms \$b\_0\$ to \$b\_n\$ are required, otherwise the algorithm would have selected \$\{b\_0,\dots,b\_{k-1},x\}\$ with \$x \ge b\_k\$ for some \$0 \le k < n\$
* for any \$0 \le k < n\$ and any \$x \le b\_n\$, \$\{b\_0,\dots,b\_{k-1},b\_k-x,b\_{k+1},\dots,b\_n\}\$ cannot be a solution, otherwise \$\{b\_0,\dots,b\_{n-1}\}\$ would have been selected
* there may exist some \$0 < x < b\_n\$ such that \$\{b\_0,\dots,b\_{n-1},x\}\$ is also valid, but that would not use less bills/coins than the selected solution
The bill/coin values \$c\_n\$ expressed in cents are computed with:
$$\begin{cases}c\_0=10000\\c\_{n+1}=\dfrac{c\_n}{(d\_n+1)/2}\end{cases}$$
where \$(d\_0,\dots,d\_9) = (1,3,4,3,3,9,7,4,3,9)\$.
```
n | c(n) | d(n) | k = (d(n)+1)/2 | c(n+1) = c(n)/k
---+-------+------+----------------+-----------------
0 | 10000 | 1 | (1+1)/2 = 1 | 10000
1 | 10000 | 3 | (3+1)/2 = 2 | 5000
2 | 5000 | 4 | (4+1)/2 = 2.5 | 2000
3 | 2000 | 3 | (3+1)/2 = 2 | 1000
4 | 1000 | 3 | (3+1)/2 = 2 | 500
5 | 500 | 9 | (9+1)/2 = 5 | 100
6 | 100 | 7 | (7+1)/2 = 4 | 25
7 | 25 | 4 | (4+1)/2 = 2.5 | 10
8 | 10 | 3 | (3+1)/2 = 2 | 5
9 | 5 | 9 | (9+1)/2 = 5 | 1
```
[Answer]
# Python 3.x: ~~266~~ 185 bytes
A straightforward modification to my example program in the question. Note that the output is no longer formatted to require 2 decimal places.
**Edit:** Thanks to Jo King for making it smaller.
```
import sys
p,m,M,T=*map(float,sys.argv[1:]),0
C=p*M
for t in range(-int(-p*m),int(p*M)+1):
n,a=0,t
for d in 1e4,5e3,2e3,1e3,500,100,25,10,5,1:n+=a//d;a%=d
if n<C:T,C=t,n
print(T/100)
```
[Answer]
# Java 10, ~~186~~ 185 bytes
```
(p,m,M)->{double r=0,t,Q=99,q;for(m*=p+.02;m<M*p;m+=.01){q=0;t=m;for(var c:new double[]{100,50,20,10,5,1,.25,.1,.05,.01})for(;t>=c;t-=c)q++;if(q<Q){Q=q;r=m;}}return"".format("%.2f",r);}
```
Takes the minimum and maximum percentages as `/100` decimals (i.e. `15%` as `0.15`).
-1 byte to fix the issue with `3.51` as potential output and golfing the way to fix rounding errors by 1 byte at the same time.
[Try it online.](https://tio.run/##lVJNb9wgEL33V4xWqgRZloA3brol5NbjRlr1GOVAMU5IF2zj8aaV5d@@ZT@qSlHVKBIwM5rHY94Mz2ZnFs/Vj73dmr6HtfFx/ADgI7pUG@vg7hACfMPk4yNYUjXD962Dlp2d8MdZU5WRU9559WjQW7iDCHpPWhbYmi5uxzM0acGQbfRqxTpVN4mEC93OuShUuFlftCrMNReSjp0WCnU4QnYmgf0S3QucSO4fRikEKwUrBJPZYZLxomQ8G5GNkBM93FN4q63Chba0m8@Vr0l3s6HjRncqZeppSg6HFGczntHBIJl95EU9Y4mqaa9Oatr8YFZzFrVrfAUhN4qcmnL/AIaeu/SrRxd4MyBvcwq3kURuSbHkVyUDweXxLASlCi4v4evP1ll0FVxxId5BIK9fEyx5WQJZ8k8CmpSj6xKG3gE@OehNcGBCM0SEpgbb@NiDiRWY5ODF45OPR1wy8dHR/1VRrnie2F8Z5esqpHhDx@ecZ3BgWP67ETLP7viLpv1v)
**Explanation:**
```
(p,m,M)->{ // Method with three double parameters and String return-type
double r=0, // Result-double, starting at 0
t, // Temp-double
Q=99, // Min amount of coins, starting at 99
q; // Temp-double for the amount of coins
for(m*=p-.02;m<M*p; // Loop in the range [`m*p-0.02`, `M*p`]
m+=.01){ // in steps of 0.01 (1 cent) per iteration
// (the -0.02 (minus 2 cents) is to fix rounding errors)
q=0; // Reset `q` to 0
t=m; // Reset `t` to the current iteration `m`
for(var c:new double[]{100,50,20,10,5,1,.25,.1,.05,.01})
// Loop over the coins (largest to smallest)
for(;t>=c; // As long as `t` is larger than or equal to the current coin
t-=c) // Remove the coin from the value `t`
q++; // And increase the quantity-counter by 1
if(q<Q){ // If the quantity-counter is smaller than the current smallest
Q=q; // Replace the smallest with the current
r=m;}} // And replace the result with the current `m`
return"".format("%.2f",r)l;}
// Return the result with 2 decimal places
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
Nθ≔×θNη≔×θNζ≔⁰θFI⪪”;‴üφ↷Σ↗SEX&¿h'⊟”³«W‹θη≧⁺ιθ¿›θζ≧⁻ιθ»﹪%.2fθ
```
[Try it online!](https://tio.run/##jU/BagIxED27XzEsFCaQhuzapQdPpYdSqCLaH0g1awbi7ppkW7D022OihwpePAzDe/PmvZmNUW7TKxvjezeMYTHuv7TDA5sVL97TrsNP2muPBw7Xc8Y4mDs0x3@N5JBd297hq/IB14OlgGUlZSNFLUUlRSNkJRJIROoZlRymjDH4LSY/hqwG/ND@nGQSO1fDxXxFOxNwaUfPgS45E2oB35xWIb@TL7nRz6m7Wvgrlo66xPbb0fZYPoi6LfOIzWKsp@KpAVHleo6P3/YE "Charcoal – Try It Online") Takes input as decimals. Link is to verbose version of code. Explanation:
```
Nθ
```
Input the bill.
```
≔×θNη≔×θNζ
```
Input the tip decimal fractions and compute the minium and maximum tip.
```
≔⁰θ
```
Start with zero tip.
```
FI⪪”;‴üφ↷Σ↗SEX&¿h'⊟”³«
```
The SEXy string expands to `10050.20.10.5.01.0.250.1.05.01` which is split into groups of three characters and cast to float.
```
W‹θη≧⁺ιθ
```
Add as many of the current denomination as necessary to reach the minimum tip.
```
¿›θζ≧⁻ιθ»
```
Remove one denomination if the maximum tip has been exceeded.
```
﹪%.2fθ
```
Format the tip for display.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~207~~ 156 bytes
Swapping to a function saved 51 bytes, unsurprisingly.
```
import StdEnv
d=[10000,2000,1000,500,100,25,10,5,1]
$n u l=snd(hd(sort[(sum[foldl(rem)m(d%(0,i))/k\\k<-d&i<-[-1..]],toReal m)\\m<-map toInt[n*u..n*l]]))/1E2
```
[Try it online!](https://tio.run/##JY6xjgIhFEV7v4JCN4wBlkGnm@nWwmSrtWQoyDAqkfcwwpj488ti9hbnnuYmdwqzxQLRLWEmYD0WD/f4yOSU3QGfKzfoVtYw9cZbWfcvTHW1WIVZrZEsJAwJHb06mupe07SAPsfgAn3M0AB1GyqZb5rP2zjeeu4@fM81b4UwhuX4M9tAoBlH6DnYO8nxiFnjdhECt8GYumsPqpyyrd8GslY7se9I2wlJlBSy/E7nYC@p8ON3@XqhBT@lPw "Clean – Try It Online")
[Answer]
# Python (~~264~~ 222 bytes)
Slightly more golfed.
```
m=[.01,.05,.1,.25,.5,1,5,10,20,50,100]
def f(a,i,j):
t,u=9**9,a*j
def g(s,d,c):
nonlocal t
if(a*i<s<u)+(c>t):t=min(c,t);return c,s
return(t+1,s)if(s>u)+(d>9)else min(g(s+m[d],d,c+1),g(s,d+1,c))
return g(0,0,0)[1]
```
[Try it Online!](https://tio.run/##bY7BboQgEIbvPAVHRicEtKRlu/oixoNBbdkobgQPfXo7tJtmDw2BYfLNx8/9K31uoT7Ptemk0iiVQUmlomJQI22FlUKj6KJ6Nk4zn8WAHm9wYTzh0diisDgUN8Yz/BARR3QZ8rCFZXPDwhM1nrTCX@P1gFK4NsElNasPwmGC931Kxx64w0iTv41IpcYIpMU2K2NrYVrixLNEKeXajX2OKjXgTyrNOwD28OknCmlBp3t23ncfEhezqGr5YpBLnY9K0fz/SL8@I2OltX@WeUZvUqlM6sd75zc)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~93 92~~ 89 bytes
```
{.01*($^a*$^b+|0...$a*$^c).min:{$!=$_;sum '✐ᎈߐϨǴd
'.ords>>.&{($!%=$_)xx$!/$_}}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rPwFBLQyUuUUslLkm7xkBPT08FxE7W1MvNzLOqVlG0VYm3Li7NVVB/NGfCw76O@xPOrzi@JUWSi5VRXS@/KKXYzk5PrVpDRVEVqFCzokJFUV8lvra29n9xYqVCmoaRsZ6JqY6hqY6RgaY1F5qYoTlczNRSz9ISrM4ULmahZ2CgY2gM1vofAA "Perl 6 – Try It Online")
Anonymous code block that takes three arguments (price, minimum percentage, and maximum percentage) and returns the tip.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 105 bytes
This will give all the solutions with minimal coin count.
```
MinimalBy[NumberDecompose[#,d=100{100,50,20,10,5,1,.25,.10,.05,.01}]&/@Range[Ceiling[#2#],#3#],Tr].d/100&
```
[Try it online!](https://tio.run/##bYy9CsIwFIV3n0IIdLqkSWrQDAVRV0XELWSIbVoDTSq1DiI@e7xDhw4O54ePwwl2vLtgR1/Z1JTp6KMPttu99ekVbm44uKoPj/7pNIG65Ix9UCAZCAYcC3CgQgLFThkm41@T5duLja3Te@c7H1tNBDFACrTrYGid40WWzoOPo260KOhKwpKjBDNm8Yfz9YxLRZWa9nLGN8iK6SP9AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Kotlin](https://kotlinlang.org), 215 bytes
```
{p:Double,l:Int,h:Int->val d=listOf(10000,5000,2000,1000,500,100,25,10,5,1)
var m=Int.MAX_VALUE
var r=0.0
(Math.ceil(p*l).toInt()..(p*h).toInt()).map{var a=it
var c=0
d.map{c+=a/it
a%=it}
if(c<m){m=c
r=it/100.0}}
r}
```
[Try it online!](https://tio.run/##nVfrbts4Fv6vp2AzSSOlqnxJPd0Y9QDZTnY2QNMOkHQvKIKAlmibiCRqRCqJN8g8zDzKvlj3OyQly0k6O5gAkW3y8Ny@75xDXSuTy/Lr4IC9rwU3ImMLVTOzkpqlKhNsqfIFS1c8z0W5FNNgZUylp4MBbdJeog1Pr8UdRLCfpKoY/NIIbaQq9WD0/dH47TB4z/O0yaGccWZkxRotyyVsCKYLUqwNK5tiLmqmYEvJUgfBmcIqCaf@MLziVaWZlkWVr5nh16RugR1WiToVpeFLQQpIbyF4zqpapiJh5yq2MYk7jpMiZnLB1qqpnRDi3B0fJm8mMS3CWslywW9I92iyZz2Ysd3DZDKOGbnAClUjK6IUtWo0Gw87mTfJ90dJELxX5Y0oJfxholTNcmWNp7XIpIH6OkP4otYJ@2uDsJVhWnmP4LBYIAlGeRdSrlekXcPnkt2uZLqiNUEh4qmybI70MYqd8UI1pdHwzJAwJeGWryl6KDP7Gn5ncrG2GzITnKzMhYsm3bhsfSWzzsng35QorrVclgX2g@CftTTC@sM1W4hbNl8boelHpSA2pwRzRKKWNS8oY4umTIkNsAyoCDYrLcuqMdMgYPj7mYDqQ2dXz2Qpi6aw6d0g7Lb43XNbwXGZMdUYaLaqaNvlhd1KUNqlpSaisi@WHeyAFbK86hFowEbDYcy6XX73ZPfShVKQf/I/CIe0bgg8l3muB3NeXgNdChZOWVKzWvzSSBABLDnWuikskOzzOVAoheH1mmWgDPRyWz6kbPTf32I2ocdoSM@x/b47wv@EPuHq7pgeEzzIEpaGSXDiuB4EfxfAFxznoFr5mgoWFe4roUMJifl5bVaqBB6oLlUjOG5W7Xe9Rj1@x35UDh/s0AlKiSby3gpbNSAMlo1YIgscJFkVwsg0@PHk46ez04/HF6efPp6jTL7AP0rwxD7H9jlqV2KX/PGEvmAFH5dBkAnqCkDxyqb2CmFe2YSGDtwr60o0tdT4jn12BcJ@qoXI1uATIstiXz63qr5GYkvX4TSKBUneynpi1dRCN7mBv0P7k8qiL0UJ2IrMGac/EMF5F7O@e1CVyRsU4ZbT8ZbWqFPizb@abdR5t0xTl37bZUZVxtLwCmwPqXiuLHdjS2ystfSNLZd7Cz5hrVjrJTAMCeMkFTLvKfSl0lfg/G3VPlGwyJWqH2l45ILTMMcE2FLxEfWw2XHFM0OvV9yE@7Jc7EcdKptjgMSWdrgVUfzIv1dsFD0DFtQ/T7Hu5AYcdOvNuXc9Hzd6n42q@/5UrPXhWbQfKbI9KBlSSf5kmz3aHVpxrQqEUBRw/TUmugh6iW9zh0pOeL28@TK6jIJHaD4VGpPQNmBPhQ4hBCPAfP9@mowXD/sJYAH@4Z8nJmgRnCu0R@36lA3RdjfX3NGmft1llW1ZlFW6IiTVmtk5jrGNthK8SYbD/yM1ehtgrk@el5ocJUdHVtckGA2/qewv2GGjQ7I4SoaT4GAQBIMBO7mr4C5a7Q2mKPULP9xyXswzngQYitR9U6F1aLMyRXtt7PDM1e2FrKbsFJmxLFjJ5apdiQDAPQ1N2DjOc5XSpcoqltp0w4e9ZL4D2Ybt5qg75IiGXp25cSHpanDD80ZQ38OXRyNoZjV/WoRP27Zn8e8178jqrFsXoA0xJGfH/7r6x/GHzyd@d9NridXWzb/RfY2jX7eXCso5rnESLm/dG23RkuvhWdezbEIPXB6jxCjYDKMk8f76bZ/Vbj9KCl653G5nl8MGgPYA@usEpY474@2B9uo6cBDgemWvYsbZpTj9WXRI062lfmnYGe5CJ21AktR5sZW6Ra2Ua@TBq92eXC4CF6Y7gQHirA68TdZ6sde58UBWcbTz4HTR3v9JkMakzXYduxnvoieJ9gCwce6gM4bu1LsW86jzaEOCTd56g1aagetrnU9yEfS8a0WDhzCyNXZB@Ge1RIm5a2v7kuLKq@CyDNGi9JQd1zVfvzs3aFPLH6KugD7YYuxdUJUj2Da5AGyvdDy6fvK0NYP7v5MZo2HYC/HX@2rqKzqfUimv6Pn6B1ths62asiVlK2rkf9KXGHWEMsIjCmwJzbZLxxbOjPLVZ/5B3iM8fq62@X1vaTgD8JZ7s2GQ2eX01YwTQ/ge9h4CuQjTd0V0X8zSoJ61wDw8BPXDVxvmBa6qeFvM2tc4N2VePrqP69glxTc6kixc18mkrnLuXkYcqpRJA633vjLydq7NrKEPGGhh9OJFgnPShDtsJ@oI5wQTjVHDXszYYTuozapGvZwCyiXPj@tlQy8wJ3epqAjtsDeEd05LWJRZ7xLPvbx@4S3dtC@U9oZDFr8ML5FcB3K4EQLNL@wLoZcaXbYQbET43ZbIeFvEjdOdPUxT@97C9rK9PWKn@8TJtRR5BmLvJF0UfuhuRuwFNUxnKerpzUuneacd09UmE984HPl6@VTizcGnL6a7BjCk90AA2oMYPWnBgai9SD/g1cCgl4WirlU9ZReECUfCoh7SKBfTmzT@w7@UjyY0bqK4c/Lp9uhtFLfLdmz7U5Onp2hcY/fQ6txcIsNv5M2@SZN3LaeIb44FaIsOevbyZYs51oAiFnrc8li7rU0z/JMo/0Gk/xDav4u4237UhlGgge/Hsvz6Pw "Kotlin – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~33~~ 32 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ñṇzi;’b⁴×H¥\ɓ_>Ƈ-Ṫ
PĊ1¦r/ÇƬL$ÞḢ
```
A monadic link accepting a list `[cost in cents, [minimum ratio, maximum ratio]]` which yields a tip amount in cents.
**[Try it online!](https://tio.run/##AVQAq/9qZWxsef//4oCcw7HhuYd6aTvigJli4oG0w5c6MsmXXMmTXz7Ghy3huaoKUMSKMcKmci/Dh8asTCTDnuG4ov///1s4MDAsIFswLjEzLCAwLjIwXV0 "Jelly – Try It Online")**
### How?
The first line is a helper Link which yields the amount given less the largest denomination note/coin:
```
“ñṇzi;’b⁴×H¥\ɓ_>Ƈ-Ṫ - Link 1, get next lower amount: integer, V
“ñṇzi;’ - base 250 number = 112835839060
b⁴ - to base 16 = [1,10,4,5,8,10,4,4,5,4]
\ - cumulative reduce with: e.g.: 1,10 5,4 10,5 25,8
¥ - last two links as a dyad:
× - multiply 10 20 50 200
H - halve 5 10 25 100
- ...yielding: [1,5,10,25,100,500,1000,2000,5000,10000]
ɓ - start a new dyadic link with swapped arguments
_ - subtract (vectorises) ...i.e. [V-1,V-5,V-10,...]
Ƈ - filter keep those which satisfy:
- - literal -1
> - greater than? (i.e. if V-X > -1)
Ṫ - tail (tailing an empty list yields 0)
```
The number of calls required in order to reach zero is used to sort the range of tip amounts, and then the leftmost is yielded:
```
PĊ1¦r/ÇƬL$ÞḢ - Main Link: [cost, [min, max]]
P - product = [cost*min, cost*max]
¦ - sparse application...
1 - ...to indices: 1
Ċ - ...what: ceiling -> [ceil(cost*min), cost*max]
/ - reduce by:
r - inclusive range (implicit floor of arguments)
Þ - sort by:
$ - last two links as a monad:
Ƭ - repeat collecting results until a fixed point is reached:
Ç - last link (1) as a monad (e.g. 32 -> [32,7,2,1,0])
L - length (i.e. coins/notes required + 1)
Ḣ - head
```
] |
[Question]
[
# Introduction
Street talk can be really difficult to understand, in particular to programmers, who aren't known to be very streetwise.
It is your job to create an interpreter to help us all survive in the urban environment.
# Challenge
Given an English sentence as input, create a program or a function that determines whether the outcome of the sentence is positive or negative.
The sentence will contain `0` to `2` negative words. As any programmer knows, a double negative results in a positive. Therefore, your code must output or return a [truthy/falsey](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) value according to the following rule:
```
No negative words -> truthy
One negative word -> falsey
Two negative words -> truthy
```
The list of negative words:
* `no`, `not`, `none`
* Anything ending in `n't`
* `never`, `neither`, `nor`
* `nobody`, `nothing`, `nowhere`
There is one edge case. Whenever a sentence begins with `No,`, that word isn't treated as a negative word when determining the result (it does count towards the number of negative words so there can be just one more).
The sentence will follow basic grammar rules (capitalization, punctuation) and will only contain words that can be found from a dictionary (luckily, this doesn't invalidate the question title). The sentence won't contain any proper nouns (sorry, Dr. No, you're out).
# Test cases
**Truthy:**
```
Yes.
It's noon.
Hello, World!
What is this?
Ain't no thang!
Never say never.
No, it's noon now.
Neither me nor you.
I didn't do nothing!
No, I am your father.
A non-alcoholic drink.
I can't get no satisfaction.
All your base are belong to us.
```
**Falsey:**
```
No.
No, no!
Not today.
Neither am I.
Don't do that!
That's no moon!
And none survived.
Is this not my car?
No man is an island.
Nosebleeds are no fun.
Nothing compares to you.
That's a no, I'm afraid.
No, I am not your mother.
```
The irony here, of course, is that some of these *should* be interpreted differently. But hey, you can't fault the speaker for not conforming to our logic.
# Rules
Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so be concise!
[Answer]
## [Retina](https://github.com/m-ender/retina), 63 bytes
```
No,
Mi`\bn(e(ith|v)er|o(|body|ne|r|t|thing|where))\b|n't\b
0|2
```
[Try it online!](https://tio.run/##RVBBagMxDLz7FcqhJIF0Kf1BoNDm0JwKpZBDtGsla@qViu3dsOC/p7KT0ouwhxnNjAIlx3h9WL0er3vZGPPujoeWV7Ryqc/TmkKWVW7Fzpkph5xy6h2f86WnQOv1oc28TIfWPOXn6/WLYmN2aRmBRbgxb@S9bOBTgrcLs6eJAkScgcurMVunWqVC6pHPSlCu@1PruDSq0RiqGkj/AWYZ1QCss0VpRcEa56bdAQ6FEuCERaUOSuBH9J304l0HNjj@Lhs6LAvOVO0jJhdP2CVXQm@9vy1pMRJgIGjJC58hCYzaby9NdWMprklhi/N/Uo2wa8yL3ANqtbQwHzprLxi02sJs2ZZkBHEMk5vIlpUwIIOLUKdHrmCk1hPZWIOo/jRygWtr6GT4UTyWaPU0dx9Upp5jOQCeAjrb/J9HD3ZrN0g90S8 "Retina – Try It Online")
### Explanation
```
No,
```
Remove `No,` from the input. Due to the capitalisation rules, this can only appear at the beginning of the input, so we don't need an explicit `^`.
```
Mi`\bn(e(ith|v)er|o(|body|ne|r|t|thing|where))\b|n't\b
```
Count the number of matches of the case-insensitive regex after the ```. It just matches all the relevant words, where I've extracted common prefixes/suffixes with the alternatives.
```
0|2
```
Count `0` or `2`s, so we turn even counts into `1` and odd counts into `0`.
[Answer]
# Bash, ~~115~~ ~~107~~ ~~99~~ ~~98~~ ~~97~~ ~~95~~ 85 bytes
Uses packages Core Utilities (for `wc`) and `grep`. Assume the sentence is given via Standard Input. **History expansion is disabled by `set +o histexpand`.**
```
((~`grep -Pio "(?!^no,)\b(no(|t|r|ne|body|thing|where)|ne(v|ith)er|.*n't)\b"|wc -l`%2))
```
Check the result: In Bash 0 is for true, 1 is for false
### How does it work?
```
(( )) # Logical evaluation: non-zero to TRUE, zero to FALSE
~ %2 # C-style arithmetic: Bit-Negate and Modulus 2
$( ) # Output of the program chain
grep -Pio "regex" # PCRE match, ignore case, output matching part one-per-line
| wc -l # Pipe to `wc` and count number of lines
```
---
18 bytes (115 to 99) saved by inspiration from [*Qwertiy*'s answer](/a/148742/71806) and [*Martin Ender*'s answer](/a/148743/71806). 1 byte thanks to [*Nahuel Fouilleul*](/u/70745).
[Answer]
# Javascript ES6, ~~89~~ ~~87~~ 86 chars
```
s=>s.match(/(?!^no,)\bn(o(|t|r|ne|body|thing|where)|e(v|ith)er)\b|n't\b|$/ig).length&1
```
## Test:
```
f=s=>s.match(/(?!^no,)\bn(o(|t|r|ne|body|thing|where)|e(v|ith)er)\b|n't\b|$/ig).length&1
console.log(`Yes.
It's noon.
Hello, World!
Never say never.
Ain't no thang!
No, it's noon now.
Neither me nor you.
I didn't do nothing!
No, I am your father.
A non-alcoholic drink.
I can't get no satisfaction.
All your base are belong to us.`.split`
`.every(f))
console.log(`No.
No, no!
Not today.
Neither am I.
Don't do that!
That's no moon!
And none survived.
No man is an island.
Nosebleeds are no fun.
Nothing compares to you.
That's a no, I'm afraid.
No, I am not your mother.`.split`
`.every(s=>!f(s)))
```
[Answer]
## [Perl 5](https://www.perl.org/), 74 bytes
**73 bytes code + 1 for `-p`.**
```
s/No,//;$_=!(s/(\bn(o(r|t|ne|body|thing|where)?|e(v|ith)er)|n't)\b//gi%2)
```
[Try it online!](https://tio.run/##RZFBa@QwDIXv/hUKdJkEpgks9FTKMrCHzmVOC0uhUJRYk5g61mA7GQby2zeVnVl6EcmL9PTp5ULePq1raE68b5rnh4@XogxN@d66kku/xMXR0rK@LXEwrl@uA3mqfi1UzouJQ0W@WtwuVu9t0/Tmx89qXd8o1OoYdwEcs6vVK1nLe/jL3upCHYy0yxeIA7q@UCeayUPAG7j0VCvhAPN/WspVJJJV0jWSvHu48SQLQBudrDSLmOGKPHsEHFOLhzOmqVodpME9ou14YGs60N64z@TQYTLoKfMEjCacsYsmQR@s3UxaDAToCVqy7HqIDFNIlBup47Q1iqzx9k0qCMda/eY7oNwaC/VHar4LRjlNonA6kRGEyc9mJp0sYUQHJkCuFl0WA7WWSIcMIvPnySU5Xw0djxfRQ0LL0dz3oHRKHLsR8OzR6Po7Hglsu27kLaI3nmDAOZt38mM6Sm53rr0wfdI2EM1ItfrHlxRTWB8v9gs "Perl 5 – Try It Online")
] |
[Question]
[
Write a program that takes in two non-negative integers **S** and **N** in that order. S represents the side length of a square grid of `.` characters. N represents the number of those `.`'s that need to be changed to `x`'s. You may assume N is no greater than S squared.
Your program needs to output this S×S square of `.`'s and N `x`'s but the requirement is that **the square must always have a diagonal line of symmetry from its top left to its bottom right**. Any grid arrangement is valid output as long as it has this symmetry.
For example, if S is 3 and N is 4 here are several grids that have this diagonal symmetry and would be valid output:
```
x.x
...
x.x
x..
.xx
.x.
...
.xx
.xx
```
The following grids however would not be valid:
```
.x.
xxx
...
(lacks diagonal symmetry)
..x
xx.
.x.
(has diagonal symmetry but not from the top left to the bottom right)
x.x
.x.
x.x
(incorrect number of x's)
```
**This is code golf so the shortest program in bytes wins!**
### Details:
* A trailing newline after the grid is fine.
* You may use any two distinct printable-ASCII characters in place of `.` and `x` if you prefer.
* If you prefer you may even output a [binary-matrix](/questions/tagged/binary-matrix "show questions tagged 'binary-matrix'") instead of a string.
* When N is 0 the output will be a pure S×S square of `.`'s with no `x`'s.
* When S is 0 the output will be an empty string (or single trailing newline).
* The output does not need to be deterministic, as long as it is always guaranteed to be valid.
### More Examples:
Not all valid arrangements are listed for each example input. Your output might look different yet still be valid.
```
S = 0, N = 0
[empty string]
S = 1, N = 0
.
S = 1, N = 1
x
S = 2, N = 0
..
..
S = 2, N = 1
x.
..
..
.x
S = 2, N = 2
x.
.x
.x
x.
S = 2, N = 3
xx
x.
.x
xx
S = 2, N = 4
xx
xx
S = 3, N = 2
x..
.x.
...
..x
...
x..
S = 4, N = 1
....
.x..
....
....
S = 4, N = 5
x..x
.x..
..x.
x...
xxx.
x...
x...
....
S = 5, N = 23
xxxxx
xxxxx
xxxxx
xxx.x
xxxx.
xxxxx
xxxxx
xxxxx
xxxx.
xxx.x
S = 7, N = 13
...x...
...x...
...x...
xxxxxxx
...x...
...x...
...x...
xxxxxxx
x......
x......
x......
x......
x......
x......
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~116~~ ~~113~~ ~~112~~ 101 bytes
```
lambda s,n:[[[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]for j in range(s)]for i in range(s)]
```
[Try it online!](https://tio.run/##dVLbjpswEH33V0xYbWU2JNpcVpWisFJf@gV9I2jlBUPMwhDZpi0v/fV0jIlglRYJM3Nm5hx87Etvzy1ur0V8utaiec8FmAgPSZLgqzqaFTdL/LIJo0Q9/Vmp5fapiiqKKopUmqhjlR5xZdKkWsQqLVoNFSgELbCU3IQDoj4h1wcoOsysahFsC9lZZh@gCrBnCQLNL6kha7WWmYVhGC@ddb/Ecln47jdq42VEWHhgAA8jR64aiYZoCSO@WiIvw0VsgFgE9twBegAcr2OGMjyAlrbTCN9FbeSMLWs7tJ7JdA3X6wHgm3A@DYsY8L8Upm8aaXVP0J0N7sc9XN3Dg2qZkL9V6iRK@lJ2JzSmP3QnGRN1/XYzLvaYai6tJvN6w5xSrVA6McrXxuYKvXtaitzbTKmJAGlc/hQ1d/0hYRet0EIQ3z3BVDTxY06jtMJq9XrCAB6BuxNig4bvQpXJune7boS1Mm8761XpQEm08AMwOUz4YRQI1lWrkAfr3wFZMTN0VPCWe8bbBUJpDBUnV6brQ280bNbpfbbuFgnM55Vpr7NtJwEswVjNx6aQ0iANgLGx4YT/sm0sfqtrsNJYuAhjZH4Iopne9TmCZ7YZlw3bumg7Rlu37NyyZzuX7l1h79IXSnfsK@W7vw "Python 2 – Try It Online")
**Input**: 2 integers `s` and `n`
**Output**: A 2D list of `True` and `False`, representing `x` and `.` respectively.
### Explanation
The strategy is to put as many `x`s on the diagonal as possible.
* If \$s\$ and \$n\$ has the same parity, then we can fill \$min(s,n)\$ diagonal squares.
* If \$s\$ and \$n\$ has different parity, then we can fill \$min(s-1,n)\$ diagonal squares.
The remaining `x`s can be split symmetrically between the 2 triangular half of the grid. For the bottom triangle, we fill from top to bottom, where each row is filled left to right. The upper triangle mirrors the bottom triangle (fill left to right, each column from top to bottom)
Thus, we can determine if a square is filled just based on its indices \$(i,j)\$:
* If \$i=j\$ (the square is on the diagonal), then that square is filled if \$i<n\$ and \$i<s-t\$, where \$t\$ is 0 or 1 depending on whether \$s\$ and \$n\$ have the same or different parity.
The following snippet evaluates to `True` or `False` if the diagonal square should be filled or not.
```
[n>i<s-(s+n&1), ...case when square is not diagonal... ][j!=i]
```
* If \$i>j\$ (the square is in lower triangle), then the number of squares in the lower triangle before this square (in fill order) is \$m = \frac{i(i-1)}{2} + j\$. Thus if this square is filled, then the number of squares filled before it is \$2m = i(i-1)+2j\$. We need to make sure that \$2m<n-s\$, otherwise the diagonal cannot be filled to the maximum.
Similarly, if \$i>j\$, then we fill if \$j(j-1)+2i<n-s\$.
The following snippet evaluates to `True` or `False` if the non-diagonal square is filled or not:
```
[i*~-i+2*j,j*~-j+2*i][i<j]<n-s
```
Combined together, this big expression evaluates to whether a square \$(i,j)\$ should be filled:
```
[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]
```
*Thanks @ovs for saving 4 bytes in a previous solution!*
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ 20 bytes
```
U:<~Zc`tnZ@)[]ett!-z
```
[Try it online!](https://tio.run/##y00syfn/P9TKpi4qOaEkL8pBMzo2taREUbfq/39jLlMA)
Characters are `#` and . The output is random, that is, it may be different every time the program is run. Running time is also random, but the program is guaranteed to finish in finite time.
## How it works
**General idea**
The code first generates a numeric vector with N ones and S^2-N zeros (`U:<~`), and transforms it into a string replacing 1 and 0 by the two mentioned characters (`Zc`). Then, a random permutation is applied (`tnZ@)`) , the result is reshaped into a square matrix of characters (`[]e`), and this is repeated (```) until the matrix equals its transpose (`t!-z`), while leaving a copy (`t`) for the next iteration or as final result.
**Detailed steps**
```
U % Input (implicit): S. Push S^2
: % Range [1 2 ... S^2]
<~ % Input (implicit): N. Greater-or-equal, element-wise. Gives
% [1 1 ... 1 0 0 ... 0] with N ones and S^2-N zeros
Zc % String where 1 becomes '#' and 0 becomes space
` % Do...while
tn % Duplicate. Number of elements. Gives S^2
Z@ % Random permutation of the integers 1, 2, ..., S^2
) % Apply as an index. This shuffles the previous string
% or char matrix, and gives a string as result
[]e % Reshape as a square matrix of chars
tt! % Duplicate twice, and transpose the second copy
- % Subtract element-wise
z % Number of nonzeros. This is the loop condition. The loop
% is exited when the result is 0, meaning that the matrix
% and its transpose are equal
% End (implicit)
% Display (implicit). The stack contains a copy of the latest
% matrix of chars, which is the first that was found to
% satisfy the symmetry condition
```
[Answer]
# JavaScript (ES6), ~~116 114~~ 110 bytes
Takes input as `(s)(n)`. Returns a matrix of Boolean values.
```
s=>n=>[...Array(s)].map((_,y,a)=>a.map((_,x)=>(p=Math.min(n&~1,s*s-s),x-y?(x<y?y*y-y+2*x:x*x-x+2*y)<p:x<n-p)))
```
[Try it online!](https://tio.run/##VZC9boMwFIV3nsJDVXzBtgIkqhQwUYeO7dKRoMaioUmUGGRHyFZEX50aRBR1@s7Pvcs5iU7oSh3bK5XN936o@aB5LnleMMZelRIWayjZRbQYfxFLBPBc3K1xBrf8XVwP7HKUWD7/RkQHmmoghtoNNpnd2MBSG8aBWZvAUOOUhaxdm0zSFgCGtPBQsSBoURJURA9GI@PZxw8fz0xmLkcmc76c7xxXI1cunw5fXJGUXumxulFvojpgXGiCZAmI5@iGqkbq5rxn5@YH7z750033BH04yn4H6b@6dotgCdMIavxWk@xGGXbATo2bwvfhrrbSBxSiiSnqYfgD "JavaScript (Node.js) – Try It Online")
### How?
The output matrix is divided into 2 parts:
* the cells located on the main diagonal (type A)
* all other cells (type B)
Whenever a type-B cell is set, its symmetrical counterpart must be set as well. We want to set as many type-B cells as possible and this number is given by:
$$p\_{n,s}=\min\left(2\left\lfloor\frac{n}{2}\right\rfloor,s(s-1)\right)$$
The number of type-A cells is therefore given by:
$$q\_{n,s}=n-p\_{n,s}$$
We define \$T(k)\$ as the \$k\$-th triangular number:
$$T(k)=\frac{k(k+1)}{2}$$
To figure out whether the type-B cell at \$(x,y)\$ must be set or not, we assign it the following ID and compare it with \$\dfrac{p\_{n,s}}{2}\$:
$$\begin{cases}
T(y-1)+x,&\text{if $x<y$}\\
T(x-1)+y,&\text{if $x>y$}\\
\end{cases}$$
Example for \$s=5\$:
$$\begin{pmatrix}
-&0&1&3&6\\
0&-&2&4&7\\
1&2&-&5&8\\
3&4&5&-&9\\
6&7&8&9&-
\end{pmatrix}$$
To figure out whether the type-A cell at \$(x,x)\$ must be set or not, we simply use \$x\$ as its ID and compare it with \$q\_{n,s}\$.
Example for \$s=5\$:
$$\begin{pmatrix}
0&-&-&-&-\\
-&1&-&-&-\\
-&-&2&-&-\\
-&-&-&3&-\\
-&-&-&-&4
\end{pmatrix}$$
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 113 bytes
Searches random matrices [S,N] until matrix g is equal to Transpose(g)
Outputs a binary matrix
```
If[#<1,"",g=(P=Partition)[k=Join@@{1~Table~#2,Table[0,#^2-#2]},#];While[g!=Transpose@g,g=P[RandomSample@k,#]];g]&
```
[Try it online!](https://tio.run/##HYxBC8IgGEB/SxOi4IvSDh2W4LVOUoMOYvBV5mRTh/MW7a/b6PZ4PJ7H3BqP2T2xWF5Ob0WOFKoKLF9JLjFll10Ma9Xxc3RBiA@dGnz0ZiIM/qB2QO5sQ5j@AtH1rXWzswveJAzjEEcj7DyT6oLhFf0V/dAb0c2prq1eFplcyFth1QHoXpfyAw "Wolfram Language (Mathematica) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 75 bytes
Here is also a deterministic version that searches all possible matrices
(it works only up to 4x4 due to memory limitations)
```
If[#<1,"",x=#2;Select[{0,1}~Tuples~{#,#},#==Transpose@#&&Tr[Tr/@#]==x&,1]]&
```
[Try it online!](https://tio.run/##DcjBCsIwDADQf1kgp4BGvGmgV2/Ceis9lBHnYJujrTAY269H3/FNqb51SnXokvVij1eAO1PT0CpwubU6alfDdibeD/9dRi3HBgQ7gYjPaS7Lp6gDRJ@DzycHUWRF4hjRnnmY67/QuT5ciTma/QA "Wolfram Language (Mathematica) – Try It Online")
*-2 bytes by @my pronoun is monicareinstate*
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, 152 bytes
```
a=`dc<<<4dk$2*1+v1-2/0k1/p`
for((q=$2-a*a-a,b=++a<$1?q/2:0;i<$1;++j>=$1?j=0,i++:0)){ printf $[i-j?i<a&j<a?1:i==a&j<b|j==a&i<b?1:0:i<q-2*b?1:0]\ ;}|rs $1
```
[Try the test suite online!](https://tio.run/##NY/BbsMgEETvfMUeUJUYIwMmimRD/Ae99NhWCo6JDKlwbKL00PTbXYLUw@y8ndNMb@K4fo/uy8JizQARAgIYpnQAor0BjoBD/uxpnOBN41jCq8ZhNfo4nJRScrhgUXBy51RU7MKr6xGdp2WzmTUW1BSGmrLXhBiFeTdXomGtS9gS4g86RV6z0hHSsO32B66LC7cz4HdHfeeUefHKdLxxWj@xf/gnONWnjDVOzVQUmT8/oP19LKksX//L5iHBrjVIxIAhnsWRSC6yi6Q6SaI6sUyZhB3agajRHnj9Bw "Bash – Try It Online")
\$S\$ and \$N\$ are read from stdin, and the output is printed to stdout. The characters used are `0` and `1` (for (for `.` and `x`, respectively).
This program prints a space between successive characters, which I think looks better (the grids are more squarish and easier to read), and it saves me a byte. If that's not acceptable, use `fold` instead of `rs` as follows (for 153 bytes):
```
a=`dc<<<4dk$2*1+v1-2/0k1/p`
for((q=$2-a*a-a,b=++a<$1?q/2:0;i<$1;++j>=$1?j=0,i++:0)){ printf $[i-j?i<a&j<a?1:i==a&j<b|j==a&i<b?1:0:i<q-2*b?1:0];}|fold -$1
```
**How it works:**
First we use `dc` to compute $$a=\left\lfloor\frac{\sqrt{4N+1}-1}{2}\right\rfloor.$$
You can check that \$a\$ is the greatest integer such that \$a(a+1) \leq N.\$ The reason this is useful is that $$a(a+1)=2(1+2+\dots+a).$$
The for loop that comes next runs through each position \$(i, j)\$ where each of the variables goes from \$0\$ to \$S-1.\$ It prints a `0` or a `1` for each \$(i,j)\$.
For convenience, \$a\$ is incremented during the for loop initialization, so it's actually \$1\$ higher than the above value during the body of the loop.
The following entries are filled in with `1`s (the others are all `0`s):
(1) Fill in each \$(i,j)\$ where \$0 \le i \lt a\$ and \$0 \le j \lt a.\$
(2) If \$a<S\$ (so that there's at least one row and one column left untouched still), fill in the entries at positions \$(a,i)\$ and \$(i,a)\$ (starting from \$i=0\$ and keeping \$i\$ below \$a-1\$), up to the number of additional entries that are still needed after step 1. These are always entered in pairs.
(3) If we still haven't marked enough entries (which can happen because we ran out of room off the main diagonal, or simply because we needed to mark an odd number of entries, but everything so far has been in pairs), then fill in entries \$(i,i)\$ on the main diagonal, starting at \$i=0,\$ until we've filled in the right number of `1`s.
Finally, the `rs` (or `fold`) at the end formats it all as a square array.
[Answer]
# [Perl 5](https://www.perl.org/), 139 bytes
```
sub f{($s,$n)=@_;$_='-'x$s x$s;$i=-1;while($n){$j=++$i%$s*$s+int$i/$s;$n<2&&$i-$j&&next;for$o($i,$j){$n-=s,^(.{$o})-,$1x,}}s/.{$s}/$&\n/gr}
```
[Try it online!](https://tio.run/##ZY/RasMwDEXf@xWi3LnOYidNoezBM@xDwgKDZHXolBJ3LCN4v56pYYPBBHrQ5UgHXdrxfFyW@P5C3awRDTjzT41D43d2NyGStEPwtnIfp3ButQAzep/nCHeI94h54CtCecP48aAUgkWvFLfT1XXDiEEjGPSyxdZH86yLGUPKrEE1mZRiKXNMJVTN5euYFtmht08Std4XxUM2b4h@M16zVbvmRJdR9LStuflXFL0cYQ@ueev@0N3Po@S/SPSiJjHfiLRJS7U3dDh@Aw "Perl 5 – Try It Online")
```
sub fungolfed {
($s,$n) = @_; # input params s and n
$_ = '-' x $s x $s; # $_ is the string of - and x
$i=-1; # start at position i=0, due to ++ below
while($n){ # while more x's to place (n>0)
$j = ++$i % $s * $s + int$i/$s; # j is the symmetrical position of i
$n<2 && $i-$j && next; # place x only in diagonal if one x left (n=1)
for $o ($i,$j){ # place x at positions i and j
$n -= s/^(.{$o})-/$1x/ # ...and decrease n if - was replaced by x
# ...that is if the position was not aleady x
}
}
s/.{$s}/$&\n/gr # put \n after each s'th char and return that
}
```
Test:
```
for my $s (0..7){
for my $n (0..$s*$s){
print "\n__________________ s=$s n=$n\n";
print f($s,$n) =~ s/./$& /gr; } }
```
Part of the output:
```
__________________ s=3 n=0
- - -
- - -
- - -
__________________ s=3 n=1
x - -
- - -
- - -
__________________ s=3 n=2
x - -
- x -
- - -
__________________ s=3 n=3
x x -
x - -
- - -
__________________ s=3 n=4
x x -
x x -
- - -
__________________ s=3 n=5
x x x
x - -
x - -
__________________ s=3 n=6
x x x
x x -
x - -
__________________ s=3 n=7
x x x
x x -
x - x
__________________ s=3 n=8
x x x
x x x
x x -
__________________ s=3 n=9
x x x
x x x
x x x
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~153~~ ~~140~~ 136 bytes
```
param($l,$n)if($l--){0..$l|%{$y=$_
-join(0..$l|%{$n-=$a=($_-eq$y-and$n)+2*($_-gt$y-and$n-gt1)
'.x'["$y;$_"-in($c+=,"$_;$y"*$a)-or$a]})}}
```
[Try it online!](https://tio.run/##fZHNasMwEITvegohNo2VWCb@CWkJgj5AoYdeCqUY0ciJiyMn/qE1jp/d3TZVUCh0T98OM3PYPZQfuqp3uihGyKik/XhQldp7UPhgeJ4hCMH7RRBAcZr00ElIiXgvc@NdNCMkKOlBKvQROqHMBqPzaPatbBurIIacTIPP6QuDbg0pE1gCb3PpM0jX0LEZKC7KCtTrwIdhHAi59wjF8b2FTxf8l8NrDi1Hjh5d65HDscOJ5djxIK8cvnX4znLi9CMvLS@xJ3aXxF0uthXG0cbpiU5o/yNCfWxVpZ/yjX7QZtvsfAqm3T9mz/gVvPnZVOm6LRpUbvBbfyI2cTYzifNvLw5ze8lAxi8 "PowerShell – Try It Online")
Unrolled:
```
param($length,$n)
if($length--){
0..$length|%{
$y=$_
-join(0..$length|%{
$draw = 1*($_ -eq $y -and $n) + # draw 1 element on the diagonal
2*($_ -gt $y -and $n -gt 1) # draw 2 elements in the corners
# or draw 0 elements (draw field char '.')
$n-=$draw # reduce the number of drawing elements
$coordCache += ,"$_;$y" * $draw # add one element or two identical elements
'.x'[$draw -or "$y;$_" -in $coordCache] # draw element directly or draw from cache
})
}
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
NθNηG←↑⊖θ.UM✂KA⁰⊘η¹x↑‖M↗P↘⭆θ§.x›η⁺ι№KAx
```
[Try it online!](https://tio.run/##TY5BT8MwDIXv@xVRT0YKExPi0p2mTYJJDFWb@AEh9doIN@mCU8qvD05P88nv6Xt@tr2JNhjK@ejHxB9p@MIIt4ft6l73optAf13wUL/jlbWqP0etDmgjDugZW8loVa0rIU9m3IdhML6FCzmL0CB@74hAiCet3gxNwveiNiUzL5kwIchNWc94JbR8cjGGWLyz63ouTCJ2Y3SeoT6EX7/4Wl1YrE5K4abVjo@@xRmq9Vxp9RrRcPlfq4bSDzit9iFJ/u6j0r/MNueX1eY5P070Dw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `S` and `N`.
```
G←↑⊖θ.
```
Fill a triangle of size `S-1` with `.`s.
```
UM✂KA⁰⊘η¹x
```
Change up to `N/2` of those `.`s to `x`s.
```
↑‖M↗
```
Reflect to create the diagonal symmetry, but leaving the diagonal empty.
```
P↘⭆θ§.x›η⁺ι№KAx
```
Count the number of `x`s and complete the diagonal using `x`s and `.`s as necessary to end up with `N` `x`s.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 97 bytes
```
->s,n{t=(?.*s+$/)*s
i=1
(t[i*-~s/s]=t[i/s-i%s*~s]=?X;i+=1)until 2>m=n-t.count(?X)
m>0&&t[0]=?X
t}
```
[Try it online!](https://tio.run/##XcxNCoMwFATgfU7hworGxPyodFGi1xDETQtCoKal77kopV49tbQL424@ZpjHfH760XjeAHMvNGlbUMhjkVEg1iiSYm8pX0DAYNYogNsD0GVV251sblQ2O7TXSDeTcRyLy2112nYZmRqZJNjL75Lg299nhGjsJZMDiwX5U@2pttRhq/etDlmGrLYsw3EVXlWs3rJmOvg6MvWz/wA "Ruby – Try It Online")
Llamda function. Returns a newline separated string with `X` and `.` can be shorter if a single line string is acceptable.
Very simple:
* Make a newline separated string of s lines of s `.`
* Set `i=1` and scan through all indexes of `i` interpreting this as both [row-then-column] and [column-then-row] and change the relevant `.` to `X` . The total number of `X` added per iteration will be 1 if it is the cell is on the diagonal, and either 2 or 0 if it is not, depending on whether the cells already contain `X`.
* End the loop when less than 2 more `X` need to be added.
* If there is still one `X` to be added, put it at top left (index 0)
* Return the string
] |
[Question]
[
We'd like to factorize a semiprime \$N\$. The goal of this challenge is to find two small integers \$u\$ and \$v\$ such that \$uvN\$ can be trivially factorized with Fermat's method, thus allowing to easily deduct the factors of \$N\$.
## The task
Given a [semiprime](https://en.wikipedia.org/wiki/Semiprime) \$N\$ and a positive integer \$k\$, we define \$x\$ and \$y\$ as:
$$x=\lceil\sqrt{kN}\rceil$$
$$y=x^2-kN$$
**Step #1 - Find \$k\$**
You first need to find the smallest possible value of \$k\$ such that \$y\$ is a [square number](https://en.wikipedia.org/wiki/Square_number) (*aka* perfect square).
This allows to factorize \$kN\$ with a single iteration of [Fermat's factorization method](https://en.wikipedia.org/wiki/Fermat%27s_factorization_method). More concretely, this immediately leads to:
$$kN=(x+\sqrt{y})\times(x-\sqrt{y})$$
(Update: this sequence is now published as [A316780](https://oeis.org/A316780))
**Step #2 - Factorize \$k\$**
You then have to find the two positive integers \$u\$ and \$v\$ such that:
$$uv=k$$
$$cu=x+\sqrt{y}$$
$$dv=x-\sqrt{y}$$
where \$c\$ and \$d\$ are the prime factors of \$N\$.
**Summary**
Your task is to write a program or function that takes \$N\$ as input and prints or outputs \$u\$ and \$v\$ in any order and any reasonable format.
## Example
Let's consider \$N = 199163\$
**Step #1**
The smallest possible value of \$k\$ is \$40\$, which gives:
$$x = \lceil(\sqrt{40 \times 199163})\rceil = 2823$$
$$y = 2823^2 - 40 \times 199163 = 7969329 - 7966520 = 2809 = 53^2$$
$$kN = (2823 + 53) \times (2823 - 53)$$
$$kN = 2876 \times 2770$$
**Step #2**
The correct factorization of \$k\$ is \$k = 4 \times 10\$, because:
$$kN = 2876 \times 2770$$
$$kN = (719 \times 4) \times (277 \times 10)$$
$$N = 719 \times 277$$
So, the correct answer would be either \$[ 4, 10 ]\$ or \$[ 10, 4 ]\$.
## Rules
* It is not required to strictly apply the two steps described above. You're free to use any other method, as long as it finds the correct values of \$u\$ and \$v\$.
* You must support all values of \$uvN\$ up to the native maximum size of an unsigned integer in your language.
* The input is guaranteed to be a semiprime.
* This is code-golf, so the shortest answer in bytes wins.
* Standard loopholes are forbidden.
## Test cases
```
N | k | Output
-----------+------+------------
143 | 1 | [ 1, 1 ]
2519 | 19 | [ 1, 19 ]
199163 | 40 | [ 4, 10 ]
660713 | 1 | [ 1, 1 ]
4690243 | 45 | [ 9, 5 ]
11755703 | 80 | [ 40, 2 ]
35021027 | 287 | [ 7, 41 ]
75450611 | 429 | [ 143, 3 ]
806373439 | 176 | [ 8, 22 ]
1355814601 | 561 | [ 17, 33 ]
3626291857 | 77 | [ 7, 11 ]
6149223463 | 255 | [ 17, 15 ]
6330897721 | 3256 | [ 74, 44 ]
```
## Example implementation
In the snippet below, the \$f\$ function is an ungolfed implementation which takes \$N\$ as input and returns \$u\$ and \$v\$.
For illustrative purposes only, the snippet also includes the \$g\$ function which takes \$N\$, \$u\$ and \$v\$ as input and computes the factors of \$N\$ in \$O(1)\$.
```
f = N => {
for(k = 1;; k++) {
x = Math.ceil(Math.sqrt(k * N));
y = x * x - k * N;
ySqrt = Math.round(Math.sqrt(y));
if(ySqrt * ySqrt == y) {
p = x + ySqrt;
for(u = 1;; u++) {
if(!(p % u) && !(N % (p / u))) {
v = k / u;
return [ u, v ];
}
}
}
}
}
g = (N, u, v) => {
x = Math.ceil(Math.sqrt(u * v * N));
y = x * x - u * v * N;
ySqrt = Math.round(Math.sqrt(y));
p = x + ySqrt;
q = x - ySqrt;
return [ p / u, q / v ];
}
[
143, 2519, 199163, 660713, 4690243, 11755703,
35021027, 75450611, 806373439, 1355814601,
3626291857, 6149223463, 6330897721
]
.map(N => {
[u, v] = f(N);
[c, d] = g(N, u, v);
console.log(
'N = ' + N + ', ' +
'u = ' + u + ', ' +
'v = ' + v + ', ' +
'N = ' + c + ' * ' + d
);
});
```
[Answer]
# Mathematica, ~~81~~ 79 bytes
*Thanks to Martin Ender for saving 2 bytes!*
```
(c=Ceiling;For[j=0;z=E,c@z>z,p=(x=c@Sqrt[j+=#])+{z=Sqrt[x^2-j],-z}];p/#~GCD~p)&
```
Pure function taking a semiprime as input and returning an ordered pair of positive integers. The `For` loop implements the exact procedure described in the question (using `#` for the input in place of `n`), with `x` as defined there, although we store `j = k*n` instead of `k` itself and `z=Sqrt[y]` instead of `y` itself. We also compute `p={x+z,x-z}` inside the `For` loop, which ends up saving one byte (on like the seventh try). Then the two desired factors are `(x+z)/GCD[#,x+z]` and `(x-z)/GCD[#,x-z]`, which the concise expression `p/#~GCD~p` computes directly as an ordered pair.
Curiosities: we want to loop until `z` is an integer; but since we're going to use `Ceiling` already in the code, it saves two bytes over `!IntegerQ@z` to define `c=Ceiling` (which costs four bytes, as Mathematica golfers know) and then test whether `c@z>z`. We have to initialize `z` to something, and that something had better not be an integer so that the loop can start; fortunately, `E` is a concise choice.
[Answer]
## JavaScript (ES7), ~~86~~ 81 bytes
```
n=>(g=k=>(y=(n*k)**.5+1|0,y+=(y*y-n*k)**.5)%1?g(k+1):n*u++%y?g(k):[--u,k/u])(u=1)
```
Edit: Saved 4 bytes thanks to @Arnauld.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~60~~ ~~49~~ 45 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/9429#9429)
```
{×1|w←⍵∨(⌈+.5*⍨×⍨-⍨⌈×⌈).5*⍨⍵×⍺:⍺∇1+⍵⋄w,⍵÷w}∘1
```
[Try it online!](https://tio.run/##TU0xTgNBDOx5BSUhJFrba@8uLQ2pkAgfiISOJhIozSmCVEFhBUkEBQpPSEeFkCjJT/yRw3tpKDya8XjGo7tx73o6Gt/eNLp@rya6eAWMobnfbeChNqWrL83bI13mbp@PdbXdbQx6NrYyvsyd/d4Oi/VzaqP5Cbol@fJYnxTju55p/oCmahvX9mpwoc/z30/SxZup4eWZ4dX5YNhUhwCBOTg6MOoLIkMqIiWQokVcgEK8JIftyb8MsUNwGIwG9uwEwGh0QoE8tUXEHMGLKwYJCiaIXAICPiGS378hcjGFgPAH "APL (Dyalog Unicode) – Try It Online")
-11b thanks to Adám, -4b courtesy of ngn along with some excellent tips from both on [The APL Orchard](https://chat.stackexchange.com/rooms/52405/the-apl-orchard)
## Explanation:
First ever APL answer so might be able to be golfed further! Explanation below is for the 49b solution. Approach pretty much just follows the algorithm in the original post, but uses the GCD to compute the factors once k, x and y are known.
```
{×1|y←.5*⍨(×⍨x←⌈.5*⍨⍵×⍺)-⍵×⍺:⍺∇1+⍵⋄w,⍵÷w←⍵∨x+y}∘1 ⍝
{ }∘1 ⍝ dfn; ⍺ is left argument (N), ⍵ is right argument acting as a counter for k incremented each recursion from 1
( x←⌈.5*⍨⍵×⍺)-⍵×⍺ ⍝ Computes x as per question for current k
y←.5*⍨(×⍨x ) ⍝ Computes sqrt(y) from x as per question (×⍨x = x^2). Note that y here actually represents sqrt(y) from the question as we do not need to store actual y
×1|y ⍝ Use 1 modulo y and 'direction' to return 0 if y is a whole number, else 1
: ⋄ ⍝ 'guard' - if the evaluation of the left side of : is true, performs the statement immediately following it, otherwise the next statement (separated by ⋄)
⍺∇1+⍵ ⍝ if guard is true, recurse with the same left argument of N, and a right argument of the new k (k+1)
w,⍵÷w←⍵∨x+y ⍝ if guard is false, computes gcd (∨) of k and (x+y) as one factor (w), and k÷w as the second factor
```
[Answer]
# Python 2, ~~127~~ ~~121~~ ~~117~~ ~~111~~ ~~107~~ ~~104~~ ~~101~~ 99 bytes
*-1 byte thanks to Neil & -3 bytes thanks to ovs*
```
N=input()
k=u=1;p=m=.5
while p%1:p=1+(k*N)**m//1;p+=(p*p-k*N)**m;k+=1
while N*u%p:u+=1
print~-k/u,u
```
[Try it Online!](https://tio.run/nexus/python2#VY9RasMwEET/fQpDCdhyU2t2tSsrQVfwLVpqnARRIvrXq7tJCWXzOW8fw@w25@VS6rXrmzXXjGPJ5/wmzffncnpvyw6HkjF0q5t7587jeBOG3BVX9g90XIeMhz67uiuHegfla7lcf/brWF/r9vKX2o8OgfvmP5EgmYiUoPau6iMsCJo8PVUAUSR6i1g8wVM0KEoQr4BBk1eOHPhpAItMCOqtyEpKCZPYQkVIRBxuc1tDmf2UYiT02/23Xw)
**Curiosities:**
`p` is initialized to `.5` so that the loop condition will be true on the first iteration. Note that it is shorter to store `p` (as `x` + `sqrt(y)`) than it is to store each of `x` and `y` separately.
[Answer]
# Axiom, ~~131~~ 115 bytes
```
v(x)==floor(x^.5)::INT;r(n)==(k:=0;repeat(k:=k+1;x:=1+v(k*n);y:=v(x*x-k*n);x^2-y^2=k*n=>break);[w:=gcd(k,x+y),k/w])
```
The function that would resolve question is r(n) above. ungolf and test
```
vv(x)==floor(x^.5)::INT
--(x-y)*(x+y)=k*n
rr(n)==
k:=0
repeat
k:=k+1
x:=1+vv(k*n)
y:=vv(x*x-k*n)
x^2-y^2=k*n=>break
[w:=gcd(k,x+y),k/w]
(4) -> [[i,r(i)] for i in [143,2519,199163,660713,4690243,11755703]]
(4)
[[143,[1,1]], [2519,[1,19]], [199163,[4,10]], [660713,[1,1]],
[4690243,[9,5]], [11755703,[40,2]]]
Type: List List Any
```
] |
[Question]
[
We define a *binarray* as an array satisfying the following properties:
* it's non-empty
* the first value is a `1`
* the last value is a `1`
* all other values are either `0` or `1`
For instance, the array `[ 1, 1, 0, 1 ]` is a valid *binarray*.
## The task
Given a non-empty array **A** of non-negative integers and a positive integer **N**, your job is to find a *binarray* **B** of length **N** which allows to generate **A** by summing an unrestricted number of copies of **B**, shifted by an unrestricted number of positions.
### Example
```
A = [ 1, 1, 2, 4, 1, 2, 2, 1, 0, 1, 0, 1, 1, 0, 1 ]
N = 4
```
For this input, the *binarray* `B = [ 1, 1, 0, 1 ]` would be a valid answer because we can do:
```
[ 1, 1, 0, 1 ]
+ [ 1, 1, 0, 1 ]
+ [ 1, 1, 0, 1 ]
+ [ 1, 1, 0, 1 ]
+ [ 1, 1, 0, 1 ]
+ [ 1, 1, 0, 1 ]
-----------------------------------------------
= [ 1, 1, 2, 4, 1, 2, 2, 1, 0, 1, 0, 1, 1, 0, 1 ]
```
### Rules
* Input can be taken in any reasonable format.
* Output can be either a native array (e.g. `[1, 1, 0, 1]`) or a binary string with or without a separator (e.g. `"1,1,0,1"` or `"1101"`)
* You're only required to print or return one valid *binarray*. Alternatively, you may choose to print or return *all of them* when several solutions exist.
* You are not required to support inputs that do not lead to any solution.
* The sum may include implicit zeros which do not overlap with any copy of **B**. The second zero in the above sum is such an implicit zero.
* Your can assume that the maximum size of **A** is 100 and the maximum size of **B** is 30.
* This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.
## Test cases
```
Input : N = 1 / A = [ 1, 2, 3, 4, 5 ]
Output: [ 1 ]
Input : N = 2 / A = [ 1, 2, 100, 99 ]
Output: [ 1, 1 ]
Input : N = 3 / A = [ 1, 1, 1 ]
Output: [ 1, 1, 1 ]
Input : N = 3 / A = [ 1, 1, 3, 2, 2 ]
Output: [ 1, 1, 1 ]
Input : N = 3 / A = [ 1, 0, 2, 1, 1, 1, 0, 0, 1, 0, 1 ]
Output: [ 1, 0, 1 ]
Input : N = 4 / A = [ 1, 2, 2, 2, 1 ]
Output: [ 1, 1, 1, 1 ]
Input : N = 4 / A = [ 1, 1, 2, 4, 1, 2, 2, 1, 0, 1, 0, 1, 1, 0, 1 ]
Output: [ 1, 1, 0, 1 ]
Input : N = 4 / A = [ 1, 1, 0, 2, 1, 0, 1 ]
Output: [ 1, 0, 0, 1 ] or [ 1, 1, 0, 1 ]
Input : N = 5 / A = [ 1, 3, 6, 9, 8, 6, 3, 4 ]
Output: [ 1, 1, 1, 0, 1 ]
Input : N = 8 / A = [ 2, 1, 0, 2, 3, 3, 1, 2, 1 ]
Output: [ 1, 0, 0, 1, 1, 1, 0, 1 ]
Input : N = 10 / A = [ 1, 2, 1, 2, 2, 1, 3, 3, 3, 2, 3, 0, 2, 1, 1, 0, 1 ]
Output: [ 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 ]
Input : N = 13 / A = [ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 ]
Output: [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 ]
Input : N = 5 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 1, 1, 1, 1 ]
Input : N = 6 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 0, 0, 0, 0, 1 ]
Input : N = 7 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 1, 0, 0, 0, 1, 1 ]
Input : N = 9 / A = [ 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1 ]
Output: [ 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
```
[Answer]
# PHP, ~~105 92 90~~ 86 bytes
[Jörg´s solution](https://codegolf.stackexchange.com/a/114493) fixed and golfed:
```
for($b=1+2**$argv[1];;)--$argc>1?$s+=$argv[$argc]*2**$i++:$s%($b-=2)||die(decbin($b));
```
takes `N` from first command line argument, values after that;
run with `-r`or [test it online](http://sandbox.onlinephpfunctions.com/code/8324bb7e85c80de294c1b07785c69ce92cb939eb).
prints binary number (format `10001`);
prints invalid solution or runs dead if there is no valid solution.
**first version** (now 97 bytes) that prints nothing for invalid input: [test it online](http://sandbox.onlinephpfunctions.com/code/0de45729a20b4528fe7a241b074dec23f5f231c9)
```
for($b=1+$m=2**$argv[1];$m/2<=$b;)--$argc>1?$s+=$argv[$argc]*2**$i++:$s%($b-=2)||die(decbin($b));
```
**breakdown**
```
for($b=1+$m=2**$argv[1];$m/2<=$b;) # second loop: loop $b from 2^N-1 by -2 to 2^(N-1)
--$argc>1 # first loop: decrease $argc ...
?$s+=$argv[$argc]*2**$i++ # while $argc>1: binary sum from last to 2nd argument
:$s%($b-=2)||die(decbin($b)); # later: if $b divides $s, print in binary and exit
```
[Answer]
# [PHP](https://php.net/), 219 bytes
```
<?for(list($g,$z)=$_GET,$d=~-$l=2**$z;$d>=$l/2;max(array_diff_assoc($r,$g)?:[0])?:$o[]=$b,$d-=2)for($r=[],$b=decbin($d),$k=0;$k<count($g);$k++)for($u=$g[$k]-$r[$k],$i=0;$i<$z;$i++)$u<1?:$r[$k+$i]+=$u*$b[$i];print_r($o);
```
[Try it online!](https://tio.run/##hVRNj9owEL3zK1A6hwSMajuwuzSke6hWVS/tZW9eKwoQIIUmkQNVu1X3r1N/xIkJqy0jTBi/efNmPE61q86L@2pXDTIhSpGIrCrFMS@2/stD8vXb45dPD0E02JQiS1c7nw0YI4iiEE3RjCOCGOF8gIyTYIzmcy6fGGnd0riES4/jCiWG9t1YUWjD0tTaRGInhzLpnupIh5FKl9knNthSaCx2sNii2j0l3dGhiLBRPtX5LWD4TmQ/M1FnBhmiGzRHd3KV/eBopkVZItpkCqURo/pOkWFCLiqyqkNtCm8boRUSbCRehpnylMqwSRG2RLQNMzGYuMqH7bHoNl9ac1xEd7379PrvGrFlk7dBNw3j26hbXSvG/yGb69qMudNjvldT09X66jias6bNWV8dsz1H4gCUf6YZZz2vEaHX3s7VTLY7YaNPXaquVZ3AqZ4JFR2aXXLZSDMKdiBw10jyCsxeEHJBNbTasdNIbKq4tcPQ4zLvAWrvih3wZlbdq@miSQ9tLoRE87SG5PPDY/DnVNTZ0YcyiM7yveMf8lr@2yJ4DmKNQLCOXyZwiOloBM8RrD/GcHhPox/pLz8VIv2drPPNJknrulz5IBBsg/sPDHO5Qsl4DEvJMIlpoNhBxIwjWMbrbLXMCx/WAYJ9jCPYL1blqVCpA/lnPDbwUwxbBns@AaF@EOQKmy@UkFyC4LQgMo/aHEPOxzGcRrBk8jGqRF4cE2Eqy1a7cvi9lBk95CHpQt7T0UOdR1XKKG/83lPhRYO/538 "PHP – Try It Online")
-4 Bytes using `[$g,$z]=$_GET` PHP 7.1 instead of `list($g,$z)=$_GET`
[Answer]
# Python, 166 bytes
```
def f(a,n):
for i in range(1<<n-1,1<<n):
b=bin(i)[2:];u,v=(int(('0{:0>%d}'%sum(a)*len(s)).format(*s))for s in[a,b])
if u%v<1>int(str(u//v*10)[::~sum(a)]):yield b
```
[Try it online!](https://tio.run/##nZJda4MwFIbv@yvOjTQp2ZqPtqvO9o@IF4q6BWxa/IIytr/uEp1OqGmh8KKBvOc5OW9yuVafZyXaNkkzyFBEFPYWkJ0LkCAVFJH6SBHzffXCiPmZXYgPsVRI4oB74XtNmgOSqkJoSb88enSS76VT1icU4VWeKlRi/Kp5p6hCK7026FKjg4jEIdYwmUHtND47GkZZFaher5sVozjwvJ@eE2LvKtM8gbi9FMaWy7JCGQoYAU5AENgQ2IYEGMZ4MWdhlBJwXW3hsxYjvSlsm6KjcKuF9l0G0U79ws7lg4xlY2vNu@lGO5uipz2sADqtsxr1hDsdEYF9tzCZau/21ssnUNGJjUPsrflPji8G9YBpdH8n1Jdvu6Qh21n9XyR7kPit2Py0j4t2zxS9PVPk3nl64/fuM2azYRl7@ws "Python 3 – Try It Online")
### How it works
Consider A and B as the digits of base *k* numbers *u* and *v*. For example (we’ll use *k* = 1000 for illustration):
A = [1, 2, 1, 3, 2, 1, 2]
B = [1, 0, 0, 1]
*u* = 1 002 001 003 002 001 002
*v* = 1 000 000 001
As many of the other answerers noticed, if B is a valid answer, then *u* is divisible by *v*. In this case,
*u* = 1 002 001 002 ⋅ *v*
This quotient, translated back to the array [1, 2, 1, 2], tells us exactly how many copies of B we need shifted to each position.
```
[1, 0, 0, 1]
+ [1, 0, 0, 1]
+ [1, 0, 0, 1]
+ [1, 0, 0, 1]
+ [1, 0, 0, 1]
+ [1, 0, 0, 1]
-----------------------
[1, 2, 1, 3, 2, 1, 2]
```
(Why? Because that is exactly how long multiplication works in base *k*.)
What the other answerers failed to notice is that **the above condition is not sufficient**. For example:
A = [1, 2, 1, 3, 2, 1, 2]
B = [1, 1, 1, 1]
*u* = 1 002 001 003 002 001 002
*v* = 1 001 001 001
*u* = 1 000 999 002 ⋅ *v*
Mathematically speaking, we can still translate that quotient back to the array [1, 1, −1, 2], which works fine if we’re allowed to use negative copies of B:
```
[1, 1, 1, 1]
+ [1, 1, 1, 1]
− [1, 1, 1, 1]
+ [1, 1, 1, 1]
+ [1, 1, 1, 1]
-----------------------
[1, 2, 1, 3, 2, 1, 2]
```
but of course the challenge does not permit negative copies. So we need an additional check.
Toward that end, we select a base *k* = 10*e* where *k* > 10 ⋅ sum(A), and check that none of the base *k* digits overflow into the next base *k* digit when we multiply the quotient by ten. That is, every *e*th base ten digit, starting at the end, in the base ten representation of the quotient times ten, must be 0. This guarantees that the quotient translates back to an array with nonnegative elements.
[Answer]
# PHP, 213 Bytes
Same way a little bit golfed
```
<?for($b=2**~-$l=$_GET[1];$b<2**$l;array_filter($t[$b++])?:$d[]=$o)for($g=count($t[$b]=$_GET[$i=0]);min($t[$b])>-1&$i<=$g-$l;$i++)for($e=$t[$b][$i],$k=0,$o=decbin($b);$k<$l;)$t[$b][$k+$i]-=$o[$k++]*$e;print_r($d);
```
[Try it online!](https://tio.run/##fVJdb4IwFH33VyzmZrFSkxbUyUrn07I/sDfWGPlQiA4I4sOybH/dXVo60S1yQtOce@53q6w6Bcsqqwabsk7XcTYKB2HIqUs9OqUzRTkNuVIDakjOGPV9hbeQ/9IIhXJkepSHGveaZm0IDYZoz86T9XK0QHqqPXsRXaSMnVtnG0JrWU/LrMrYGEOyJ/DonPp0gSd2qehMp7Jmt/P3ENzUsjAx@EWdthZPo9Xb9nRezkxRl26290t0M@R6FOfvaih9cFs1vy2adxFvqx50qW2HN2W@3pRBf6Xm/7PKc6//vBE75fOGkFfrA6xenl/J57E4pM0IEiJO@DBHEEl3PP6ewF5qAb5JAVGAHOzFuq7XH6tNvm9SVDYhRI6jyPIRklBJKIkOsJVxeSwaY1ddFMglU0S850XHk6cJv4c8kLDFXAJyxzHuqTQCdFEUdpJRKGWSxlHrGhEBuwD1xIp2DuommLy9OmoMqajqvGhWtekpjbPyztTgKikhocO3Yii@Tj8 "PHP – Try It Online")
## PHP, 344 Bytes first working
After my first answer I have decide to make a longer try that give back all valid solutions.
```
<?foreach(range(2**($l=$_GET[1])-1,2**($l-1))as$b){$t[$b]=($g=$_GET[0]);for($i=0;$t[$b]&&$i<=count($g)-$l;$i++){$e=reset($y=array_slice($t[$b],$i,$l));foreach(str_split(decbin($b))as$k=>$v)$t[$b][$k+$i]=$y[$k]-$e*$v;if(min($t[$b])<0)unset($t[$b]);}}foreach($t as$k=>$v)if(max($v)>0)unset($t[$k]);echo join(",",array_map(decbin,array_keys($t)));
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/07f41c350db36f3709a13fd3c4c71c8e23e0aa5c)
## Breakdown
```
foreach(
range(2**($l=$_GET[1])-1
,2**($l-1)
) # make decimal range of a binarray with given length
as$b){
$t[$b]=($g=$_GET[0]); # make a copy for each possible solution pattern
for($i=0;$t[$b]&&$i<=count($g)-$l;$i++){ # Loop till solution is valid or reach last digit
$e=reset($y=array_slice($t[$b],$i,$l)); # take first value of a sequence with the length
foreach(str_split(decbin($b))as$k=>$v)
$t[$b][$k+$i]=$y[$k]-$e*$v; # replace values in copy
if(min($t[$b])<0)unset($t[$b]); # kill solution if a minimum <0 exists
}
}
foreach($t as$k=>$v)if(max($v)>0)unset($t[$k]); # drop all solutions where the sum is not zero
echo join(",",array_map(decbin,array_keys($t))); #Output all solutions
```
[Answer]
## Python, 205 bytes
```
def f(a,l):
b=lambda s:b(s[:-1])*sum(a)*8+int(s[-1])if s else 0
c=lambda n:n and(n/sum(a)/4%2 or c(n/sum(a)/8))
for i in range(2**~-l,2**l):
j=bin(i)[2:]
if b(a)%b(j)<1 and not c(b(a)/b(j)):return j
```
Returns a binary string without separator. As @AndersKaseorg points out, there are inputs for which @fəˈnɛtɪk's solution doesn't work because the division represents a negative coefficient which is disallowed. To work around this, I use a very large base and test that there is no borrow in the division.
[Answer]
# Pyth, 32 bytes
```
f!|%FKiRJysQ,QT>#sQj/FKJ+L1^U2tE
```
[Try it online](https://pyth.herokuapp.com/?code=f%21%7C%25FKiRJysQ%2CQT%3E%23sQj%2FFKJ%2BL1%5EU2tE&input=%5B1%2C+1%2C+2%2C+4%2C+1%2C+2%2C+2%2C+1%2C+0%2C+1%2C+0%2C+1%2C+1%2C+0%2C+1%5D%0A4)
### How it works
```
^U2tE Cartesian power [0, 1]^(N - 1)
+L1 prepend 1 to every list
f filter for lists T such that:
sQ sum(A)
y double
J assign to J
iR ,QT convert [A, T] from base J
K assign to K
%F fold modulo
| logical OR with
/FK fold integer division over K
j J convert to base J
>#sQ filter for digits greater than sum(A)
! logical NOT
```
The strategy is similar to my [Python answer](https://codegolf.stackexchange.com/a/124462), except that since Pyth has builtins for base conversion, we can use a more efficient base *k* = 2 ⋅ sum(A), and check directly that every digit of the quotient is at most sum(A).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~77~~ ~~74~~ ~~96~~ 80 bytes
```
n->a->[v|d<-divisors(b=Pol(a)),(v=Vec(d))%2==v&&vecmin(Vec(b/d))>=0&&d%x&&#d==n]
```
Returns all solutions.
First converts the array `a` to a polynomial `b`. Then chooses from the divisors `b` the polynomials `d` such that the coefficients of `d` are all `1` and `0`, and the coefficients of `b / d` are all nonnegative, and `d(0) = 1`, and `deg(d) = n + 1`. Finally, converts them back to arrays.
[Try it online!](https://tio.run/##lVLdasMgGL3fU3wwKgqG@ZN0DdQ8w652U3qR1nYIWxrSIrvYu2eJaRZd3CBwEPH88Hm0LhuTvNXtGRS0VVKUSbGzX3qbaGPN9dJc8UG9XN5xSQjFVr2ejlgTshJKWYTs6fhhKtwfHp6640IxhPTqE6FHrVS1b@vGVDd8xpzgHXAKgoKkkFLIYE/Iw0iLieaMUcjzgJZ3usdfhHRuEaXZkDyCOQybMC@d5hgQpwdFSicp9yP/z/bnmYmyu6i7zbqrgcLGbfrOAt2m1wkvTDrwyNCceeV688oRg9vvaDYW919gLDCK2Ctlv1udIzSslxqelxrypYbwK/2sTtR@Aw "Pari/GP – Try It Online")
] |
[Question]
[
The [*SKI calculus*](https://en.wikipedia.org/wiki/SKI_combinator_calculus) is a variant of the Lambda calculus that doesn't use lambda expressions. Instead, only application and the combinators *S*, *K*, and *I* are used. In this challenge, your task is to translate SKI terms into Lambda terms in [β normal form](https://en.wikipedia.org/wiki/Beta_normal_form).
---
## Input Specification
The input is an SKI term in the following textual representation. You may choose to receive an optional trailing newline. The input is composed of the characters `S`, `K`, `I`, `(`, and `)` and satisfies the following grammar (in ABNF form) with `sterm` being the start symbol:
```
sterm = sterm combinator ; application
sterm = combinator ;
sterm = '(' sterm ')' ; grouping
combinator = 'S' | 'K' | 'I' ; primitives
```
## Output Specification
The output is a lambda term with no free variables in the following textual representation. You may choose to output an optional trailing newline. The output shall satisfy the following grammar in ABNF form with `lterm` being the start symbol:
```
lterm = lterm operand ; application
lterm = ALPHA '.' lterm ; lambda
lterm = operand
operand = '(' lterm ')' ; grouping
operand = ALPHA ; variable (a letter)
```
## Constraints
You may assume that the input has a β normal form. You may assume that the β normal form uses at most 26 different variables. You may assume that both input and output are representable in 79 characters.
## Sample inputs
Here are a couple of sample inputs. The output is one possible output for the given input.
```
input output
I a.a
SKK a.a
KSK a.b.c.ac(bc)
SII a.aa
```
## Scoring
The shortest solution in octets wins. Common loopholes are prohibited.
[Answer]
# Ruby, 323 bytes
I can't believe this piece of crap works at all:
```
h={};f=96;z=gets.chop
{?S=>'s0.t0.u0.s0u0(t0u0)',?K=>'k0.l0.k0',?I=>'i0.i0'}.each{|k,v|z.gsub!k,?(+v+?)}
loop{z=~/\((?<V>\w1*0)\.(?<A>(?<B>\w1*0|[^()]|\(\g<B>+\))+)\)(?<X>\g<B>)/
s=$`;t=$';abort z.gsub(/\w1*0/){|x|h[x]=h[x]||(f+=1).chr}if !t
z=$`+?(+$~[?A].gsub($~[?V],$~[?X].gsub(/\w1*0/){|a|s[a]?a:a.gsub(?0,'10')})+?)+t}
```
Using regex substitution to perform β-reduction on raw strings is some Tony-the-Pony stuff. Nonetheless, its output looks correct at least for easy testcases:
```
$ echo 'I' | ruby ski.rb
(a.a)
$ echo 'SKK' | ruby ski.rb
(a.(a))
$ echo 'KSK' | ruby ski.rb
((a.b.c.ac(bc)))
$ echo 'SII' | ruby ski.rb
(a.(a)((a)))
```
Here's it handling `K(K(K(KK)))` with some debug output, which takes about 7 seconds on my laptop, because regular expression recursion is *slow*. You can see its α-conversion in action!
```
$ echo 'K(K(K(KK)))' | ruby ski.rb
"(l0.((k10.l10.k10)((k10.l10.k10)((k10.l10.k10)(k10.l10.k10)))))"
"(l0.((l10.((k110.l110.k110)((k110.l110.k110)(k110.l110.k110))))))"
"(l0.((l10.((l110.((k1110.l1110.k1110)(k1110.l1110.k1110)))))))"
"(l0.((l10.((l110.((l1110.(k11110.l11110.k11110))))))))"
(a.((b.((c.((d.(e.f.e))))))))
```
[Answer]
# Python 2, 674
```
exec u"""import sys
$ V#):%=V.c;V.c+=1
c=97;p!,v,t:[s,t.u({})][v==s];r!:s;u!,d:d.get(s,s);s!:chr(%)
def m(s,x):%=min(%,x);-(%==x)+x
$ A#,*x):%,&=x
C='()';p!,x,y:s.__$__(%.p/,&.p/);m!,x:&.m(%.m(x));u!,d:A(%.u(d),&.u(d));s!:%.s()+s.C[0]+&.s()+s.C[1:]
def r(s):x=%.r();y=&.r();-x.b.p(x.a,y).r()if'L'in`x`else s.__$__/
$ L(A):C='.';u!,d:L(d.setdefault(%,V()),&.u(d))
x=V();y=V();z=V()
I=L(x,x)
K=L(y,L/)
S=L(x,L(z,L(y,A(A/,A(z,y)))))
def E():
t=I
while 1:
q=sys.stdin.read(1)
if q in')\\n':-t
t=A(t,eval(max(q,'E()')).u({}))
t=E().r()
t.m(97)
print t.s()""".translate({33:u'=lambda s',35:u':\n def __init__(s',36:u'class',37:u's.a',38:u's.b',45:u'return ',47:u'(x,y)'})
```
Note: after `while 1:`, 3 lines are indented with a tab character.
This is basically the code behind <http://ski.aditsu.net/> , translated to python, greatly simplified and heavily golfed.
**Reference:** (this is probably less useful now that the code is compressed)
V = variable term
A = application term
L = lambda term
c = variable counter
p = replace variable with term
r = reduce
m = final variable renumbering
u = internal variable renumbering (for duplicated terms)
s = string conversion
(parameter s = self)
C = separator character(s) for string conversion
I,K,S: combinators
E = parse
**Examples:**
```
python ski.py <<< "KSK"
a.b.c.a(c)(b(c))
python ski.py <<< "SII"
a.a(a)
python ski.py <<< "SS(SS)(SS)"
a.b.a(b)(c.b(c)(a(b)(c)))(a(d.a(d)(e.d(e)(a(d)(e))))(b))
python ski.py <<< "S(K(SI))K"
a.b.b(a)
python ski.py <<< "S(S(KS)K)I"
a.b.a(a(b))
python ski.py <<< "S(S(KS)K)(S(S(KS)K)I)"
a.b.a(a(a(b)))
python ski.py <<< "K(K(K(KK)))"
a.b.c.d.e.f.e
python ski.py <<< "SII(SII)"
[...]
RuntimeError: maximum recursion depth exceeded
```
(this ↑ is expected because `SII(SII)` is irreducible)
Thanks Mauris and Sp3000 for helping to kill a bunch of bytes :)
[Answer]
# [Haskell](https://www.haskell.org/), 232 bytes
```
data T s=T{a::T s->T s,(%)::s}
i d=T(i. \x v->d v++'(':x%v++")")d
l f=f`T`\v->v:'.':f(i(\_->[v]))%succ v
b"S"x=l$l.(a.a x<*>).a
b"K"x=l(\_->x)
b"I"x=x
p?'('=l id:p
(p:q:r)?')'=a q p:r
(p:q)?v=a p(l$b[v]):q
((%'a')=<<).foldl(?)[l id]
```
[Try it online!](https://tio.run/##RY3PbsIwDMbveQqrooo9Rh4gIu25yjG9ARqBUhEtdP0DVaVpz965vSDL9u/7bNl3P3zfYpznyj89lDCY8tdrzbDLuHxiSloPfyJAZUoMCo4TjLusgnG7lSj1lDIklFAlItSmPpfnI89HLZXUNQY8fu2yw3giSofX9QqjuCQumUzcRIVeeZj2Hxkpz7Zd7HV/IpYFy0m0OX8xEUKlW4Gt7nRPuSRpPHTQ6n71KB9Ztxg3l@WV7kRtEFPpJZn9nlT9E6uIOR2WO6f54UMDBkLzvPX@@oQNvJoYmtsACh6@hZr7qudCOGuFdVa4gtmhc7SkcGjRFUQ8QGZHloo34tskYXENS0T/ "Haskell – Try It Online")
### How it works
This is a different parser frontend to [my answer to “Write an interpreter for the untyped lambda calculus”](https://codegolf.stackexchange.com/a/58830/39242), which also has an [ungolfed version](https://github.com/andersk/tiny-lambda/blob/master/TinyLambda.hs) with documentation.
Briefly, `Term = T (Char -> String)` is the type of lambda calculus terms, which know how to apply themselves to other terms (`a :: Term -> Term -> Term`) and how to display themselves as a `String` (`(%) :: Term -> Char -> String`), given an initial fresh variable as a `Char`. We can convert a function on terms to a term with `l :: (Term -> Term) -> Term`, and because application of the resulting term simply calls the function (`a (l f) == f`), terms are automatically reduced to normal form when displayed.
[Answer]
# Common Lisp, 560 bytes
*"Finally, I found a use for `PROGV`."*
```
(macrolet((w(S Z G #1=&optional(J Z))`(if(symbolp,S),Z(destructuring-bind(a b #1#c),S(if(eq a'L),G,J)))))(labels((r(S #1#(N 97))(w S(symbol-value s)(let((v(make-symbol(coerce`(,(code-char N))'string))))(progv`(,b,v)`(,v,v)`(L,v,(r c(1+ n)))))(let((F(r a N))(U(r b N)))(w F`(,F,U)(progv`(,b)`(,U)(r c N))))))(p()(do((c()(read-char()()#\)))q u)((eql c #\))u)(setf q(case c(#\S'(L x(L y(L z((x z)(y z))))))(#\K'(L x(L u x)))(#\I'(L a a))(#\((p)))u(if u`(,u,q)q))))(o(S)(w S(symbol-name S)(#2=format()"~A.~A"b(o c))(#2#()"~A(~A)"(o a)(o b)))))(lambda()(o(r(p))))))
```
### Ungolfed
```
;; Bind S, K and I symbols to their lambda-calculus equivalent.
;;
;; L means lambda, and thus:
;;
;; - (L x S) is variable binding, i.e. "x.S"
;; - (F x) is function application
(define-symbol-macro S '(L x (L y (L z ((x z) (y z))))))
(define-symbol-macro K '(L x (L u x)))
(define-symbol-macro I '(L x x))
;; helper macro: used twice in R and once in O
(defmacro w (S sf lf &optional(af sf))
`(if (symbolp ,S) ,sf
(destructuring-bind(a b &optional c) ,S
(if (eq a 'L)
,lf
,af))))
;; R : beta-reduction
(defun r (S &optional (N 97))
(w S
(symbol-value s)
(let ((v(make-symbol(make-string 1 :initial-element(code-char N)))))
(progv`(,b,v)`(,v,v)
`(L ,v ,(r c (1+ n)))))
(let ((F (r a N))
(U (r b N)))
(w F`(,F,U)(progv`(,b)`(,U)(r c N))))))
;; P : parse from stream to lambda tree
(defun p (&optional (stream *standard-output*))
(loop for c = (read-char stream nil #\))
until (eql c #\))
for q = (case c (#\S S) (#\K K) (#\I I) (#\( (p stream)))
for u = q then `(,u ,q)
finally (return u)))
;; O : output lambda forms as strings
(defun o (S)
(w S
(princ-to-string S)
(format nil "~A.~A" b (o c))
(format nil (w b "(~A~A)" "(~A(~A))") (o a) (o b))))
```
### Beta-reduction
Variables are dynamically bound during reduction with `PROGV` to new Common Lisp symbols, using `MAKE-SYMBOL`. This allows to nicely avoid naming collisions (e.g. undesired shadowing of bound variables). I could have used `GENSYM`, but we want to have user-friendly names for symbols. That is why symbols are named with letters from `a` to `z` (as allowed by the question). `N` represents the character code of the next available letter in current scope and starts with 97, a.k.a. `a`.
Here is a more readable version of `R` (without the `W` macro):
```
(defun beta-reduce (S &optional (N 97))
(if (symbolp s)
(symbol-value s)
(if (eq (car s) 'L)
;; lambda
(let ((v (make-symbol (make-string 1 :initial-element (code-char N)))))
(progv (list (second s) v)(list v v)
`(L ,v ,(beta-reduce (third s) (1+ n)))))
(let ((fn (beta-reduce (first s) N))
(arg (beta-reduce (second s) N)))
(if (and(consp fn)(eq'L(car fn)))
(progv (list (second fn)) (list arg)
(beta-reduce (third fn) N))
`(,fn ,arg))))))
```
### Intermediate results
Parse from string:
```
CL-USER> (p (make-string-input-stream "K(K(K(KK)))"))
((L X (L U X)) ((L X (L U X)) ((L X (L U X)) ((L X (L U X)) (L X (L U X))))))
```
Reduce:
```
CL-USER> (r *)
(L #:|a| (L #:|a| (L #:|a| (L #:|a| (L #:|a| (L #:|b| #:|a|))))))
```
[(See trace of execution)](http://paste.lisp.org/display/152086)
Pretty-print:
```
CL-USER> (o *)
"a.a.a.a.a.b.a"
```
### Tests
I reuse the same test suite as the Python answer:
```
Input Output Python output (for comparison)
1. KSK a.b.c.a(c)(b(c)) a.b.c.a(c)(b(c))
2. SII a.a(a) a.a(a)
3. S(K(SI))K a.b.b(a) a.b.b(a)
4. S(S(KS)K)I a.b.a(a(b)) a.b.a(a(b))
5. S(S(KS)K)(S(S(KS)K)I) a.b.a(a(a(b))) a.b.a(a(a(b)))
6. K(K(K(KK))) a.a.a.a.a.b.a a.b.c.d.e.f.e
7. SII(SII) ERROR ERROR
```
The 8th test example is too large for the table above:
```
8. SS(SS)(SS)
CL a.b.a(b)(c.b(c)(a(b)(c)))(a(b.a(b)(c.b(c)(a(b)(c))))(b))
Python a.b.a(b)(c.b(c)(a(b)(c)))(a(d.a(d)(e.d(e)(a(d)(e))))(b))
```
* *EDIT* I updated my answer in order to have the same grouping behavior as in [aditsu's answer](https://codegolf.stackexchange.com/a/53319/903), because it costs less bytes to write.
* The remaining difference can be seen for tests 6 and 8. The result `a.a.a.a.a.b.a` is correct and does not use as much letters as the Python answer, where bindings to `a`, `b`, `c` and `d` are not referenced.
### Performance
Looping over the 7 passing tests above and collecting the results is immediate (SBCL output):
```
Evaluation took:
0.000 seconds of real time
0.000000 seconds of total run time (0.000000 user, 0.000000 system)
100.00% CPU
310,837 processor cycles
129,792 bytes consed
```
Doing the same test a hundred of times lead to ... "Thread local storage exhausted" on SBCL, due to a [known limitation](http://marc.info/?l=sbcl-help&m=122900564918691) regarding special variables. With CCL, calling the same test suite 10000 times takes 3.33 seconds.
] |
[Question]
[
### Background
[Bilibili](https://www.bilibili.com/) is a China-based video sharing platform, similar to Nico Nico Douga in Japan, and Youtube around the world.
Since the establishment, Bilibili had been using the *AV code* to reference a video. An AV code is a string of 3 or more characters, starting with `av` and followed by a natural number, like `av82054919`.
However, since 23 March 2020, [Bilibili introduced a new referencing system called the *BV code*](https://www.bilibili.com/blackboard/activity-BV-PC.html). This time, the code is a string of exactly 12 characters, starting with `BV` and followed by 10 alphanumerical characters, like `BV1XJ41157tQ`. Still, users can use both codes to reference a video, and there is a conversion algorithm between the two.
*(For your information, the two examples reference the same video)*
### [The algorithm](https://www.zhihu.com/question/381784377/answer/1099438784)
To convert from AV code to BV code:
1. Remove the `av` part of the AV code.
2. Do a bitwise XOR between the result in step 1 (as a number) and `177451812`.
3. Add `8728348608` to the result in step 2.
4. Convert the result in step 3 to a 6-digit base-58 number with digits `fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF` in place of `0, 1, ..., 57` respectively. Here, `0, I, O, l` are omitted to eliminate ambiguity. Assume the result is `abcdef`.
5. The BV code is then `BV1db4a1c7ef`.
To convert from BV code to AV code:
1. Remove the 1st to 3rd, the 6th, the 8th and the 10th characters. Assume the result is `abcdef`.
2. Rearrange the result in step 1 to `cbdaef`.
3. Treat the result in step 2 as a base-58 number with digits `fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF` in place of `0, 1, ..., 57` respectively. Convert this base-58 number into decimal.
4. Subtract `8728348608` from the result in step 3.
5. Do a bitwise XOR between the result in step 4 and `177451812`.
6. The AV code is then `av` followed by the result in step 5.
### Example
To convert `av82054919` to BV code:
1. Removing `av` from the code results in `82054919`.
2. \$82054919\text{ XOR }177451812=242727971\$
3. \$242727971+8728348608=8971076579\$
4. \$8971076579\_{10} = (13,38,43,6,30,7)\_{58}\$ → `1J5XtQ`
5. Substituting: `BV1[X][J]4[1]1[5]7[t][Q]` → `BV1XJ41157tQ`
To convert `BV1XJ41157tQ` back to AV code:
1. Remove the bracketed numbers: `[BV1]XJ[4]1[1]5[7]tQ` → `XJ15tQ`
2. Rearranging the characters results in `1J5XtQ`.
3. `1J5XtQ` → \$(13,38,43,6,30,7)\_{58} = 8971076579\_{10}\$
4. \$8971076579-8728348608=242727971\$
5. \$242727971\text{ XOR }177451812=82054919\$
6. Prepending `av` to the result, we have `av82054919`.
### Challenge
Write two independent programs or functions, one receiving the AV code as input and outputting the corresponding BV code, and one receiving the BV code as input and outputting the corresponding AV code. Both the prefixes `av` and `BV` are case insensitive, you may choose either upper or lower case to accept or output. Each code should work even without the code from the other.
You may assume that the input for both programs must have a valid format, and the number in its corresponding AV code is between 1 and 2147483647 inclusive.
### Test cases
```
AV code <-> BV code
av82054919 <-> BV1XJ41157tQ
av123456789 <-> BV1yn411L7tG
av1 <-> BV1xx411c7mQ
av2147483647 <-> BV1Fr4k1q7G1
```
You may check your results through this [tool](https://bvtoav.com/) (not developed by me). Click the first button after entering the AV/BV code into the input, then the textbox will show the result.
### Winning condition
The total length of the codes of the two programs (measured in bytes) will be your code length, and since this is a code-golf challenge, the submission with shortest code length for each language wins. No standard loopholes.
[Answer]
# [Python 2](https://docs.python.org/2/), 170 + 150 = 320 bytes
### AV to BV, ~~180 179 173~~ 170 bytes:
```
lambda s:"BV1{2}{4}4{5}1{3}7{1}{0}".format(*["fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"[((int(s[2:])^177451812)+8728348608)/58**i%58]for i in range(6)])
```
[Try it online!](https://tio.run/##PZBtb9MwFIW/91dcBSElZZTacWK3WpHYxorGQOz9pRTJbZzVLHE8281aovz2zkHavt17nnOO5au3blUpvMsnv3cFLxcZBzsODq5Rg9uGtKRJWtTELW1Q2wzbYJBXpuQu7M@C/L7Kzke3Z0cXVyVG28NHk/47eJK1uOMrtnBkY2/0N3Xylf49Ta6n8cP6x@X3n7@@PC@Pg1kYSuVCO8PjefQHUUoSxBCOPjCKWUxYOmTRp4T1@/J9wub@SZAgFRiuHkSYRvNo9w7MWoFbCVhWmYByXTipCwFOlsLCs3QryGSeCyOU81G9drYnS10ZB3Zre11lIZXoWv0@sC6TatwD4PUeLGqYQMl1aJ3xxEi99988sLqQLgz2P34OosibFzX2zjzkdbdp4//UaV3DZOKHHa8ZHiZkhEbgQ@CventCEEqoO@vxGuGYJCllb3CrPDylbtrBV3Gz8eKSll0CI0IJi1NCX@mxIY/oiU7RCw "Python 2 – Try It Online")
### BV to AV, ~~165 158~~ 150 bytes:
```
s=input()
n=0
for i in 6,4,8,3,10,11:n=n*58+"fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF".find(s[i])
print"av"+`n-8728348608^177451812`
```
[Try it online!](https://tio.run/##PVBdT8IwFH3fr7ipL6CT0K1bCxET8QOjaPxE1GgYrJPq1tW2DPDPY1mib/eec@7JOVet7byUwWZWphx6gBDamJ6QamEbTU/22l5WahAgJMQ@8Zkf@rjtY9yVPbkbsT2UvZTpXWd8e3L/WAR4ffyl45/@t6j4czJnU0tW5kmdy4tT@jmMRoPwY3H1cHl9c7ScnaFWJmTaMK/irekpLaRFSYX2JnKf0YCFhMVt9o4pJRFmOJhsXDTP2wG9kGDnHOrAxSK3QuUcrCi4gaWwc0hFlnHNpYW6hvFEoUptwaxNXSYXkm/7uL1lbCpk1wNIKh@mlXtAkaiGsdoxWii/FreMyoVtoIP9Q9RsOnHt67R5UkzTpOsOHchXfFaHcnPdxnn@j@6rScWCdkQ6uAPOCPojPL4gGEfU3npJhYOQRDFl/@RaOnJI7WBL/oGrlQNntNheBJhQwsKY0D/2TJMv/E0H@Bc "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/index.html), 518 465 439 422 420 412 406 402 401 bytes
*-6 bytes thanks to Surculose Sputum. (I didn't know Python could be made that unreadable!)*
*-4 bytes thanks to Gavin S. Yancey.*
*-1 yet another byte gone thanks to Surculose Sputum*
Encode:
```
def s(x):
b,a=(int(x[2:])^177451812)+8728348608,''
while b:a+='fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'[b%58];b//=58
return f'BV1{a[2::2]}4{a[5]}1{a[3]}7{a[1::-1]}'
```
Decode:
```
def z(i):
i=i[3:5]+i[6:9:2]+i[10:];a,q,m=i[2]+i[1]+i[3]+i[0]+i[4:],0,1
for c in a[::-1]:q,m=q+m*'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'.index(c),m*58
return'av'+str((q-8728348608)^177451812)
```
[Try it online!](https://tio.run/##pVFdb5swFH3nV1iVKkwhKQaDHXdMWrc1U9dOa7t13RCTTEIWt4Hw4VKSKb@d2VT9eN/L9b3n3HN17nW5kct14ff9PFuABnYWM0Dq8AiKQsIu9lhi/UaE4ABR5Fk2JR71MQ1d6pimAR6WYpWBlHE7Mhe/1vPLyc3Fh6vvuYc27@/qcHtciTb7yZc0lbhrfpSfitOP5PYsuJ76f@7Pv33@8vXdw@zEjNP9gCZH6eFhFFAD1Jm8rwuwMI@v0V@uPDAv2WGVBclOA36yI@pBjI1QsjMNbX0LhbYuIhH7LEhsEYdsonQqQS5LjrhTObkiHxEdfB1cHTBLHNdBBlisazADogA8HmYzrans/OB/lhuLYp51cGY5@cHLdiZvTbuRNYTV6OWor2/di7xc1xI0m8bQxlaiyLQ3VY8bOReFWhfw1gFpC6KBVXAtSmiNm3IlJNwDb0ZvwZ6l2tLWUz0N5K01iHS1helQlbX@aoXpSSqoLIoe56pE9fS8pZ4b4AmaDBPVr9ycYoQCIi8M3iLPx0FI6DO5KRR5RuRUk09g1ylwRnKt8BAmmPohJk/sSY3vUEWmqP8H)
A fairly simple solution comprised of parts of [this](https://gist.github.com/ianoxley/865912/e10cb707cda6aac9e9a6b61d846381300e91498c) and [this](https://learnmeabitcoin.com/guide/base58). Can probably be golfed down a lot, when I get the time. I think it is golfed down to a good-enough level now. *And now it works*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~192~~ ~~164~~ 163 (81+82) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**AV to BV - ~~96~~ ~~82~~ 81 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):**
```
þ•A³ú[•^•2G&©I•+žL¨…lIOм{œ•F
mʒØà\ç×н˜=ˆ§kð€³ä‘λ°Ð‘ç«(вÍè\pÌ•èÅвA"BV1db4a1c7ef"r‡
```
[Try it online](https://tio.run/##yy9OTMpM/f//8L5HDYscD20@vCsayIgDYiN3tUMrPYEM7aP7fA6teNSwLMfT/8Ke4GqgkBtX7qlJh2ccXhBzePnh6Rf2np5je7rt0PLswxseNa0BGrLkUcOMc7sPbTg8Acg4vPzQao0Lmw73Hl4RU3C4B6hdz/Nw64VNjkpOYYYpSSaJhsnmqWlKRY8aFv7/n1hmYWRgamJpaAkA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8P7HjUscjy0@fCuaCAjDoiN3NUOrfQEMrSP7vM5tOJRw7IcT/8Le4KrgUJuXLmnJh2ecXhBzOHlh6df2Ht6ju3ptkPLsw9veNS0BmjIkkcNM87tPrTh8AQg4/DyQ6s1Lmw63Ht4RUzB4R6gdj3Pw60XNjkqOYUZpiSZJBomm6emKRU9alj4X@d/YpmFkYGpiaWhJVdimaGRsYmpmbkFmA3ERoYm5iYWxmYm5gA).
**BV to AV - ~~96~~ 82 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):**
```
•1ïÓî•S£ιθSƵª.IžL¨…lIOм{œ•F
mʒØà\ç×н˜=ˆ§kð€³ä‘λ°Ð‘ç«(вÍè\pÌ•èÅβ•2G&©I•-•A³ú[•^„avì
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcMiw8PrD08@vA7ICj60@NzOczuCj209tErP8@g@n0MrHjUsy/H0v7CnOhgo78aVe2rS4RmHF8QcXn54@oW9p@fYnm47tDz78IZHTWsObT685FHDjHO7D204PAHIOLz80GqNC5sO9x5eEVNwuAeoXc/zcOu5TUCGkbvaoZWeQIYuEDsCNe6KBjLiHjXMSyw7vOb/f6cwwwgvE0NDU/OSQAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/0cNiwwPrz88@fA6ICv40OJzO8/tCD629dAqPc@j@3wOrXjUsCzH0//CnupgoLwbV@6pSYdnHF4Qc3j54ekX9p6eY3u67dDy7MMbHjWtObT58JJHDTPO7T604fAEIOPw8kOrNS5sOtx7eEVMweEeoHY9z8Ot5zYBGUbuaodWegIZukDsCNS4KxrIiHvUMC@x7PCa/zr/ncIMI7xMDA1NzUsCuYCcyjwgx8e8xB3EqagAcpLNc8EybkUm2YaF5u6GAA).
NOTE: The TIO's use `S` with `.I` (convert to character-list and \$n^{th}\$ permutation builtin) instead of `œ` with `è` (get all permutations and index into the list), since generating all permutations is of course way too slow.
### Explanation:
**AV to BV**:
```
þ # Only leave digits of the (implicit) input (to remove "av")
•A³ú[• # Push compressed integer 177451812
^ # Bitwise-XOR the two integers together
•2G&©I• # Push compressed integer 8728348608
+ # Add the two integers together
žL # Push builtin string "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210"
¨ # Remove the last character (the "0")
…lIO # Push string "lIO"
м # Remove those three as well
{ # Sort the remaining characters in the string
œ # Get a list of all permutations of this string
•F\nmʒØà\ç×н˜=ˆ§kð€³ä‘λ°Ð‘ç«(вÍè\pÌ•
# Push compressed integer 1563341720558629316384554749509959660779122984425616460522557465911652079492533
è # Index it into the list of permutations:
# "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"
Åв # Convert the integer to this custom base
A # Push the lowercase alphabet
"BV1db4a1c7ef" # Push string "BV1db4a1c7ef"
r # Reverse the three values on the stack
‡ # Transliterate the lowercase alphabet to the base-converted
# characters in "BV1db4a1c7ef"
# (after which the result is output implicitly)
```
**BV to AV**:
```
•1ïÓî• # Push compressed integer 32111112
S # Convert it to a list of digits: [3,2,1,1,1,1,1,2]
£ # Split the (implicit) input-string into parts of that size
ι # Uninterleave it
θ # Only keep the last result
S # And convert it to a flattened list of characters
Ƶª # Push compressed integer 270
.I # And take the 270th 0-based permutation
žL¨…lIOм{œ•F\nmʒØà\ç×н˜=ˆ§kð€³ä‘λ°Ð‘ç«(вÍè\pÌ•è
# Same as in the AB to BV conversion above,
Åβ # but the other way around (convert from the custom base to integer)
•2G&©I•- # Subtract 8728348608
•A³ú[•^ # Bitwise-XOR it with 177451812
„avì # Prepend "av"
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•A³ú[•` is `177451812`; `•2G&©I•` is `8728348608`; `•F\nmʒØà\ç×н˜=ˆ§kð€³ä‘λ°Ð‘ç«(вÍè\pÌ•` is `1563341720558629316384554749509959660779122984425616460522557465911652079492533`; `•1ïÓî•` is `32111112`; and `Ƶª` is `270`.
The `1563341720558629316384554749509959660779122984425616460522557465911652079492533` is generated by [this Jelly builtin](https://tio.run/##BcHVDYNQAADAmXD4xAkW3P5wd2eMLtSkSed63DV5190A/D@/LwCgiMbMogKTs90ehm62XfCHmesjD@OKTDb0Wv1JGmSeaFTME5Fy1xxFN@gzFUCcpFlelFXdtP0wTvOybvtxXvdDMyzHC6IkK6qmG6ZlO67nB2EEwQiK4QRJvQ) (minus 1, since Jelly uses 1-based indexing and 05AB1E uses 0-based indexing).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 191 + 181 = 372 bytes
Saved ~~4~~ ~~5~~ ~~8~~ 15 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
# AV to BV
# [C (gcc)](https://gcc.gnu.org/), ~~224~~ \$\cdots\$ ~~198~~ 191 bytes
```
r[]=L"BV1__4_1_7";e(a,w)long a,w;{w=(strtol(a+2,0,10)^177451812)+8728348608;for(a=6;a--;w/=58)r["6483:;"[a]-48]="fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"[w%58];wprintf(r);}
```
[Try it online!](https://tio.run/##RVFrT8IwFP3ur2iakLSyhXV0a7HORFQwisa3KE5SJq8BG3aTgYTfjuUl90N7T3vu6T23gdkNguVSNXyvBssvpNmkTdJkULSRNDI8jKMu0ImYZx5KUpXGQyTztmEZxMKfhDHqEE5snOfM5kXKXYuLTqyQ9FwhTVNkBc/hWDWgS3nxSMCG9E3KfQ923uOvh1L9/vzxeWST2dlAub/l7/6k/SZ7vJXSafI6voyuLlhYc16qxe7PzdP17d1pFlRgI8s53BfZWPWjtIMUFovlSPYjhMH8AOgIelIdyom2NIdywm3LoSVSgoYGxC5Sx2V8i9arTSjT3bmUwYXYC7Q2Anom9StKiMPSe03XcBZpWGNpdQOnUw0DNtreVhQdkG9WJTsxPQ6AdKcg9CwRHif933bcQXKCC9t0/RoW@Xy4M7CKnb0azCXAPAEol2AADaB9hb4BWqsNi3@6/q7Nyb7uI4JbwuJgsfwD "C (gcc) – Try It Online")
# BV to AV
# [C (gcc)](https://gcc.gnu.org/), ~~224~~ \$\cdots\$ ~~186~~ 181 bytes
```
char*d="fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF",b;long w;c(char*s){for(w=b=0;b<6;w+=index(d,s["6483:;"[b++]-48])-d)w*=58;printf("av%ld",w-8728348608^177451812);}
```
[Try it online!](https://tio.run/##XZBrT8IwFIa/8yuWJiQt2yId3VosMxEVDKIRL4hOTHbhsgEDNty4hN@OdYAaz4emT8857zlvXXXgurudO7SjgmeC/tvUeyh3WpePzxMNry5GkbGuzv2k92oPmbMgy/hldh02rmjQ1Nv10uDz9unm7v48dWtAcfh4Gg6klLswk4vRpj@NYGo6ZpE7FYOnsumHXm8JPSW2gEFY6ZQDy5HlrkpYF6keSgumzvgs8sNFHwI7yY89oKQqoxorEWYU2QemlOiYYQ3x7W5i@yFE0iYnichm2onVNTeik2lFnZRxGSgCsFYiukHZgbJTw4SKDQxCwZb/Cjh7gWobdxoEY50uWqJc4CoU2KSL@h6XS4EunRyytYiM8JzW8VFMOJegsCEFwnxQif11b9qHdoJODtdsGuKyHBwNfMfRej6W1DNJ/GliBV3Ef/Iu/P9y7JBgPkbvIVDsPwXb3Hb3BQ "C (gcc) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 208 bytes
## AV code to BV code, 117 bytes:
```
≔⍘"0|7mγη≔I✂θ²χ¹θ≔⍘⁺⁻|θη&θη⍘!,/>#iγ”\`>⊟∨↖κ2¹W«ε➙⊗MιΦ/⁷Aêμ⁵S⁶Dt÷r≔l⪪≦|⭆±⊗υ↓1↖Þ»χZ⁹~”θ≔⁺×f⁻⁶Lθθθ⭆BV1db4a1c7ef⎇№βι§θ⌕βιι
```
[Try it online!](https://tio.run/##VY9LT4NAFIX3/gocN0MyRkBa2jQxAbRqLVql1kfcDDCFURjKDPRh/O84QBPr4t7FuefcfCdMMA9znNa1LQSNGXSwIH7JKYsh@ADaj5UBpMQqUhJ1dLT3uFiU0E9pSGCBFAMpuiZHlabiz3TwaJZWAnqUye3QckMFeeBNMpGJvWCzqFMa6QDhGJ1dnNAWQV7A8j2Pnoavj5f@c2boO/eL97@dgq7JG04GQWluxcvqhk2urM9pb3F9Hlfe/O5@Zm/CMfhP1yLNaUYEBEv5vqPrI2VKWFwmsFC7Ol1oJmFk45bJwysInIUeBSbWQ4s06TnhDPMddPNK@gKkUBm0y1sWkW1Ta0xlvVZW26WO6hqvB4bWM4f6sD5dp78 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⍘"0|7mγη
```
Get the constant `177451812` into a variable as we need it twice because we don't have a bitwise XOR builtin.
```
≔I✂θ²χ¹θ
```
Extract the value in the AV code as a number.
```
≔⍘⁺⁻|θη&θη⍘!,/>#iγ”\`>⊟∨↖κ2¹W«ε➙⊗MιΦ/⁷Aêμ⁵S⁶Dt÷r≔l⪪≦|⭆±⊗υ↓1↖Þ»χZ⁹~”θ
```
Subtract the bitwise AND from the bitwise OR giving the bitwise XOR, add the offset, then perform custom base conversion using a compressed version of the given string.
```
≔⁺×f⁻⁶Lθθθ
```
Pad the string to 6 characters.
```
⭆BV1db4a1c7ef⎇№βι§θ⌕βιι
```
Substitute the characters in the appropriate positions in the BV code.
## BV code to AV code: 91 bytes:
```
≔⍘"0|7mγη≔⁻⍘⭆684921§θ±Iι”\`>⊟∨↖κ2¹W«ε➙⊗MιΦ/⁷Aêμ⁵S⁶Dt÷r≔l⪪≦|⭆±⊗υ↓1↖Þ»χZ⁹~”⍘!,/>#iγθavI⁻|θη&θη
```
[Try it online!](https://tio.run/##TY7LbsIwEEX3/YrU3TiSUWsaCAgJKaH0AYR3KVTduIlx3IIhsQkU8e/GEFRxN6O5M3fmhDFJwxVZaO1JyZmAPpF0pFIuGARf4OHgLgGymI2s2K7dXHYCLjbyejMvAVlDUK441SI2GU@9iYjuYIKsLmVEUdggUkFuGyELzD9X0bA6HTyN3pdF/Nf4Tct7P@EZnZG48q2cnfxYv4pW0/3plCYvj2wTjNvdvrcNn4GJX1Peovv6HT9TmkliMPtmoCAgGfhvzr8v3FxtuaS99IQWn47lhiei3DGqae1P8LTlYFxy1UAXssUR "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⍘"0|7mγη
```
Get the constant `177451812` into a variable again.
```
≔⁻⍘⭆684921§θ±Iι”\`>⊟∨↖κ2¹W«ε➙⊗MιΦ/⁷Aêμ⁵S⁶Dt÷r≔l⪪≦|⭆±⊗υ↓1↖Þ»χZ⁹~”⍘!,/>#iγθ
```
Extract the characters from the appropriate positions of the BV code, perform custom base conversion, and subtract the offset.
```
avI⁻|θη&θη
```
Print the bitwise XOR prefixed by `av`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 322 bytes
```
f=(s,[a,b,c,d,e,f]=(g=n=>n?g(n/58|0)+'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'[n%58]:'')((s.slice(2)^177451812)+8728348608))=>'BV1'+d+b+4+a+1+c+7+e+f
F=s=>'av'+([...'315078'].map(n=>'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'.search(s[2-~n])).reduce((x,y)=>x*58+y)-8728348608^177451812)
```
[Try it online!](https://tio.run/##pZFdb9MwFIbv8yt8g2zj1NSJU7uMFDFYi8ZAGx9jUILmJE6XLXW6OCspbPvrxZlU4J7b9zmv9JxzLtVa2awpV@3A1LnebosYWX@u/NTP/NzXfpHEaBGbeGKeL5B5EsnbISaw@Frn78dnJ68@fFoGbPPyqhn93L8u1/qLupBpyzv7efXaHB6Iy6PodBYubt5@fPPu@MWPbArn5lEkk6cQYoQstVWZaRTg70wIHjHJAkykCGTI5WgoMY4ncP@UQZKTlHCiCCMZEUSTwpvG1kG1hgTNKaUwZNFQSJjQpVoh5/s/jtRq1WQXyM6Dwb1JMKaNzm@cKOr8jXPqHkeSbPDgr@k//ttW2xbE4NxTaxkMIz5mY/BsMAFukbNDzlgk2hPHWBDyaCTkH7gxDh6JdtbDXdh1LszEsm8EjAsuwxEXOzpt@BW7FjPmndO2KZcIU7uqyhbBbwbih1NUIJ6Aahc/FCHGXi9Ji7o5UG5P5B4O0gT3o788ALLa2LrStKoXqCc@KJDCPpiiFOM97w7vbX8D "JavaScript (Node.js) – Try It Online")
A simple and stupid solution. Not so creative. But it at least works.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 295 bytes
```
F=t=>'bv1BD4E1C7A9'.replace(/[9-F]/g,c=>'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'[((t.slice(2)^177451812)+8728348608)/58**('0x'+c-9)%58|0])
G=s=>'av'+([7,5,9,4,11,12].map(n=>x=x*58+'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF'.search(s[n])|0,x=16717449)|x^177451812)
```
[Try it online!](https://tio.run/##pY9fU5tAFMXf@RT70tndZEO4ZGGXsWTGaMCx2qn9Y20pHTeIESWAsEVs08@egjPp9L2v53fOvefcq1Y1SZ1VelKUN@luF/jan@NVC4tjvoQjcehhs06rXCUpmUbeJIina5b0ltuv5c177@ri@MOnjQ3PRw@1@3PxmLXpF3UnV5p3zefqpDhdivsz5zKcrX@cf3zz9t3hUxLgiBBtNnnWn7TpdxCCOyDBpmMpbDnj0rUknTpyNCLY6vA4mXj0lSO3VkyN0G/636rFYxIJ5jCPcQbAwI7NjapI4c87vxs5cvw//cwmVXVyR5qoiOnWYp0PrgDBuUe33T99dzptNPLRtaFaaVsO98BDrydztLiEq1MO4Ah90TOwZ9xxhfwLn4sengkdDnAvdl0vJmIzJGzggsuZy8WeBjV/gEcRgnFt6jrbEGo2VZ5pgr8VmL6Mz5E/R/lefgliSo2hpHlb1kvVTyKRYmgV08H6y0AoKYumzFMzL9dkIAwFRFGGQrKi9MD4TQ92fwA "JavaScript (Node.js) – Try It Online")
Thank Arnauld for -7 bytes
[Answer]
# perl -pl (+ bc), 186 + 189 = 375 182 + 187 = 369 bytes
## AV to BV
```
s/^..//;@_=(split//,fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF)[`echo "obase=58;@{[($_^177451812)+8728348608]}"|bc`=~/\d+/g];$_="BV1$_[3]$_[1]4$_[0]1$_[2]7$_[4]$_[5]"
```
[Try it online!](https://tio.run/##HchbT4MwGMbxez@FIVxsma60fUtLCMmcx@g0HucBOwYMNxTXbiCe/ehW5sXzy5O/zpYFM6ZEo24XIb8XBa1SF3mF0MbDnZqcezdnOxdXzwS/bz8t3Y/@Iq@z23gmkgreymt9MD/c5Y8DNtyn05fjy6OT063XdK8djrN0ptYtlcRlFjDh9z7Dlh2NMOfAsMCk3RGcCArCdYT8tr6SdBz8oPtJB02lb0eB1R9iOwqpbMASGh25CkTyRlhlJi1j4loQh4GHvbW4xoQCc7n4/80IBg6CusB/la5yNS/Npi7@AA "Perl 5 – Try It Online")
This uses `bc` to do the decimal to base-58 conversion.
## BV to AV
```
$n=$x=0;%_=map{$_=>$x++}split//,fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF;@y=@_{/1(.)(.)4(.)1(.)7(.)(.)/};$n=58*$n+$_ for@y[2,1,3,0,4,5];$_=av.(($n-8728348608)^177451812)
```
[Try it online!](https://tio.run/##Jc7dToNAEAXge5/CizUB2RYGdrtrCAarFlOrsf7UqlGCtVVaWLaAFWz66uJWk5nkfJmLM3KaJ7RpkPBQ5VnuXuilkVyj0DtElWFsCpnEpWni2WP2dn0wHp7c3KU21MeLvPPdXcar6UP0wV9LUhX38kz0T9l8QEeB8/55cXt@eXX0Nem5fu354doEra2rIWq3kf3T3LiqmvJ9JAwU7s6y3K@fbAzYwRYmmD676pVo1dY0JFqc2dwhvGNx/QUYIxQ42HrTdEcw7hMAysrhjkItFAasDLaoKoUJS/8uvZwsYMkC@MlkGWeiaFoy@QU "Perl 5 – Try It Online")
If you have only 1 line of input, the first 8 bytes can be removed.
Update: Removed 4 + 2 = 6 bytes, because you don't need to quote the strings.
[Answer]
# [Prolog](https://github.com/mthom/scryer-prolog), 725 bytes
```
:-use_module(library(clpz)).
:-use_module(library(lists)).
v(A,B):-var(A),var(B).
d(N,D):-v(N,D),!.
d(N,D):-nth0(N,"0123456789",D).
e(N,D):-v(N,D),!.
e(N,D):-nth0(N,"fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF",D).
b(0,_,[0]).
b(1,_,[1]).
b(A,B,C):-A#>1,E#>=0,L#=E+1,(nonvar(C),length(C,L);nonvar(A)),A#<B^(E+1),A#>=B^E,labeling([down],[E]),length(C,L),reverse(C,F),c(A,B,F).
c(0,_,[]).
c(A,B,[C|D]):-A#>0,C#>=0,C#=<B,E#>=0,C#=A mod B,E#=A//B,c(E,B,D).
a([a,v|A],['B','V','1',E,C,'4',B,'1',D,'7',F,G]):-H=[B,C,D,E,F,G],I=177451812,J=8728348608,K#>=0,L#>=0,K#=L xor I+J,L#=(K-J)xor I,O in 1..9,indomain(O),length(A,O),maplist(d,M,A),maplist(e,N,H),b(L,10,M),b(K,58,N),label([L,K]),maplist(d,M,A),maplist(e,N,H).
```
Clear version:
```
:- use_module(library(clpz)).
:- use_module(library(lists)).
v(A, B) :- var(A), var(B).
% Base 10.
d(N, D) :- v(N, D), !. % Keep variable.
d(N, D) :-
nth0(N, "0123456789", D).
% Base 58.
e(N, D) :- v(N, D), !. % Keep variable.
e(N, D) :-
nth0(N, "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF", D).
% Base conversion. Base B, Number A, Array C.
b(0, _, [0]).
b(1, _, [1]).
b(A, B, C) :-
A #> 1,
nonvar(B),
E #>= 0,
L #= E + 1,
( nonvar(C), length(C, L)
; nonvar(A)
),
A #< B ^ (E + 1),
A #>= B ^ E,
labeling([down], [E]),
length(C, L),
reverse(C, F),
c(A, B, F).
% Required for b.
c(0, _, []).
c(A, B, [C|D]) :-
A #> 0,
C #>= 0,
C #=< B,
E #>= 0,
C #= A mod B,
E #= A // B,
c(E, B, D).
% Bidirectional decoder.
a([a, v|A], ['B', 'V', '1', E, C, '4', B, '1', D, '7', F, G]) :-
H = [B, C, D, E, F, G],
I = 177451812,
J = 8728348608,
K #>= 0,
L #>= 0,
K #= L xor I + J,
L #= (K - J) xor I,
O in 1..9,
indomain(O),
length(A, O),
maplist(d, M, A),
maplist(e, N, H),
b(L, 10, M),
b(K, 58, N),
label([L, K]),
maplist(d, M, A),
maplist(e, N, H).
```
] |
[Question]
[
Inspired by [A014486](https://oeis.org/A014486).
**Challenge**
Given an integer input in base 10, construct a representation for the binary forest corresponding to the input. Representations include, but are not limited to, nested arrays and strings.
**How?**
Convert the input to binary. `1`s represent branches, and `0`s represent leaves.
To make this easier to understand, let's use `834` (1101000010 in binary) as an example.
---
We start with the first digit. The first digit is a `1`, so we draw branches:
```
\ /
1
```
or as an array, `{{1}}`
---
The next digit is `1`, so we draw more branches (we go from left to right):
```
\ /
1
\ /
1
```
or as an array, `{{1, {1}}}`
---
The next digit is `0`, so we place a leaf:
```
0
\ /
1
\ /
1
```
or as an array, `{{1, {1, 0}}}`
---
The next digit is a `1`, so we place a branch:
```
\ /
0 1
\ /
1
\ /
1
```
or as an array, `{{1, {1, 0, {1}}}}`
---
Repeating the process, we obtain the following tree after the 8th digit:
```
0 0
\ /
0 1
\ /
1 0
\ /
1
```
or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}}`
---
For the remaining digits, we draw more trees:
The 9th digit is a `0`, so we place a leaf (aww, it's a young shoot!)
```
0 0
\ /
0 1
\ /
1 0
\ /
1 0
```
or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}, 0}`
---
When we use all the digits, we end up with this:
```
0 0
\ /
0 1
\ /
1 0 0
\ / \ /
1 0 1
```
or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}, 0, {1, 0}}`
---
That looks weird, so we pad a zero to complete the tree:
```
0 0
\ /
0 1
\ /
1 0 0 0
\ / \ /
1 0 1
```
or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}, 0, {1, 0, 0}}`
Note that the flattening the array yields the original number in binary, but with a padded zero.
**Criteria**
* The output must clearly show the separation of the trees and branches (if it is not a nested array, please explain your output format).
* Extracting all digits from the output must be identical to the binary representation of the input (with the padded zero(s) from the above process).
**Test cases**
The output may differ as long as it meets the criteria.
```
0 -> {0}
1 -> {{1, 0, 0}}
44 -> {{1, 0, {1, {1, 0, 0}, 0}}}
63 -> {{1, {1, {1, {1, {1, {1, 0, 0}, 0}, 0}, 0}, 0}, 0}}
404 -> {{1, {1, 0, 0}, {1, 0, {1, 0, 0}}}}
1337 -> {{1, 0, {1, 0, 0}}, {1, {1, {1, 0, 0}, {1, 0, 0}}, 0}}
```
**Scoring**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest bytes wins!
[Answer]
# Befunge, ~~138~~ ~~117~~ 104 bytes
```
p&1v
%2:_v#:/2p9p00+1:g00
3\9g<>$\:!v!:<
9g!v ^,"}"_1-\1-:
"0"_2\"1{",,:|:,
`#@_\:#v_"}",>$\:8
,"0":-1<^
```
[Try it online!](http://befunge.tryitonline.net/#code=cCYxdgolMjpfdiM6LzJwOXAwMCsxOmcwMAozXDlnPD4kXDohdiE6PAo5ZyF2IF4sIn0iXzEtXDEtOgoiMCJfMlwiMXsiLCw6fDosCmAjQF9cOiN2XyJ9Iiw-JFw6OAosIjAiOi0xPF4&input=MTMzNw)
**Explanation**
Line 1 reads a number from stdin, and line 2 converts that number to a binary sequence which it stores in the playfield on line 10. Lines 3 to 5 then iterate over those binary digits, outputting the appropriate tree representation as each digit is processed. The Befunge stack is used to keep track of the depth into the tree and how much leaf space is left at each level so we know when to create a new branch. Lines 6 and 7 handle the final `0` padding to fill up any empty leaves.
In order to golf this as much as possible, I removed the commas from the output as well as the extraneous outer braces. This still hasn't beat the Mathematica solution, but it's been fun trying.
If you want to see what it looked like with the original verbose output format, I saved an earlier version of the code [here](http://befunge.tryitonline.net/#code=cCYxdgolMjpfdiM6LzJwOXAwMCsxOmcwMAosInsiPD4kXDohdjwhOjwzZzAwOQorM3Ahdl4sIn0iXz4xLVwiLCIkMS06OWcwMmc5OQosIjAiXzJcIjF7IiwsOnw6CjhgI3ZfXDojdl8ifSIsPiRcOgosIiwwIjotMTxeLAoifSI8QCw&input=MTMzNw) (131 bytes).
[Answer]
# Mathematica, ~~167~~ 161 bytes
```
b=Append;a=If[#&@@#>0,a[Rest@#~b~0,a[#,#3[#,{1,#4,#2},##5]&,#3,#2,##4]&,#2,##3],
#2[Rest@#~b~0,0,##3]]&;a[#~IntegerDigits~2,If[c=#3~b~#2;Tr@#>0,a[#,#0,c],c]&,
{}]&
```
Anonymous function. Takes a number as input, and returns an arbitrarily nested list of numbers as output. Line breaks added for clarity. Uses some mechanism involving continuations, but I'm too tired to think about it any longer.
[Answer]
# Mathematica, ~~115~~ ~~109~~ ~~108~~ ~~104~~ 98 bytes
```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},0,i={##2};#]&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&])&
```
Generates error messages that can safely be ignored. Outputs a binary forest. It's slightly different from the sample output because `1` is a `Head`, not the first element of a list. (e.g. `1[0, 0]` instead of `{1, 0, 0}`)
**Error-free version (104 bytes)**
```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},i={0}];(i={##2};#)&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&])&
```
**Explanation**
```
i=#~IntegerDigits~2;
```
Convert input to a base-2 list. Store it in `i`.
```
f:=
```
`SetDelay` `f` the following (evaluated whenever `f` is called):
```
Switch[If[i=={},0,i={##2};#]&@@i,0,0,1,f~1~f]
```
`Switch` statement.
First, if `i` is empty, output `0`. If not, output the first element of `i`and drop it from the list. Use the output as the control variable.
If the control variable is `0`, output `0`. If it is `1`, output `1[f, f]` (recursive).
```
NestWhileList[f&,f,i!={}&]
```
While `i` is not empty, keep calling `f`. Output the result, wrapped with `List`.
**Example**
```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},0,i={##2};#]&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&])&[1337]
```
>
> `{1[0, 1[0, 0]], 1[1[1[0, 0], 1[0, 0]], 0]}`
>
>
>
**Alternative solution (120 bytes)**
Identical to my 104 byte solution but converts the output into the format given in the question.
```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},i={0}];(i={##2};#)&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&]//.1[a__]:>{1,a})&
```
[Answer]
# JavaScript (ES6), ~~96~~ ~~89~~ ~~80~~ ~~79~~ ~~74~~ 73 bytes
```
f=($,_=~Math.log2($))=>0>_?[(g=f=>$&1<<~_++&&[1,g(),g()])(),...f($,_)]:[]
```
```
<input type="number" value="1337" oninput="document.querySelector('#x').innerHTML=JSON.stringify(f(+this.value))"/><br/><pre id="x"></pre>
```
Defines a function `f` that returns a nested array. The HTML code is just for testing.
[Answer]
# Python 2, ~~133~~ ~~118~~ 117 bytes
Partially recursive, partially iterative. I tried using an integer, but the tree starts with the most significant bits, so I don't think it's worth it.
```
def t():global b;a=b[:1];b=b[1:];return a and'0'<a and[1,t(),t()]or 0
b=bin(input())[2:]
L=[]
while b:L+=t(),
print L
```
[**Try it online**](https://tio.run/nexus/python2#bYxBCoMwFET3/xR/p9IukibYEpsbeIOQRYLRBuQrIdLj2yh0U7oYZhhm3j6EEXPdqGlevJvRd057o7jtfHGubJdC3hKhQ0dDxarnGQy/ltMhuyRkUMaR6kjrVqrG3JSFXhsL71ecA3rVX/SxhzVFytjvY3lFjITJ0RTqtlGAfxh4QvCXgl8MAw5SQitAMglciDs8hPwA)
[Answer]
# Java 8, 367 bytes
Golfed:
```
class f{static String r="";static int p=0;static void g(char[]s,int k){if(p>=s.length||s[p]=='0'){r+="0";p++;return;}else{r+="{1";p++;g(s,k+1);g(s,k+1);r+="}";}if(k==0&&p<s.length)g(s,0);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);r+="{";g(Integer.toBinaryString(q.nextInt()).toCharArray(),0);r+="}";System.out.print(r);}}
```
Ungolfed:
```
class f{
static String r="";
static int p=0;
static void g(char[]s,int k){
// if there's empty space in last tree or current character is a 0
if(p>=s.length || s[p]=='0'){
r+="0";
p++;
return;
}
// if current character is a 1
else{
r+="{1";
p++;
// left branch
g(s,k+1);
// right branch
g(s,k+1);
r+="}";
}
// if they're still trees that can be added
if(k==0 && p<s.length)g(s,0);
}
public static void main(String[]a){
java.util.Scanner q=new java.util.Scanner(System.in);
r+="{";
g(Integer.toBinaryString(q.nextInt()).toCharArray(),0);
r+="}";
System.out.print(r);
}
}
```
[Answer]
# [DUP](https://esolangs.org/wiki/DUP), 84 bytes (82 chars)
```
0[`48-$1_>][\10*+]#%1b:[$1>][2/b;1+b:]#[['{,1.b;1-b:FF'},][0.b;1-b:]?]⇒F[b;0>][F]#
```
For golfing reasons, I got rid of the outer curly braces and the commas because they are not necessary for reconstructing the trees.
Example outputs:
```
0 → 0
1 → {100}
44 → {10{1{100}0}}
63 → {1{1{1{1{1{100}0}0}0}0}0}
404 → {1{100}{10{100}}}
1023 → {1{1{1{1{1{1{1{1{1{100}0}0}0}0}0}0}0}0}0}
1024 → {100}00000000
1025 → {100}0000000{100}
1026 → {100}000000{100}
1027 → {100}000000{1{100}0}
1028 → {100}00000{100}
1337 → {10{100}}{1{1{100}{100}}0}
4274937288 → {1{1{1{1{1{1{10{1{100}{1{1{100}{10{1{1{10{1{1{100}{100}}0}}0}0}}}0}}}0}0}0}0}0}0}
4294967297 → {100}00000000000000000000000000000{100}
```
Explanation:
```
0[`48-$1_>][\10*+]# While loop to read in the characters and convert them into a
base-10 integer.
0 Push 0 (temporary value)
[`48-$0>] # While input character-48 (digit)>-1
[ ]
\ Swap top values
10 Push 10
* Multiply (temporary value by 10)
+ Add to input value
% Pop stack (EOL)
1b: Variable b=1 (bit count)
[$1>][2/b;1+b:]# While loop to convert the number to base-2 digits on the
data stack, MSB on top. Each iteration increments bit count b.
[$1>] # While (DUP>1)
[ ]#
2 Push 2
/ MOD/DIV (pushes both mod and div on the stack)
b;1+b: Fetch b, increment, store b
[['{,1.b;1-b:FF'},][0.b;1-b:]?]⇒F
[ ]⇒F Define operator F:
pop top stack value
[ ] ? if value != 0:
'{,1. print '{1'
b;1-b: fetch b, decrement b, store b
F execute operator F
F execute operator F again
'}, print '}'
[ ]? if value == 0:
0. print '0'
b;1-b: fetch b, decrement b, store b
[b;0>][F]#
[b;0>] # While (fetch b, b>0==true)
[F]# execute operator F
```
Try it out with the online [Javascript DUP interpreter on quirkster.com](http://www.quirkster.com/iano/js/dup.html) or clone [my GitHub repository](https://github.com/m-lohmann/DUPEsolang.jl) of my DUP interpreter written in Julia.
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.