text
stringlengths 180
608k
|
---|
[Question]
[
### Background
This challenge is about the game of Go. Go is a game played on a board with a square grid `N x N`. You don't have to know how to play the game to do this challenge, but if you are interested, google "Tromp-Taylor rules" for a minimal and precise set of rules to play a full game.
Let's use a `4 x 4` board. As the game starts, two players, black (`X`) and white (`O`), alternately place a stone on an empty grid starting with black.
At some point of the game, the board may look like this.
```
. . O .
. X X .
. X . .
. O O .
```
Black has 1 group, and white has 2 groups. A *group* is a group of stones that are connected horizontally or vertically.
```
. X X .
X . X .
X X . .
. . X X
```
Black has 3 groups on this board.
```
. . O .
. X X .
. X . .
. O O .
```
Back to the first example, the upper group of white has 2 liberties and the lower group of white has 3 liberties. *Liberty* is the number of empty spaces connected horizontally or vertically to a group.
```
X . O X
. . . .
. . . O
. . O X
```
There are 3 black groups on this board each with 2, 1, and 0 liberties. In an actual game a group with 0 liberties are taken out of the board, but you don't have to care about that in this challenge.
### Challenge
The input is a `4 x 4` Go board position, where there is 1 black group and any number of white groups.
The output is the number of liberties that the black group has.
The input can be encoded in any way that can hold \$3^{4\times4}\$ distinct values.
The output is an integer, when optionally printed, up to base 16.
### Examples
```
. . . .
. X . .
. . . .
. . . . -> 4
. . . .
. X X .
. . . .
. . . . -> 6
X X . .
X . . .
. . . .
. . . . -> 3
X X O .
X O . .
O . . .
. . . . -> 0
. X X .
. X . X
. X X X
. . . . -> 8
O X X .
O X . X
O X X X
. O O O -> 2
O X X O
O X O X
O X X X
. O O O -> 0
```
The last case is an impossible position in the actual game, but it is valid for this challenge.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
~Go1Y6Z+*z
```
[Try it online!](https://tio.run/##y00syfn/v8493zDSLEpbq@r//2gjBUMgNLBWADEMFAwhDEMQwwDIBMJYAA "MATL – Try It Online")
Takes input as a \$4\times 4\$ matrix with `0` representing an empty point, a `1` representing a black stone, and a `2` representing a white stone.
Bonus, contains `Go`!
```
% implicit input M
~ % logically negate: push matrix of 1s where there are empty points
Go % Push matrix, mod 2: get matrix of 1s where black stones are
1Y6 % Push [0 1 0; 1 0 1; 0 1 0], the matrix of adjacencies
Z+ % two-dimensional convolution maintaining size
*z % multiply and count the number of nonzero entries.
% (implicit) convert to string and display
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 19 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
Takes input as an integer matrix with `1` for empty squares, `2` for white and `3` for black stones.
```
+´∘⥊1⊸=∧3=«˘⌈»˘⌈»⌈«
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgK8K04oiY4qWKMeKKuD3iiKczPcKry5jijIjCu8uY4oyIwrvijIjCqwoK4o2JPnso4ouIbSniiL7ii4jin5xGIl8uT1gi4oqQbeKGkDTigL804qWK8J2VqX3CqCDin6gKIi4uLi4uWC4uLi4uLi4uLi4iCiIuLi4uLlhYLi4uLi4uLi4uIgoiWFguLlguLi4uLi4uLi4uLiIKIlhYTy5YTy4uTy4uLi4uLi4iCiIuWFguLlguWC5YWFguLi4uIgoiT1hYLk9YLlhPWFhYLk9PTyIKIk9YWE9PWE9YT1hYWC5PT08iCuKfqQ==)
`«˘⌈»˘⌈»⌈«` Shift the matrix by one from each of the four directions and take the element-wise maximum.
`3=` For each value in this new matrix, is it equal to 3? This gives 1 for each square adjacent to a black stone on the board.
`1⊸=∧` *And* is the square empty?
`+´∘⥊` Count the 1's by summing.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 56 bytes
```
Count[ListConvolve[{r={0,1,0},1-r,r},#,2,0]^#,_.+_.a,2]&
```
[Try it online!](https://tio.run/##jc5BC4JAEAXgu79iYMFLo816NwKvHbrLJkMoCamwbV6W/e1bYSArhsFcHryPeR2bW92xaa/sG8h9MTx7U57ahymGfhzuY11anVtCieRQJhq1Q4EZkroIrNJdlTJmKvZn3b6hgOQATSmUghj2R4istRLhew7hkzhIcjU5jGCd8n@Ugz/8q/yb0kxpLtPm4HDi9JiD@bxKKaAUUFpSmm5JaS7TJnX@BQ "Wolfram Language (Mathematica) – Try It Online")
Takes input as a 2d array, with `1` for empty, `0` for white, `a` for black.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~75~~ 26 bytes
```
(?<=X....|X)_|_(?=X|....X)
```
[Try it online!](https://tio.run/##XcsxCoAwDAXQPfcQKpScQHF0/OsfhOrg4OIgjj2XB/BitSkKaoefn0ezzfuyTmlQCXIe4sV7m5Xrx@S6pqXmF1mHGFzXMtrKOiWborTQJ@5KfpD2iao/REbkitd5uaTSGm@EIQxREEBB5MALLw "Retina 0.8.2 – Try It Online") Link includes test suite that converts from double-spaced newline-delimited examples using `.` to comma-delimited strings using `_`. Works with boards of any height. Explanation: Counts the number of `_`s which are either adjacent or exactly 5 characters away from an `X` (which represents one directly above or below).
Edit: Saved 49 bytes thanks to @tsh by hard-coding the size of the board. Previous 75-byte answer works on any rectangular size of board:
```
(?<=X|X(?(1)$)(?<-1>.)*¶.*(?=.(.)*))_|_(?=X|(?<=(.)*.).*¶(?<-2>.)*(?(2)^)X)
```
[Try it online!](https://tio.run/##XYuxDsIwEEP3fAdIuSpYamdKP@FWD4jAwMDCgBjzXf2A/li4i4pUuMFnP9mv@/vxvNUzQg7LHFJIyf8@Xv3XOB1HFsYp9rITS4f@BOmWGV2cRkTzIrlkCyxedgKBNbw8eNnGg1yEUivsAuiCr6yW/IH0EoE/qAbVrG7mbUnQHVeoDtWhNqiqDaqJbuAH "Retina 0.8.2 – Try It Online") Link includes test suite that accepts double-spaced examples using `.` although code requires `_`. Explanation: Uses .NET balancing groups to count the number of `_`s with any `X` that is adjacent to the left, above, right or below respectively.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes
```
4(36₄vV§↵R)∑2O
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLilqF2UyIsIjQoMzbigoR2VsKn4oa1UiniiJEyTyIsIiIsIjYzTzZcbjMzMzNcbjMzM09cbjMzTzYiXQ==)
Messy port of Kevin Cruijssen's 05AB1E answer.
Two things increase the byte count of this:
* We have to explicitly vectorise replace (`V`)
* Transposing creates a character matrix, so we use a more convoluted method.
```
4( ) # Four times...
36₄vV # Replace 36 with 26
§↵R # Rotate 90°
∑2O # Count the 2s in the result.
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4FTx:øí}J2¢
```
-1 byte thanks to *@emanresu*
Takes a list of strings as input, with `1` for empty spots; `0` for black; and just `O` (could be any character besides `012`) for white.
[Try it online](https://tio.run/##MzBNTDJM/f/fxC2kwurwjsNra72MDi36/z9aycDQ30BJR8kQCCCUP5gCCsYCAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU3lua8ijhnl6EY8aFtYe2q3DpeSYXFKamANXYV8JFPMvLYHx/pu4hVRYHd5xeG2tl9GhRf91Dm2z/x8drWQIBEo6SoYGEMoQQcXqIMkaYJM1gGgyMDTELusPlvUHC/ujmww10sDQAGKBAbKsP0TWHyLrD5X19/eHyfqDhf2xyRoY@hugOMcfTAEFY2MB).
**Explanation:**
Uses the legacy version of 05AB1E, because it can zip/transpose on a list of strings, where the new version would require character-matrices. In the new version the `ø` would be `€SøJ` (convert each to a character-list; zip/transpose; join back to strings), so using the legacy saves 3 bytes here.
```
4F # Loop 4 times:
T # Push 10
x # Double it (without popping): 20
: # Replace all "10" to "20" in the strings of the list
# (which uses the implicit input-list in the first iteration)
øí # Rotate the 4x4 block once clockwise:
ø # Zip/transpose; swapping rows/columns
í # Reverse each inner row
}J # After the loop: join to have a single string
2¢ # Count how many 2s are in this string
# (after which it is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~35~~ 32 bytes
```
≔⪫E⁴S⸿θPθ≔⁰ηFθ«≧⁺∧№KVX⁼KK.ηι»⎚Iη
```
[Try it online!](https://tio.run/##LU27CsIwFJ3NV4RON1CLg5uTFAeFmqIgGVyC1jYYk5qHi/jt8aa63HsenHMug3QXK3VKa@9Vb2BnlYFGjrAs6daMMRyDU6YHxkpanF2B78lWpIk6qBGdAJn@w4uSDshu1lGU6ZvMsOnnHVQ/BGh19CVdmyvUNmK27br7yZp9Fx/SGMgbIk9snlFqP9mTWBV5P3fP2mlUIfyQWnfSAcKfWEsfYGBslRIXoiJcVAKPEKTinKf5S38B "Charcoal – Try It Online") Link is to verbose version of code. Only works for boards of height 4, but accepts any width (including variable width). Explanation:
```
≔⪫E⁴S⸿θ
```
Input the board. (Save 7 bytes if a JSON string with each line delimited by carriage returns is an acceptable input format, in which case this works for any size of board.)
```
Pθ
```
Output the board without moving the cursor.
```
≔⁰η
```
Start with `0` liberties.
```
Fθ«
```
Loop over the string.
```
≧⁺∧№KVX⁼KK.η
```
Increment the number of liberties if this is a `.` with at least one orthogonally adjacent `X`.
```
ι
```
Move to the next character.
```
»⎚Iη
```
Clear the canvas and output the final count of liberties.
Edit: Saved 3 bytes by hard-coding the size of the board as suggested by @tsh on my Retina answer. Previous 35-byte answer works for any size of board in human-readable format:
```
WS⊞υι≔⪫υ⸿θPθ≔⁰ηFθ«≧⁺∧№KVX⁼KK.ηι»⎚Iη
```
[Try it online!](https://tio.run/##RY4/C8IwEMVn8ylCpwvU4u4kxUGhpihIBpegsQnGpM0fHcTPHtN2cDnufu/uvbtK7q6W65TeUmmBYWf6GE7BKdMBIbiNXkIssSJrtPFedQb2VpkRFRdXkBIPWWmiDqrPNwGG/@KqxDJPd@twxviDFg3vZ@2oOhmg1dGXeGNuUNuYb1shHmdrDiI@uTGQzQs2RmyHyLWf5AlWBSGz96KdQsfvvqjWgjvI7Qxr7gNIQtYpUcYqRFnFcmEMVZRSlJYv/QM "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: `WS⊞υι≔⪫υ⸿θ` converts the input into a single carriage-return delimited string, after which the remaining 25 bytes are the same.
[Answer]
# Python 3, 121 112 90 bytes
```
def l(b,n=0):
for i in range(36):
if b[i]>0==b[i-1]*b[i+1]*b[i-6]*b[i+6]:n+=1
return n
```
Edit -9 bytes: @LeopardShark outgolfed me with another Python3 answer, but luckily I was able to golf my code 1 byte lower than theirs, albeit by abusing lax input restrictions even more: the flattened 6x6 list is now lengthened to a 68 item list, where the first 32 items are total junk, and simply space the indices out properly.
Edit -22 bytes: @LeopardShark's 73 byter made me realize I could actually use `range(36)` instead of my solution iterating over a string with `ord()`, plus a few tweaks to the conditional, brings this down to 90 bytes, which is I think as short as I can get this code without wholesale copying LeopardShark's solution using `sum()`. But hey! at least the input doesn't need 32 garbage entries at the start of the list anymore.
I feel like there's way better ways to do this, but both getting the right range to iterate on and evaluating the conditional stumped me as to shorter ways than this.
Takes input as an list of length 36, representing a flattened 6x6 grid, where only the central 4x4 actually holds useful data. Black pieces are marked with `0`, whites with `-1`, and empty spaces with `1`. The "padding" on the exterior is also filled with `-1`.
The program just loops through each square in the board, and checks if any of the four adjacent squares are equal to 0. If it is, that square is a liberty, and a counter is incremented.
[Working TIO link with test cases now that I've removed the walrus](https://tio.run/##vZNRa4MwEMff71Pc3nSNoDhkCNnjPkHfSii2i1tAkpJEmn16pzG0Q8MoY12OeOZHuPt78j992g8ly2F44y12yYFImqc1YKs0ChQSdSPfeVJWE0TR4mEn2EtO6Zizgj2OaTOnrJpPFavlhhaAmtteS5QAoGhWgKM57KcXy401SHE3VsTwnNaeXOMbLEIsoIvB4kZ4Cc8Y@b0I948iXOyj3c39/k6EWotQ69Lqnr8jOnnnd@Smu4cIFWaxgmrZT8VFKB8/iQAGYPrjkZvJMFvdc2ikOXPt/fNEKlKSnDyTnMHCsbNhEU9aSJt0iTfd6N009VhMbr8wfKAY6o7HGq8tX5vOcIC5SsDpMHwB)
[Answer]
# [Python 3](https://docs.python.org/3/), 71 bytes
```
lambda p:sum(p[x+1]+p[x-1]+p[x+6]+p[x-6]>8 for x in range(36)if p[x]<1)
```
This checks each cell next to a blank one to look for a black stone.
It takes its input as an array of 36 `1` (white), `9` (black) and `0` (empty), with the board surrounded by `1`.
This was much longer (113 B), but des54321’s 6×6 input strategy helped to shorten it.
Thanks to Chris for pointing out that `f=` was unnecessary.
[Try it online!](https://tio.run/##lY/RagMhEEXf9yvmUbMbyJCy1JDkR8w8bFFboTFiDGy/fms0sFjaJpGB4XK5Z7z@K36c3Hoyu8P0ORzf1AB@c74cmZdji9SmtSyr7Yvqaf8K5hRgBOsgDO5ds3XPrYHk0hb5pLSBqM@RjXzTQHp@UEor2IG0ORmuSSmRYAEvHSzGDm6Csm@zj8kJHSBRhgQdL8GBYYXGm6bxwbrI8ikpVx3chhIubVGp1a@KOL9PEU9TRHVd/JV7iIIzBeccPtOo7lC@I6p@4h4FKwpWFPxJwTL/UHDO4QOU6Rs "Python 3 – Try It Online")
] |
[Question]
[
This challenge is from a game, [Keep Talking And Nobody Explodes](https://keeptalkinggame.com/).
*It's hard to say how this mechanism works. The engineering is pretty impressive, but there must have been an easier way to manage nine wires.* — from the [manual](https://ktane.timwi.de/HTML/Wire%20Sequence.html)
# Input
Exactly 9 "wires", each which is labeled 'A', 'B', or 'C', and is colored red, blue, or black.
Input format and type doesn't matter, as long as they uniquely identify the wires. In particular, the alphabets can be encoded arbitrarily, so can the colors.
# Objective and Output
Output the indices of the wires that needs to be cut. The output format and type doesn't matter either, as long as they uniquely identify the wires to be cut.
# Which wire to cut?
If the wire has color \$X\$ and it's the \$N\$th wire of that color that you have seen so far, look at the entry of color \$X\$ on row \$N\$ of the table. If and only if the wire's label is listed on that entry, it is to be cut.
$$
\begin{array}{c|ccc}
& \text{Red} & \text{Blue} & \text{Black} \\ \hline
\text{1st} & \text{C} & \text{B} & \text{A, B, or C} \\
\text{2nd} & \text{B} & \text{A or C} & \text{A or C} \\
\text{3rd} & \text{A} & \text{B} & \text{B} \\
\text{4th} & \text{A or C} & \text{A} & \text{A or C} \\
\text{5th} & \text{B} & \text{B} & \text{B} \\
\text{6th} & \text{A or C} & \text{B or C} & \text{B or C} \\
\text{7th} & \text{A, B, or C} & \text{C} & \text{A or B} \\
\text{8th} & \text{A or B} & \text{A or C} & \text{C} \\
\text{9th} & \text{B} & \text{A} & \text{C}
\end{array}
$$
# Example
Assuming the wires are 1-indexed, and given the following input:
```
Blue C
Blue C
Black C
Black B
Black A
Red C
Blue C
Black A
Black A
```
The 1st wire is the 1st blue wire, which is not connected to B, so leave it.
The 2nd wire is the 2nd blue wire, which is connected to A *or* C, so cut it.
The 3rd wire is the 1st black wire, so cut it.
The 4th wire is the 2nd black wire, which is not connected to A nor C, so leave it.
The 5th wire is the 3rd black wire, which is not connected to B, so leave it.
The 6th wire is the 1st red wire, which is connected to C, so cut it.
The 7th wire is the 3rd blue wire, which is not connected to B, so leave it.
The 8th wire is the 4th black wire, which is connected to A *or* C, so cut it.
The 9th wire is the 5th black wire, which in not connected to B, so leave it.
So the output is `[2,3,6,8]`.
[Answer]
# JavaScript (ES6), ~~75 74~~ 67 bytes
Expects a list of `[color, label]` pairs, using `0-2` for both. Returns a binary array describing which wires must be cut.
```
a=>a.map(([c,w])=>(m[c]/=8)>>w&1,m=[334844576,228136272,611931512])
```
[Try it online!](https://tio.run/##hY5LC8IwEITv/RV7kgTWatKnSApt7cmeBE8hh1BbUfoQLfrza3xdLOJp@HZ2hjnqq74U58Opn7bdrhwqMWgRabvRJ0JkgTdFRUQaWaiZCGkU3SYMGyEdxw1d1wt85Dxkjs8Djj5jC4d5jCs6FF176SEGAXOExAhDSI1whE22ep/zbfZykjxO1w93aVmPZFeXdt3tSUWkBSCfnwimQOEPNnkccfLF8YfNBBP/2xeP2VKUDnc "JavaScript (Node.js) – Try It Online")
### 63 bytes
We can save a few bytes by taking `A=1, B=2, C=4` and returning a list of zero / non-zero values.
```
a=>a.map(([c,w])=>w&=m[c]/=8,m=[334844576,228136272,611931512])
```
[Try it online!](https://tio.run/##hY5PC4JAFMTvfop3CoWXtaupESuoecpT0GnZw7JpFP4jJT@@rVGXJDrN@z1mhrnJh@zU/dr2y7o552PBRslCaVeyNU2ucBAWC4cFq7gSKxZgxbjjuIHrbnwPKQ2I41GfokfI1iEbQoU1qqbueoiAAUGItVCERIuLcEz3@ljrd3ZK34YsSg6TaWcYU7Ipc7tsLmZhcgOAv5wIukDgD9Z5nHH8xdGH9QQd/9sXzdkQljU@AQ "JavaScript (Node.js) – Try It Online")
### How?
Each color is encoded as a bit mask describing the wire labels for the 1st to the 9th appearance.
```
# | 9 8 7 6 5 4 3 2 1 (0)
Label | CBA CBA CBA CBA CBA CBA CBA CBA CBA ---
-------+-----------------------------------------
Red | 010 011 111 101 010 101 001 010 100 000 -> 334844576
Blue | 001 101 100 110 010 001 010 101 010 000 -> 228136272
Black | 100 100 011 110 010 101 010 101 111 000 -> 611931512
```
Whenever a color appears, we right-shift the corresponding bit mask by 3 positions (by dividing it by 8) and we test the bit 0, 1 or 2 according to the label.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 25 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ċṪ$Ƥżḅ3Ʋị“µỵƓṢ⁴ż]¶:ɼ’ḃ7¤&
```
A dyadic Link accepting a list of the wire colours on the left and a list of the wire labels on the right which yields a list of indicators of whether to cut each wire.
Inputs:
```
Red : 1 A : 1
Blue : 2 B : 2
Black : 3 C : 4
```
Outputs:
```
Cut : non-zero (truthy)
Don't cut : zero (falsey)
```
**[Try it online!](https://tio.run/##y0rNyan8//9I98Odq1SOLTm65@GOVuNjmx7u7n7UMOfQ1oe7tx6b/HDnokeNW47uiT20zerknkcNMx/uaDY/tETt////0UY6CkBkDEOGcG7s/2gTHQUIMgJLQNhAhmEsAA "Jelly – Try It Online")**
[Here](https://tio.run/##AW0Akv9qZWxsef//xIvhuaokxqTFvOKBuOG4hTPhu4vigJzCteG7tcaT4bmi4oG0xbxdwrY6ybzigJnhuIM3wqQm/@G7tOKAnFJCS0PigJ1p4rGu4rGubzHDpy9U//9CQktLS1JCS0sKQ0NDQkFDQ0FB "Jelly – Try It Online") is an easier to use version accepting the colours, `RBK` (red, blue, black), on the first line and the labels, `ABC` on the second line, which yields a list of wire numbers to cut.
### How?
```
ċṪ$Ƥżḅ3Ʋị“...’ḃ7¤& - Link: colours, labels
Ʋ - last four links as a monad - f(colours):
Ƥ - for prefixes:
$ - last two links as a monad - f(prefix):
Ṫ - tail -> current wire's colour
ċ - count -> number of such wires seen before
ż - zip with (colours)
3 - three
ḅ - convert (zip result items) from base (3)
X = the indexes to check in the flattened table
¤ - nilad followed by link(s) as a nilad:
“...’ - 41650313607423351764917
7 - seven
ḃ - bijective-base -> [4,2,7,2,5,5,1,2,2,5,1,5,2,2,2,5,6,6,7,4,3,3,5,4,2,1,4]
Y = the flattened table as bitmasks of labels to cut
ị - (each of X) index into (Y)
& - (that) bitwise AND with (labels) (vectorises)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 119 bytes
```
s`(\d)(?<=(\1.*?)+)
$1$#2
%`(23|4|26|19)A|(22|1[136]|03|5|06|29)B|(2[148]|04|6|17|09)C|(07|28)[AB]|([10]2|18)[AC]|01|27
```
[Try it online!](https://tio.run/##JYtBCsJAEATv@w0jzCjIzCRmE1DCJs/YBCKYgxcP6rH/vo4Idamm@rV9Hs9bKe@V5jvTcLnSrKfDwEcOlVY7C/uVrEYDa6E9J5AZNGvdLpAaZ0gL63n0PWvT@djAywjpeQJJhHWc07iAssri359O3ikslqJTcMQZg6Rgf03OFw "Retina 0.8.2 – Try It Online") Takes input as list of digit + letter pairs where the digit is `2` for Red, `1` for Blue and `0` for Black. Output is a list of whether each wire should be cut. Explanation:
```
s`(\d)(?<=(\1.*?)+)
$1$#2
```
After each digit insert its cumulative appearance count.
```
%`(23|4|26|19)A|(22|1[136]|03|5|06|29)B|(2[148]|04|6|17|09)C|(07|28)[AB]|([10]2|18)[AC]|01|27
```
For each wire check whether it needs to be cut.
[Answer]
# [Rust](https://www.rust-lang.org/), 89 bytes
```
|w|w.scan([0;3],|a,&(c,l)|{a[c]+=1;Some(b"TGjEQBMERBuFgCkDJD"[2*a[c]-2+c/2]>>c%2*3+l&1)})
```
[Try it online!](https://tio.run/##jVVZc9owEH73r9h4plgGx1xpSg24g0nSY6YPpZ2@UIZRjAhqbMPY8kAC/Ha6Epe5OtGDdey3u9@uduU4TcRqGEFIeURMmGuAI2ACpjxmCTRB070gZQBtbT9T/3k3e5u5pXXYAE5xre2s28kk4IIYfyLDtEM6IYtgkXEYpuh0HA@k02CN7U9HXLBkQn1GzPoO6Y@DcYyokAp/tNaxIzYTxLTTaBqj5W0gcujIS4emC6U04a/M2gskUSUpHxwiW3Va2Z/25X5CI@5fEVOdLvd0AvrIgrfTaV0gc8Kk/WYWRGXEUkRMbWnauA@YLxyn8Zv5jb7ryvRpxSJ8GU9BjBgkIubRE0xpAk8sYjEVbOBoxbwmAxpQQTEeXWAQ83IilpADtW7vVt5u1bLAswDvA4WaOqlEg3O4DeZou1apxnuV1hllbwu8EaOLFi/Yfp9R8f5n@/aybe/8dq33IauXycZJ0pTRnbvasbuLudp5@ng2lFYG@JYmm@0bjBg5Y9NYs03N1g@w/jh85BE2dhO6tzdprQ6V3hoxRIoceAQl265m6ltqvoADOSwx1Jodt0L9ACl9hDR5RmRpL5G2Cbd8U9on6MC0X/mE5LpGy7DA8OSnbfSybSUHH8ILln4k8C1LSN4/lsuhnBWaUG40eP1AutROV9vwu7xY6Uk1pd5oAKnmCc@VzU04a40J9pQIoiuiz5e6hT02cBzMguMM43HYT8WwRnI7i7bd2ycFzaiuTSN1A/misodPnyCrxXQxtROfRqRbqld71oJaOeJbgbmY067fKzTL9Z/jkJFH/dfnv/c/vO/3HS99eGo/332707uVvARdVwo@RuC6/rtKvloIkPnSXFmQU6@85KIcShqaliZswz3gPnOcr4LFdQ3/EZJPw6AWdByQh1SM4wYuwmZacy14cOAhIlKgQGT9wqmv6Zpw7ULHJUMEWeufC9aIQaF7gNvdqSyBmbz@IVFgG38EMSYqc6WZdDufZMJnm0cRg1j9Aw "Rust – Try It Online")
## Explanation:
Both colors and labels are encoded as numbers from 0-2. The output is a number for every wire: 1 if it should be cut, 0 otherwise. The `b"TG...D"` string contains a binary encoding of the above table. The labels to be cut in every cell is transformed into a 3-bit mask. Three of these masks can be packed into two bytes (Red and Blue in the first byte and Black in the second byte). The 6-th bit (which is unused) is also set, to make all the characters ASCII printable (to not need escape sequences or raw strings).
[Answer]
# [J](http://jsoftware.com/), 61 bytes
Takes in values as `Red Blue Black -> 0 1 2`, `A B C -> 0 1 2` transposed, so color stands above letter in the matrix. Returns a bit-mask of wires to be cut.
```
(9 3 3$-.#:2005405163341131167346014x){::~(1#.{:=}:)\@{.|:@,]
```
[Try it online!](https://tio.run/##JYzBCsIwEETv/YqhFZpAu@xm04grhYLgyZNnxVsPfoEQ9ddjMQwP5s1hnqWlfsVs6DGAYRsj4XS9nIs7QKG7kToLzFPkSZJqFFGRtNeYWOLLZ7Ovk46yzR/ztyXT25bhXnxZ4Vo60iP4etwIBOEfrq2pJpvXlRv/Aw "J – Try It Online")
### How it works
The table is encoded in `(9 3 3$-.#:2005405163341131167346014x)`. Convert the long number to base 2, negate it, and reshape to `9 3 3`. With a index like `4 1 1` (5th blue B) we get a 1, corresponding to cut. I use the negated form so we have a leading 1. Fun fact: the table razed to a list in base 2 `412446475888127182066337` is prime!
```
t{::~(1#.{:=}:)\@{.|:@,]
{. the first row (colors)
\@ for each prefix (1, 1 1, 1 1 2, …)
{:=}: compare last element to all other
1#. and count the occurrences
,] prepend this to the original list
|:@ and transpose it
t{::~ get the corresponding bit of the table
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 33 bytes
```
⭆θ§”)∧∨⦃↧dG↓◨h↓WK”⍘⁺№E…θκ§λ⁰§ι⁰ι³
```
[Try it online!](https://tio.run/##TY5NCwIhEIb/inhSMBjr2Mn11CFY6LjsQUxaSdbaj6hfb35FKzOP887AvKMHNWmvXAjtZMeFXJb43c7qQZ4MieU0Xs2bYOA8RklI5AAbmVDmUPuQ6xwFtfw1MUONmk1xI61bZyL9Gv2Ts/xoZ@Tg8w13@r/DMQR0o23VNuaBxncMoeswl3F9JRQ2mSJxv52Kyr4Pu5f7Ag "Charcoal – Try It Online") Link is to verbose version of code. Takes input as list of digit + letter pairs where the digit is `2` for Red, `1` for Blue and `0` for Black. Output is a binary string of whether each wire should be cut. Explanation:
```
θ Input list
⭆ Map over elements and join
”...” Compressed binary lookup table
§ Cyclically indexed by
№ Count of
§ ⁰ First character of
ι Current entry in
… κ Prefix of
θ Input list
E Map over entries
§ ⁰ First character of
λ Inner entry
⁺ Concatenated with
ι Current entry
⍘ ³ Interpreted as base 3
Implicitly print
```
As an example, the last wire from the example, `0A`, is the fifth black wire, therefore there are four wires in the prefix, resulting in a string `40A`. This converts as `4 * 9 + 0 * 3 + A`, where the letters are decoded using `a=10, ... z=35, A=36, ... Z=61`, resulting in a final total of 72. The use of uppercase letters here just requires the entire lookup table to be rotated by 36 bits, so it's not necessary to encode the letters.
[Answer]
### [Python 3](https://python.org), 92 bytes
```
def f(w):
m,i=[41855572,28517034,76491439],1
for c,t in w:t&m[c]and print(i);i+=1;m[c]>>=3
```
Takes input as a list of (color, wire) tuples. Color is coded red=0, blue=1, and black=2. Wires are coded A=1, B=2, and C=4. So the example is
```
[(1, 4), (1, 4), (2, 4), (2, 2), (2, 1), (0, 4), (1, 4), (2, 1), (2, 1)]
```
`m` is the encoded table. The 1st row is encoded in the least significant bits. In binary:
```
table = [
# 9 8 7 6 5 4 3 2 1 <- table row
# CBA CBA CBA CBA CBA CBA CBA CBA CBA
0b_010_011_111_101_010_101_001_010_100,
0b_001_101_100_110_010_001_010_101_010,
0b_100_100_011_110_010_101_010_101_111
]
```
After checking a color/label combination, the table column is shifted by 3 bits so that it doesn't need to keep track of the 1st red wire, 2nd red wire, etc.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε•1ä)eι()2×rK•b3ô3ô¯yн©¢è®èyθ讈
```
Input as a pair of `[color, wire]`, where the colors are `red=2, blue=1, black=0` and wires are `A=0, B=1, C=2`. Outputs a list of 0s and 1s, where the 1s are the position of the wires we should cut.
[Try it online.](https://tio.run/##yy9OTMpM/f//3NZHDYsMDy/RTD23U0PT6PD0Im@gQJLx4S1AdGh95YW9h1YeWnR4xaF1h1dUntsBYpxu@/8/OtpQxyhWB0oaQElDMGkAJI1QZA2gZCwA)
**Explanation:**
```
ε # Map over each pair `y` of the (implicit) input:
•1ä)eι()2×rK• # Push compressed integer 2199241953913589502631010
b # Convert it to binary: 111010001101101010010010100101100101010010010011011101110001111001101110001100010
3ô # Split it into parts of size 3: ["111","010","001","101","101","010","010","010","100","101","100","101","010","010","010","011","011","101","110","001","111","001","101","110","001","100","010"]
3ô # Split that list into parts of size 3 again: [["111","010","001"],["101","101","010"],["010","010","100"],["101","100","101"],["010","010","010"],["011","011","101"],["110","001","111"],["001","101","110"],["001","100","010"]]
¯ # Push the global array
yн # Get the first item of the pair
© # Store it in variable `®` (without popping)
¢ # Count the amount of times it occurs in the global array
è # Use that to index into the list of triplets
® # Push the first item of variable `®` again
è # Use that to index into the triplet
yθ # Push the last item of the pair
è # Use that to index into the binary-string
®ˆ # Add the first item of variable `®` to the global array
# (after which the resulting list 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 `•1ä)eι()2×rK•` is `2199241953913589502631010`.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 107 bytes
```
_,O;P(int*T){for(int R[3]={O=0};9>O++;"T+R&%*{9+*"[_/7]>>_%7&1&&printf("%d ",O))_=*T+R[*T++/3]++*9+*T++;}
```
[Try it online!](https://tio.run/##NYxNCoMwEIW3xSt0MwQM5qeoFSoS9AqKuAshFFuLi9qiFhchZ7dJoTN8M28evOlPj77fd81r0UTjtNKOmOE1ewmtzFRp6jKxoqhqxgTq2LHFITUFowckdZyrqtJhjlOM37OLDBEKb4B4TYguacda6QaLM8UYdRmnhd396@d1nCICJoAA/L0tUkEJBjJ@5p7Lj9SRuP57iQesCKCJtoW47Wq@r595gkQEdv8C "C (gcc) – Try It Online")
Takes an array of { color 1, label 1, color 2, label 2, ...
Each entry of table is encoded in three triplets of bits , one for each color, where each bit represent a label
```
r b bla RedBluBla
abcabcabc
1st c b abc -> 001010111
2 b ac ac -> 010101101
3 a b b -> 100010010
4 ac a ac -> 101100101
5 b b b -> 010010010
6 ac bc bc -> 101011011
7 abc c ab -> 111001110
8 ab ac c -> 110101001
9 b a c -> 010100001
```
Then all bits are joined, spilt by 7 , reversed and converted to a string `T+R&%*{9+*`.
To get the the target bit position we multiply by 9 the table line we need and we add color value and label value.
Then we divide by 7 to get the character we need in the encoded string and we shift back by modulo 7
] |
[Question]
[
Although what is a [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle) is well-known and we already can [generate](https://codegolf.stackexchange.com/questions/3815/generate-pascals-triangle) it, the task is now different:
**Output** \$n\$ first lines of the Pascal's triangle as colored bricks.
Color number is computed as maximal power of \$d\$, that divides the needed-to-color element or \$7\$ if power is more than \$7\$.
Numbered colors are (\$0\$-based): default, red, green, yellow, blue, magenta, cyan, white (default color is 0th, red is 1st, .. white is 7th).
* Any space-filling (I mean not `.`,`'` or `"` or smth small) character
can be used for bricks, even `'\u2588'`.
* Whitespace before or after the bricks are optional.
* Brick horizontal length (\$1\$ or \$2\$) is your choice.
* You may choose any convenient output method -- ansi text or graphics or HTML or whatever
* If you choose output letters or color numbers instead of coloring the triangle itself, you should specify in the text of your answer which character corresponds to which color, but output wouldn't look so nice)
**Input** Integers \$n\$ and \$d>1\$ in any convenient method.
This is code-golf, the shortest code in each language wins.

[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~157 153 143 139~~ 135 bytes
*Saved several bytes thanks to @AlexeyBurdin*
*Saved ~~4~~ 8 more bytes thanks to @ceilingcat*
Outputs with ANSI colors.
```
long p,a,s,c,L;f(n,d){for(a=0;c=a++-n;puts(""))for(;p=c<a;printf(c<0?" ":"\e[3%dm@@",L),s=++c<1?1:s*a/c-s)for(L=0;p*=d,L<7&s%p<1;L++);}
```
[Try it online!](https://tio.run/##HcxLCsIwFEDRuasIASVpXrBVQfAl6AKyA52EV1MKbRqMn4G4deNnfDmXdEdUyjDFjiXwkIHAYRARWvkM00V4WyNZr5SOmG7XLDiX8hcwWTIe06WP1yDI1HvO@I6fzsf1vB0PBw5OQrZKkWn2zS5Xfkk6/6n7PlNlW3Bmu8jzZBp0Skl8lfvUt2z0fRSSPWeMBbGpga0kzl7lTWHwXS768QE "C (gcc) – Try It Online") (no colors on TIO)
### Example output for \$f(40,2)\$
[](https://i.stack.imgur.com/jMZkP.png)
### Formula
At row \$r\$ and column \$c-1\$, we have:
$$P\_{r,c-1}={r\choose c-1}=\frac{r!}{(c-1)!(r-c+1)!}$$
On the same row and the next column \$c\$, we have:
$$\begin{align}P\_{r,c}={r\choose c}&=\frac{r!}{c!(r-c)!}\\
&=\frac{r-c+1}{c}\times\frac{r!}{(c-1)!(r-c+1)!}\\
&=\frac{r-c+1}{c}\times P\_{r,c-1}\\
&=\frac{r+1}{c}P\_{r,c-1}-P\_{r,c-1}\end{align}$$
which is translated as `s = s * a / c - s` in the C code (with \$a=r+1\$).
### Commented
```
long p, a, s, c, L; // declare a few 64-bit integers
f(n, d) { // n = number of rows, d = colorization parameter
for(a = 0; a++ < n; puts("")) // for a = 1 to n, with a linefeed added after each
for( // iteration:
c = a + ~n; // for c = a - n - 1 to a - 1:
p = c < a; //
printf( // update the output after each iteration:
c < 0 ? // if c is negative:
" " // just append a space
: // else:
"\e[3%dm@@", // append the ANSI color code, followed by '@@'
L // set the 2nd digit of the color code
), //
s = ++c < 1 ? 1 // increment c; set s to 1 while c is less than 1
: s * a / c - s // then, update s to s * a / c - s
) //
for( // compute the color L:
L = 0; // start with L = 0
p *= d, // multiply p by d
L < 7 & s % p < 1; // stop if L = 7 or p does not divide s
L++ // increment L
); //
} //
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~158~~ ~~134~~ 132 bytes
```
n,d=input()
o=r=[1]
exec"print''.join([`i`for i in range(8)if c%d**i<1][-1]*2for c in r).center(2*n);r=o+map(sum,zip(r,r[1:]))+o;"*n
```
[Try it online!](https://tio.run/##HcrRCsIgFADQ975CBjF1NlJ6iJZfIsKGc3WDXeXmoPp5o87zye9yT2hqRTVbwLwVLnbJknXa7@IrhiYTYGnb/pEAuRthXBIxYICMJrxFfhawsLCfpYSr9u6gvTS/Ev5F9CFiicSNRDGQTd06Zf7cVvWBzEmR0xcvRJeGRmKtp6MyXw "Python 2 – Try It Online")
22 bytes from tips by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
Uses `01234567` as the 8 characters instead of 8 colors.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17~~ 16 bytes
```
ÝεyÝcI7LmδÖO}».c
```
[Try it online!](https://tio.run/##ASQA2/9vc2FiaWX//8OdzrV5w51jSTdMbc60w5ZPfcK7LmP//zQwCjI "05AB1E – Try It Online")
```
Ý # range 0..input
ε } # for each number y in that range:
yÝ # range 0..y
c # binomial coefficient (yields a row of the triangle)
I # second input
7L # range 1..7
m # power (yields [input, input², ..., input**7])
δÖ # double-vectorized divisible-by
O # sum each inner list
» # join by newlines, joining sublists by spaces
.c # center
```
### [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes, no binomial coefficient built-in
```
1λ£0ªDÁ+}εI7LmδÖOºJ}.c
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f8NzuQ4sNDq1yOdyoXXtuq6e5T@65LYen@R/a5VWrlwyUN@AyAgA "05AB1E – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
1Ø0j+ƝƊ⁸СṖọ«7ịØaḤz⁶ZṚ€
```
[Try it online!](https://tio.run/##AT8AwP9qZWxsef//McOYMGorxp3GiuKBuMOQwqHhuZbhu43Cqzfhu4vDmGHhuKR64oG2WuG5muKCrP/Dp1n//zIw/zI "Jelly – Try It Online")
A full program taking the number of rows as its first argument and the power as its second. Outputs the triangle to STDOUT. Colours are represented by `z` for 0/default and `a` to `g` for 1 to 7+.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~24~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
FNNÝcεU7ÝR.ΔmXsÖ])».c
```
First input is the amount of rows `n`, second input the power-base `d`.
Outputs `[0,7]` instead of the colors, and only outputs a single digit for the bricks (with spaces).
[Try it online.](https://tio.run/##ASkA1v9vc2FiaWX//0ZOTsOdY861VTfDnVIuzpRtWHPDll0pwrsuY///NDAKMg)
**Explanation:**
```
F # Loop in the range [0, (implicit) input n):
NN # Push the current loop-index twice
Ý # Pop the top one, and create a list in the range [0, index]
c # Calculate the binomial coefficient of the index and this ranged list
# i.e. 10 choose [0,1,2,3,4,5,6,7,8,9,10]
# → [1,9,36,84,126,126,84,36,9,1]
ε # Map each value to:
U # Pop and store the current value in variable `X`
7Ý # Push a list in the range [0,7]
R # Reverse it to make the range [7,0]
.Δ # Find the first digit which is truthy for:
m # Take the (implicit) input d to the power of the current digit
Xs # Push variable `X` and swap the two values
Ö # Check if `X` is divisible by this digit ** `d`
] # Close the find_first; map; and loop
) # Wrap all lists into a list
» # Join each inner list by spaces, and then each string by newlines
.c # Centralize the lines by padding leading spaces
# (after which the result is output implicitly)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~41~~ ~~36~~ ~~32~~ ~~29~~ 25 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
_p1 ä+T}h[]à)m£_XuVpZa7}f
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X3AxIOQrVH1oW13gKW2jX1h1VnBaYTd9Zg&footer=rm1hNyC4w7f7&input=MjAKMw)
```
h ) // run input times
[]à // starting with empty 2d array (permutations of [])
_ } // function that:
p1 // appends 1
T // and prepends 0
ä+ // sums consecutive elements
m // for each line
£ // for each element
f // find first number (starting at 0) that return false this function:
_ } // f(Z)
Xu // triangle element modulo
Vp // 2nd input raised to
Za8 // absolute difference
```
Uses numbers [7...0] as colors
Footer inverts colors to [0...7] for simpler output
Saved a lot thanks to @Shaggy
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes
```
Nθ⊞υ¹FN«P⭆υ×¹¹ΣE⁸¬﹪κXθμ↙⊞υ⁰UMυ⁺κ§υ⊖λ
```
[Try it online!](https://tio.run/##TY7NCsIwDIDP7il6zKDCJh7EncRdBCeD@QJ1i27YNrNrVRCfva7@gLkkfEm@pG6FqUlI7ze6d3bn1AENXOIsKt3QguMsHesjGQb/A3HMHtGkcNJ2vem0hcqO6VSIPqzsO4UDpClnlVMQ4IKzHVkoqHGS4MxZSbdwhzMVfyMbfXRFWOZ001s82kB@TyTvtujXpJTQTUCldEMwrexGN3gPKMfaoEJtsQH5cT69n0XzxE@v8gU "Charcoal – Try It Online") Link is to verbose version of code. Takes the number of rows as the second input. Output uses digits `1-8` to represent the colours (`1` = default). Explanation:
```
Nθ
```
Input the base.
```
⊞υ¹
```
Start the first row with a single `1`.
```
FN«
```
Loop over each row.
```
P⭆υ×¹¹ΣE⁸¬﹪κXθμ↙
```
For each cell, determine its divisibility by the first 8 powers of the base, and take the sum. Then multiply by 11 to duplicate the digit. (Alternatively, casting to string and then duplicating the digit also works.) Don't move the cursor while printing, instead finish by moving the cursor down and left.
```
⊞υ⁰UMυ⁺κ§υ⊖λ
```
Add another column to the row and calculate each row as the sum of the two cells above.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 123 bytes
```
->n,d{(0..n).map{|w|' '*(n-w)+(0..w).map{|i|"\e[#{30+(b=[*1..w].combination(i).size).downto(0).find{|w|b%d**w<1}}m##"}*''}}
```
[Try it online!](https://tio.run/##LcxLCoMwFEDRrYih5KM@Yp3WbiR1YBqFDPIiNRJazdrTCp2eC/e16Xee@9zcsTY7kwDIwY3LfsSDFlQwbCKvTo9/t0f5mBTZO1kx3SvR/tIAT@@0xTFYj8xyWO1n4mB8xOCZ5DBbNOdSX4wQ8dam5Agpk6A0pbxsYS1m1cr6OuQv "Ruby – Try It Online")
] |
[Question]
[
## Background
A spanning tree ([Wikipedia](https://en.wikipedia.org/wiki/Spanning_tree)) of an undirected graph is a subgraph that is a tree which includes all of the vertices of the original graph. The following is an example of a spanning tree of a 4-by-4 grid graph.

## Task
Given two positive integers `w` and `h`, output **any valid spanning tree of the grid graph** which has `w` vertices horizontally and `h` vertices vertically. There are lots of valid answers; just output one of them. Your code is even allowed to give different outputs across runs, as long as all of them are valid.
## Input and output
The input is two positive integers `w` and `h`.
The output is a representation of a spanning tree. **The output format is restricted to "a list of pairs of numbered vertices"**, in order to prevent various boring answers (as discussed in the sandbox). Also, the vertex numbering should be in **row-major order**, e.g.
```
0 - 1 - 2 - 3
| | | |
4 - 5 - 6 - 7
| | | |
8 - 9 - 10- 11
```
or
```
(0,0) - (0,1) - (0,2) - (0,3)
| | | |
(1,0) - (1,1) - (1,2) - (1,3)
| | | |
(2,0) - (2,1) - (2,2) - (2,3)
```
You can choose to use 0-based or 1-based indexing for vertices. Also, you may output nested or flattened arrays.
## Scoring & winning criterion
The standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest valid submission in bytes wins.
## Example I/O
### `w=3, h=2`
If you want to output the following graph
```
+-+-+
| |
+ +-+
```
The list-of-vertex-pairs representation will be (using 0-based indexing for example):
```
[(0, 1), (0, 3), (1, 2), (1, 4), (4, 5)]
```
or
```
[((0, 0), (0, 1)),
((0, 0), (1, 0)),
((0, 1), (0, 2)),
((0, 1), (1, 1)),
((1, 1), (1, 2))]
```
### `w=1, h=1`
The graph is a single vertex with no edges, and its only spanning tree is the graph itself. Your code should output an empty list (which means no edges).
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 9 bytes
```
|\'2':+!:
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6qJUTdSt9JWtOLiSlMwVjABACnuA9o=)
this is a composition equivalent to the lambda `{|\'2'+!x}`. the trailing `:` forces `!` (and therefore the whole composition) to be monadic.
```
!2 3 /odometer
(0 0 0 1 1 1
0 1 2 0 1 2)
+!2 3 /flip
(0 0
0 1
0 2
1 0
1 1
1 2)
2':+!2 3 /pairs (sliding window size 2)
((0 0;0 1)
(0 1;0 2)
(0 2;1 0)
(1 0;1 1)
(1 1;1 2))
|\'2':+!2 3 /cumulative(\) max(|) each(')
((0 0;0 1)
(0 1;0 2)
(0 2;1 2)
(1 0;1 1)
(1 1;1 2))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
lambda w,h:zip(R(w-1)+R(w*h),R(1,w*h))
R=range
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFcJ8OqKrNAI0ijXNdQUxtIaWVo6gRpGOqAGJpcQbZFiXnpqf8LijLzShTSNEx0jDW5uJSUlLgMdHUNdXWNdHWNuWoUFKCIy0RBwVRBwUxBwRxZ1EJBwVJBwdBAwdAQpPc/AA "Python 2 – Try It Online")
**49 bytes**
```
lambda w,h:[(i-w**(i>=w),i)for i in range(1,w*h)]
```
[Try it online!](https://tio.run/##TctLCsIwFEbheVbxk1EScqFp66OFuhF1ENGYC5qWUAiCe48IDoQz@uAsrzXOqa1hOtWHf16uHsXG8aiYijGKD1PRlnWYMxickH2635SzxUR9rkvmtCKo3nZaCCmlaIgcUUvUiTfwS/TABtgCu3/dAwPgGjj3fesH "Python 2 – Try It Online")
Both of these produce a list corresponding to a spanning tree like this (for `w=4, h=3`):
```
0--1--2--3
| | | |
4 5 6 7
| | | |
8 9 10 11
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Full program. Prompts for `[h,w]` from stdin. Prints pairs of `[y,x]` coordinates.
```
2⍮/,↑⊢∘⌽\↓⍳⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkGXI862gv@Gz3qXaev86ht4qOuRY86Zjzq2RvzqG3yo97NQHX/gSq4gHSwK5AID1Z3LUvNK1FXUA9OLS7OzM8LKMoEc72K8/PUuUAk0NhqoFIgBSS9gv39HvXuqv2vAAYFXMYKJlwwtpGCMQA "APL (Dyalog Extended) – Try It Online")
`⎕` prompt for numeric input from the console
`⍳` an array of those dimensions containing the **ɩ**ndices of an array of those dimensions
`↓` split into list of rows
`⊢∘⌽\` [boustrophedonise](https://codegolf.stackexchange.com/a/150153/43319)
`↑` combine rows into matrix
`,` ravel matrix into list
`2⍮/` adjacent pairs (lit. for every overlapping run of 2 elements, juxtapose the 2 elements)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
*L©¹<L쮦ø
```
-2 bytes by porting [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/195413/52210), but is 1-based instead. So it will output the graph in this format (i.e. `w=5, h=3`):
```
1--2--3--4--5
| | | | |
6 7 8 9 10
| | | | |
11 12 13 14 15
```
[Try it online.](https://tio.run/##AR0A4v9vc2FiaWX//ypMwqnCuTxMw6zCrsKmw7j//zUKMw)
**Explanation:**
```
* # Multiply the (implicit) width and height inputs with each other
L # Create a list in the range [1,w*h]
© # Store this list in variable `®` (without popping)
¹< # Push the width-input again, and decrease it by 1
L # Create a list in the range [1,w-1]
ì # Prepend it in front of the earlier list
® # Push the list [1,w*h] from variable `®` again,
¦ # and remove the 1 to make it the range [2,w*h]
ø # Zip/transpose to create pairs of the two lists
# (after which this list of pairs is output implicitly as result)
```
---
**Original 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:**
```
*LIä2Å€R}˜ü‚
```
1-based. Will output the graph in this format (i.e. `w=5, h=3`):
```
1--2--3--4--5
|
6--7--8--9--10
|
11-12-13-14-15
```
[Try it online.](https://tio.run/##ASEA3v9vc2FiaWX//ypMScOkMsOF4oKsUn3LnMO84oCa//81CjM)
**Explanation:**
```
* # Multiply the (implicit) width and height inputs with each other
L # Create a list in the range [1,w*h]
Iä # Split it into the height-input amount of equal-length parts
2Å€ } # Apply to every 2nd (index % 2 == 0) item:
R # Reverse the inner list
˜ # Then flatten it to a single list of integers again
ü # Apply to each overlapping pair of values:
‚ # Pair them together
# (after which this list of pairs is output implicitly as result)
```
[Answer]
# [R](https://www.r-project.org/), 42 bytes
```
function(w,h)cbind(a<-1:(h*w-1),a+w^!a%%w)
```
[Try it online!](https://tio.run/##K/qfpmCr8D@tNC@5JDM/T6NcJ0MzOSkzL0Uj0UbX0EojQ6tc11BTJ1G7PE4xUVW1XPN/moaxjonmfwA "R – Try It Online")
Creates the spanning graph
```
1-2-3
|
4-5-6
|
7-8-9
```
Node `i` is connected to node `i+1` in general, or to node `i+w` if `i` is a multiple of `w`. This corresponds to a connecting node `i` to node `i+w^d` where `d=1` if `i` is a multiple of `w`, and `d=0` otherwise.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 9 bytes
```
⌈\¨2⍮/,⍤⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/9OA5KOejphDK4we9a7T13nUu@RR7@b//9MUjBVMuNIUjBSMAQ "APL (Dyalog Extended) – Try It Online")
[Adám's golfing](https://codegolf.stackexchange.com/questions/195408/spanning-tree-of-a-rectangular-grid/195420?noredirect=1#comment465224_195420) of [my algorithm](https://codegolf.stackexchange.com/a/195425/24908)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~44~~ 41 bytes
[crossed out 44 is still 44](https://codegolf.stackexchange.com/a/194711/18535)
```
->w,h{(1...w*h).map{|x|[x,x+=x%w<1?w:1]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165cJ6Naw1BPT69cK0NTLzexoLqmoia6QqdC27ZCtdzG0L7cyjC2tvZ/gUJatImOcSwXl5KSEpehrq6Rrq6xrq4JlwIM1HCZ6uqa6eqa6@paIIta6hoa6Boa6hoagbT@BwA "Ruby – Try It Online")
1-based solution
[Answer]
# [Rockstar](https://codewithrockstar.com), 215 bytes
```
g takes w,h
let j be 0
while j is less than h
let i be 0
while i is less than w
let c be j*w+i
let p be c-1
if i is 0
let p be c-w
if p is as high as 0
say "("+p+"-"+c+")"
build i up
build j up
```
It can be invoked like
```
g taking 3,2
```
with the output as
```
(0-1)
(1-2)
(0-3)
(3-4)
(4-5)
```
you can also [try it online](https://codewithrockstar.com/online)!
[Answer]
# [JavaScript (V8)](https://v8.dev/), 68 bytes
Takes input as `(w)(h)`. Prints pairs of 0-based numbered vertices.
```
w=>g=(h,n=0,p=n)=>((n/w&1?n--:++n)%w?n:n=p+w)<w*h&&g(h,n,print(p,n))
```
[Try it online!](https://tio.run/##XcvNCsIwEATgu08hBcOuSdC0DUjrti/ipQj98bCEWpq8faxY/LsN883cmrm5X8fBTXo@xZaip6oj6BXTUTlipAqAD16YmrUupGTc@ZoLJic9nv2@F6J7zpUbB57AKUaMr5zkISsSLLct5AgZlpu1v3D6lvRPTLCrGAT7LTaYVSwu@PMxn88i8QE "JavaScript (V8) – Try It Online")
Recursively creates the following pattern (here with \$w=4\$):
```
0→ 1→ 2→ 3
↓
4← 5← 6← 7
↓
8→ 9→10→11
↓
… ←14←15
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
×ḶsUÐeFṡ2
```
Explanation:
```
×ḶsUÐeFṡ2 the main and only link, takes the dimensions as input
× multiply the dimensions
Ḷ create the range of 0..h*w-1
s split into chunks of length w, I have no idea how does this part refer to w
Ðe at even indices
U reverse the chunks
F flatten
ṡ2 split in overlapping slices of length 2 (path -> edge list)
```
The tree is actually a snake-like path:
```
01234
98765
ABCDE
```
[Try it online!](https://tio.run/##ARwA4/9qZWxsef//w5fhuLZzVcOQZUbhuaEy////NP8z "Jelly – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
NθNηF×θη¿ιI⟦⎇﹪ιθ⊖ι⁻ιθι
```
[Try it online!](https://tio.run/##TcuxCsIwEIDh3ae48Q7iomNHXRwqDt3EIaZXcpAm5pIIPn0suDh@/PzOW3XJht4v8dXqta1PVsw07P7tNy9JASdZuWA24IlAFkAhuKnEiidbKt4n1mj1g2OaW0goBjIZOLNTXjlWnrfBwCixlV/cJA@iofcDHPv@Hb4 "Charcoal – Try It Online") Link is to verbose version of code. Outputs using the following format:
```
0-1
|
2-3
|
4-5
```
Alternative solution, also 22 bytes:
```
NθNηF×θη¿ιI⟦⎇‹ιθ⊖ι⁻ιθι
```
[Try it online!](https://tio.run/##TcqhDgIxDIBhz1NUtskwIE@CIQGCOEcQY/SyJrfdrdtIePoxgUB@@X/nrbrFzq2d4lrLtYYnKyYaNv/23dOigKMEzpgMeCKQCVAIbiqx4MHmgveRNVr94JlzRjGQyMCRnXLgWPjVdwMXifUXu@RBNLS2g33bvucv "Charcoal – Try It Online") Link is to verbose version of code. Outputs using the following format:
```
0-1
| |
2 3
| |
4 5
```
Bonus version:
```
NθFNFθ«J⊗κ⊗ι¿∧κ∨¬ι‽←+-↑✂+|⁰⊕ι
```
[Try it online!](https://tio.run/##TY3LCsIwFETX7VdcskpoCtWlrgQ3Fani4wP6uMVgHm1M3KjfHqNScDec4cy0l9q2ppYhlHrwrvKqQUtHtkx7Y4H@Q8bgy0YGjzTZeDWcDF0b30js6JVxmLJgUU9ED3SlY8NhZ2llXOQcDrXujIpbcW1vhXZ0scXecSBZTj4ayhtOzXngcJSiRUqyJ@FQcCh1a1Ghdr@faLxCmBcwK0J@l28 "Charcoal – Try It Online") Link is to verbose version of code.
] |
[Question]
[
Your task is to take two single-variable integer polynomial expressions and multiply them into their unsimplified first-term-major left-to-right expansion (A.K.A. [FOIL](https://en.wikipedia.org/wiki/FOIL_method) in the case of binomials). Do not combine like terms or reorder the result. To be more explicit about the expansion, multiply the first term in the first expression by each term in the second, in order, and continue in the first expression until all terms have been multiplied by all other terms. Expressions will be given in a simplified LaTeX variant.
Each expression will be a sequence of terms separated by `+` (with exactly one space on each side) Each term will conform to the following regular expression: (PCRE notation)
```
-?\d+x\^\d+
```
In plain English, the term is an optional leading `-` followed by one or more digits followed by `x` and a nonnegative integer power (with `^`)
An example of a full expression:
```
6x^3 + 1337x^2 + -4x^1 + 2x^0
```
When plugged into LaTeX, you get \$6x^3 + 1337x^2 + -4x^1 + 2x^0\$
The output should also conform to this format.
Since brackets do not surround exponents in this format, LaTeX will actually render multi-digit exponents incorrectly. (e.g. `4x^3 + -2x^14 + 54x^28 + -4x^5` renders as \$4x^3 + -2x^14 + 54x^28 + -4x^5\$) You do not need to account for this and *you should not include the brackets* in your output.
## Example Test Cases
```
5x^4
3x^23
15x^27
```
---
```
6x^2 + 7x^1 + -2x^0
1x^2 + -2x^3
6x^4 + -12x^5 + 7x^3 + -14x^4 + -2x^2 + 4x^3
```
---
```
3x^1 + 5x^2 + 2x^4 + 3x^0
3x^0
9x^1 + 15x^2 + 6x^4 + 9x^0
```
---
```
4x^3 + -2x^14 + 54x^28 + -4x^5
-0x^7
0x^10 + 0x^21 + 0x^35 + 0x^12
```
---
```
4x^3 + -2x^4 + 0x^255 + -4x^5
-3x^4 + 2x^2
-12x^7 + 8x^5 + 6x^8 + -4x^6 + 0x^259 + 0x^257 + 12x^9 + -8x^7
```
## Rules and Assumptions
* You may assume that all inputs conform to this exact format. Behavior for any other format is undefined for the purposes of this challenge.
+ It should be noted that any method of taking in the two polynomials is valid, provided that both are read in as strings conforming to the above format.
* The order of the polynomials matters due to the expected order of the product expansion.
* You must support input coefficients between \$-128\$ and \$127\$ and input exponents up to \$255\$.
+ Output coefficents between \$-16,256\$ and \$16,384\$ and exponents up to \$510\$ must therefore be supported.
* You may assume each input polynomial contains no more than 16 terms
+ Therefore you must (at minimum) support up to 256 terms in the output
* Terms with zero coefficients should be left as is, with exponents being properly combined
* Negative zero is allowed in the input, but is indistinguishable from positive zero semantically. Always output positive zero. Do not omit zero terms.
Happy Golfing! Good luck!
[Answer]
# [R](https://www.r-project.org/), ~~159~~ ~~153~~ 148 bytes
```
function(P,Q,a=h(P),b=h(Q))paste0(b[1,]%o%a[1,],"x^",outer(b,a,"+")[2,,2,],collapse=" + ")
h=function(s,`/`=strsplit)sapply(el(s/" . ")/"x.",strtoi)
```
[Try it online!](https://tio.run/##VY3BCoMwEETv/QpZEBK6Vo3a9lD/oZ6l0lgUhdAEEyH9ertiKe1pZ2fezk5LH1yipZ@fDzfqJ7tihbIc2JVjS6Pi3EjruoS1dYq3UIdynQi@AdSz6ybWokTYA68FoqDooZWSxnYlBPsA@G4ov@UW7/G9tG6yRo2OW2mMerFOMRtDcCA4Bn8AJMDpkS89g9w3GdVEwjdpTqIgQ5xXh0QBCFHimxN9@WdXlAJRFL9otgWUi@3iSIqME5V/DhPi0s1d1wz48gY "R – Try It Online")
I really wanted to use `outer`, so there's almost surely a more efficient approach.
[Answer]
# [Haskell](https://www.haskell.org/), ~~131~~ 122 bytes
```
(%)=drop
f s=do(a,t)<-reads s;(i,u)<-reads$2%t;(a,i):f(3%u)
p!q=3%do(a,i)<-f p;(b,j)<-f q;" + "++shows(a*b)"x^"++show(i+j)
```
[Try it online!](https://tio.run/##NYvRDoIwFEPf@YrL4pI7B4lAoolzv7JkBAhThMEg7u/nRH1qe9r22j3aYQgBKZPNMtmkAyebCXW2slu@tLpx4ASabPvHQ0lXEXvDrh1WdGOJTWdZ0f1k4qoDK7DO7rudBQEOhHPXTy@H@lgz4tUvo@F3Fp7ajCDBLmZcAcnZqzJeLl4VUfLSqxOBFEjx5R9QERbe "Haskell – Try It Online")
`f` parses a polynomial from a string, `!` multiplies two of them and formats the result.
*H.PWiz saved 9 bytes. Thanks!*
## Ungolfed
```
type Monomial = (Int, Int) -- a^i
type Polynomial = [Monomial]
parse :: String -> Polynomial
parse s = do (a, s') <- reads s
(i, s'') <- reads (drop 2 s')
(a, i) : parse (drop 3 s'')
(!) :: String -> String -> String
p!q = drop 3 (concat terms)
where terms = [term (a*b) (i+j) | (a,i) <- p', (b,j) <- q']
term a i = concat [" + ", show a, "x^", show i]
p' = parse p
q' = parse q
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~102 100~~ 98 bytes
```
->a,b{a.scan(w=/(.*?)x.(\d+)/).map{|x|b.scan(w).map{|y|(eval"[%s*(z=%s;%s),z+%s]"%y+=x)*"x^"}}*?+}
```
[Try it online!](https://tio.run/##LcnRCoIwFIDhV4kDg21HZxrURSwfxBxslVcW0qjOdHv2heDl//3vjwt50Lm82MItVvmbffGfrriSrSDFr3cUlVBPOy2Rotv@BiHyx9eO0DEv@ayZPzMvihmZ74EF1CQkkIGUZIspT7uhgyOZBk9kaiwbMnsooF5ljQP0@Q8 "Ruby – Try It Online")
### How?
First step: get all the numbers from both polynomials: `scan` returns the numbers as an array of pairs of strings.
Then, do a cartesian product of the 2 lists. Now we have all the numbers where we need them, but still in the wrong order.
Example: if we multiply `3x^4` by `-5x^2`, we get the numbers as `[["3","4"],["-5","2"]]`, the first idea was to zip and flatten this list, and then put the numbers into an expression to be evaluated as `[3*-5, 4+2]`. Actually, we don't need to reorder the numbers, we could do it inside the expression by using a temporary variable: the expression becomes `[3*(z=4,-5),z+2]`.
After evaluating these expressions, we get the coefficient and exponent, we need to join them using `"x^"`, and then join all the tems using `"+"`.
[Answer]
## Haskell, ~~124~~ 121 bytes
```
import Data.Lists
f!x=map f.splitOn x
z=read!"x^"!"+"
a#b=drop 3$do[u,v]<-z a;[p,q]<-z b;" + "++shows(u*p)"x^"++show(v+q)
```
Note: TIO lacks `Data.Lists`, so I import `Data.Lists.Split` and `Data.List`: [Try it online!](https://tio.run/##hY1Nb4JAEIbv/Iph9ABFiLCsmlhuPZr04NF0kzVoJOVjhcVu/PN0Vkx6KImnmXnneWYusvs@leVQVKppNXxILaNd0elor8pC/4uds2uySio4R50FPmswzj1rTzJ30Qh0MUBHzo5Z3jYK2DxvDv3i9vUe3kFuD2pxfbTHLUIAGATdpfnpvP5N@VYeZ@8WXP2hkkUNGeSNA6B6vdftroY5eDMfkBuRIgAyIxKGMEGsaEMf1kbEVMLEiKUV4jG2M8MJjY08HzGiUirsKT/qhJTSsefR2PKcgmRjE2o4AoZLI9YvTCsSlnD@J5LJxg0BCQ6/ "Haskell – Try It Online")
Edit: -3 bytes thanks to @Lynn.
[Answer]
# Pyth - 39 bytes
```
LmsMcdK"x^"%2cb)j" + "m++*FhdKsedCM*FyM
```
[Try it online](http://pyth.herokuapp.com/?code=LmsMcdK%22x%5E%22%252cb%29j%22+%2B+%22m%2B%2B%2aFhdKsedCM%2aFyM&test_suite=1&test_suite_input=%226x%5E2+%2B+7x%5E1+%2B+-2x%5E0%22%2C+%221x%5E2+%2B+-2x%5E3%22%0A%225x%5E4%22%2C%223x%5E23%22%0A%223x%5E1+%2B+5x%5E2+%2B+2x%5E4+%2B+3x%5E0%22%2C+%223x%5E0%22&debug=0).
[Answer]
# [JavaScript (Babel Node)](https://babeljs.io/), 118 bytes
Takes input as `(a)(b)`.
```
a=>b=>(g=s=>[...s.matchAll(/(-?\d+)x.(\d+)/g)])(a).flatMap(([_,x,p])=>g(b).map(([_,X,P])=>x*X+'x^'+-(-p-P))).join` + `
```
[Try it online!](https://tio.run/##fYxBTsMwEEX3nKLKpjMkdps4pmwcxAGQuqxUauqkSWhlkohEyLcPY7kboGL1Z/68NxfzZcbq8zxMrDRlbVnXn@q5UbNRRakKaNWoij3nfOQfZqren62FFbCn11OMjoOPVYsHBIO8sWZ6MQPA/i1xyXBAVbRQIomh2yVb37n7Xbx0ehkzYAPbIiK/9OfuuIgXx7nqu7G3Nbd9Cw1E0uk8QoiE05mIEO9@3R@oJ2/jdErBMqfXHk9D7fdblgi4DBRBOYW4uiH/ODm9ur5MPS6pyB59Q4P0Ils7vfnf9CJRmZQ/RBEuBGTkz98 "JavaScript (Babel Node) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 193 bytes
```
import re
f=re.finditer
lambda a,b:' + '.join(' + '.join(`int(m.group(1))*int(n.group(1))`+'x^'+`int(m.group(2))+int(n.group(2))`for n in f('(-?\d+)x\^(\d+)',b))for m in f('(-?\d+)x\^(\d+)',a))
```
[Try it online!](https://tio.run/##dYrBDsIgEAXv/Yq9wUolsUcT4480DRBAMbIQQpP69Sgn68HTe5OZ/Kr3RFNrIeZUKhQ3@Etx0geyoboyPHU0VoMezZmBACYfKRDfXRWo8ihvJa2ZnxAPnenLSrBtYeInmxDFPvuw8qkAQSDwnPHjdbYCt3nhfdloELuP/7xGbO0N "Python 2 – Try It Online")
Side note: First time doing a code golf challenge, so sorry if the attempt sucks haha
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 110 bytes
```
\S\S+(?=.*\n(.+))
$1#$&
|" + "L$v` (-?)(\d+)x.(\d+).*?#(-?)(\d+)x.(\d+)
$1$4$.($2*$5*)x^$.($3*_$6*
--|-(0)
$1
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyY4Jlhbw95WTysmT0NPW1OTS0HFUFlFjatGSUFbQclHpSxBQUPXXlMjJkVbs0IPTOlp2Suji3GpGKqYqOhpqBhpqZhqaVbEgdjGWvEqZlpcuro1uhoGICX//5tVxBkBDTaviDMEUrpGFXEGXIYQMRDHGAA "Retina – Try It Online") Explanation:
```
\S\S+(?=.*\n(.+))
$1#$&
```
Prefix each term in the first input with a `#`, a copy of the second input, and a space. This means that all of the terms in copies of the second input are preceded by a space and none of the terms from the first input are.
```
|" + "L$v` (-?)(\d+)x.(\d+).*?#(-?)(\d+)x.(\d+)
$1$4$.($2*$5*)x^$.($3*_$6*
```
Match all of the copies of terms in the second input and their corresponding term from the first input. Concatenate any `-` signs, multiply the coefficients, and add the indices. Finally join all of the resulting substitutions with the string `+`.
```
--|-(0)
$1
```
Delete any pairs of `-`s and convert `-0` to `0`.
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~192~~ 176 bytes
```
P =INPUT
Q =INPUT
D =SPAN(-1234567890)
P P D . K ARB D . W REM . P :F(O)
B =Q
B B D . C ARB D . E REM . B :F(P)
O =O ' + ' K * C 'x^' W + E :(B)
O O ' + ' REM . OUTPUT
END
```
[Try it online!](https://tio.run/##PY49D4IwEIbn9lfcBkgwWFo/SDpQqYkx0oIQtw7ORgaX/vt6iDJc3ss9z13u/Rof45OHQCzIc2OHnpJ26WqQN1s1cbZhBRfb3f6QJ9SiWsMaLlB16tvdodNXTEvKU2wSShTIlioy0@Pi6Z@nJs@iZ0AaiCDFusAKzci7CM@loEkZq4Qa8ufzphn66THd1CFw7wpEGfOOY@beMSGmAQJBs2IeI2Uf "SNOBOL4 (CSNOBOL4) – Try It Online")
```
P =INPUT ;* read P
Q =INPUT ;* read Q
D =SPAN(-1234567890) ;* save PATTERN for Digits (or a - sign); equivalent to [0-9\\-]+
P P D . K ARB D . W REM . P :F(O) ;* save the Koefficient and the poWer, saving the REMainder as P, or if no match, goto O
B =Q ;* set B = Q
B B D . C ARB D . E REM . B :F(P) ;* save the Coefficient and the powEr, saving the REMainder as B, or if no match, goto P
O =O ' + ' K * C 'x^' W + E :(B) ;* accumulate the output
O O ' + ' REM . OUTPUT ;* match ' + ' and OUTPUT the REMainder
END
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 114 bytes
```
{my&g=*.match(/(\-?\d+)x\^(\d+)/,:g)».caps».Map;join " + ",map {"{[*] $_»{0}}x^{[+] $_»{1}}"},(g($^a)X g $^b)}
```
[Try it online!](https://tio.run/##LYxLCsIwGIT3nuInlJL0qX24sBRP4F5ojcRqo2I1WBcpISfrrheLKbr6mPmGEZf3Y226AdwWSqO6weWlF3Xs01xxjOtwW599ImuKZ8bBhpNpjBomeosdE8X9dXsCAh9Q0DEBCqnKO4BznEa11FpSVfn/uNIa6QBz7FBG9sDBoSeiTbHo2QAtRpmkqf0JE0kzy6WkSZ7PhRU5CgCF6c/YQYKI@QI "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 130 bytes
```
lambda a,b:' + '.join([`v*V`+'x^'+`k+K`for V,K in g(a)for v,k in g(b)])
g=lambda s:[map(int,t.split('x^'))for t in s.split(' + ')]
```
[Try it online!](https://tio.run/##RY3LCoMwEEX3/YqBLiZpovhsQfAL3LuxipGitT7RIPbrbVItXV3OfcyMb/kcemcrw/vWiq54CBC8CBAYoPka6p4k@XKJc4ZrhixvWJSXwwQxj6DuoSKCalx4s2NBU3qqwuPSHCSdGEndSy7NeWxrSfQZ@t1IvZh/tv5H0@0MtueexklNoCR4XTNHJbc1s5UYzppZyNHeXY0u0n/bU3z4nlJL1XxfGyrwkQMa7p6ogoN0@wA "Python 2 – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~192~~ 190 bytes
```
n=>m=>string.Join(g=" + ",from a in n.Split(g)from b in m.Split(g)select f(a.Split(p="x^")[0])*f(b.Split(p)[0])+p+(f(a.Split(p)[1])+f(b.Split(p)[1])));Func<string,int>f=int.Parse;string p,g;
```
Query syntax seems to be a byte shorter than method syntax.
[Try it online!](https://tio.run/##fY9Na4QwEIbv/RUhp6R@oNF0C2489lB6KPTQw9KAKyqBNSuahbB/3k42tmgpe8lMnnneIamnqJ7U/HLR9X4yo9JduO59KcurmLUoe1F6EL@elSadwChAOGzHc48qpDTS8cdwUoZ09MaOjvW/bGpOTW1QS6oFDQJbiekh@aKPLTn@0BsIhoCsTHpIgW0kAJQW69cqbcpWwBm/V@PUFB6jIeyK@XNUpnlTuiFXgrmVOaYEZ1ayDMOWh834CTD8bGdlCiViVibOTj12939Cmbe5l8DJoWRL1Ne/kRwWLQtTZ3MA7NkRaLjLRYmVu7tBlwOJcb7JZX4CAnPx@Rs "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
ṣ”+ṣ”xV$€)p/ZPSƭ€j⁾x^Ʋ€j“ +
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuZqQ6iKMJVHTWs0C/SjAoKPrQUysx417quIO7YJzGyYo6Ct8P///2h1k4o4YyBb16gizgRIG1TEGZmaggSAEqbqOgrqusYQGaACI/VYAA "Jelly – Try It Online")
Full program. Takes the two polynomials as a list of two strings.
### Explanation (expanded form)
```
ṣ”+ṣ”xV$€µ€p/ZPSƭ€j⁾x^Ʋ€j“ + ” Arguments: x
µ Monadic chain.
€ Map the monadic link over the argument.
Note that this will "pop" the previous chain, so
it will really act as a link rather than a
sub-chain.
ṣ”+ ṣ, right = '+'.
Split the left argument on each occurrence of
the right.
Note that strings in Jelly are lists of
single-character Python strings.
€ Map the monadic link over the argument.
$ Make a non-niladic monadic chain of at least
two links.
ṣ”x ṣ, right = 'x'.
Split the left argument on each occurrence of
the right.
V Evaluate the argument as a niladic link.
/ Reduce the dyadic link over the argument.
p Cartesian product of left and right arguments.
€ Map the monadic link over the argument.
Ʋ Make a non-niladic monadic chain of at least
four links.
Z Transpose the argument.
€ Map the monadic link over the argument.
ƭ At the first call, call the first link. At the
second call, call the second link. Rinse and
repeat.
P Product: ;1×/$
S Sum: ;0+/$
j⁾x^ j, right = "x^".
Put the right argument between the left one's
elements and concatenate the result.
j“ + ” j, right = " + ".
Put the right argument between the left one's
elements and concatenate the result.
```
### Aliasing
`)` is the same as `µ€`.
A trailing `”` is implied and can be omitted.
### Algorithm
Let's say we have this input:
```
["6x^2 + 7x^1 + -2x^0", "1x^2 + -2x^3"]
```
The first procedure is the Parsing, applied to each of the two polynomials. Let's handle the first one, `"6x^2 + 7x^1 + -2x^0"`:
The first step is to split the string by `'+'`, so as to separate the terms. This results in:
```
["6x^2 ", " 7x^1 ", " -2x^0"]
```
The next step is to split each string by `'x'`, to separate the coefficient from the exponent. The result is this:
```
[["6", "^2 "], [" 7", "^1 "], [" -2", "^0"]]
```
Currently, it looks like there's a lot of trash in these strings, but that trash is actually unimportant. These strings are all going to be evaluated as niladic Jelly links. Trivially, the spaces are unimportant, as they are not between the digits of the numbers. So we could as well evaluate the below and still get the same result:
```
[["6", "^2"], ["7", "^1"], ["-2", "^0"]]
```
The `^`s look a bit more disturbing, but they actually don't do anything either! Well, `^` is the bitwise XOR atom, however niladic chains act like monadic links, except that the first link actually becomes the argument, instead of taking an argument, if it's niladic. If it's not, then the link will have an argument of `0`. The exponents have the `^`s as their first char, and `^` isn't niladic, so the argument is assumed to be `0`. The rest of the string, i.e. the number, is the right argument of `^`. So, for example, `^2` is \$0\text{ XOR }2=2\$. Obviously, \$0\text{ XOR }n=n\$. All the exponents are integer, so we are fine. Therefore, evaluating this instead of the above won't change the result:
```
[["6", "2"], ["7", "1"], ["-2", "0"]]
```
Here we go:
```
[[6, 2], [7, 1], [-2, 0]]
```
This step will also convert `"-0"` to `0`.
Since we're parsing both inputs, the result after the Parsing is going to be this:
```
[[[6, 2], [7, 1], [-2, 0]], [[1, 2], [-2, 3]]]
```
The Parsing is now complete. The next procedure is the Multiplication.
We first take the Cartesian product of these two lists:
```
[[[6, 2], [1, 2]], [[6, 2], [-2, 3]], [[7, 1], [1, 2]], [[7, 1], [-2, 3]], [[-2, 0], [1, 2]], [[-2, 0], [-2, 3]]]
```
Many pairs are made, each with one element from the left list and one from the right, in order. This also happens to be the intended order of the output. This challenge really asks us to apply multiplicative distributivity, as we're asked not to further process the result after that.
The pairs in each pair represent terms we want to multiply, with the first element being the coefficient and the second being the exponent. To multiply the terms, we multiply the coefficients and add the exponents together (\$ax^cbx^d=abx^cx^d=ab(x^cx^d)=(ab)x^{c+d}\$). How do we do that? Let's handle the second pair, `[[6, 2], [-2, 3]]`.
We first transpose the pair:
```
[[6, -2], [2, 3]]
```
We then take the product of the first pair, and the sum of the second:
```
[-12, 5]
```
The relevant part of the code, `PSƭ€`, doesn't actually reset its counter for each pair of terms, but, since they're pairs, it doesn't need to.
Handling all pairs of terms, we have:
```
[[6, 4], [-12, 5], [7, 3], [-14, 4], [-2, 2], [4, 3]]
```
Here, the Multiplication is done, as we don't have to combine like terms. The final procedure is the Prettyfying.
We first join each pair with `"x^"`:
```
[[6, 'x', '^', 4], [-12, 'x', '^', 5], [7, 'x', '^', 3], [-14, 'x', '^', 4], [-2, 'x', '^', 2], [4, 'x', '^', 3]]
```
Then we join the list with `" + "`:
```
[6, 'x', '^', 4, ' ', '+', ' ', -12, 'x', '^', 5, ' ', '+', ' ', 7, 'x', '^', 3, ' ', '+', ' ', -14, 'x', '^', 4, ' ', '+', ' ', -2, 'x', '^', 2, ' ', '+', ' ', 4, 'x', '^', 3]
```
Notice how we've still got numbers in the list, so it's not really a string. However, Jelly has a process called "stringification", ran right at the end of execution of a program to print the result out. For a list of depth 1, it really just converts each element to its string representation and concatenates the strings together, so we get the desired output:
```
6x^4 + -12x^5 + 7x^3 + -14x^4 + -2x^2 + 4x^3
```
[Answer]
# JavaScript, ~~112~~ 110 bytes
I found two alternatives with the same length. Call with currying syntax: `f(A)(B)`
```
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(a=>P(B).map(b=>a[0]*b[0]+'x^'+(a[1]- -b[1]))).join` + `
```
```
f=
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(a=>P(B).map(b=>a[0]*b[0]+'x^'+(a[1]- -b[1]))).join` + `
console.log( f('5x^4')('3x^23') )
console.log( f('6x^2 + 7x^1 + -2x^0')('1x^2 + -2x^3') )
console.log( f('3x^1 + 5x^2 + 2x^4 + 3x^0')('3x^0') )
console.log( f('4x^3 + -2x^14 + 54x^28 + -4x^5')('-0x^7') )
console.log( f('4x^3 + -2x^4 + 0x^255 + -4x^5')('-3x^4 + 2x^2') )
```
```
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(([c,e])=>P(B).map(([C,E])=>c*C+'x^'+(e- -E))).join` + `
```
```
f=
A=>B=>(P=x=>x.split`+`.map(x=>x.split`x^`))(A).flatMap(([c,e])=>P(B).map(([C,E])=>c*C+'x^'+(e- -E))).join` + `
console.log( f('5x^4')('3x^23') )
console.log( f('6x^2 + 7x^1 + -2x^0')('1x^2 + -2x^3') )
console.log( f('3x^1 + 5x^2 + 2x^4 + 3x^0')('3x^0') )
console.log( f('4x^3 + -2x^14 + 54x^28 + -4x^5')('-0x^7') )
console.log( f('4x^3 + -2x^4 + 0x^255 + -4x^5')('-3x^4 + 2x^2') )
```
*-2 bytes ([Luis](https://codegolf.stackexchange.com/questions/182972/multiply-two-integer-polynomials/182983#comment440284_182983)): Remove spaces around `split` delimiter.*
---
# JavaScript, 112 bytes
Using `String.prototype.matchAll`.
```
A=>B=>(P=x=>[...x.matchAll(/(\S+)x.(\S+)/g)])(A).flatMap(a=>P(B).map(b=>a[1]*b[1]+'x^'+(a[2]- -b[2]))).join` + `
```
```
f=
A=>B=>(P=x=>[...x.matchAll(/(\S+)x.(\S+)/g)])(A).flatMap(a=>P(B).map(b=>a[1]*b[1]+'x^'+(a[2]- -b[2]))).join` + `
console.log( f('5x^4')('3x^23') )
console.log( f('6x^2 + 7x^1 + -2x^0')('1x^2 + -2x^3') )
console.log( f('3x^1 + 5x^2 + 2x^4 + 3x^0')('3x^0') )
console.log( f('4x^3 + -2x^14 + 54x^28 + -4x^5')('-0x^7') )
console.log( f('4x^3 + -2x^4 + 0x^255 + -4x^5')('-3x^4 + 2x^2') )
```
] |
[Question]
[
## Introduction *(may be ignored)*
Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers. This is the second challenge in this series. The first challenge can be found [here](https://codegolf.stackexchange.com/questions/181268/new-order-1-how-does-this-feel).
In this challenge, we use Gray codes to rearrage the natural numbers. A Gray code, or "reflected binary code" is a binary encoding in such a way that two successive values differ in only one bit. A practical application of this encoding is to use it in [rotary encoders](https://en.wikipedia.org/wiki/Rotary_encoder), hence my reference to *["Turn My Way"](https://www.youtube.com/watch?v=yuUi6MKyRwU)*.
[](https://i.stack.imgur.com/yU6yA.png)
Note that this encoding leaves some degree of freedom. For example, following binary 1100, there are four possible following codes: 1101, 1110, 1000 and 0100. This is why I will define \$a(n)\$ as the smallest, not previously used value that differs only one character in binary encoding. This sequence corresponds with [A163252](http://oeis.org/A163252).
Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is [A163252](http://oeis.org/A163252).
## Task
Given an integer input \$n\$, output \$a(n)\$ in integer format (*not* in binary format).
\$a(n)\$ is defined as the least positive integer not occurring earlier in the sequence such that \$a(n-1)\$ and \$a(n)\$ differ in only one bit when written in binary.
*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 3\$, etc. Please mention this in your answer if you choose to use this.*
## Test cases
```
Input | Output
--------------
1 | 1
5 | 4
20 | 18
50 | 48
123 | 121
1234 | 1333
3000 | 3030
9999 | 9997
```
## Rules
* Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
* Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour. In [A163252](http://oeis.org/A163252), \$a(0)\$ is defined as 0. For this challenge, we will ignore this.
* Default [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
* [Default 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 the shortest answers in bytes wins
## Final note
See the following related (but not equal) PP&CG questions:
* [Finding the next Gray code (input and output in binary)](https://codegolf.stackexchange.com/questions/95194/incrementing-gray-codes)
* [Generate the all Gray codes of length n](https://codegolf.stackexchange.com/questions/32871/give-me-the-gray-code-list-of-bit-width-n)
[Answer]
# JavaScript (ES6), 65 bytes
1-indexed.
```
n=>{for(o=p=[k=1];o[k]|~-(i=p^k)&i?k++:k=o[p=k]=!!n--;);return p}
```
[Try it online!](https://tio.run/##Xc1dC4IwFMbx@z7FvImNWG7O6EVOfRAxENOwyc6Y1k0vX30JktDO1QM//pxb@Sj7yrV24AYvtW/AGzg@G3QUwUKuQRYZ5rp4fThtwZ41W7YnvVodNGBuQRcQRYbzjGWuHu7OEPv2FZoeu3rd4ZU2VBJCGCNxTOTiXzazpIEkYm52YTRTGpJM1K9Kwl9KCDGZEkoEuB9vwnFs/Rc "JavaScript (Node.js) – Try It Online")
### Commented
```
n => { // n = index of requested term
for( // for loop:
o = // o = storage object for the terms of the sequence
p = // p = last term found in the sequence
[k = 1]; // k = current term
o[k] | // if k was already encountered
~-(i = p ^ k) & i ? // or (p XOR k) has more than 1 bit set:
k++ // increment k
: // else:
k = o[p = k] // set o[k], set p to k
= !!n--; // stop if n is equal to 0 or set k to 1; decrement n
); // end of for()
return p // return p
} // end
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ 20 bytes
```
ṀBLŻ2*^1ị$ḟ⁸Ṃ;
0Ç⁸¡Ḣ
```
[Try it online!](https://tio.run/##y0rNyan8///hzgYnn6O7jbTiDB/u7lZ5uGP@o8YdD3c2WXMZHG4HMg8tfLhj0X@dRw1zdO0eNczVOdx@bNOjpjWR//8b6pjqGBnomBroGBoZg7CJjiUQAAA "Jelly – Try It Online")
A full program that takes n as the single argument. Works for all test cases. Also note that, although not required, it handles n=0.
### Explanation
Helper link: find next term and prepend
```
Ṁ | maximum of list so far
B | convert to binary
L | number of binary digits
Ż | 0..above number
2* | 2 to the power of each of the above
^ | exclusive or with...
1ị$ | ... the most recent term in the list so far
ḟ⁸ | filter out anything used already
Ṃ | find the minimum
; | prepend to existing list
```
Main link
```
0 | start with zero
Ç | call the above link
⁸¡ | and repeat n times
Ḣ | take the last term added
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~142~~ ~~138~~ ~~124~~ ~~123~~ ~~132~~ ~~130~~ 98 bytes
* increased to account for import, saved a byte thanks to [@kevin-cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
* switched collection to int array thanks to [@olivier-grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%c3%a9goire)
```
n->{int s[]=new int[9*n],j,k=0;for(;n-->0;s[k=j]++)for(j=0;s[++j]>0|n.bitCount(j^k)>1;);return k;}
```
[Try it online!](https://tio.run/##fZDBa8IwFMbP9q94FITEtiFOPbisvQwGO@zk0XUQtUrSNi1J6hD1b88S7HbcBy957yN870ckP/NMHmon2r7TFqSfyWBFQ46D2lvRKTJjUdQPu0bsYd9wY@CDCwXXCLyM5db7b@Pbl3dlq1Ol0/EugEPuVFZchbJgtmWuqm/w/XY9U2Uq0zqn7NhpxFSWFZSZbZ3LMklw8GQejCSRZUFviuyEfe0GZZH8qnExZ5jpyg5aQc3uziMGnBFzpDp34gCth0Ubq4U6EUKA65PBI3zQ5mJs1ZJusMTvbLlF8XRp4AZT86niNA7FkcIxZtEkUD2iwDz/RU3@zzmEHJNywvu@uaDxZ0jPtan8gAzGPvuX5x49zrtzc7dyT9StqJs/LUIt3YJS6tZePw "Java (JDK) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~19~~ 17 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
êÑ{╚α8è╙mc┼σ▀»É▲ü
```
[Run and debug it](https://staxlang.xyz/#p=88a57bc8e0388ad36d63c5e5dfaf901e81&i=1%0A5%0A20%0A50%0A123%0A1234%0A3000%0A9999&a=1&m=2)
It stops working at some point after the specified domain due to the hardcoded bit index iteration. (32767)
Unpacked, ungolfed, and commented, it looks like this.
```
z0, push an empty array, literal zero, and the input, in that order
- the zero represents the last calculated value in the sequence
- the array contains all the previous ones
D repeat the rest of the program n times (from input)
+ append the last calculated value to the array
17r [0 .. 16] (these are the bit indices necessary to cover the input range)
{|2nH|^m calculate candidate values; previous value with each of these bits toggled
n- remove all values previously calculated
|m keep the minimum candidate remaining
```
[Run this one](https://staxlang.xyz/#c=z0,+++++++%09push+an+empty+array,+literal+zero,+and+the+input,+in+that+order%0A++++++++++%09+-+the+zero+represents+the+last+calculated+value+in+the+sequence%0A++++++++++%09+-+the+array+contains+all+the+previous+ones%0AD+++++++++%09repeat+the+rest+of+the+program+n+times+%28from+input%29%0A++%2B+++++++%09append+the+last+calculated+value+to+the+array%0A++17r+++++%09[0+..+16]+%28these+are+the+bit+indices+necessary+to+cover+the+input+range%29%0A++%7B%7C2nH%7C%5Em%09calculate+candidate+values%3B+previous+value+with+each+of+these+bits+toggled+%0A++n-++++++%09remove+all+values+previously+calculated%0A++%7Cm++++++%09keep+the+minimum+candidate+remaining&i=1%0A5%0A20%0A50%0A123%0A1234%0A3000%0A9999&m=2)
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
1-based indexing
```
l=[0];p=0
exec"n=0\nwhile(p^n)&(p^n)-1or n in l:n+=1\np=n;l+=p,;"*input()
print p
```
[Try it online!](https://tio.run/##JU1NC4JAFLy/X/HYQ2gWrJqHlD3atUu3LChbcEmej8dK@evNtYH5OAwzPPluoGxuh5dFg6KUmntz1beKjQb7ta0ioxv6dK63Ed8p3qy6TwdBQkfYl5SYtCE2VPWJ4V2lto549FEMLI488rysAqwTeJHRloDoZQqGGD4w3EPIrWWP9flUiwzyLzzFPt5zCgVkGgoNaZYHHiDXWsNxwQ8 "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 79 bytes
This takes a lot of time (9999 wasn't finished after running locally for 7 minutes)
```
l={0};p=0;n=input()
exec'p=min({p^2**k for k in range(n)}-l);l|={p};'*n
print p
```
[Try it online!](https://tio.run/##JY09C8JAEET7/RVLmnyAkETTeFwZWxtrIcZTj5ybZbmgIea3nx4Ww0zxeMOzf4xUh368GtSYJElweilXxbpUpC3x5LMczNv0KeunpWzhc10UA95GwQEtoXR0Nxnl68blyn30wqtKCwIWSx45/JwAr4d1Bk8ymT0gepljIUYvxm@IuzfssT0eWpFR/sBFTDeEChqoS2hKqOptzO4L "Python 2 – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 21 bytes
```
!¡λḟ¤ȯεΣz≠ȯ↔Θḋ→¹`-N)ø
```
[Try it online!](https://tio.run/##ATUAyv9odXNr//8hwqHOu@G4n8KkyK/Otc6jeuKJoMiv4oaUzpjhuIvihpLCuWAtTinDuP///zEyMw "Husk – Try It Online") `¡§ḟ¤ȯεΣz≠ȯ↔Θḋ→`-Nø` would work if not for type-inferencing issues.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes
```
Last@Nest[#~Join~{Min[BitXor[Last@#,2^Range[0,20]]~Complement~#]}&,{0},#]&
```
[Try it online!](https://tio.run/##HYqxCsIwFAB/RQh0etDX1A4OQtBNbBEnIUQIEmKgSaR9W0h@PVYPbrrzmt7Ga3IvXe2xXvVKYjIrSVYu0YWSRhfkydEjLvIfGfDnXQdrJAJHpco5@s9svAlUmMoNJMzAVFNviwu0a4VtRepg2GYYEDre/9xDj4hw2Mi1fgE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 46 bytes
```
{⍵⌷2∘{(~⍺∊⍵)∧1=≢⍸≠⌿↑⌽∘⊤¨⍺,⊃⌽⍵:⍵,⍺⋄⍵∇⍨⍺+1}⍣⍵⊢1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v/pR79ZHPduNHnXMqNaoe9S761FHF1BI81HHckPbR52LHvXueNS54FHP/kdtEx/17AUqe9S15NAKoEKdR13NIJHerVZArAPS2t0CMq2j/VEvSIG2Ye2j3sUgka5FhrX/0x61TXjU2/eob6qnP1DrofXGICP7pgYHOQPJEA/P4P9pCoZcaQqmQGxkAGKACEMjYwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes
```
≔⁰θFN«⊞υθ≔¹ηW¬‹θ⊗η≦⊗ηW∧›η¹∨¬&θη№υ⁻θη≧÷²ηW№υ⁻|θη&θη≦⊗η≔⁻|θη&θηθ»Iθ
```
[Try it online!](https://tio.run/##jZBNasMwEIXX8SlmOQIVmtJFS1apAyEQp6E3UGLFGnAkWz/JovTsqmxr4xZKZzdP8943o7MS9mxEG@PaOWo0PnLo2aq4GAu4013wh3A9SYuMwWexOAanMEwji@xYclBDe1fUSsCD8biXzmHPYWPCqZU1KpYKKtFlS9bnxrWucWul8ImmOCwZh3c7xr2Rv5OTw0A/eNJLaYL2wyYV6eCyPIN8UKN8OsFv6Ea15PA0x/1IyIxEHLM4/IL@cUEW/5s0/d9XcbSUViiF89gztorx@eU1Ptzabw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁰θ
```
Initialise the result to 0.
```
FN«
```
Loop `n` times.
```
⊞υθ
```
Save the previous result so that we don't use it again.
```
≔¹ηW¬‹θ⊗η≦⊗η
```
Find the highest bit in the previous result.
```
W∧›η¹∨¬&θη№υ⁻θη≧÷²η
```
While that bit is greater than 1, if the bit is set in the previous result, try subtracting that bit to see if the result is an unseen result. This ensures that the potential results are tried in ascending order of value.
```
W№υ⁻|θη&θη≦⊗η
```
Now try XORing that bit with the previous result, doubling the bit until an unseen result is found. This handles the cases when a bit needs to be set, again in ascending order of value, but also the case when the least significant bit needs to be toggled, which the previous loop doesn't bother to test (because it's golfier to test for that here). If the previous loop found an unseen result then this loop never runs; if it didn't then this loop will uselessly retest those results.
```
≔⁻|θη&θηθ
```
Update the result by actually XORing the bit with it.
```
»Iθ
```
Output the final result at the end of the loop.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~21~~ ~~20~~ 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÎFˆ∞.Δ¯θy^bSO¯yå_*
```
Pretty inefficient, so the larger the input, the longer it takes to get the result. Does work for input `0` as well, though.
[Try it online](https://tio.run/##AScA2P9vc2FiaWX//8OORsuG4oieLs6Uwq/OuHleYlNPwq95w6VfKv//MjA) or [verify the first \$n\$ terms](https://tio.run/##ASsA1P9vc2FiaWX//8OORsuG4oieLs6Uwq/OuHleYlNPwq95w6VfKv9dwq//MTAw).
**Explanation:**
```
Î # Push 0 and the input
F # Loop the input amount of times:
ˆ # Pop the current number and add it to the global_array
∞.Δ # Inner loop starting at 1 to find the first number which is truthy for:
¯θy^ # XOR the last number of the global_array with the loop-number `y`
b # Convert it to binary
SO # Sum it's binary digits
¯yå_ # Check if the loop-number `y` is NOT in the global_array yet
* # Multiply both (only if this is 1 (truthy), the inner loop will stop)
# (after the loops, output the top of the stack implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org/), 101 bytes
```
import Data.Bits
(u!n)0=n
(u!n)m|q<-minimum[x|r<-[0..62],x<-[xor(2^r)n],notElem x u]=(n:u)!q$m-1
[]!0
```
[Try it online!](https://tio.run/##NY3BasMwEETv@op1CEQisVAM6UFEh5jm0Et/QKggik1EvZItS9SE/LsrEnqbmd15c7PzTzcMq8MxxASfGbvovv/tu02Wty7NhObKM6H8S@BjOtfovMOMennEc60F52@NOSxFLiHS5isybw4@pOvQISyQjaJeZlZNW6yPpFfaVGK9gwItpPzwCTg/ngyZSoJ2BNozuEupy8WQFFrnC0TBfAu/Jbqk1s4dNEBTuPqMwIHu@xjwaXZix1h532wI2lJUMEZXFrZP8gs2rX8 "Haskell – Try It Online")
It seems a shame to incur an import just for `xor`, but I haven't found a good work-around yet. I also wonder if there's a better way to express the loop.
[Answer]
# [R](https://www.r-project.org/), 90 bytes
```
function(n){A=1
while(sum(A|1)<n)A=c(min((x=bitwXor(A[1],2^(0:30)))[x>0&!x%in%A]),A)
A[1]}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPs9rR1pCrPCMzJ1WjuDRXw7HGUNMmT9PRNlkjNzNPQ6PCNimzpDwiv0jDMdowVscoTsPAythAU1MzusLOQE2xQjUzT9UxVlPHUZMLpKD2f5qGJRBo/gcA "R – Try It Online")
] |
[Question]
[
I was playing around with cellular automaton and I found one that had some interesting behavior. Here's how it works:
It reads a binary string from left to right, if it encounters a `1` followed by `2` other values it will append a `0` to the result and continue reading. If it encounters a `0` (or there are less than 3 values left) it will append the current value and a `1` and continue reading. At the end of the string it will append a single `1` to the result.
Here's a worked out example of one generation
```
01011111
^
```
We first encounter a `0` so we append `01` to our result
```
01011111
^
01
```
Now we encounter a `1` so we append a zero and skip the next two values
```
01011111
^
010
```
We encounter another `1` so we do the same
```
01011111
^
0100
```
We now have another `1` but not enough space to jump so we append the current cell and a `1` (in this case `11`)
```
01011111
^
010011
```
We are at the end so we append a single `1` and terminate this generation
```
01011111
^
0100111
```
# Task
Given input in any reasonable format you must create a function or program that computes one generation of the automaton.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question so answers will be scored in bytes, with fewer bytes being better.
# Sample implementation
Here is a sample implementation in Haskell (defines a function `d`, but the program prints a iterations indefinitely):
```
d('1':_:_:x) = "0" ++ d x
d(a:x) = a:'1':d x
d x = "1"
r x = x:map d(r x)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0VD3VDdKh4IKzQVbBWUDJQUtLUVUhQquFI0EiFiiVYgJWAhhQqQGkMlriIwq8IqN7FAIUUDyNP8n5uYmWdbUFoSXFKkUpqXk5mXWqxSBDTQ0MDAUOk/AA "Haskell – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~26~~ ~~22~~ 21 bytes
Thanks to @CowsQuack for 4 bytes by combining regexes! And @ØrjanJohansen for another byte with some regex combinations.
```
Ó1../3
Ó./&1
Ó31/0
A1
```
[Try it online!](https://tio.run/##K/v///BkQz09fWOuw5P19NUMgZSxob4Bl6Ph//@GBgaGBgA "V – Try It Online")
Uses substitute multiple times and appends a 1 at the end. Nothing too fancy. I have a version that remaps `1` and `0` in insert mode to get the desired effect, but it's quite a bit longer.
(Multiple replacement version: [Try it online!](https://tio.run/##K/v/3/TwxsiCw5MN9fT0jfVTuQ5P1tNXMwRSxob6BkC@o@H//waGBgaGAA "V – Try It Online"))
[Answer]
## JavaScript (ES6), 56 bytes
Takes input as an array of characters. Returns a string, or the number `1` if given an empty array.
```
f=([v,...a])=>v?(+v&&a[1]?a.splice(0,2)&&'0':v+1)+f(a):1
```
### Demo
```
f=([v,...a])=>v?(+v&&a[1]?a.splice(0,2)&&'0':v+1)+f(a):1
console.log(f([...'01011111']))
console.log(f([...'10']))
```
### Animated version
Examples of stable inputs: 0101, 010011111
```
f=([v,...a])=>v?(+v&&a[1]?a.splice(0,2)&&'0':v+1)+f(a):1
s = '1';
setInterval(_=>o.innerHTML=s=''+f([...s]), 200)
```
```
<input oninput="s=this.value" value="1" />
<pre id=o style="font-size:32px"></pre>
```
[Answer]
# [Python 2](https://docs.python.org/2/), 88 bytes
```
I,r=input(),[]
while I:a=I[0]and len(I)>2;b=a<1;r+=[I[0]]*b+[+b];I=I[a*2+1:]
print r+[1]
```
[Try it online!](https://tio.run/##RYoxCsMwDAD3vEJjEnmIPcZ1d71BaLBpIIagGuNS@nq3IUPhuOWufNr@VNc7mRqyllcbJ8MyvPd8bEBrDMSLRH3AselI0935FOLN@oqBzyRzQsYknn5nnB3aVYZSszaoyFZ658WANXD5j3wB "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 89 bytes
```
x=input()
y=0
k=[]
while x[y:]:v=1-x[y]*(y<len(x)-2);k+=[x[y]]*v+[v];y+=3-2*v
print k+[1]
```
[Try it online!](https://tio.run/##LYjbCoQgEEDf/YoevSSk@1bNlwzzGCSGK2HmfL1tsBwOHE7msn@T771BSPkqUgmGSURAEvcejm1oyDPNFZz9FWnJ67El2ZT1aokG8L2kq8FKCxv4WK@ryGdIZYgGHfWO0@jG1z/0AA "Python 2 – Try It Online")
-4 bytes thanks to Rod
-6 bytes thanks to ovs
-1 byte thanks to micsthepick
[Answer]
# [Swift 3](http://swift.sandbox.bluemix.net/#/repl/59792f764877037828e141d9), 147 bytes
-1 thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
```
func g(i:[Int]){var r=[Int]();var s=ArraySlice(i);while let e=s.popFirst(){if 0<e&&2<s.count{r+=[0];s=s.dropFirst(2)}else{r+=[e,1]}};print(r+[1])}
```
Ungolfed, returning the value rather than printing:
```
func iterate(state: [Int]) -> [Int] {
var result = [Int]()
var inputSlice = ArraySlice(state)
while let element = inputSlice.popFirst() {
if 0 < element && 2 < inputSlice.count {
result += [0]
inputSlice = inputSlice.dropFirst(2)
}
else {
result += [element, 1]
}
//debugPrint(result.map(String.init).joined(separator: ""))
}
return result + [1]
}
```
[Answer]
# [Nim](http://nim-lang.org/), 70 bytes
```
import re,sugar
x=>x.multiReplace([(re"1..","0"),(re"(.)","$#1")])&"1"
```
[Try it online!](https://tio.run/##ZVBLCoMwEN17iiEtJQEJzlawh@i2dCESbcAYSSJ4@zR2UZzp7j3eb5jFurwGP0CUYwtfJPcWYgp2mdQPQFcBmOHtYQQhTrg5EyQKYUiMTcOsVEUWpSOsmGbxL8vC/Czk5bydnVYMx0a2bvUhQTB13KY@VFHu3X3XbpuTfZh17gcjnzIYgVqLuvxJ1QeTWhV2vaBQL3UrH1M5fwA "Nim – Try It Online")
`multiReplace` allows us to do substitutions simultaneously. The index of the tuple within the sequence acts as the priority if there is a situation where more than one substitution can be made. The priority rises the lower the index is.
[Answer]
# [Python 2](https://docs.python.org/2/), 81 bytes
**Both input and output are lists** (thanks to Erik the Outgolfer)
```
def f(Z):return Z and((1>Z[0]or 3>len(Z))and[Z[0],1]+f(Z[1:])or[0]+f(Z[3:]))or[1]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0rTqii1pLQoTyFKITEvRUPD0C4q2iA2v0jB2C4nNQ8orwkUjgaJ6RjGagM1RBtaxWrmFwEFwDxjIA/ENYz9X1CUmVcCNDPaQEfBUEcBQiJQrCYXQgUyB0UGRRWaLpChsZr/AQ "Python 2 – Try It Online")
**Some cases**
```
[0,1,0,1,1,1,1,1] --> [0,1,0,0,1,1,1]
[0] ----------------> [0,1,1]
[1] ----------------> [1,1,1]
[] -----------------> [1]
[0,1] --------------> [0,1,1,1,1]
[1,0] --------------> [1,1,0,1,1]
```
# [Python 2](https://docs.python.org/2/), 85 bytes
**Both input and output are strings** (initial solution)
```
def f(Z):return Z and(('0'==Z[0]or 3>len(Z))and Z[0]+'1'+f(Z[1:])or'0'+f(Z[3:]))or'1'
```
[Try it online!](https://tio.run/##VYwxCsMwDEX3nkKbbLxYyRZID2KToRCHFIochDv09I7cJbG299//On5lzzzUuqYNNhPsJKl8hSHAi1dj0OM8h@iXLDA@P4m1YtVAyxwSOh1FmhabRbt/GpUaEtZD3lz0L3ry1A7t48ru0Jmu1RnSUT0B "Python 2 – Try It Online")
**Some cases**
```
'01011111'--> 0100111
'0'---------> 011
'1'---------> 111
''----------> 1
'01'--------> 01111
'10'--------> 11011
```
**Explication** It is simplily a golf of a recursive method.
[Answer]
# [Perl 5](https://www.perl.org/), 62 + 2 (`-F`) = 64 bytes
```
$r.=$F[$i]&&$i+2<@F&&($i+=2)?0:"$F[$i]1";++$i<@F&&redo;say$r.1
```
[Try it online!](https://tio.run/##K0gtyjH9/1@lSM9WxS1aJTNWTU0lU9vIxsFNTU0DyLI10rQ3sFKCyBkqWWtrq2SCJYtSU/KtixMrgToN//83MDQwMPyXX1CSmZ9X/F/X11QPKPJf1w0A "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
This is a direct port of the sample implementation Haskell code.
```
f=->s{s=~/^1../??0+f[$']:s=~/./?$&+?1+f[$']:?1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWN_XTbHXtiquLbev04wz19PTt7Q2006JV1GOtQEJAvoqatr0hVMjesBaibX2BQlq0koGhgSEIKMVCRGGGAgA)
## More readable
`$&` is the matched text from the previous regexp match (`=~`) and `$'` is the text after the match.
```
f = ->s{
if s =~ /^1../ then "0" + f[$']
elsif s =~ /./ then $& + "1" + f[$']
else "1"
end
}
```
[Answer]
# [Julia 0.6](http://julialang.org/), ~~69~~ 65 bytes
```
~s=s>""?s<"1"?"01"*~s[2:end]:length(s)>2?"0"*~s[4:end]:s*"11":"1"
```
[Try it online!](https://tio.run/##VU87CsJAEO1zCnlVkmomiMWiifeQFILBRJZVnIjdXn2zKurMVI/3ZS4PPx03KUXZSQt0sgWjAzHqKIfGDeHUOz@E8zyWUrVNlt7K@qNIDWa4nEl7Ga/PVcxR4tehuN2nMPtQVsVXww/RH7JiFU2KZ203fh3QCWJTZbp0mVmxM/mnBQ "Julia 0.6 – Try It Online")
Ungolfed and commentated algorithm:
```
function ~(s)
# Return "1" on the empty string
# (End case for automata ending in "0" or "1..")
if s == ""
return "1"
# "0" always becomes "01"
elseif s[1] == '0'
return "01" * ~s[2:end]
# "1.." always becomes "0"
elseif length(s) > 2
return "0" * ~s[4:end]
# Otherwise, append "11"
# (End case for automata ending in "1" or "1.")
else return s * "11"
end
end
```
[Try it online!](https://tio.run/##jZBBa4QwFITv/oohPayWsiRL6aGwpZeeC70ue0g1rikaxURkL/51@6J1m9BLA4E4mfnGvK@h1vJpnsvB5E63BlNqsyQB7vCh3NAbMMFAuqsUVNO5K6zrtbkslvTNFMilVSjbHnJwbSOdhDIFOaApzCncE2O/ZxlFdAmL4xGM0QfQ3yrWSm@X9SivFp8qbxtlSRLeq2qrfPgkzj6/47sIQCbcY7KnwzOVn@lu5fnev8QAWCtzcRW9GS84xMgf4uNKXHjvNIV@1FY9QHYd6dSw/N5/RiG2USyT8P1bl6WmBeR1UyS051dbtSMmehkXfrGko7G72qRZst2x24n/HkWgBjIPdBHaI38YCBNcRKiIFcKilrhGsPkb "Julia 0.6 – Try It Online")
* -3 bytes thanks to MarcMush: Test the value of `s` instead of `s[1]`
* -1 byte thanks to MarcMush: Rewrite with `s>""` instead of `s==""`
[Answer]
# [Scala](http://www.scala-lang.org/), 131+29=160 bytes
This is inside a function taking the string `a` as parameter and returning the output as a string.
```
var s=""
var k=0
for(c<-0 to a.length-1)breakable{if(k>0){k-=1
break}
if(a(c)==49&c<a.length-3){s+="0"
k+=2}else s+=a(c)+"1"}
s+"1"
```
I do have to `import util.control.Breaks._`, so I need to add those 28 bytes plus a trailing linefeed.
[Try it online!](https://tio.run/##PY7BTgQhEETP9ld0OBjIZCagXjTLJnr35AcYhmVWBIEAGhPCt48zRrcv1XmpSlXRyqvVfqSYK35W6ycdQ83RT0/ZKFemV4A4vxtd8VnZgOa7mnAq@JhSg6uTWTDlqE0pVD281GzDmf2pbOuXylgkIbA/TnJYYqb6MHKsEdXkTTjXt1Gwea9SszfNLtQdOWtulAJ@cYeNKaqZlHf31/pwid2yVgZJOAE3yJtufDG4gd06EEE6lF3WDpC2OdUHSrjgYj8cj0iG/@EXTBiDvv4A "Scala – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 108 bytes
```
n=>{var t="";for(int i=0,b=n.Length;i<b;){if(n[i]>'0'&i+2<b){t+="0";i+=3;}else t+=n[i++]+"1";}return t+"1";}
```
[Try it online!](https://tio.run/##fYsxT8MwEIV3/wrLA7XlUjkwOs6CxFQGxNCh6pAYN5wUzpJ9qYSs/PaQphsC3g1P9973fL73MYV5zIA9f/vKFD4t80ObM38tLFNL4Pklwjt/aQGlKux5RF9nSstge7OmdzO6plzaxMkJYc8xSUDi4My2c7jbB@zpw0LdWVXgLPEIp2ZjNnegH@pOFdJOGGFBu0c7hSEHviQLpPVJi0rYKQUaEy7p@s2WsaeIOQ5hd0hAYQ8YZC@FqYyprhJK2d@Ryvy4f9C/K7Nq7Sc2zd8 "C# (.NET Core) – Try It Online")
Input taken as a string, and a string is returned as output.
] |
[Question]
[
***See also: [Wordagons](https://codegolf.stackexchange.com/questions/92297/hexagolf-wordagons)***
## Challenge
Given a hexagon and a number `n` as input, output the same hexagon rotated `n` times.
## Hexagon
The hexagon will be a string like so:
```
a b c
d d e e
f f o g g
h h i i
j k l
```
The hexagon will always be regular and will only ever contain the printable ASCII characters:
```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
```
## Rotation
To find how much to rotate the hexagon by, multiply `n` by 60 degrees to get the angle of rotation. For example, using the above hexagon, if `n` is 2, we multiply that by 60 to get 120 degrees. Then, we rotate the hexagon by 120 degrees:
```
j h f
k h f d
l i o d a
i g e b
g e c
```
Note that each side has moved *two* sides clockwise.
If `n` is positive, you should rotate the hexagon clockwise. If `n` is negative, you should rotate the hexagon anticlockwise.
`n` will always be an integer in the range -6 to 6 inclusive.
## Examples
Input:
```
. u .
. | .
l - + - r
. | .
. d .
```
`n` = 3
```
. d .
. | .
r - + - l
. | .
. u .
```
---
Input:
```
- - -
/ \
< >
\ /
- - -
```
`n` = -1
Output:
```
- \ >
- /
- -
/ -
< \ -
```
---
Input:
```
h e x a
g o n s a
n d t r i a
n g l e s m a
k e m e s a
d l y m a
d d e r
```
`n` = 6
Output:
```
h e x a
g o n s a
n d t r i a
n g l e s m a
k e m e s a
d l y m a
d d e r
```
## Winning
The shortest program in bytes wins.
[Answer]
# Python 2, ~~160~~ ~~158~~ ~~156~~ ~~148~~ 124 bytes
***Prepare to be amazed!*** The resulting text is drawn on a canvas... by a [`Turtle`](https://docs.python.org/2/library/turtle.html)! :D
```
from turtle import*
h,n=input()
up()
rt(n*60)
l=0
for c in h:
write(c);fd(9);l-=1
if" ">c:fd(9*l);rt(90);fd(15);lt(90);l=0
```
[**Try it online**](https://trinket.io/python/132af14245) - Supports decimal rotations as well!
---
If you would prefer the turtle to be shaped like one, you can add the line `t.shape("turtle")`.
View the revision history to see past versions.
**Aliases used**:
`up()` - `penup()`
`rt()` - `right()`
`lt()` - `left()`
`fd()` - `forward()`
`bk()` - `backward()`
*Thanks to [Sherlock9](https://codegolf.stackexchange.com/users/47581/sherlock9) for the [suggestions](https://chat.stackexchange.com/transcript/message/32192714#32192714)!*
[Answer]
# Python 2.7, 151 bytes
```
h,n=input()
s=1-len(h)
e=enumerate
exec n%6*"h=[''.join(c>' 'and h[y-x-3*s/2>>1][x*2+y*6+s>>2]or c for x,c in e(l))for y,l in e(h)];"
print'\n'.join(h)
```
Example:
```
% python2.7 hexarot.py <<<'[[" h e x a "," g o n s a "," n d t r i a ","n g l e s m a", " k e m e s a "," d l y m a "," d d e r "],-1]'
a a a a
x s i m a
e n r s s a
h o t e e m r
g d l m y e
n g e l d
n k d d
```
[Answer]
# Perl, ~~120~~ ~~119~~ ~~113~~ ~~107~~ ~~104~~ 102 bytes
Includes +6 for `-0pXi`
Run with the hexagon on STDIN (padded with spaces so all lines have the same length) and the number of rotations after -i.
```
perl -0pXi1 rotagon.pl
a b c
d d e e
f f o g g
h h i i
j k l
^D
```
`rotagon.pl`
```
s!(.)!$X=(3*($w=y/
//*2)/4+($-="@-"/$w)-"@+"%$w)/2*--$w+2*$--.25;/^\C{$X}(.)/;$1!eg while$^I--%6
```
Finally got the rotation matrix to be shorter than the old double loop
[Answer]
## JavaScript (ES6), ~~130~~ 127 bytes
```
f=(s,n)=>n%6?f(s.split`
`.map((s,i,a)=>s.replace(/./g,(c,j)=>(a[(i+z-j)/2+z]||c)[(i+j-z)/2+i]||c,z=a.length>>1)).join`
`,n-1):s
```
Originally based on my answer to [Rotate a diamond tiling](https://codegolf.stackexchange.com/questions/52220/rotate-a-diamond-tiling) although I might now be able to rewrite that answer along the lines of this answer.
] |
[Question]
[
This one is simple to describe and I could hardly believe that this was not golfed before:
For a given image (whatever format is supported by your language), find the unique colors and output a list of the colors.
* Print the color code in hex RGB, that is a hash sign `#` followed by 2 digits for R, 2 digits for G and 2 digits for B. (`#xxxxxx` where x can be 0-9, A-F and/or a-f).
* The hex code shall be followed by a space and the decimal pixel count, then a newline (`\n` or `\r\n`).
* The list shall be sorted by count descending (most frequent color at the top).
* If there's a tie (two colors with the same amount), the order is not important.
* The image will not contain transparency, so any alpha value is not important. The alpha value may not be part of the output.
* An image size of 4000x3000 must be supported (that may matter to type definitions)
Sample image "10red 20blue 30black 40white": [](https://i.stack.imgur.com/QTE4O.png)
Expected output:
```
#FFFFFF 40
#000000 30
#0000FF 20
#FF0000 10
```
Sample image "blue gradient": [](https://i.stack.imgur.com/5s1Ob.png)
One of the expected outputs (since the order of same colors may vary):
```
#718DFF 19
#5571FF 15
#3855FF 11
#8DAAFF 11
#1C38FF 7
#AAAAFF 7
#8D8DFF 6
#AAC6FF 6
#C6C6FF 5
#C6E2FF 4
#001CFF 3
#E2E2FF 3
#FFFFFF 3
```
Sample image "testImage", kindly provided by [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo):
[](https://i.stack.imgur.com/z07VA.gif)
Expected output:
```
#FFFFFF 18042
#000000 1754
#FF3300 204
```
Similar to [this question](https://codegolf.stackexchange.com/q/47776/16901), but the output is text, not an image.
[Answer]
# Bash + coreutils, 54
* 7 bytes saved thanks to @manatwork
```
grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'
```
This assumes STDIN input of [Imagemagick's .txt format](http://www.imagemagick.org/Usage/files/#txt).
[Ideone.](https://ideone.com/Xm2NOI)
---
If the above input format is too much of a stretch, then we can add Imagemagick conversion from any format:
# Bash + coreutils + Imagemagick, 71
```
convert $1 txt:-|grep -oE '#\w+'|sort|uniq -c|sort -nr|awk '$0=$2" "$1'
```
Here, the input image filename is passed in as a command-line parameter.
[Answer]
# Mathematica, 91 bytes
```
StringRiffle@SortBy[Tally["#"<>IntegerString[#,16,2]&/@Join@@#~ImageData~"Byte"],-Last@#&]&
```
Uses a completely different method from [@DavidC's answer](https://codegolf.stackexchange.com/a/81286). Unlike that one, this can support images with any size and color count. Explanation:
```
#~ImageData~"Byte" Take the RGB values of the image...
Join@@(...) Flatten to a list of colors...
"#"<>IntegerString[#,16,2]&/@(...) Convert each color to #012def format...
Tally[(...)] Convert to a list of {color, multiplicity}
pairs (this does most of the work)...
SortBy[(...),-Last@#&] Order by the multiplicity descending...
StringRiffle@(...) And create a string with the desired format.
```
[Answer]
## PowerShell v2+, 187 bytes
```
$a=New-Object System.Drawing.Bitmap $args[0]
$b=@{}
0..($a.Height-1)|%{$h=$_;0..($a.Width-1)|%{$b["#"+-join($a.GetPixel($_,$h).Name[2..7])]++}}
$b.GetEnumerator()|Sort value -des|FT -h -a
```
Re-uses almost all of the code from my answer on [Get the most dominant color](https://codegolf.stackexchange.com/a/80452/42963). So, please reference that for full explanation.
The changes here are in indexing `$b` in the third line to match the explicit output format requirements, and in the last line we `sort` by `value` in `-des`cending order, then pipe to `Format-Table` with `-H`ideTableHeaders and `-A`utoSize as parameters. It's very rare to actually use `FT` here on PPCG, since output is implicit at the end of execution, but here it's very useful to ensure we get only the correct parts output.
### Examples
The first is the "red" test image from the Dominant Color challenge, the second is the "testimage" from this challenge.
```
PS C:\Tools\Scripts\golfing> .\color-count.ps1 C:\Tools\Scripts\golfing\img\red.png
#ff0000 139876
#dcd9cf 3056
#f2f1ed 1512
#ffffff 1508
#ffe6e6 1488
#ffe3e3 8
#eae8e2 4
#fffbfb 4
PS C:\Tools\Scripts\golfing> .\color-count.ps1 C:\Tools\Scripts\golfing\img\z07VA.gif
#ffffff 18042
#000000 1754
#ff3300 204
```
[Answer]
# JavaScript (ES6), ~~359~~ 355 bytes
### Saved 4 bytes thanks to @Neil
```
u=>{i=new Image;i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}
```
## Demo
```
f=u=>{i=new Image;i.crossOrigin='';i.src=u;e=document.createElement`canvas`;c=e.getContext`2d`;i.onload=_=>{w=e.width=i.width;h=e.height=i.height;c.drawImage(i,0,0);d=c.getImageData(0,0,w,h).data;for(o={},i=0;i<d.length;i+=4)++o[s='#'+`00000${(d[i]<<16|d[i+1]<<8|d[i+2]).toString(16)} `.slice(-7)]?0:o[s]=1;Object.keys(o).sort((a,b)=>o[b]-o[a]).map(c=>console.log(c+o[c]))}}
f('http://i.imgur.com/acPudA9.gif')
```
```
<input value="https://i.imgur.com/acPudA9.gif" onchange="console.log('-------');f(this.value)">
```
Other test cases I uploaded to imgur to support CORS:
* <https://i.stack.imgur.com/T95xA.png> 
* <https://i.stack.imgur.com/OMLlA.png> 
The specific color data on these two seems to have altered slightly when uploading for some reason but it still prints the same amount of occurrences for those two test cases.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
jmj;_d_SrSm+\#.[\06.Hid256'Q8
```
[Try it online!](http://pyth.herokuapp.com/?code=jmj%3B_d_SrSm%2B%5C%23.[%5C06.Hid256Q8&input=[[15%2C15%2C15]%2C[16%2C16%2C16]%2C[15%2C15%2C15]]&debug=0)
(The online interpreter cannot read image, so I stripped of that part and inputted the result of reading that image, which is a list of color triplets. The part responsible for reading the image is `'`, a single colon.)
[Proof of functionality of `'` a single colon](https://github.com/isaacg1/pyth/blob/master/macros.py#L324)
[Answer]
# Mathematica ~~103~~ 92 bytes
```
{"#"<>IntegerString[255Round[List@@#],16,2],#2}&@@@DominantColors[#,9999,{"Color","Count"}]&
```
---
## Example
[](https://i.stack.imgur.com/YZXiO.png)
---
## Explanation
`DominantColors` normally returns a list of colors and counts representing the main clusters in a picture.
When the number of colors requested exceeds the number of colors in the image, the exact pixel colors are returned. (I am assuming that fewer than 10 000 colors will be in the input image.)
[](https://i.stack.imgur.com/CSdah.png)
---
`{"#"<>IntegerString[255Round[List@@#],16,2],#2}` converts the base 10 color values with hexadecimal values.
---
Note: there are only 5 colors in the mandrill image. (I used `ColorQuantize[<image>,5]` to reduce the number of colors in the standard mandrill image.)
[Answer]
# [Java (1.4+)](http://openjdk.java.net/), ~~483~~ 428 bytes
```
import java.util.*;class I {public static void main(String[] a) throws Exception {java.awt.image.BufferedImage i = javax.imageio.ImageIO.read(new java.io.File(a[0]));Map m=new HashMap();String s;for(Integer x=0,y=0,c;y<i.getHeight();y++)for(x=0;x<i.getWidth();m.put(s=x.toHexString(((c=i.getRGB(x++,y))&0xff0000)>>16)+x.toHexString((c & 0xff00)>>8)+x.toHexString(c&0xff),m.get(s)==null?1:(int)m.get(s)+1));System.out.print(m);}}
```
~~Try it online!~~ (Doesn't work online)
---
Ungolfed:
```
import java.util.*;
class I {
public static void main(String[] a) throws Exception {
java.awt.image.BufferedImage i = javax.imageio.ImageIO
.read(new java.io.File(a[0]));
Map m = new HashMap();
String s;
for (Integer x = 0, y = 0, c; y < i.getHeight(); y++)
for (x = 0; x < i.getWidth(); m
.put(s = x.toHexString(((c = i.getRGB(x++, y)) & 0xff0000) >> 16)
+ x.toHexString((c & 0xff00) >> 8)
+ x.toHexString(c & 0xff), m.get(s) == null ? 1
: (int) m.get(s) + 1))
;
System.out.print(m);
}
}
```
---
The `toString()` of map outputs like this:
```
{7c7c7c=6, 1d57a5=20468, 121212=7, d3d3d3=3, bdbdbd=9, 949494=2, 333=14, 626262=3, cacaca=2, 141414=5, fff=11, c9c9c9=1, e8e8e8=1, 919191=4, 161616=5, c2c2c2=1, 646464=7, 979797=12, fafafa=2, 808080=1, 7b7b7b=1, 484848=4, b9b9b9=2, f1f1f1=2, 6b6b6b=6, 363636=15, 262626=4, d8d8d8=2, 868686=4, 757575=1, 575757=3, a7a7a7=2, cecece=2, dcdcdc=2, c3c3c3=2, 1d1d1d=5, 727272=9, 656565=2, 3a3a3a=3, 7d7d7d=10, 393939=5, 797979=3, 222=31, 8f8f8f=2, 454545=4, 181818=9, 2e2e2e=2, 222222=1, 1c1c1c=19, b8b8b8=2, e1e1e1=5, 232323=5, 8a8a8a=3, 959595=7, 6a6a6a=9, 434343=7, 5c5c5c=3, 111=20, 909090=3, 424242=4, 212121=1, 1a1a1a=6, 202020=7, efefef=1, 565656=5, 6e6e6e=7, 767676=3, 323232=2, eee=5, 444=18, 2c62ab=1, 717171=2, b1b1b1=3, 6c6c6c=3, 545454=7, 515151=17, 2f2f2f=2, 4a4a4a=3, 888888=6, 6d6d6d=3, 898989=3, a3a3a3=5, 7e7e7e=9, ddd=9, b6b6b6=3, 2b2b2b=5, 313131=5, 8d8d8d=1, a2a2a2=2, 696969=3, a5a5a5=3, 4f4f4f=5, 828282=7, 191919=5, 606060=4, 6f6f6f=4, 8b8b8b=3, ebebeb=2, 555=19, 929292=3, 131313=11, 999999=5, d2d2d2=2, 444444=9, 474747=4, dddddd=1, 585858=8, 5a5a5a=3, 000=9887, afafaf=2, dfdfdf=3, 747474=3, 666666=4, a1a1a1=4, 2a2a2a=11, 4d4d4d=6, 818181=2, 878787=5, 215aa6=1, d9d9d9=4, b5b5b5=3, b4b4b4=3, 737373=4, aeaeae=3, bbb=15, 242424=4, 2d2d2d=8, 888=19, c1c1c1=1, 494949=9, dbdbdb=5, ccc=19, 5d5d5d=3, 5f5f5f=1, 414141=6, c8c8c8=3, aaa=16, 1e1e1e=3, 707070=2, 9e9e9e=2, 373737=7, 9d9d9d=2, 1b1b1b=4, 303030=7, 535353=10, 595959=2, 8e8e8e=3, 383838=5, 939393=18, 616161=2, 686868=6, dadada=1, e3e3e3=2, 5b5b5b=3, a4a4a4=5, 8c8c8c=5, a6a6a6=11, 292929=6, 4c4c4c=3, 151515=6, fefefe=2, 787878=2, 505050=2, e2e2e2=1, 1f1f1f=9, adadad=2, ababab=1, 5e5e5e=6, 252525=4, 4e4e4e=3, 282828=7, a8a8a8=4, 9c9c9c=3, aaaaaa=1, 101010=5, b7b7b7=2, 969696=6, 7f7f7f=4, 555555=2, a9a9a9=5, 343434=8, 999=17, 777777=3, ffffff=76669, f0f0f0=4, bbbbbb=1, 1e58a5=1, b3b3b3=4, 777=20, 636363=2, d4d4d4=1, 2c2c2c=5, 848484=1, 3c3c3c=3, bfbfbf=2, 3e3e3e=9, 333333=4, 7a7a7a=3, 858585=4, 4b4b4b=3, 272727=7, 111111=6, 666=13, 9b9b9b=1, bcbcbc=4, cfcfcf=2, 9a9a9a=1, 404040=21, 525252=3, 989898=4, 171717=5, 3b3b3b=2, c4c4c4=1, 3f3f3f=7, 464646=1, cdcdcd=2, b2b2b2=33, c5c5c5=2, bababa=2}
```
---
Please don't post 1.8 specific golfs suggestions, unless it works in older Java, me no want.
**Example:** Lambdas don't work in more versions of Java than they do work in.
[Answer]
# [Tcl/Tk](http://tcl.tk/), 134 bytes
```
console s
lmap s [concat {*}[[image c photo -fi $argv] d]] {dict inc D $s}
dict fo k\ v [lsort -int -s 2 -inde 1 -de $D] {puts $k\ $v}
```
`d` is for `data`.
# [Tcl/Tk](http://tcl.tk/), 232 bytes
```
console s
set I [image c photo -fi $argv]
set i 0
time {set j 0
time {dict inc D #[join [lmap s [$I g $i $j] {format %02X $s}] ""]
incr j} [image h $I]
incr i} [image w $I]
dict fo k\ v [lsort -int -s 2 -inde 1 -de $D] {puts $k\ $v}
```
##
`wish sort_pix.tcl QTE4O.png`
[](https://i.stack.imgur.com/IjIke.png)
---
`wish sort_pix.tcl 5s1Ob.png`
[](https://i.stack.imgur.com/RDD13.png)
---
`wish sort_pix.tcl z07VA.gif`
[](https://i.stack.imgur.com/3UDbL.png)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 1110 bytes
```
{{}({}[(()()()()()){}])}{}(<>)<>([]){{}({}()<({}()<({}()<>)>)>)<>([])}{}<>{({}<({}<({}<(()()<>)>)>)>)<>{(<>)<>(()()()){({}[()]<<>({}<([([(({})<>[({})]<>)])]<>)<>{({}()<([{}])<>({}<>)<>>)<>}{}<>{}<>>{})({}<({}<({}<>)<>({}<>)<>({}<>)<>>)<>({}<>)<>({}<>)<>({}<>)>)<>({}<({}<>)<>({}<>)<>>)<>({}<>)<>({}<>)>)}{}<>((){[()](<{}>)}{})((){[()](<{}({}())<>{}{}{}>)}{}){{}(<<>(()()()){({}[()]<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)}{}>)}{}<>({}<({}<>)<>({}<>)<>({}<>)<>>)<>({}<>)<>({}<>)<>({}<>)<>}({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}(()()()()){((({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}>)<{({}[()]<<>({}<>)>)}{}>)}{}<>}{}<>(()()()())([][()])({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>){({}[()]<(<(()()()())([][()])({}(<>))><>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)<{({}[()]<([([({}<({}<({}<({}<(({})<>)<>>)>)>)>)<><({}<>)>]{}<(())>)](<>)){({}())<>}{}({}<><{}{}>){{}<>(<({}<({}<({}<({}<({}<({}<({}<({}<>)>)>)>)<>>)>)>)>)<>({}<({}<({}<({}<<>>)>)>)>)>)}{}({}<({}<({}<({}<>)>)>)>)<>>)}{}<>{}{}{}{}>[()]){({}[()]<({}<({}<({}<({}<>)>)>)>)<>>)}{}<>>)}{}{({}[()]<>)<>}<>
```
[Try it online!](https://tio.run/##pVPJasMwEL3nK3yUDgVZqSGHQT9idEgOhZLSQ69C3@7OpsWOnVCKGC0zT7Pp6fZz/fx@@/i63pclpWxSno2xZdiUo82ohmAhmDlawRgL/RwsDQEgGkJCPVQhT4ohVFJvJQTHtBFQRegZB24QMdMSERx5FrcUdKa0BE5qEgmLgpPto4cO2F/Yt5Xd6xtBKsUqEmVvIGVW2V7D@VLimYbYqYOwU760CjsI0mNYdbQksYKLUu0lwH4Br0vHHv4nBdM4Y4wi0M@quorXbGHz9tXA8Up/1S3mwT6N0JEzw3MiQhBRaieFDXIdpO8tDTh2GP7isauMCNvTnZvIBNZahVZafojyJVAXOWwqJMna85Izlw8PrjfSArTdFtNs8lRPXOg/UsJy8Q9veHiPlwpnSkFYFndxg5vGwZ19t7q2TmeR0Z1Gfxk8YobBoaxPHjF@8qQ/@WnC/Xu1HJx@AQ "Brain-Flak – Try It Online")
Well that was an adventure. Turns out, Brain-Flak is not very good at image processing. Who knew?
I'll start off by noting that this technically doesn't meet the strict output format requested. If you want that enforced let me know and I'll try to add translation code. For now it outputs decimal numbers: each 4 numbers represents a color in the order RED GREEN BLUE COUNT.
Next up, input. Allowed input formats were more flexible so I used the format easiest for Brain-Flak to parse (that I could find): [Netpbm](https://en.wikipedia.org/wiki/Netpbm_format) P6. Unfortunately, Brain-Flak could not parse decimal numbers from the P3 format because all Netpbm images start with the character `P` and Brain-Flak can't handle decimal input from files containing non-numeral characters. So P6 was used instead, because P6 stores color information as bytes, which are treated as numbers in ASCII input mode. There remained a challenge because the header information was *not* encoded usefully, but fortunately I didn't need any of that information so it is just discarded. This program doesn't fully adhere to the Netpbm standard because it does not allow newlines within the header, but newlines are not *required* by the standard so the inputs are valid Netpbm files.
Last caveat, the version on TIO is actually not correctly configured for "official" operation because (to my knowledge) I can't supply files as input on TIO, nor could I supply bytes corresponding to unprintable ASCII in the direct input. For official operation the `-a` flag is needed to take input as raw bytes and `-f` to take input from a file. The sample input on the TIO link was instead manually translated from the example on the [Netpbm wiki page](https://en.wikipedia.org/wiki/Netpbm_format#PPM_example).
Additionally, I'd like to thank the Brain-Flak wiki for providing helpful snippets of code to work from. In particular, the Bubble-Sort implementation [here](https://github.com/DJMcMayhem/Brain-Flak/wiki/Stack-Operations) was instrumental to the final step once I had gotten a count for every color, since I didn't really have any idea where to start otherwise. It took heavy modification, but I'm glad I didn't have to start from scratch.
[Here](https://tio.run/##pVZta@M4EP5s/YqBfrEhhSS9HgvrNezdtUfhrl3SPWgo@aA4SizqSEFWmi4mv703I/lF3qa7cJdgx7HlmXmemXlGS8OlOl@X/On1NYqiM/gyu/ryeXYFZ4zV9TGuj49xnLTfpD4ukmN9pIX31sgdFIKvhIFnXu5FxeI0S9Isipylv7l5gqu7axY/LpKaXnK3/9J6B2ttQPC8gJ18ESVDN3GShucsoS/ZOoOvhqtqjV4uGj8jyAuuNgKMO1sNk/Pp5a/O0bFzdG/RUUneDoVQwMvSe6vANgaNWDGWZnUY2V5ZWYaLt/pZrMhHKdYWKsvzJ4afKGre@v3un9uvRBcGnnYHsdWA6CiJBmAoulyXmq7AFsLZR9I9h3FLuMtAskh7C9ctd3oNs9Gfo98Ig3P6iF@8wNcf6WeBlhbujBgbch8pg3453abjSNd04CnxkAqRP4FcgxIv1vMAEmkruPUhD8FmgcHQ8OlnWdLgmGnLrUCD2x3HTLgLrYSyBMy7aXD91HbHzQ9t@lpjWeIQR/0Ha2W/Bb6sdLnHt1dyjQkSKhcVSOW57gwh9DipKSVxWh@drSS809u8WWNmLS@hQuOfYExJVg2bW27zAs17mC43STSI6EblRvCKsGBJuoYJ@KeE1cfem3vlD1EKDN/bXg3gUv/Fabj4qkTbPhilLXwTtn2Rnag@X9PYXqkXBc@9bzefkLbIuuX@ZvO80wxtWq@EqMRkGZYlPRL2Ts5/Xlc@o1i8peAK9m1zBRVgUKkYG3J2jeyuwnbHOnlT5/8ReFOSAjXDWDhIW8BamsqixgxyBLzCTju0xdCLbRw3dtH7IBOdF@cnCx73XXZsqhN5QVJcEVEPGPEs9b6pPNjty9Krm21U2aUEKm2sVBsWcMXeds3Vi7SnFRabzxcuKWwglvd3M6@VHUjk0iGkHsC4Hbv4vyaxIhHratArlVertHboaFztqwLUfrvEoFvZqCC@nSTshHTOxE5gbm8nYOUW5xUOrPcjyf5fKHtFJDoNamKaJqxLVPQ2qGkbVEhx/oDS0Y2Kj9D/RXI/Qj4fzfFOJXKtGk8j/wyt@IEQTqW2zTBYiQpPTfLgFvqpQSXVzzW9@wZzKg0jNwXZ@36a@dqmjkYrzowvvYUfgLh04Yj0s8eTFoecOS9OqdERRwDOTE1L4iBrOIgeIIM5EePI@Q5TegLSiVXtNHZ1WEgc5vm8w4bRZ/0CL6dGd8Z6UWqPwfLA4JL2Bz7QUNfOIK4OfIdAlqLUB5gnBPW9ELs9VL9bwA1CtcUOazdbQWIAgEVNr/uxgOz2eWz1UKpcrlAIcSJtuFnyjQhKDeP7bNELjvmdlsqOUAjMBtML0ootTf9uH0ShLLW1eksYXD@8Uae3gIKpi1tDtAUaDZm2O4g20Ipqmw0GQtgiGAKKEhQImyLzk7ExsNIH1WzenNCT8HRhuW1OuAubiWdhcAC6pQQqbo2eZ6hoB7xKUNRkiXtMV@Pkt9ttjnG3eTlo05vtrpQ5quEOV9rX1/GHMYwvJzC@mAa/4/738sIfkzGbTD/AFNcAbhEAhv@muGZ6OaX7DH3i9S/dk3f@/Qs "Brain-Flak – Try It Online") is the ungolfed and commented version of the code. Brain-Flak is a bit too verbose to include a usefully formatted explanation right in this post, but the ungolfed version on TIO contains everything I would include in one with better formatting than I could manage here, so if you're interested please take a look.
There may be golfing yet to do, my [previous](https://codegolf.stackexchange.com/a/161083/71434) Brain-Flak answer went through a lot of revisions, but hopefully the lessons learned there gave this a better starting point.
[Answer]
# Python 2, 186 bytes
```
import Image
I=Image.open(input()).convert('RGB')
w,h=I.size
r=['#'+('%0.2X'*3)%I.getpixel((i%w,i/h))for i in range(w*h)]
for a,b in sorted(set((r.count(v),v)for v in r))[::-1]:print b,a
```
[Try it online!](https://tio.run/##HY7NCoJAFEb3PsVAyNxr0/TjTnDTJty2CqSF1U0v5Mwwjlq9vJmrDw4czuc@obEmnSZunfVBFG1VU1Tky2rryAAb1wdA1HdrBvIB5Pl0lBiNqskL3fGXIp@XciXXIOOdPlxkkmJc6JqC4ze9ADgeFW8bxKf1ggUb4StTE4xJg9foDyt1@@NuvkAP6CgA@LnXmwADqmERh0VELLNss79mzrMJ4qaqafoB)
Disclaimer: Presented outputs are one-liners for readability. Code outputs result with space and line separation as requested by challenge.
Output for 10red 20blue 30black 40white:
```
[('#FFFFFF', 40), ('#000000', 30), ('#0000FF', 20), ('#FF0000', 10)]
```
Ouput for blue gradient:
```
[('#718DFF', 19), ('#5571FF', 15), ('#8DAAFF', 11), ('#3855FF', 11), ('#AAAAFF', 7), ('#1C38FF', 7), ('#AAC6FF', 6), ('#8D8DFF', 6), ('#C6C6FF', 5), ('#C6E2FF', 4), ('#FFFFFF', 3), ('#E2E2FF', 3), ('#001CFF', 3)]
```
Output for test image
```
[('#FFFFFF', 18042), ('#000000', 1754), ('#FF3300', 204)]
```
Explanation:
```
w,h=I.size # field size stores tuple of values of width and height of image
I.getpixel((i%w,i/h)) # returns tuple of base10 RGB values
('%0.2X'*3) # format string to convert int into hex
set((r.count(v),v)for v in r) # generate set of unique pairs count-color
sorted(set(...))[::-1] # apply sorted(), as it sorts set of tuples by firts elements and reverse sort
print b,a # swap values in tuples and print
```
[Answer]
# SmileBASIC, 165 bytes
```
DEF C A
L=LEN(A)DIM C[L],N[L]FOR J=0TO L-1FOR I=0TO U-1ON A[J]-C[I]GOTO@L
NEXT
U=U+1@L
C[I]=A[J]INC N[I]NEXT
RSORT.,U,N,C
FOR I=0TO U-1?"#";HEX$(C[I],6),N[I]NEXT
END
```
Image is given as an array of 32 bit ARGB color values (the alpha value is trimmed when the number is converted to a 6 digit hex string)
] |
[Question]
[
Write a program or function where a matrix A (maximum value of dimensions of the matrix is 100) is transformed to a new matrix B. Each element of the new matrix B is the sum of the positive neighbors of the corresponding element of the matrix A.
Only neighbors in the four orthogonal directions are considered, and the edges do not wrap around.
Example input:
```
1 2 3
4 -1 -2
-3 -4 10
1 2 10
```
Output:
```
6 4 2
1 6 13
5 12 10
2 11 12
```
Rules:
* As input use integers.
* This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 9 bytes
```
t0>*1Y6Z+
```
[Try it online!](http://matl.tryitonline.net/#code=dDA-KjFZNlor&input=WzEgMiAzOzQgLTEgLTI7LTMgLTQgMTA7MSAyIDEwXQ)
### Explanation
The input matrix is multplied by an appropriate mask to make negative values equal to 0. Then a 2D convolution is applied to compute the sum of neighbours of each entry.
```
t % Take input implicitly: 2D array. Duplicate
0> % Is each entry positive? This gives a mask of positive values
* % Multiply: set negative values of input array to zero
1Y6 % Predefined literal: [0 1 0; 1 0 1; 0 1 0]
Z+ % 2D convolution preserving size. Implicitly display
```
[Answer]
# Octave, ~~46~~ ~~44~~ 40 bytes
~~Saved 2 bytes thanks to [@flawr](https://codegolf.stackexchange.com/users/24877/flawr)~~
[@LuisMendo's](https://codegolf.stackexchange.com/users/36398/luis-mendo) kernel was 4 bytes shorter than @flawr's.
```
@(M)conv2(M.*(M>0),(x='aba')~=x','same')
```
Just like [@LuisMendo's](https://codegolf.stackexchange.com/a/78652/42892) answer! Only less... golfy.
You can see it here on [ideone](http://ideone.com/ov2cuv).
[Answer]
## JavaScript (ES6), ~~99~~ 94 bytes
```
a=>a.map((b,i)=>b.map((_,j)=>(g=(c=j,k=j)=>c[k]>0&&c[k])(a[i-1])+g(a[i+1])+g(b,j-1)+g(b,j+1)))
```
Accepts and returns a two-dimensional array.
Edit: Completely rewritten when I discovered that default arguments work when you pass an explicitly undefined value, such as when you index off the end of an array.
[Answer]
# JavaScript (ES6), ~~95~~ 93 bytes
```
document.write("<pre>"+(
m=>m.map((a,r)=>a.map((_,c)=>(s=(x,y=0)=>(n=(m[r+y]||0)[c+x])>0&&n)(1)+s(-1)+s(0,1)+s(0,-1)))
)([[ 1, 2, 3 ],
[ 4, -1, -2 ],
[ -3, -4, 10 ],
[ 1, 2, 10 ]])
.join`\n`)
```
[Answer]
## Python with SciPy, 127 bytes
```
from scipy.signal import*
lambda A,r=range(3):convolve2d([[x*(x>0)for x in y]for y in A],[[0,1,0],[1,0,1],[0,1,0]],mode='same')
```
This computes the result using [Luis Mendo's method](https://codegolf.stackexchange.com/a/78652/45941).
[Try it online](http://sagecell.sagemath.org/?z=eJwli8EKhCAURfdB__B2abwGq1kNOOB3iAunNITUsIj6-1Ha3HfO416bood9ctv92t0S9ArObzEdbV1Zvmr_mzUITDzpsBgy0s8UwxnX0wwzkfJqyfVl1MYEF7gAtyp4FxQKpWTYI8uQE_t8H1fo42x4s2tvGlpXdSW4zB0YEEaFIN8IXdZuKNKNmfKnZ8WeVmZVdlty4QBLBP0DOjs3fQ==&lang=sage)
[Answer]
## Mathcad, bytes
Uses standard 2D convolution of the filtered array with a 3x3 kernel. Variants with negative element sums and diagonal kernel also added as part compensation for the program not being in the running for least bytes.
[](https://i.stack.imgur.com/hntnY.jpg)
---
No byte count entered as Mathcad scoring has yet to be determined. However, using keyboard equivalence, it is the region of 28 bytes assuming that matrix input doesn't count towards the total.
Note that what you see in the image above is exactly how the solutionn is entered and displayed in Mathcad.
[Answer]
# Jelly, ~~23~~ ~~20~~ 18 bytes
```
0;+ḊṖ
ZÇ€Z+Ç€
+AHÇ
```
[Try it online!](http://jelly.tryitonline.net/#code=MDsr4biK4bmWClrDh-KCrForw4figqwKK0FIw4c&input=&args=WzEsMiwzXSxbNCwtMSwtMl0sWy0zLC00LDEwXSxbMSwyLDEwXQ)
## Algorithm
Let's say there is only one row: [1,2,3,4].
Let's say A is the result of prepending a zero, i.e. [0,1,2,3,4].
B is the result of removing the first item, i.e. [2,3,4].
Then the final result is simply A+B vectorized, then removing the last item.
Now, the algorithm is to apply this to every row as well as every column, then find their vectorized sum.
### To each column?! I thought Jelly does not support this...
You're right. Therefore, I transposed it, applied to each row, then transposed it again.
### Algorithm for removing negative numbers
Here, you just add to each number their absolute. It effectively eliminates negative numbers while doubling each positive number. Then, just halve the whole matrix.
[Answer]
# Pyth, 36 bytes
```
Lm+Vt+d0+0dbJmm/+.akk2dQ.b+VNYyJCyCJ
```
[Try it online!](http://pyth.herokuapp.com/?code=Lm%2BVt%2Bd0%2B0dbJmm%2F%2B.akk2dQ.b%2BVNYyJCyCJ&input=%5B1%2C2%2C3%5D%2C%5B4%2C-1%2C-2%5D%2C%5B-3%2C-4%2C10%5D%2C%5B1%2C2%2C10%5D&debug=0)
Direct translation of my [answer in Jelly](https://codegolf.stackexchange.com/a/78820/48934).
] |
[Question]
[
### Challenge
Recognize ASCII art numbers. To make things interesting, three random points in the image might be flipped. For example:
```
*****
* **
**
**
**
**
```
### Input
A 7x7 ASCII art number generated by the below Python script.
### Output
A digit.
### Testing script
Here's a Python script (2.6+) to generate the test cases:
```
import random
digits = '''\
***
** **
** **
** **
** **
** **
***
*
***
*
*
*
*
*****
***
* **
*
**
**
**
******
***
* **
*
***
*
* **
***
**
***
* **
* **
******
**
**
*****
**
****
*
*
* *
***
****
**
*****
* *
** **
** *
****
*****
**
**
**
**
**
**
****
** **
** **
****
** **
** **
****
***
** **
** **
** *
****
**
**** '''.split('\n\n')
def speckle(image, num_speckles):
grid = [list(row) for row in image.split('\n')]
for i in range(num_speckles):
row = random.choice(grid)
row[random.randint(0, 6)] = random.choice([' ', '*'])
return '\n'.join([''.join(row) for row in grid])
digit = random.choice(digits)
print(speckle(digit, 3))
```
[Answer]
## APL (~~87~~ 85)
```
1-⍨⊃⍒(,↑{7↑'*'=⍞}¨⍳7)∘(+.=)¨{49↑,(16/2)⊤⎕UCS⍵}¨↓10 3⍴'嵝䍝뫂傁ဣ␋䠁䊫낫䢝䊅넂垵僡ᑨ嘙쐅嘹䜝䪀슪퀪岹亝尵䌧뮢'
```
Explanation:
Each possible ASCII number is encoded in 48 bits. (The 49th bit is always zero anyway). The string `嵝䍝뫂傁ဣ␋䠁䊫낫䢝䊅넂垵僡ᑨ嘙쐅嘹䜝䪀슪퀪岹亝尵䌧뮢` has three characters per ASCII number, each of which encodes 16 bits.
* `↓10 3⍴`: split the data string into 10 3-char groups, each of which encodes a number.
* `{`...`}¨`: for each of the groups:
+ `(16/2)⊤⎕UCS⍵`: get the first 16 bits of each of the three characters
+ `,`: concatenate the bit arrays into one array
+ `49↑`: take the first 49 elements. There are only 48, so this is equivalent to adding a `0` at the end.
* `,↑{7↑'*'=⍞}¨⍳7`: read 7 lines of 7 characters from the keyboard, make a bit array for each line where `1` means the character was a `*`, and join them together.
* `(+.=)¨`: for each possible digit, calculate how much bits the input had in common with the digit.
* `⍒`: get the indices for a downwards sort of that list, so that the first item in the result is the index of the largest number in the previous list.
* `⊃`: take the first item, which is the index of the digit
* `1-⍨`: subtract one, because APL indices are 1-based.
[Answer]
## Python
I'm sure there will be OCR solutions, but the probability of mine being accurate is much higher.
```
import difflib as x;r=range;s='2***3**1**1**3****3****3**1**1**3***23*4***6*6*6*6*4*****12***3*2**6*5**4**4**4******2***3*2**6*3***7*2*2**3***23**4***3*1**2*2**2******4**5**21*****2**5****7*6*2*3*3***22****2**5*****2*3*2**2**1**2*3****11*****5**5**4**5**4**4**42****2**2**1**2**2****2**2**1**2**2****12***3**1**1**3**1**2*3****5**2****2'
for c in r(8):s=s.replace(str(c),' '*c)
s=map(''.join,zip(*[iter(s)]*7));a=[raw_input("") for i in r(7)];l=[[x.SequenceMatcher('','|'.join(a),'|'.join(s[i*7:(i+1)*7])).ratio()] for i in r(10)];print l.index(max(l))
```
Input one line of text at a time.
Not sure of a better way to deal with the asterisks without increasing the character count.
[Answer]
# JavaScript (ES6), 89
```
f=n=>(a=1,[a=(a+a^c.charCodeAt())%35 for(c of n)],[4,25,5,16,0,11,32,13,10,1].indexOf(a))
```
**Usage:**
```
> f(" *** \n * ** \n * \n ** \n ** \n ** \n ******")
2
```
**Un-golfed version:**
```
f = (n) => (
// Initialize the digit's hash.
a=1,
// Hash the digit.
// 35 is used because the resulting hash is unique for the first ten digits.
// Moreover, it generates 4 1-digit hashes.
[a = (a + a ^ c.charCodeAt()) % 35 for(c of n)],
// Compare the hash to pre-computed digit hash.
// The matching hash index is the digit.
[4,25,5,16,0,11,32,13,10,1].indexOf(a)
)
```
[Answer]
# Bash+ImageMagick+tesseract, 316 chars
Here's a stab at an OCR solution. Its not very accurate though, even when telling tesseract that we have just one char and it is a digit. Moderately golfed, but still somewhat readable:
```
w=0
c()((w=${#2}>w?${#2}:w))
mapfile -c1 -Cc -t l
h=${#l[@]}
{
echo "# ImageMagick pixel enumeration: $w,$h,1,gray"
for y in ${!l[@]};{
for((x=0;x<w;x++));{
[ "${l[$y]:$x:1}" != " " ]
echo "$x,$y: ($?,$?,$?)"
}
}
}|convert txt:- i.png
tesseract i.png o -psm 10 <(echo "tessedit_char_whitelist 0123456789")
cat o.txt
```
The script takes input from stdin, so we can pipe from the test script.
Note I have put `tee >( cat 1>&2 )` in the pipeline just so we can see what the test script actually generated.
### Example output (This was a pretty good run with only 1 incorrect char out of 6):
```
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
***
** **
* **
** *
****
***
****
Tesseract Open Source OCR Engine v3.02 with Leptonica
9
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
*
*** *
*
*
*
*
*****
Tesseract Open Source OCR Engine v3.02 with Leptonica
1
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
***
** **
** **
** **
** **
* **
***
Tesseract Open Source OCR Engine v3.02 with Leptonica
0
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
*****
**
****
*
*
** *
***
Tesseract Open Source OCR Engine v3.02 with Leptonica
5
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
****
**
*****
* *
*** ***
** **
****
Tesseract Open Source OCR Engine v3.02 with Leptonica
5
$ python ./asciitest.py | tee >(cat 1>&2 ) | ./scanascii.sh
***
* **
*
**
***
**
******
Tesseract Open Source OCR Engine v3.02 with Leptonica
2
$
```
[Answer]
## LÖVE2D, 560 Bytes
```
t=...;g=love.graphics g.setNewFont(124)g.setBackgroundColor(255,255,255)A=g.newCanvas()B=g.newCanvas()x=1 y=1 g.setColor(255,255,255)g.setCanvas(B)g.clear(0,0,0)for i=1,#t do x=x+1 if t:sub(i,i)=="\n"then x=1 y=y+1 end if t:sub(i,i)=="*"then g.rectangle("fill",x*16,y*16,16,16)end end u=B:newImageData()g.setCanvas(A)S={}for i=0,9 do g.clear(0,0,0,0)g.print(i,48,0)r=A:newImageData()s={i=i,s=0}for x=0,16*8 do for y=0,16*8 do a=u:getPixel(x,y)b=r:getPixel(x,y)s.s=s.s+math.abs(a-b)end end S[i+1]=s end table.sort(S,function(a,b)return a.s<b.s end)print(S[1].i)
```
First, draws a blocky representation of the input text, then, for each number 0 - 9, overlays a number, checks how many similar pixels there are, and prints the number which got the closest. Very basic OCR. It matches all the Test Cases, and performs reasonably well with mutations.
Call with:
```
love.exe "" "INPUT"
```
] |
[Question]
[
You are given a 16-bit machine and told to implement multiplication of arbitrary-sized integers. Your registers can only hold 16-bit numbers, and the biggest multiply instruction takes two 8-bit inputs and generates a 16-bit result.
Your program must take as input two arbitrary-sized positive numbers and output their product. Each input number is encoded on its own line as a little-endian byte array where each byte is a 2-digit hex number. The output must be similarly formatted. Perhaps best explained with an example:
**input**
```
1f 4a 07
63 a3
```
**output**
```
fd 66 03 a7 04
```
which encodes the multiplication 477727\*41827=19981887229.
You can assume that the last (most significant) byte of each input number is nonzero, and the last chunk of the number you output must be nonzero. Both input numbers will be at most 100 bytes long.
Smallest code wins.
Remember, the biggest multiply you are allowed to use is 1 byte \* 1 byte, and no integer types bigger than 2 bytes!
[Answer]
# Perl, 137 characters
```
($x,$y)=<>;while($x=~s/.. *//s){$e=hex$&;$i=0;$s=$r[$i]+=$e*hex,$r[$i]&=255,$r[++$i]+=$s>>8 for$y=~/.. */gs;$y="00$y"}printf'%02x 'x@r,@r
```
## Caveats
* Sometimes prints an extra `00` byte at the end of the result. Of course the result is still correct even with that extra byte.
* Prints an extra space after the last hex byte in the result.
## Explanation
The explanation is going to be a bit long, but I think most people here will find it interesting.
First of all, when I was 10 years old, I was taught the following little trick. You can multiply any two positive numbers with this. I will describe this using the example of 13 √ó 47. You start by writing the first number, 13, and *dividing* it by 2 (round down each time) until you reach 1:
```
13
6
3
1
```
Now, next to the 13 you write the other number, 47, and keep *multiplying* it by 2 the same number of times:
```
13 47
6 94
3 188
1 376
```
Now you cross out all the lines where the number on the left is *even*. In this case, this is only the 6. (I can’t do strike-through in code, so I’ll just remove it.) Finally, you add all the remaining numbers on the right:
```
13 47
3 188
1 376
----
611
```
And this is the right answer. 13 √ó 47 = 611.
Now, since you are all computer geeks, you will have realised that what we’re actually doing in the left and right columns is `x >> 1` and `y << 1`, respectively. Furthermore, we add the `y` only if `x & 1 == 1`. This translates directly into an algorithm, which I’ll write here in pseudocode:
```
input x, y
result = 0
while x > 0:
if x & 1 == 1:
result = result + y
x = x >> 1
y = y << 1
print result
```
We can re-write the `if` to use a multiplication, and then we can easily change this so that it works on a byte-by-byte basis instead of bit-by-bit:
```
input x, y
result = 0
while x > 0:
result = result + (y * (x & 255))
x = x >> 8
y = y << 8
print result
```
This still contains a multiplication with `y`, which is arbitrary-size, so we need to change that into a loop too. We’ll do that in Perl.
Now translate everything to Perl:
* `$x` and `$y` are the inputs in hex format, so they have the *least* significant byte *first*.
* Thus, instead of `x >> 8` I do `$x =~ s/.. *//s`. I need the space+star because the last byte might not have a space on it (could use space+`?` too). This automatically puts the removed byte (`x & 255`) into `$&`.
* `y << 8` is simply `$y = "00$y"`.
* The `result` is actually a numerical array, `@r`. At the end, each element of `@r` contains one byte of the answer, but halfway through the calculation it may contain more than one byte. I’ll prove to you below that each value is never more than *two* bytes (16 bits) and that the result is always one byte at the end.
So here is the Perl code unravelled and commented:
```
# Input x and y
($x, $y) = <>;
# Do the equivalent of $& = x & 255, x = x >> 8
while ($x =~ s/.. *//s)
{
# Let e = x & 255
$e = hex $&;
# For every byte in y... (notice this sets $_ to each byte)
$i = 0;
for ($y =~ /.. */gs)
{
# Do the multiplication of two single-byte values.
$s = $r[$i] += $e*hex,
# Truncate the value in $r[$i] to one byte. The rest of it is still in $s
$r[$i] &= 255,
# Move to the next array item and add the carry there.
$r[++$i] += $s >> 8
}
# Do the equivalent of y = y << 8
$y = "00$y"
}
# Output the result in hex format.
printf '%02x ' x @r, @r
```
Now for the proof that this always outputs *bytes*, and that the calculation never generates values greater than *two* bytes. I’ll prove this by induction over the `while` loop:
* The empty `@r` at the beginning clearly has no values greater than 0xFF in it (because it has no values in it at all). This concludes the base case.
* Now, given that `@r` contains only single bytes at the beginning of each `while` iteration:
+ The `for` loop explicitly `&=`s all values in the result array with 255 *except the last one*, so we only need to look at that last one.
+ We know that we always remove only one byte from `$x` and `$y`:
- Therefore, `$e*hex` is a multiplication of two single-byte values, which means it’s in the range `0 — 0xFE01`.
- By the inductive hypothesis, `$r[$i]` is one byte; therefore, `$s = $r[$i] += $e*hex` is in the range `0 — 0xFF00`.
- Therefore, `$s >> 8` is always one byte.
+ `$y` grows an extra `00` in each iteration of the `while` loop:
- Therefore, in every iteration of the `while` loop, the inner `for` loop runs for one more iteration than it did in the previous `while` iteration.
- Therefore, the `$r[++$i] += $s >> 8` in the last iteration of the `for` loop always adds `$s >> 8` to `0`, and we already established that `$s >> 8` is always one byte.
+ Therefore, the last value stored in `@r` at the end of the `for` loop is also a single byte.
This concludes a wonderful and exciting challenge. Thanks a lot for posting it!
[Answer]
# OCaml + Batteries, 362 characters
A standard O(n\*m) schoolboy multiplication algorithm. Note that in order to meet the challenge requirements, the operations are done on the bytes of strings, which in OCaml are (conveniently, in this case) mutable. Note also that the accumulator `s` never overflows 16 bits, since 2(2^8 - 1) + (2^8 - 1)^2 = (2^8 - 1)(2^8 + 1) = 2^16 - 1.
```
let(@)=List.map
let m a b=Char.(String.(let e s=of_list(((^)"0x"|-to_int|-chr)@nsplit s" ")in
let a,b=e a,e b in let m,n=length a,length b in let c=make(m+n)'\000'in
iteri(fun i d->let s,x=ref 0,code d in iteri(fun j e->let y=code e in
s:=!s+code c.[i+j]+x*y;c.[i+j]<-chr(!s mod
256);s:=!s/256)b;c.[i+n]<-chr!s)a;join" "((code|-Printf.sprintf"%02x")@to_list c)))
```
For example,
```
# m "1f 4a 07" "63 a3" ;;
- : string = "fd 66 03 a7 04"
# m "ff ff ff ff" "ff ff ff ff" ;;
- : string = "01 00 00 00 fe ff ff ff"
```
[Answer]
**C Solution**
This solution does no input validation. It's also only lightly tested. Speed was not really a consideration. Malloc's memory, and isn't particularly clever about how much it grabs. Guaranteed to be enough, and more than necessary.
m() accepts a string, expects two newlines in the string, one after each number. Expects only numbers, lowercase characters, spaces, and newlines. Expects hex digits to always be a pair.
No multiply operation is ever used (knowingly). Shifting is performed on 8-bit variables. One 16-bit addition is performed. No 32-bit data types.
Shrunk by hand, and only mildly. **edit:** more obfuscation, fewer chars :D Compiles with warnings with gcc.
Characters: 675
```
typedef unsigned char u8;
#define x calloc
#define f for
#define l p++
#define E *p>57?*p-87:*p-48
#define g(a) --i;--a;continue
void m(u8*d){short n=0,m=0,a,b,i,k,s;u8*t,*q,*r,*p=d,o;f(;*p!=10;n++,l){}l;f(;*p
!=10;m++,l){}t=x(n,1);q=x(m,1);r=x(n,1);p=d;a=n;i=0;f(;*p!=10;i++,l){if(*p==32){
g(a);}t[i]=E;t[i]<<=4;l;t[i]|=E;}a/=2;b=m;i=0;l;f(;*p!=10;i++,l){if(*p==32){g(b)
;}q[i]=E;q[i]<<=4;l;q[i]|=E;}b/=2;f(k=0;k<8*b;k++){if(q[0]&1){o=0;f(i=0;i<n;i++)
{s=o+t[i]+r[i];o=s>>8;r[i]=s&255;}}f(i=n;i;i--){o=t[i-1]>>7&1;t[i-1]*=2;if(i!=n)
t[i]|=o;}f(i=0;i<m;i++){o=q[i]&1;q[i]/=2;if(i)q[i-1]|=(o<<7);}}k=(r[a+b-1]==0)?a
+b-1:b+a;f(i=0;i<k;i++){printf("%02x ",r[i]);}putchar(10);}
```
You can test with this:
```
int main(void){
m("1f 4a 07\n63 a3\n");
m("ff ff ff ff\nff ff ff ff\n");
m("10 20 30 40\n50 60 70\n");
m("01 02 03 04 05 06\n01 01 01\n");
m("00 00 00 00 00 00 00 00 00 00 00 00 01\n00 00 00 00 00 00 00 00 02\n");
return 0;
}
```
Result:
```
$ ./long
fd 66 03 a7 04
01 00 00 00 fe ff ff ff
00 05 10 22 34 2d 1c
01 03 06 09 0c 0f 0b 06
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 160 bytes
```
x=>y=>x.map((t,i)=>y.map(u=>(f=i=>(c=s[i]>>8)&&f(i++,s[i]=c+~~s[i],s[i-1]%=256))(i,s[i]=~~s[i++]+`0x${t}`*`0x${u}`)),s=[])&&s.map(t=>(t<16?0:'')+t.toString(16))
```
[Try it online!](https://tio.run/##TY3BbsIwEER/JQeKd3GIkkJThFhz4wc4oki2AkGu0jjCCwpC8OvBSS@9jObNSDM/5mZ8ebEtzxt3PPU76jtSd1Jd8mtaAI4tBh7hSgoqskFL8gdbKLXC6bQCK2U8MJXy9RrMQPOs@KDPrxwR7F87dlIWUqfd5MFPPRvN9akRY0@HIoz58YjDBW@yfJuuhUDJCbs9X2xzhizs9aVrvKtPSe3OsAORVdHSROm3SHxbW9aRRhD5IjKLfwn2bw "JavaScript (Node.js) – Try It Online")
Lot newer language than that time though
[Answer]
# 8086 DOS .COM file, 134 bytes
It works now!
What better language to do this in than 16-bit assembly?
```
00000000: b9 c8 00 89 cd 31 c0 f3 50 89 e7 e8 5d 00 92 aa .....1..P...]...
00000010: 74 f9 29 e7 87 fb 89 e6 8d 3a e8 4e 00 9c 56 57 t.)......:.N..VW
00000020: 89 d9 ac f6 e2 03 05 ab 83 15 00 4f e2 f4 5f 5e ...........O.._^
00000030: 47 9d 74 e6 80 39 00 74 01 4b 01 df 01 e5 29 ef G.t..9.t.K....).
00000040: 89 ee ac 88 c3 b1 04 d2 e8 e8 10 00 93 24 0f e8 .............$..
00000050: 0a 00 b0 20 e8 0d 00 4f 75 e8 cd 20 3c 09 76 02 ... ...Ou.. <.v.
00000060: 04 27 04 30 b4 02 88 c2 cd 21 c3 b2 00 b4 01 cd .'.0.....!......
00000070: 21 2c 30 72 0e 3c 0a 72 02 2c 27 b1 04 d2 e2 00 !,0r.<.r.,'.....
00000080: c2 eb ea 3c f0 c3 ...<..
```
My first, and likely last 16-bit 8086 program. üò´
Assembly (NASM with C comments because of syntax highlighting):
```
// sed -i -e 's#//#;#g' dosmult.asm
// nasm -f bin dosmult.asm -o dosmult.com
// The default, but never harmed anyone.
[bits 16]
// 8086 code only! If I use 386 instructions or any of that,
// I would ruin the challenge.
[cpu 8086]
// COM files start at 100h.
org 100h
section .text
start:
// Create a 400 byte buffer on the stack.
// 200 will be reserved for the input, and 200 for the output.
mov cx, 200
// Save 200 in BP for later, it will be useful.
mov bp, cx
// Push 0 200 times making a 400 byte zeroed buffer on the stack
xor ax, ax
rep push ax
mov di, sp
// Read the first line of hex digits.
.getline_loop:
call gethex
// Swap DL to AL and store with STOSB
xchg dx, ax
stosb
// Loop if it was a space
jz .getline_loop
// Get length
sub di, sp
// Store length in BX
xchg di, bx
// Save the pointer to input in SI
mov si, sp
// Load the pointer to output in DI (SI + 200)
lea di, [si + bp]
// Begin multiplication, grade school byte by byte
// Instead of creating a third buffer, we process the data
// as the user inputs it.
.loop:
call gethex
// Save flags from gethex so we know when to stop
pushfw
// Save SI and DI
push si
push di
// Loop counter
mov cx, bx
.mult_loop:
// Load next byte from first input
lodsb
// Multiply by the input byte
mul dl
// 16-bit add to [DI]
// We actually add to AX, then do STOSW.
add ax, [di]
stosw
// Add the carry bit.
adc word [di], 0
// Decrement DI after STOSW incremented it by 2 to iterate
// on each byte.
dec di
// while (--cx)
loop .mult_loop
.mult_loop_end:
// Restore DI and SI
pop di
pop si
// Increment output pointer
inc di
// Restore flags from gethex
popfw
// Jump if we got a space.
jz .loop
.loop_end:
// Was there a trailing zero?
cmp byte[di + bx], 0
jz .nodec
.dec:
// If so, decrement the count.
dec bx
.nodec:
// Calculate the length with ugly pointer arithmetic.
// I feel there is a better way to do this.
add di, bx // ptr += len
add sp, bp // sp += 200 (sp = output)
sub di, sp // ptr -= output
// Store output array in SI.
mov si, sp
// Print each byte in hex
.print_loop:
// Load byte
lodsb
// puthex(AL >> 4)
mov bl, al
mov cl, 4
shr al, cl
call puthex
// puthex(AL & 0Fh)
xchg ax, bx
and al, 0Fh
call puthex
// putc(' ')
mov al, ' '
call putc
// Loop for every byte from DI.
dec di
jnz .print_loop
.print_loop_end:
// exit, not bothering to clean anything up. :P
int 20h
// Prints hex digit in AL.
// Must be <= 0fh
puthex:
cmp al, 9
jbe .no_hexa
.hexa:
add al, 'a' - '9' - 1
.no_hexa:
add al, '0'
// Fallthrough
// Prints AL to stdout.
putc:
mov ah, 2h
mov dl, al
int 21h
ret
// Reads a hex byte.
// Returns in DL.
// Sets whether it ended in a space in the Z flag.
gethex:
mov dl, 0
.start:
// Read char into AL
mov ah, 1h
int 21h
// Subtract ASCII '0'
sub al, '0'
// If we hit a space or newline, they will trigger the 'below'
// condition
jb .ret
// Was AL '0'-'9'? If not, correct it to 'a'-'f'.
cmp al, 10
jb .no_hexa
.hexa:
// Correct AL
sub al, 'a' - '9' - 1
.no_hexa:
// DL = (DL << 4) + AL
// 8086 doesn't have shift by immediate.
mov cl, 4
shl dl, cl
// Add to BL
add dl, al
// Loop
jmp .start
.ret:
// Check if AL before the subtraction was a space.
cmp al, ' ' - '0'
ret
```
Naturally, being a 16-bit instruction set, I am only doing 8-bit and 16-bit arithmetic (and I don't use the 16-bit `mul`).
Beats the Perl answer by 3 bytes. Granted, this is binary machine code and that is source code, so I guess this isn't that much to get excited about. However, 8086 lacks a lot of the features Perl has (about 1/3 of it is just I/O and hex conversion üò´).
I am sure there are multiple optimizations possible here. A lot of my knowledge is from writing 32-bit and 64-bit code, so I am not fully knowledgeable in the 16-bit tricks.
Input is from stdin, in space separated lowercase hex, each ending in a new line. It is not line buffered, so no typos allowed! :P
Output is printed to stdout.
] |
[Question]
[
A finite-permutation is a function which takes an \$n\$-tuple and produces an \$n\$-tuple such that every element of the input is present in the output, and the ordering does not rely on the values of the inputs.
We can unambiguously represent these permutations with an \$n\$-tuple where each element is the index of where it will end up. For example:
$$
(3 \,\, 2 \,\, 1 \,\, 0)
$$
This permutation reverses a \$4\$ element tuple. The first element goes to the 3rd (last) position, the second goes to the 2nd (penultimate) position etc.
With this representation a valid permutation is just any list of size \$n\$ which contains the numbers \$0\$ through \$n-1\$.
Now if we want let's apply a permutation, \$(5 \,\, 2 \,\, 1 \,\, 4 \,\, 3 \,\, 0)\$, but first lets color 3 elements red.
$$
(A,\color{red}{B},C,\color{red}{D},\color{red}{E},F) \\
\underset{\,(5 \,\, 2 \,\, 1 \,\, 4 \,\, 3 \,\, 0)\,}{\xrightarrow{}}\\
(F,C,\color{red}{B},\color{red}{E},\color{red}{D},A)
$$
Now if we just look at how the permutation effects the order of highlighted elements we get:
$$
(\color{red}{B},\color{red}{D},\color{red}{E}) \\
\longrightarrow{}\\
(\color{red}{B},\color{red}{E},\color{red}{D})
$$
Which is the permutation \$(0\,\,2\,\,1)\$.
One permutation is a *sub*-permutation of another if it is the permutation acting on some subset of the elements of the tuple. So
$$
(0\,\,2\,\,1)\subseteq(5 \,\, 2 \,\, 1 \,\, 4 \,\, 3 \,\, 0)
$$
by the example shown above. Every permutation is a sub-permutaton of itself.
## Task
Given two permutations \$A\$ and \$B\$ determine if \$A\$ is a sub-permutation of \$B\$. You should output one of two distinct values. One if \$A\$ is a sub-permutation of \$B\$ and the other if a does not.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the goal is to minimize your source code as scored in bytes.
You may take permutations in any reasonable format, this includes formats that use 1 indexing instead of 0 indexing.
## Test cases
```
[] [0,1,2] -> True
[0] [0,1,2] -> True
[0,1] [0,1,2] -> True
[0,1,2] [0,1,2] -> True
[1,0] [0,1,2] -> False
[0,1,2,3] [0,1,2] -> False
[] [2,1,0] -> True
[0] [2,1,0] -> True
[0,1] [2,1,0] -> False
[1,0] [2,1,0] -> True
[0,2,1] [2,1,0] -> False
[0,2,1] [3,2,1,0] -> False
[0,2,1] [5,2,1,4,3,0] -> True
[0,1,2] [5,2,1,4,3,0] -> False
[2,1,0] [5,2,1,4,3,0] -> True
[1,2,0] [5,2,1,4,3,0] -> True
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 25 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⍺≡∊(⊂⍺)∩⍋⍤,¨⊃,/(⊢,,¨)\⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37Uu@tR58JHHV0aj7qagBzNRx0rH/V2P@pdonNoxaOuZh19oMQiHSBHM@ZR79ZaAA&f=e9Q31dNf4VHbBAUDhUfdLQrpYHbao96lj/qmegX7@3GpR8eqK0BBuoJ6tIGOoY4RXOhR71yFkKLSVKAyA7ggfmU6hlBhQsqgEniVGeoY4DXNLTGnGG6cjjFQDr86VL8a6SDMx@NX3MpQ/IqpDGYrqi/wGGcENRC/cajqjHWQVeJWZwpWZ6JjDFaLMyowlcGMQ1iD2zgA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
`⊃,/(⊢,,¨)\⍵` generates all non-empty subsequences and is taken from [this tip](https://codegolf.stackexchange.com/a/211449/64121).
`⍋⍤,¨` converts each subsequence to a sub-permutation by getting the indices that would sort the sequence.
`(⊂⍺)∩` intersects that list of sub-permutations with the left input.
`⍺≡∊` checks if the flattened result of that matches the left argument.
Without dealing with the empty list the last two steps could be `(⊂⍺)∊`, adding the empty list to the sub-permutations would be longer: `(⊂⍬),`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
ṗv⇧$c
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZd24oenJGMiLCIiLCJbNSwyLDEsNCwzLDBdXG5bMiwxLDBdIl0=)
Port of Jonathan Allan's Jelly answer.
```
ṗ # Powerset
v⇧ # Grade up each
$c # Is the input contained in that?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
æεD{kQ}à
```
Inputs are in the order \$B,A\$.
[Try it online](https://tio.run/##yy9OTMpM/f//8LJzW12qswNrDy/4/z/aVMdIx1DHRMdYxyCWKxrENogFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVC6P/Dy85tdanOjgisPbzgv87/6OhoAx1DHaNYnejYWB0FBM8AjatjiCEApFGEDHUMsKjRMYYIGumA5GHWwHgGaFyYNTABuJkIFUYwNcY6WARNwYImOsaEJODOR5WAGBkbCwA).
**Explanation:**
```
æ # Get the powerset of the first (implicit) input-list B
ε # Map over each list:
D # Duplicate the current list
{ # Sort the copy
k # Get the index of each value in the list
Q # Check if this is equal to the second (implicit) input-list B
}à # After the map: pop and push the maximum to check if any was truthy
# (which is output implicitly as result)
```
[Try it online with step-by-step debug lines.](https://tio.run/##VU@9TsMwEN77FKfMHgqUBQlloBKqxNK56mCSi3xq5DP2mRBVLDwJExMrPADsPAQvEhyHorJ9p@/3OOhbwmEoVtZFCRdQlMuyAG3rhFbq472cFdcoIAbBcYc@pIObfDfkgwCNxtH3@XKZ5TfMDvgePaCuTOJtgi0FUTnWxWBAQ2AvWEPFrs@l30@v@/91ZGt8OHQdyRPxy5OQbnN0Hv71ttzvHqcRVwarHTR8GNEACeBd1G2Y8rDiNOZvfKpfHzuTQdseOp3kPorpFXSGxqTJ7zHEdnr7WQ3D5lydqhO1UGdqvp1tRjzf/gA)
[Answer]
# JavaScript (ES6), ~~74~~ 70 bytes
Expects `(A)(B)` in 1-indexing format. Returns \$0\$ or \$1\$.
```
A=>F=([v,...B],C=[0])=>v?F(B,C)|F(B,[...C,v]):A.every(i=>~~v<(v=C[i]))
```
[Try it online!](https://tio.run/##jZHLDoIwFET3/ghtcm3koQtjMdCEL3BXuyBYFEPAADYhMfw6grIQ5eGqzZyZ9M7t1Vd@HmTRrVgm6UnWIa0dansUcQWEEFcAo3wlMLXV3kMuMPxoD94wBkrgrUOkklmJImpXldohRRmPBMZ1kCZ5GksSp2ek8UN2Ly6l0PDiUw8RFxhxHQwwm8w30ychGDO41ccNLTMbpo89PAZf6kQWzPdkm/YCa7AGbV38x9bzaceEe36cDy2ui0/2B@uPDc4WmTVYMG7pfqHfsn4C "JavaScript (Node.js) – Try It Online")
### Commented
```
A => // A[] = candidate sub-permutation
F = ( // F is a recursive function taking:
[v, // v = next value from the main permutation
...B], // B[] = remaining values in the main permutation
C = [0] // C[] = subset of B[], with a leading 0 to take
// 1-indexing into account
) => //
v ? // if v is defined:
F(B, C) | // try a recursive call where C[] is left unchanged
F(B, [...C, v]) // try a recursive call where v is added to C[]
: // else:
A.every(i => // for each entry i in A[]:
~~v < (v = C[i]) // make sure that v is less than C[i]
// (v is initially undefined and coerced to 0)
// and update v to C[i]
) // end of every()
```
[Answer]
# [Factor](https://factorcode.org/), 47 bytes
```
[ all-subseqs { } suffix [ arg-sort ] map in? ]
```
[Try it online!](https://tio.run/##jZPBCsIwDIbve4r4AJO104uC3hQvXtSTeKijk8HcZtOBInv22m0q6tJhSiGkX37SpI1FpHNldpvVejkBgZhHCCgvpcwi@eEN5VUrUQc0QqGk1rdCJZmGqefdPbB2t6uyOwAG3HoVfNoA/BlsVSnfbOCkKZY5aJrlJN1lmbOKhl2IFH@FQyKBgGuIP/X/6wRFuzvRpYkimFOaEuYOabIVLzj8wXvhceONbFKb0Dc8kv0W5u8LuoUrsweRpj6WR/uWsZkMlnGcXMEeqJOPudJwgLMoIMnmcDBx@wtmdWRoHg "Factor – Try It Online")
Is the first input in the inverse permutations of the subsequences of the second input?
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Or only 5 bytes for a count of the ways - `ŒPỤ€ċ`
```
ŒPỤ€e@
```
A dyadic Link accepting the permutation on the left and the potential sub-permutation on the right (both 1-indexed).
**[Try it online!](https://tio.run/##y0rNyan8///opICHu5c8alqT6vD/UcOMw8sd9IGc//@jo6NjdaINdAx1jGJjuXSiow3QuDqGGAJAJoqQoY4BFjU6xqiCQJ6RDkgp3BpkLtgaJAGImSgqjNDVwISMdbAImoIFTXSMkawAOxxDAqIZXSIWAA "Jelly – Try It Online")**
### How?
```
ŒPỤ€e@ - Link: permutation, P; potential sub-permutation, S
ŒP - powerset (i.e. all sub-sequences) of P
€ - for each:
Ụ - grade up (1-based indices sorted by their respective values)
@ - with swapped arguments - f(S, that):
e - S exists in that?
```
[Answer]
# Python3, 117 bytes:
```
f=lambda x,y,p=0,q=0:not x or(y and(k:=(x[0]-p>=0)==(y[0]-q>=0))and any([f(x[k:],y[k:],x[0],y[0])*k,f(x,y[1:],p,q)]))
```
[Try it online!](https://tio.run/##dZLNboMwEITP5SlWuWBXmwhCK1VIzrHHnnoDVDmJUa0Q49huFaS@O11o0ioJvSDvzDfrn8V24b012ZN1fV@LRu7XWwlH7NCKBA8iyU0b4AitYx1Is2W7XLBjkVRzuxIJF4J1Q3EYCk4@MR0rakJ2eYXd@B1wHDB@v0OyaJ2SbPHAK857vbetC@AUgvQh8mI2mxUVFAmmuKxgvoJX96Eiyk9omE6rQ32jp3jZ41k2/oxjNmWRtsQxdnGMG208xp96Sv/sdwsvp/GzkeG/1uNoPWB2vf1432v3FD51mwzTW0d160CDNlDrJijHXlpDs/ALbxsdWFyamPM8upO4xg0I2EvLaFALMpWTzZv6lA3S@H55X87LVem/Sh8jaM4p6r2iEdeMetA/s4ms04bQoHzwYAd7G/P@Gw)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 38 bytes
```
MemberQ[(o=Ordering)/@Subsets@#2,o@#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zc1Nym1KDBaI9/WvygltSgzL11T3yG4NKk4taTYQdlIJ99BOVbtfwBQoiQ6Lbq6VqfaUMdIx7g21tY2pKg0NZYLLmWIT07HCL8sUBy3vJEOitluiTnFGNp1TPApAcoZ64CMwe5snHJgZ8Nl0U2FuAu3ZmP82mEKTHQIKjEDKzHVMcHlTHD4oalCNwxiCyHDQGGJS9V/AA "Wolfram Language (Mathematica) – Try It Online")
Expects f[A,B].
] |
[Question]
[
### The challenge:
Assuming you have \$ X \$ collections, each collection \$ C\_i \$ has a name \$ N\_i \$ and a capacity \$ N\_i \$ of elements - Determine which collection will be overflowed first while counting the occurrences of the names in a cyclic list. Also print how many cycles of the list occurred.
**Example**:
4 Collections are available:
* Name: "cat", Capacity: 3
* Name: "dog", Capacity: 4
* Name: "parrot", Capacity: 1
* Name: "otter", Capacity: 5
Given the list: `["dog","cat","parrot","otter","otter","cat","parrot","cat","cat","dog"]`, "parrot" collection will be overflowed first, since we've counted two "parrot"s to the "parrot" collection which has a capacity of 1. At the point of the overflow, there were only 1 dog, 2 cats, 2 otters - these collection are still capable to get more elements. 0 cycles occurred in that case.
Another example that demonstrate the cyclic property:
For the same collections, given the list: `["dog","cat","cat","parrot","otter"]`, "cat" collection will be overflowed first, since after reading the last element "otter", we continue reading the list again from the start ("dog"), and we are reaching 4 cats before any other collection reaches the capacity. 1 cycle occurred in that case.
---
### Assumptions:
* Collections with \$ C\_i = 0\$ are possible.
* In case there will never be an overflow, the program should print falsely value.
* It is possible to meet elements in the list that has no collection to be counted into, although you can assume all elements in the list contains `[A-Za-z]` characters only.
* Name of a collection contains `[A-Za-z]` characters only.
* Names of collections and elements are case sensitive.
* It is possible to get no collections or an empty list as an input.
---
### Input:
* A list of collections, each collection has a name and capacity. (You can pass the names and the capacities in two different arguments that keep the relative order).
* A list of elements, each element.
You can pass the input in any sensible way. Possible options:
```
[[["cat",3],["dog",4],["parrot",1],["otter",5]],["dog","cat","parrot","otter","otter","cat","parrot","cat","cat","dog"]]
[["cat",3,"dog",4,"parrot",1,"otter",5],["dog","cat","parrot","otter","otter","cat","parrot","cat","cat","dog"]]
["cat","dog","parrot","otter"],[3,4,1,5],["dog","cat","parrot","otter","otter","cat","parrot","cat","cat","dog"]]
cat,3
dog,4
parrot,1
otter,5
dog,cat,parrot,otter,otter,cat,parrot,cat,cat,dog
```
---
### Output:
* The name of the collection that will overflow first.
* The amount of reading cycles on the list.
or falsely if no collection will ever be overflowed.
---
### Scoring:
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest bytes wins.
---
### Test Cases:
```
[[["cat",3],["dog",4],["parrot",1],["otter",5]],["dog","cat","parrot","otter","otter","cat","parrot","cat","cat","dog"]] --> "parrot",0
[[["cat",3],["dog",4],["parrot",1],["otter",5]],["dog","cat","cat","parrot","otter"]] --> "cat",1
[[["cat",7],["dog",8]],["dog","cat"]] --> "cat",7
[[["cat",7],["dog",8]],["woof","meow"]] --> False
[[["cat",7],["dog",8]],["Cat","Dog"]] --> False
[[["cat",1],["dog",0]],[]] --> False
[[["cat",0],["dog",0],["parrot",1],["otter",5]],["otter","otter","otter","otter","otter","parrot","dog"]] --> "dog",0
[[],["dog","cat"]] --> False
```
[Answer]
# JavaScript (ES6), 63 bytes
Expects `(c)(a)`, where `c` is an object holding the collections (keys = names, values = capacities), and `a` is the list of items.
Returns either `[name, count]` or `0`.
```
(c,e=n=0)=>g=a=>a.every(s=>~--c[e|=c[s],v=s])?e&&g(a,n++):[v,n]
```
[Try it online!](https://tio.run/##vZTfa4MwEMff91dIHkpCY6tso0WIe9jYPyE@hHjKhk1KIpaxH/@607Q6cBWyMnsPOZJcch9y38srr7kR@mVf@VJl0OSswYICkywgLC4YZzFfQQ36DRsWf/m@SOCDicSktGYmJQ@wWBSYU7lckiipqUwboaRRJaxKVeAcvyPBKxTdUpSpAkV3FO251qpdCilSVQUaRfefBCd2n9roIaaP@PGj7eP0OHbnU0I8b732hojg5j9wzkLZXA7W4dgLwvMsmxPLdpTW9f6/2MCycWE5KJW3MDtQhxloWpZnXhpwIXm0BXjqK3xVkvBEEnQkc6R3Jgl6kmnVjvtlyg9azibetFOK1eKvDrqCTC@qT2jBRn/BXP0TNt8 "JavaScript (Node.js) – Try It Online")
### Commented
```
( c, // c = object describing the collections
e = // e = flag to detect whether at least one item requested in the
// list has a non-zero capacity
n = 0 // n = cycling counter
) => //
g = a => // g is a recursive function taking the list of items a[]
a.every(s => // for each value s in a[]:
~--c[ // try to decrement c[s] and apply a bitwise NOT on the result
e |= c[s], // set e if c[s] is non-zero (before being decremented)
v = s // set v to s
] // this yields 0 if and only if c[s] is defined and was set to 0
// (if c[s] is undefined, --c[s] is NaN and ~--c[s] is -1)
) ? // end of every(); if truthy:
e && // abort if e = 0, so that we don't loop forever
g(a, n++) // otherwise, increment n and do a recursive call
: // else:
[v, n] // return the result pair
```
[Answer]
# [Io](http://iolanguage.org/), ~~157~~ 153 bytes
```
method(~,\,(if(X := ~values max,X,0)* ~size)repeat(i,if(~hasKey(x := \at(i% \size)asString)and~atPut(x,~at(x)-1)at(x)<1,return list(x,(i/ \size)round))))
```
[Try it online!](https://tio.run/##rY9BS8QwEIXv/RVDQcjIiFtUFNGT3kQQvOyhl7BNdwPdpCSpVA/56zVp3ODKungwh0xm8t6XF6mnFm7voZ62wm10wzzVxGTLlnHq33g3CAtbPtKSFngK3soPgUb0gjsmKQj9htsn8c7GGROnJ1DPKm5fnZFqjVw1nruXwbGRwoGNeFbhXO8qMsINRkEnbbxm8vzLbfSgGgxrahk8854hrDqtBCRSueKupAvctY1el3SZ254bo4OgyhPtnDAlXSEVAOm5ZEqk7NgJc/1xndq0Rz8CQh@@6TpVFEeiXu9HvTmc4z9oD3O2x5jtb7BqH7b4BvudcDh@lk@f "Io – Try It Online")
## Explanation (Ungolfed)
```
method(a, b, // Take inputs a & b.
(if(X := a values max, X, 0) // The max of an empty list is nil, so we gotta return 0 if max is nil.
* a size) repeat(i, // Repeat max of capacities * dict size:
if(a hasKey(x :=b at(i%b size)asString) // If the dict a has (x := b's current cyclic index)
and a atPut(x,a at(x) - 1)at(x) < 1, // And decrementing that index results in 0:
return list(x,(i/b size)round) // Return [x, iteration # / size of list]
)
) // After the Repeat: If nothing is returned from the if expression,
) // a falsy value will be returned by default.
```
[Answer]
# [R](https://www.r-project.org/), 99 bytes
```
function(e,k)(which(sapply(rep(e,sum(unlist(k))),function(y)k[[y]]<<-k[[y]]-1)<0)[1]-1)%/%length(e)
```
[Try it online!](https://tio.run/##rZLfaoMwFMbvfQrJKCQQmbKNDmZ2s7GXkF6IO1YxJpLEiU/vbKxZLSsrnTc5@XPO@X1JPjXIL1A5lx0b8lZkppQCA60I7ooyK7BOm4b3WEEz7uq2xq3gpTa4IoRQV9CTKkn63S6Og2kSRCQOSRIdJpv7DQexNwUGMmSSc7BFmtlGKEsNYg8Ufco9Yo8UNalSctyKKJLGgELsibwAhxqE0SzDNpHaMpc8p/7Es@NpOY2HeuLf@UHw6ruM0JvfAc8seqKVeN7Kyn/V72TZ0@hWTdujpudL@CVnuzKnkzIfQTXIzpE@Uq5hZc6bfcL3k@/8FyU6UsIFZZXW4dz6CpOcO/lSdNZZ@Nn@8Q1m/sspV11/@AY "R – Try It Online")
Accepts 'elements' as a character vector and 'collections' as a named list of capacities.
Returns the element name and the number of full cycles at overflow, or `NA` if overflow never happens.
**How?**
```
overflow=o=
function(e,k) # e=elements, k=collections
(which( ... )[1] # get the first index of...
sapply( # a loop over...
rep(e,sum(unlist(k))), # ...lots of repeats of the elements...
function(y) # ...at each loop returning...
k[[y]]<<-k[[y]]-1 # ...the number of free spots left in the collection,
)<0 # that is less than zero,
-1)%/%length(e) # minus 1, DIV the number of elements
) # (so it's the number of complete loops,
# rather than the loop-in-progress)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~62~~ 46 bytes
```
¿Φθ№η§ι¹«W¬Φυ№θκFη⊞υ⟦№Eυ§λ¹κκ⟧⟦⊟§Φυ№θι⁰I⊖÷LυLη
```
[Try it online!](https://tio.run/##dY8xa8MwEIXn5FccniRQIaHt1Cm4FDwEsgsNQlaiI7Zky3JoU/rbVSmxSjt0Oe6O9713p4z0yskuxt004cmSN@yC9mRkULvZBmIY7EJjW/1OkMGGUspgpC/rv3JT5Hs5ZLYg3Q1hgLmYhOERyEjhc71aDPZosZ/7AjY2vOIFW01@pW7p/9dk42syXh2dB9JY5XWvbdAtuVIKt6WhcJgnQ2YG56w8eExWvBgtL8wlI13BsQz1h@p0bdxwp/MnIkdu8klyCilFJM@vGDnnlZKhYo@C8ap1p4o95W6Q3ru03ubBhRRVsWfxo7kzSy3aRSdEfLh03w "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of `[capacity, name]` pairs and an array of elements. Explanation:
```
¿Φθ№η§ι¹«
```
If there are no collections with an element, do nothing (falsy value), otherwise:
```
W¬Φυ№θκ
```
Repeat until an element causes the collection to overflow...
```
Fη⊞υ⟦№Eυ§λ¹κκ⟧
```
... for each element in the input, push its previous appearance count and the element to the predefined empty list. If the pair appears in the collection, this means that we had already exhausted it and this element now makes the collection overflow.
```
⟦⊟§Φυ№θι⁰I⊖÷LυLη
```
Get the first element to overflow, plus calculate the number of iterations of the above loop and decrement it, which gives the number of whole cycles.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 95 bytes
Input is a dictionary and a list. This outputs an empty set if no collection overflows, a tuple otherwise.
```
f=lambda c,l,n=0:{*c}&{*l}and(c[(x:=l.pop(0))]and f({**c,x:c[x]-1},l+[x],n+1)or(x,n//-~len(l)))
```
[Try it online!](https://tio.run/##nZJRb4MgEMff/RSEhwXsddV0yxoSn7ZvYXxwiJsJAkGSuhj31R21tWvt6sNeOLj73R3/A/PlPrXa7owdhjKRef1e5IiDBJVErAt5/9CFss9VQXhKWpbIR6MNiSjNvA@VpAtDDi3jaZut4x7kym9ArWKqLWlBbTbrbykUkZTSwYnGNShBaYAQ6TDPHWZbwIX@wOwJsMmt1d4VA9bOCYvZcw8oHeMw0mdmIn7tLHw8HtdDfkbh/03/bH1d8eVUcTdLXqL2Wpceq4XeL3KvY/u3GxXxiYoO1HUomkL3Bc4HeM@eZV@OcVHldK94pC7fIMiCoNQWcS2l4K7SClDlRN2gSqHxdzBfx9hKOVKSG8p/oR8 "Python 3.8 (pre-release) – Try It Online")
In Python 3.9 this will be 2 bytes shorter as `{**c,x:c[x]-1}` can be replaced by `c|{x:c[x]-1}` due to [this change](https://www.python.org/dev/peps/pep-0584/).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
åài¹ÞvÐyk>©è<D0‹iyN¹g÷‚që®ǝë0
```
First input is the list of names, second is a flattened list of collections.
[Try it online.](https://tio.run/##yy9OTMpM/f//8NLDCzIP7Tw8r@zwhMpsu0MrD6@wcTF41LAzs9Lv0M70w9sfNcwqPLz60Lrjcw@vNvj/P1opJT9dSUcpObEEThYkFhXlgxj5JSWpRUqxXNEQCWMdiGIThBJDmCId01gA)
**Explanation:**
```
å # Check for each string in the first (implicit) input-list if
# it's in the second (implicit) input-list
ài # If any is truthy:
¹ # Push the first input-list again
Þ # Cycle it indefinitely
v # Loop over each name `y`:
Ð # Triplicate the collection list (which will use the implicit
# second input-list in the first iteration)
yk # Get the index of name `y` in this list
> # Increase this index by 1
© # Store it in variable `®` (without popping)
è # Use this index+1 to index into the collection-list again
< # Decrease this integer by 1
D0‹i # If this count is now negative:
N # Push the loop-index `N`
¹g # Push the length of the first input-list
÷ # Integer-divide the index by this length
y ‚ # Pair it with name `y`
q # And exit the program
# (after which this pair is output implicitly as result)
ë # Else (the count is still 0 or positive):
® # Push the index from variable `®`
ǝ # And insert the new count back into the collection-list at
# this index
ë # Else (none of the names is in the collection-list)
0 # Push a 0
# (after which it is output implicitly as falsey result)
```
NOTE: We could omit the final `ë0` so it will implicitly output the second input as falsey result, since only `1` is truthy in 05AB1E. But this might cause confusion if the second input-list is a single pair, which we might confuse as a truthy pair result instead.
[Answer]
# [PHP](https://php.net/), ~~106~~ ~~104~~ 102 bytes
```
function($a,$b){for(;$b;++$i)foreach($b as$x)if(!isset($a[$x]))$b=0;elseif(!$a[$x]--)return[$x,$i|0];}
```
[Try it online!](https://tio.run/##rVNbT4MwFH4ev@K4NBlkNWFeMiPisiheEjMWfPCBEMKwOIxSUrpsyfS3zxbKNiczPvjSc/m@75zDKc2n@epikE9zjTBGWchIThlPsxfdCR3Pcz34ACd8Gnqj@9Ft6Y@H3qNjWJqGOCl4ATb4WssHrSWOdhzxtn15jKH9TF@EdyK8PBKVZbonAso5YcI/hQBLScnDpQ7XTKxYG7sDV2F1Sr0qVeNmoLVkyv@PmRonU7wS6zV160M1GdiXcPaj6ra83yhfD3tWzzSnNBHyd0LnlT6J3gryN@1V@Q3X9aZ2lUrYWwtNJfyNbW7Ye/ep2u/e5j67XvLWnZZL@3ahzdvcTBnIXzOxV8ksi3lKMx1FGE2MZUKZbqGJ1e2i1BABieKpjiYQFWhhpIl@kBYF4YLto0VgGGhimxYRRSVUJQ8PDUb4jGUiwCj9MAPrcyW61cVAvYioEB4YsNQASDyl8FrQLCRZTJ@JXkIYxnfj0HEf8A5GxXNCiST5ZoCl6QWi0rZAcmyJHAUwgM6T69504Bw6N8P7h84WTzmW9rn6Ag "PHP – Try It Online")
More verbosity:
```
function( $a, $b ) {
for( ; $b; ++$i ) { // loop infinitely if original list is not empty
// (and +1 cycle counter)
foreach( $b as $x ) { // start/restart cycling of list
if( ! isset( $a[$x] ) ) { // if item on list is not in collection...
$b = 0; // empty the list to return Falsey above
} elseif( ! $a[$x]-- ) // or if item collection has reached 0...
return [ $x, $i | 0 ]; // return the set of item and cycle counter
}
}
}
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 27 bytes
```
?ȯsM÷L⁰▼øfo€⁰→mGλ←`Vḣ¢²o>⁰#
```
[Try it online!](https://tio.run/##yygtzv7/3/7E@mLfw9t9HjVueDRtz@EdafmPmtaAOG2Tct3P7X7UNiEh7OGOxYcWHdqUbwcUV/7//3@0Un5JSWqRkg5BuiCxqCi/BMhIyU9Xiv0frWGgo5ScWKKkqQNigQSBLEO4OiDHFKZZMxYA "Husk – Try It Online")
Takes two arguments: a list of strings in the format `["dog","dog","cat"]` and a list of number-string pairs in the format `[(2,"dog"),(3,"cat")]`.
Prints a number-string pair or nothing.
I have checked all test cases and the program passes them.
Note that the interpreter doesn't like extra spaces in inputs.
If the second input is an empty list, its type needs to be specified or the interpreter can't deduce it and gives a type error.
An empty list of number-string pairs is given as `[]:LPNLC`.
Apparently the first input can be empty without any issues.
## Explanation
```
Two arguments, one explicit (list of string, accessed through ⁰ by default, ² inside a lambda),
one implicit (list of pairs).
mGλ←`Vḣ¢²o>⁰# For each pair (n,x), replace n by index of first overflow.
m Map over list of pairs:
G Replace pair (n,x) by (f n x,x) where f is
λ an anonymous function:
f takes two arguments, one explicit (n, accessed through ⁰) and one implicit (x)
² First program input.
¢ Cycle infinitely
ḣ and take prefixes.
`V 1-based index of first prefix that satisfies:
# Number of occurrences of x
o>⁰ is greater than n.
← Decrement to get 0-based index.
fo€⁰→ Remove pairs whose string never occurs in the list:
f Filter by
→ right part
o€ is an element of
⁰ first input.
Because Husk is lazy, the index calculation is never performed for the removed pairs.
?ȯsM÷L⁰▼ø Produce output.
? If the filtered list is empty,
ø return the empty string.
ȯsM÷L⁰▼ Otherwise return this:
▼ take lexicographic minimum,
M apply on its left part:
÷ integer division by
L⁰ length of first input
ȯs cast to string (to keep types consistent).
```
I could save a few bytes by returning `(0,"")` as the falsy value instead of using strings, but it's also a valid "truthy" output and thus ambiguous.
Since Husk is strongly typed, I can't return a pair for some inputs and a non-pair for others.
[Answer]
# [Haskell](https://www.haskell.org/), ~~274 235~~ 228 bytes
```
a!e=[(x,y-sum[1|x==e])|(x,y)<-a]
u(h:t)
|and[b>=0|(a,b)<-h]=h:u t
|1>0=h:[]
s((a,b):t)
|b<0=a
|1>0=s t
c#l=let o=u$scanl(!)c$cycle l in(s$last o,length o`div`length l)
c&l
|or[x`elem`l|(x,y)<-c]=print$c#l
|1>0=print"False"
```
[Try it online!](https://tio.run/##XVHRbuIwEHzPV2xT1EukcAVd@4Iwj/2JKJKNvcFWFzuyHQoS/87ZCaVSX2LPzszueKNF@ESi2008IWurc3NZhvHYrq9nxrCrr7lSb5eiK8ZKb2JdwFVY1e53bHWtRLNPnO6Y3owQE7XerdK97YpQTeRs2G9XTNzZkHTymRhhBMfGRZDCUvVUy4W8SEIgMLYKCxIh8Q2hPUQNjitz4ndAdSFfKLVzvj1zJDxy@o4pOzZ4Y@MijbgPnHD5IShgeTsKY4FBW5VSxLL5VzdVqdyhbN7ybRDeu1ReZ@BiRF8273X30s6a2fNQfSse5y96hvM3@7sbP3CQGuVnANND1OjxTwBhL3ASZBSgjf7ytyh4z2HwTo0SEw1k8i56EEQQIg7ZosBjHL3NfByHtLgk2Gz3Hl53BSwhryW1A3dC35P7QlXxwOusmlZrUmQRjbPQ/JgexQD3Xb/Ow2eUgo08JXApgbG9sUk/818a7WMUaDEMaEN@iOagUHo82hhAOu8xDM4qYw/zY6c8ucP081UB/wE "Haskell – Try It Online")
* Saved 45 bytes thanks to @Zgarb !
`&` If there's any valid entry prints result, otherwise prints False.
`#` produces a list of all steps and returns a tuple of :
* element overflowed(`s`) of last iteration ,
* iterations length / list length
`u` stops infinite list when overflow happens.
`!` decremnts corresponding entry of list cycled
] |
[Question]
[
A first order separable ordinary differential equation is (arguably) the easiest type of differential equation to solve, and takes the form of
$$N(y)\frac{dy}{dx} = M(x) \\
y(x\_0) = y\_0$$
For two given functions \$N(y)\$ and \$M(x)\$ and an initial condition \$y(x\_0) = y\_0\$.
Your task is to take \$N(y)\$, \$M(x)\$, \$x\_0\$ and \$y\_0\$ and output the solution to that differential equation.
## How to solve a separable differential equation
The differential equation
$$N(y)\frac{dy}{dx} = M(x)$$
can be solved through the following method:
$$
\begin{align}
N(y)\frac{dy}{dx} & = M(x) \\
\int{N(y)\frac{dy}{dx}dx} & = \int{M(x)dx} \\
\int{N(y)dy} & = \int{M(x)dx}
\end{align}
$$
Once the integrals have been calculated, we can remove one of the constants of integration, leaving the equation
$$f(y) = g(x) + c$$
where
$$
f(y) = \int{N(y)dy} \\
g(x) = \int{M(x)dx}
$$
After this, \$c\$ can be calculated by applying the initial condition:
$$
c = f(y\_0) - g(x\_0)
$$
and a final solution for \$f(y)\$ can be given.
## Challenge
You are to take in four inputs:
* The function \$N(y)\$
* The function \$M(x)\$
* \$x\_0\$
* \$y\_0\$
Both \$x\_0\$ and \$y\_0\$ can be any real number, and can be taken as input in many reasonable manner (i.e. a list, tuple, two integers etc.). The functions, in order to avoid having to focus on parsing mathematical input, will be limited to a type of [Laurent polynomials](https://en.wikipedia.org/wiki/Laurent_polynomial) - i.e polynomials in the form
$$
p(x) = \alpha \cdot x^n + \beta \cdot x^{n-1} + \dots + \gamma + \delta \cdot x^{-2} + \epsilon \cdot x^{-3} + \dots + \zeta \cdot x^{-m+1} + \eta \cdot x^{-m} \\
\alpha, \beta, \dots, \eta \in \mathbb{R}, \:\: n, m \in \mathbb{N}
$$
Notice that we'll never have \$x^{-1}\$ in the polynomial, and that because of this, the integrals will always be Laurent polynomials of the same form (with \$x^{-1}\$ included *after* integrating).
With inputs in this format, there are multiple ways you could represent them for input. As with the mapping, any reasonable representation is acceptable, and if you aren't sure, ask. However, here are some that are definitely allowed (for the example \$p(x) = 3x^2 + x + 6 - 2x^{-2} + 7x^{-5}\$):
* Nested list: `[[3, 2], [1, 1], [6, 0], [-2, -2], [7, -5]]`
* A pair of lists of coefficients: `[3, 1, 6] and [0, -2, 0, 0, 7]`
* A string representation: `"3x^2 + x + 6 - 2x^-2 + 7x^-5"`
* etc.
Given these four inputs, you are to output the solution to the differential equation they represent.
In order to avoid having to algebraically manipulate your solutions to get into the form \$y(x) = ...\$, you can output *two* Laurent polynomials, in the same form as the input; one representing \$y\$ and the other \$x\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins!
## Test cases
Both the MathJax and text-based inputs will be included for each example, where the text based will use the nested list input format above. In addition, I will walk through the first example for clarity.
```
In:
N = [[1, -2]]
M = [[6, 1]]
1 -> 1/25 = 0.04
Out:
y = [[-1, -1]]
x = [[3, 2], [28, 0]]
```
$$
\begin{align}
\frac{1}{y^2}\frac{dy}{dx} & = 6x \\
y(1) & = \frac{1}{25} = 0.04 \\
\\
\int{N(y)dy} & = \int{M(x)dx} \\
\int{\frac{1}{y^2}dy} & = \int{6xdx} \\
-\frac{1}{y} & = 3x^2 + c \\
-25 & = c + 3 \implies c = -28 \\
-\frac{1}{y} & = 3x^2 - 28
\end{align}
$$
```
In:
N = [[2, 1], [-4, 0]]
M = [[3, 2], [4, 1], [-4, 0]]
1 -> 3
Out:
y = [[1, 2], [-4, 1]]
x = [[1, 3], [2, 2], [-4, 1], [-2, 0]]
```
$$
N(y) = 2y - 4, \:\: M(x) = 3x^2 + 4x - 4 \\
y(1) = 3 \\
\:\\
y^2 - 4y = x^3 + 2x^2 - 4x + c \\
c = -2 \\
y^2 - 4y = x^3 + 2x^2 - 4x - 2 \\
$$
```
In:
N = [[1, 0]]
M = [[3, 2], [2, 0]]
0 -> 0
Out:
y = [[1, 1]]
x = [[1, 3], [2, 1]]
```
$$
N(y) = 1, \:\: M(x) = 3x^2 + 2 \\
y(0) = 0 \\
\:\\
y = x^3 + 2x + c \\
c = 0 \\
y = x^3 + 2x \\
$$
[Answer]
# [Python 2](https://docs.python.org/2/), ~~123~~ 122 bytes
```
def f(p,P):R=[[[a/-~b,b+1]for a,b in F]for F in P];a,b=map(lambda F,x:sum(a*x**b for a,b in F),R,p);R[1]+=[a-b,0],;print R
```
[Try it online!](https://tio.run/##TY49b4MwEIZ3fsWNNjlS40YZQKzMiPXkwRagWgJjAa2SpX@d2CGtctP79Ujn79vX7OS@d/0AA/PY8KKtiEh/ZL8GzSlXw7yARgPWQf00dZSNKkNYTdqzUU@m01DjrVi/J6bTW5oaeMc4tuh52VKuThXpzKBQWPrFug3a3U5@XjZY72sSodG6PlLBn9ets65IwCM0UEH/o0cWe548n4WG70ycxQUh5wiMKEfIpFIIRNcQKsUT9nm04cJAxjQaygIljmlYyCguR/lXBVYE8c/mL@CNkMfwAQ "Python 2 – Try It Online")
Straight-forward implementation. A function that takes arguments in the form `(y, x), (N, M)`, and prints the resulting 2 polynomials to `STDOUT`.
[Answer]
# [SageMath](https://doc.sagemath.org/html/en/index.html), ~~60~~ ~~59~~ 58 bytes
Saved a byte thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)!!!
```
lambda N,M,b:desolve(diff(y,x)*N-M,y,b)
y=function('y')(x)
```
[Try it online!](https://sagecell.sagemath.org/?z=eJw1jU0OgjAQhfc9xeyYqUOAgi5IOAJcACEBoZEEWyP-tLcXML7dy_e-PF2cxdzd-qGDikvu82Fc7PwecZi0Rs-OZBWW7Lkn4Qv9MpfnZA0GPiB0JIS2j58IkwHEJPKtYjhJx1AnDEmkjg0xoJI-zBhS6Vp1yKTbyrZId5r8yerWMUPcEOUC1ixX-8HR3TszoMb9iYi-JlEvxw==&lang=sage&interacts=eJyLjgUAARUAuQ==)
Inputs two functions \$N(y)\$ and \$M(x)\$ and a boundary condition \$[x\_0,y\_0]\$ and returns the solution to the differential equation \$N(y)\frac{dy}{dx}=M(x)\$ where \$y(x\_0)=y\_0\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
DSolve[{y'@x#==#2,y@#3==#4},y,x]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yU4P6csNbq6Ut2hQtnWVtlIp9JB2RjIMKnVqdSpiFX7H1CUmVfikBZtqF8ZXREbZ6SjYKZQoaNgCET6RqaxXDB5IwWQvIKugomOgrFCRZyRgraCiUIFRACo2hih1BChAmicARDF/gcA "Wolfram Language (Mathematica) – Try It Online")
Tool for the job, and all that. Uses Mathematica's builtin `DSolve`. The TIO link shows the input and output formats (a warning message is issued for the second case, but the solution is correct). This builtin does automatically solve for \$y\$ in terms of \$x\$.
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 50 bytes
```
f(N,M,a,b):=ic1(ode2(N*'diff(y,x)=M,y,x),x=a,y=b);
```
[Try it online!](https://tio.run/##hYtBCsIwFET3HqMg/sSRNml10ZAjtEcopLaBgFWpEZKNV4@16NrVDDPvTSa4yaTZ@Pvsrr625vIYVbLUooFBz2rtzoJuwyip5bvBWUsRgekGn0DQBlH3TKXVJ0sij53EiQcIiFweGVOb9bPk5@eI7LXNftOCSx4PFUoeOrmveFi6QPnHEV9eokCxsOkN "Maxima – Try It Online")
Takes maths-like expressions as input, e.g. `3*x^2+4*x-4`. Outputs a quaint formatted ASCII string!
[Answer]
# JavaScript (ES6), 114 bytes
Just a port of [@SurculoseSputum's answer](https://codegolf.stackexchange.com/a/205490/58563).
Takes input as `([y, x])([N, M])`.
```
p=>P=>(R=P.map(p=>p.map(([a,b])=>[a/++b,b])))[1].push([(g=i=>R[i].reduce((t,[a,b])=>t+a*p[i]**b,0))(0)-g(1),0])&&R
```
[Try it online!](https://tio.run/##bY3BDoIwEETvfgUnsgulFiTeyjcYrpseCgJikDaA/j62Gkw03mZ35s1c9UPP9dTbJRnNuVlbuVpZnGQBpTzxm7bgTvsSQJpVCmVBeh/HldeIlCpu7/MFCDrZy6KkXvGpOd/rBmBhG7LEOrLOiqKKCUQQmHSQIhMKw7BcazPOZmj4YDpogQQXOQtShUBEKQuSTCkWEB39U7nZ3Q9w@KQzr1w2cQXiTTkz8yL/tv7UCG9soz90tkHrEw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
I like card game challenges so I made this one for the Italian card game Scopa. My family has been playing this game since time immemorial. It has a very interesting scoring system that should be fun to golf. I will post an answer in R to get the fun started, that I am sure people will improve upon.
**The challenge: figure out the number of points scored in a round of Scopa, given the cards the player captured during the round as input.**
There are 40 cards in a Scopa deck. If you are using an international deck you remove the 8s, 9s, and 10s, leaving A,2,3,4,5,6,7,Q,J,K in each suit.1 There are two players or partnerships, and after every round, all cards end up captured by one or the other of the two players. The score is counted as follows (more information [here](https://www.pagat.com/fishing/scopone.html)):
* The player with the most **cards** scores 1 point.
* The player with the most **diamonds** (or coins if using the Italian deck) scores 1 point.
* The player with the **7 of diamonds** (or coins), known as the *sette bello* or beautiful seven, scores 1 point.
* The player with the highest ***primiera*** scores 1 point. A player's *primiera* score is the sum of the scores of the highest-value card that the player captured in each suit (see table below). If you do not have at least one card in every suit, you lose by default even if your score would exceed your opponent's score. In the exceedingly rare case that neither player has at least one card in every suit, the player with the higher *primiera* total scores the point.2
### Table of primiera scores
```
| Rank | Value |
| ----- | ----- |
| 7 | 21 |
| 6 | 18 |
| A | 16 |
| 5 | 15 |
| 4 | 14 |
| 3 | 13 |
| 2 | 12 |
| Q,J,K | 10 |
```
So a player can score at most 4 points in a round.3 If there is a tie, which is possible for cards, diamonds, or *primiera*, no one scores the point.
It's important to realize that since each card must be captured by one of the two players, you can infer what cards the other player must have taken even if you only know what cards one player took. You will need to do this to correctly score *primiera*.
## Challenge rules
### Input
Your code should take as input the cards captured by a single player during a round of Scopa.
***Input must be in string format, in which one character represents the rank of each card and one character its suit.*** This removes the potential loophole of passing the *primiera* scores in directly as input. Conversion of card ranks to *primiera* scores must be done in the program. However you may choose to use a single string separated by spaces or commas, an array of strings, or any other format. For example if you choose to encode ranks as `76A5432QJK` and suits as `DCHS` you could use inputs such as `['7D', '6H', 'QD', 'JS']` or `'7D,6H,QD,JS'`.
### Output
An integer from 0 to 4 representing the player's score.
### Winning
Shortest answer in bytes wins!
## Test cases
`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "7C", "6C", "4C", "3C", "2C", "7H", "4H", "2H", "5S", "3S", "QS", "JS", "KS"]`
**Scores 4**: 1 point for >20 cards, 1 point for >5 diamonds, 1 point for the 7 of diamonds, and 1 point for scoring 78 in *primiera* (7,7,7,5 where opponent has 7,6,5,K for 64)
`["3D", "7C", "6C", "AC", "5C", "4C", "3C", "2C", "QC", "4H", "7S"]`
**Scores 0**: <=20 cards, <=5 diamonds, no 7 of diamonds, and only scores 69 in *primiera* (7,7,4,3 where opponent has 7,7,6,K for 70)
`[7D", "6D", "AD", "5D", "4D", "3D", "2D", "7C", "6C", "AC", "5C", "4C", "3C", "2C", "7H", "6H", "AH", "5H", "4H", "3H", "2H"]`
**Scores 3**: 1 point for >20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. The *primiera* would be 63 (7,7,7) and the opponent can only score 51 (7,Q,Q,Q) but since this hand has no spades it loses the point by default.
`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "QC", "QH", "QS"]`
**Scores 3**: <=20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. The *primiera* only scores 51 (7,Q,Q,Q) and the opponent can score 63 (7,7,7) but since the opponent's hand has no diamonds this hand wins the *primiera* point by default.
`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "7C", "7H"]`
**Scores 3**: <=20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. Even though this hand has no spades, it still wins *primiera* by a score of 63 to 57 (7,7,7 versus 7,6,6) because the opponent's hand has no diamonds.
`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "QC", "QH"]`
**Scores 2**: <=20 cards, 1 point for >5 diamonds, 1 point for 7 of diamonds. This hand has no spades, and opponent's hand has no diamonds. Opponent wins *primiera* by a score of 63 to 41 (7,7,7 versus 7,Q,Q).
`[]` (empty array)
**Scores 0**
---
1: At least in our family, Jack outranks Queen in Scopa but this is irrelevant for scoring purposes.
2: I've been playing this game since childhood and have never seen that happen but your code had better be able to handle that case!
3: There are bonus points for "sweeps" scored during the round which I am ignoring for the purpose of this challenge.
[Answer]
## Ruby, ~~156~~ 153 bytes
```
->a{b='';([a[40],a.scan(/.d/)[5],a=~/;d/,'dchs'.gsub(/./){l=a.scan /.(?=#$&)/;l.size<10&&b+=(';865432'.tr(l*'','')+?0)[0];l.max}.sum>b.sum||p]-[p]).size}
```
[Try it online!](https://tio.run/##rdJLa4NAEAfwu59isSWrjdnd@ixYEyQeQnISj8se1kealLyIDbSN6Ve3ZkxIoRRSWg8/UIeZ/S@z3aVv9RQFda8v92mAsa9xyW0mDEnKTK40SnKqc6d5Dz6on1MD59msxOSp3KXNT6rvF0FbiijRBsHNbUen/oKU8/fi8Z51Omk30LD/4Dq2ZWLystUWdxgbGOvdAdM5E03tUr4eSLlb9tOjVbURPb4ROvQ41FzhqhepBlJdMAQd0AYt0ARj0BtCPWiDFmiC3gi@gyboJFADxuAYnCSqMJr51reuIej8MCEeXiZ4px7XZ7h@TpvEBcM2yZds1jnhL@e3dzgGJ9ElTzw63c@f@3nn0//fyY6dhCJIIbMZyteokpWCmmeDplyS5/V81Swfwp4bHjcxHk@i4SjBBjrvJmMMNlsoxSqvPwE)
```
->a{
b=''; # stores primiera of other player
([ # this array stores all checks
a[40], # check if >20 cards (>40 characters)
a.scan(/.d/)[5], # check if >5 diamonds
a=~/;d/, # check if 7 of diamonds
'dchs'.gsub(/./){ # for each suit, build a string with...
l=a.scan /.(?=#$&)/; # find all cards with this suit
l.size<10&& # if there are less than 10, the other person has some, so
b+= # append to their score string the following:
(';865432' # start with all the cards
.tr(l*'','') # remove the ones we have
+?0) # add back the JQK at the end
[0]; # take the highest
l.max} # return the highest card that we have
.sum # take the sum of the codepoints
>b.sum # check if it's greater than the other player's sum
||p # if not, evaluate to nil
]-[p]) # remove all nils
.size} # count how many are left
```
This uses `;865432000` to represent `76A5432QJK` respectively, and suits are in lowercase. (The choice of characters is because subtracting 38 from each gives their primiera value, but we never actually do so because only the relative difference matters.)
We don't check whether either player is missing a suit because it is unnecessary -- since all cards are counted as 38 plus their actual value, if someone is missing a suit, the highest score they can get is (21+38)\*3 = 177, which is less than (10+38)\*3 + 21+38 = 203, the lowest score the other player can get. We cannot have the two players missing an unequal nonzero number of suits, because a player can only be missing 0, 1, or 2 suits, and if someone is missing 2 suits they have all the cards of the other 2 suits.
[Answer]
# R, ~~320~~ ~~298~~ ~~265~~ ~~238~~ ~~229~~ ~~224~~ ~~211~~ ~~209~~ 179 bytes
This is a solution mostly due to @digEmAll, in the form of a function.
[Try it online!](https://tio.run/##rZJPa4NAEMXvfopoEXfbCeiqsZEaED2InsRjyUEkwUD@iDHQfnq7PiMJlEJbcpgfs8PwZt7utv026LeXY9XtTkdWUxGcLwcKg7Jp9p@0D5bLl4pZFr2S6wtakGr5NtdPuioThxesYM3b/HTpNi2rmCdbjNAgI5ORysgNThUzYplGMhIZhSw15bnbmFzfHfWar4RJUuXd8i1zzVcuyXQtKyHbPzck6FB@8PlwUKcTX5m838p5mhdrNNMWYAi6oAPaoABz0IvQDzqgDQrQS1AHBegW6AFzMAWzQuN89jRzFKxhfxMPQfeHQXl0G@RdpUzlj45@P270tQDD0dedU3vyizVs5V8Xm4JZfHOXJ9dLe5SsN3l5@J4QFINgXbZlNfzl8Un6Lw "R – Try It Online")
```
function(h,S=sum,A=apply,l=99+c(11,8,5:2,6,!1:3)%o%!!1:4)S(S(p<-outer(c(7:2,'A','K','J','Q'),c('D','C','H','S'),paste0)%in%h)>20,S(p[1:10])>5,p[1],S(A(l*p,2,max)-A(l*!p,2,max))>0)
```
Below is the best of my old mediocre attempts for 209 bytes.
*edit: golfed down by aliasing some functions, then by taking Doorknob's idea of adding a constant to the score instead of checking the suits.*
*next edit: got rid of some redundancy and then incorporated some improvements from Giuseppe*
*next edit: -2 bytes thanks to digEmAll*
I am terrible at this, so I'm sure someone can improve on this if they care to take the time. I feel like the `sapply` and `function` are super long and could get rid of them but I can't figure out how. Inputs are two-character strings in the standard notation.
```
function(h,s=sum,l=c(11,8,5:2,6,!1:3)+99)s(length(h)>20,s(grepl('D',h))>5,'7D'%in%h,s(sapply(c('D','C','H','S'),function(i,r=c(7:2,'A','K','J','Q')%in%substr(h[grep(i,h)],1,1))s(l[r][1],-l[!r][1],na.rm=T)))>0)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 193 bytes
```
x=>x.Count/21+x.Count(g=>g>48)+x.Sum(g=>g/40)/6+("".Sum(m=>{var r=x.Where(g=>g/10==m);return(r.Any()?r.Max()%10+50:0)-(r.Count()<10?" ".Max(l=>x.Contains(m*10+l)?48:l+50):0);})>0?1:0)
```
[Try it online!](https://tio.run/##tZNta9swEMdZtzLWTyEMBd3S2PJTXOrYwSSMLGkZxoO@CHkRXCU1xMqQ5c6j9LNnyjldm41B2ahf/Cyf7u5/d5LzqptXxfZTLfL@ZVGpfiFUfLbDMto2UdyYw00tlOXYnf2SrqJ4FXvnoA1ZXeKn5TGweh1qvDl6@85AcxnF93cLSWTUmNe3XPLW0WZRVEIouaqloNJMxA8KA2leLRoKpzbr@OyCQVfvtGLQt9kA0x6//2Cg27qtSqhFISpaftRBaxh45xdrHQw6OnyAmA1svdqGJ3eb4oYoXilaKVmI1WxOCvGtVkCimFzLQvHLQnC6pGg1M77muaLlbpcaw3E2MszP4oY3X5a0nNlzIB1ig9bU76uFusWK2BkxpunEcT0/IT0SPA9hc@g6AObXzW68FADCE/1gRYJ/n83vjWBk6AQ9ZIL0kR7SRTrIFBkM0R/pIV2kgwzGaEc6SD9DH2SKnCCnmfEAIbEskuUbySviHZTl/iGWIP2/CKfDJ@Hg99TsHzt@uXzbdw@ZtH0/m4T7OI/Dstz/OogJcjp66j4d74f8WjLBY6@v3sehgPNLgOz/I32xDw94@xM "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# JavaScript (ES6), ~~171~~ 163 bytes
Takes input as a set of cards, using their standard representation.
```
c=>(c.size>20)+((g=o=>[..."CHSD"].map(s=>[..."JQK2345A67"].map((v,i)=>(S=o^c.has(v+s))?m="111345679"[++n,i]||12:0,n=m=0)|(n?0:T=1,t-=m),T=t=4)|t*T)(1)>g``)+S+(n>5)
```
[Try it online!](https://tio.run/##vdJPa8IwGAbwu5@i5JSsNbbpnzAhlaIH0VOJN3FYuuo6bCKmOBj97p28KooiDDa8/A7pS9@nT/qZ7TOT78pt3VX6vWhXos1FjHNqyu8iZi6xMV4LLeI5pRQNx3KEFrTKtticjibplPlBmET89ADvnZIcXiGFfsvpR2bw3jaEDCqBPM87jEb8Fc1tWznlomk81ncdJSrhkgargdufCc@pu6IizkzUIiBN/TIj2CPxerkktrSxikPS5loZvSnoRq/xCqviy5JFjeeIj5BjoQhMwBAMQB9kYAryIcyDAeiDDORjOAcZGEqYAVNwAk4lWhBCrF7PkrneFcYKOo8y@nebEzB8kCIdXlLwuz1u5@9d/D7LsZEITI6NXHXkn5u6yeh3/uu@JuB0dOklHZ/u4ik7@bmF537hzTb2aNvtv9H@AA "JavaScript (Node.js) – Try It Online")
### Commented
```
c => // c = set of cards
(c.size > 20) + ( // +1 point if we have more than 20 cards
( g = o => // g is a function taking the flag o (for 'opponent')
[..."CHSD"].map(s => // for each suit s, ending with diamonds:
[..."JQK2345A67"] // for each rank v at position i, sorted from
.map((v, i) => // lowest to highest primiera score:
(S = o ^ c.has(v + s)) ? // if the player owns this card, set S to 1 and:
m = "111345679"[++n, i] // increment n; update m to the score of this
|| 12 // rank (we use the official score - 9)
: // else:
0, // do nothing
n = m = 0 // start with n = m = 0
) | // end of inner map()
( n ? 0 : T = 1, // if n = 0, set T to 1
t -= m ), // subtract m from t
T = t = 4 // start with T = t = 4
) | t * T // end of outer map(); yield t * T
)(1) > g`` // +1 point if g(1) is greater than g(0)
) + // (we test this way because the scores are negative)
S + // +1 point if we own the 7 of diamonds
(n > 5) // +1 point if we own more than 5 diamonds
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 41 bytes
```
39ÝsK‚εg9y@Oy0å•Dδ¿m(/d•₆вy.γT÷}è€àO)}`›O
```
[Try it online](https://tio.run/##yy9OTMpM/f/f2PLw3GLvRw2zzm1Nt6x08K80OLz0UcMil3NbDu3P1dBPAbIfNbVd2FSpd25zyOHttYdXPGpac3iBv2ZtwqOGXf7//0crGRgo6SgoGRiCSSMwaQwmTcCkKZg0A5OWINIQrN4QrN4QrMYQrMYQrMYILGsEFjcCixiDTTMGqzEGm2BsASbNlWIB "05AB1E – Try It Online") or [check all test cases](https://tio.run/##yy9OTMpM/V9TVqns8t/Y8vDcYu9HDbPObU23rHTwrzQ4vPRRwyKXc1sO7c/V0E8Bsh81tV3YVKl3bnPI4e21h1c8alpzeIG/Zm3Co4Zd/v91/hsYKBgYKhgYKRgYKxiYKBiYKhiYKRhYKhgaKBgaKhiaKBiaKhiaKRgZKBiZKBiZKRgbKxibKhhbKhhbKBibcwHVQ1UaKRgaI9QbWoLUGxtwYTUfqxaQFYYKRkYKRsZgu0yB1nHhcp6BhYKBOdgWoEssCSkDmmxAjFFcCgA).
Suits `DCHS` are respectively represented by `0123`. Ranks `7A65432KJQ` are respectively represented by `0123456789`. Those are taken as strings, not integers, as required by the challenge (but then 05AB1E converts them to integers when needed anyway).
As in other solutions, we add a large constant (14) to each primiera score in order to make the check for missing suits unnecessary.
```
39Ý # range 0..39 (the list of all cards in the game)
sK # remove all elements that appear in the input
‚ # pair with the input: [player's hand, opponent's hand]
ε } # map each hand to a list of its 4 subscores:
g # first subscore: length (number of cards)
9y@O # second subscore: count elements <= 9 (diamonds)
y0å # third subscore: is 0 (representing 7D) in the list
y.γT÷} # group the hand by suit
•Dδ¿m(/d•₆в è # map each rank to its primiera score
ۈ # maximum primiera score in each suit
O # fourth subscore: the sum of those
`› # for each subscore: is player's > opponent's?
O # sum
```
```
[Answer]
# [MS SQL Server 2017](https://docs.microsoft.com/en-us/sql/sql-server/sql-server-technical-documentation?view=sql-server-2017), 525 bytes
```
CREATE FUNCTION f(@ NVARCHAR(MAX))RETURNS TABLE RETURN
SELECT q/21+IIF(d>6,2,IIF(d=6,1,0))+IIF(m=0,IIF(n=0 AND a>b,1,0),IIF(n=0 OR a>b,1,0))p
FROM(SELECT SUM(q)q,MAX(IIF(s='D',q,0))d,SUM(a)a,MIN(q)m,SUM(b)b,MIN(10-q)n
FROM(SELECT s,COUNT(k)q,MAX(IIF(r=k,v,0))a,MAX(IIF(r=k,0,v))b
FROM(SELECT LEFT(value,1)r,s,ASCII(RIGHT(value,1))-38 v
FROM STRING_SPLIT('7;,68,A6,5,4,3,2,Q0,J0,K0',','),(VALUES('D'),('C'),('H'),('S'))s(s))d
LEFT JOIN(SELECT LEFT(value,1)k,RIGHT(value,1)u FROM STRING_SPLIT(@,','))a
ON r+s=k+u GROUP BY s)t)t
```
Try it on [db<>fiddle](https://dbfiddle.uk/?rdbms=sqlserver_2017l&fiddle=8c7ba6bc9c62f4cd2de336fed2e03afe).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 334 bytes
```
$
¶234567JQKA
r`.\G
$&C $&D $&H $&S
+`((\w\w).*¶.*)\2
$1
T`67AJQK`8960
%O$`(\w)(\w)
$2$1
m`^(?=(...)*)(.C )*(.D )*(.H )*(.S )*
$3;$#1 $#2 $#3 $#4 $#5;${2}${3}${4}$5
m`^(?=(9D))?...;
$#1;
(;(?!.*10).* 0.*;).*
$1
\d[C-S]
1$&
19\w
21$*@
\d+(\w )?
$*@
(@)?;(@*) @* (@*).*;(@*)¶@?;((?!\2))?@* @* ((?!\3))?.*;((?!\4))?.*
$#1$#5$#6$#7
1
```
[Try it online!](https://tio.run/##jU5NS8QwFLy/XzGycUkihm3SD5cibUnAsnuQEm9WqaAHD3oQYQ/i39ofsH9sfVkRPCh6mPeazryZeXl4fXy@2x/Li2kvCLutdXlRVqth3dHLZMYLEnMPMQ@MnhFBJ5OU42bcKKN3W6PVaEEio6uprDq@m86W5YKOL8XEKpVAwjL/NN3K5lwaY5RW0ngoLU04zP4wI08SrhazDGJmGY6RM4pavNl38eYY@bsovryWQamGDWvim5pkLZsjo7MFN8PC6Jp3ajbeX/vTeAPKxJyy5bgB2UzolokT7gfVUHrJVjW1bLVCq5E2O6S127b8n61Hy3HMJTo9XUrXn1R@@E49uK6YlWJWUbbfVwFlQBdQBOQBLsAGDAGVR@mRezgP61H1yHvYHkWEixgiVhHrSO5L2XkU3/SDT/oq0o/@P55wRNmj44hDlktx9Fu9VcA6pJSh5zJ/yKpk/h8r@gA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
$
¶234567JQKA
r`.\G
$&C $&D $&H $&S
```
Create a list of all 40 cards.
```
+`((\w\w).*¶.*)\2
$1
```
Remove the cards the player holds.
```
T`67AJQK`8960
```
Replace each rank by its sort order, which is 9 for `7` and 10 less than its value for other cards.
```
%O$`(\w)(\w)
$2$1
```
Sort the cards by suit and rank.
```
m`^(?=(...)*)(.C )*(.D )*(.H )*(.S )*
$3;$#1 $#2 $#3 $#4 $#5;${2}${3}${4}$5
```
Count the number of cards in each suit and also capture the highest ranked card in each suit, capturing the highest diamond twice.
```
m`^(?=(9D))?...;
$#1;
```
Check whether the highest diamond was the 7.
```
(;(?!.*10).* 0.*;).*
$1
```
Delete all of the highest cards if one of the suits has no cards.
```
\d[C-S]
1$&
19\w
21$*@
\d+(\w )?
$*@
```
Convert the highest cards to their unary score and sum them together. Also convert the total number of cards and suit lengths to unary.
```
(@)?;(@*) @* (@*).*;(@*)¶@?;((?!\2))?@* @* ((?!\3))?.*;((?!\4))?.*
$#1$#5$#6$#7
```
Score points if the total, diamonds, or primiera, is higher.
```
1
```
Total the score.
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 235 bytes
```
{s[9]=35;s[8]=32;s[7]=30;s[6]=29;s[5]=28;s[4]=27;s[3]=26;s[2]=s[1]=s[0]=24;a[$1 $2]=s[$1]}END{while(i++<4){D=0;for(j=0;j<10;j++){if(a[j i]<1){B[i]=s[j];D++}if(A[i]<a[j i])A[i]=a[j i]}x+=A[i];y+=B[i]}print(20<NR)+(D<5)+(1<a[9 4])+(y<x)}
```
[Try it online!](https://tio.run/##JYu7bsMwDEX3foUHDxK0mLT8gqShhbtm6Cpo8NCgcoomiAskgaBvd6@a4fJc8oDL7bTvafNTcG1nNj@CDA5gA/bB8QR24AhqcABbsAc5uM1TGQ0u2iy@pqr@v9YU8vthTrev@P0polJWyzS7xhzPV7GCqyUMpWSKR7H4tYrBkkxvPpb3NZhZqQz1ioN9elm6e/Z8V66s5qFc@cmXa/z5FdzYw4dUYrYdJuFxqnRAfdi7zPuO7WVEBqRHOkQjLTJVBEdwBEdwBEdwBMdwDMdwDMdwDMd/ "AWK – Try It Online")
Suits map to 1234 (4 is diamonds), values map to 0123456789. This program transforms the test cases into the accepted format:
```
BEGIN{RS=", ";FS="";t[7]=9;t[6]=8;t["A"]=7;t[5]=6;t[4]=5;t[3]=4;t[2]=3;t["Q"]=2;t["J"]=1;t["K"]=0;u["D"]=4;u["C"]=1;u["H"]=2;u["S"]=3}{gsub("[\\[\"\\]]","",$0);print t[$1],u[$2]}
```
My goal was just to beat the leading Python implementation :D
[Answer]
# [Python 3](https://docs.python.org/3/), ~~249 245 239~~ 238 bytes
*-4 bytes thanks to @ovs*
*-6 bytes thanks to @movatica*
```
lambda C:sum([len(C)>20,'7D'in C,len([c for c in C if'E'>c[1]])>5,p(C)>p({n+s for n in'9876543210'for s in S}-C)])
p=lambda C:[not S.strip(''.join(C)),sum(max([(c[1]==s)*int('9gcdefil99'[int(c[0])],22)for c in C]+[0])for s in S)]
S='DcHS'
```
[Try it online!](https://tio.run/##rZFPb5tAEMXvfIoRPexuso34Y4xBwpKFW7lJD604bjmQ9eLS2mvEYilVlM/usuM6pK0ipWouv8NjZt57S/uj/7rX4bHOvhy31e52XUGemsOOiq3SNGfzwOMkXpJGQ86tJCTU@w4kWAWamrwjcyn8smTziLd2o6X3@tLglB6mSDKLp9EkDHyPWM3YzeLhbc5K5rTZo6nQ@x6KK9N3TUsJufq2b2wAxm2aXXVHBbU@WWbYRaN7SpKNXKu62SYJEVaQwitZyYOAjQHLSyuOtqx0iows5aogx2EZemV6WRlF1V2rZK/WHC6qbmNY6gBAp3rIoKYnySptZ50GnYNw3y8@fHQ5uJ8WReGWYlCz7Hxn6OY8Hp9wuHfjpZ2dIn1khJwgQ2SA9JCxxHnkBBkiA2S8Qh0ZIKMCZ5AeMkHOCveBjVk8myX8y8FHRs@4eXJ0i3@/F/5bt5d7nhpOkf6p4ZPO4bn5f2Q5vXOCnC3Hnt7q1xu@6u343Orp1eDVEv/xj43qKWPOG1hIlYLP4fNBKZ3C8Om6kt9TSDjcNHqTwoxDvj3cpiCPPwE "Python 3 – Try It Online")
] |
[Question]
[
## Challenge
Given a grid size, obstacles' positions, player position and target position your task is to find a path for the player to get to the target and avoid the obstacles at the same time (if necessary).
[](https://i.stack.imgur.com/10YGB.png)
---
## Input
* **N**: Grid size `N x N`
* **P**: Player's position `[playerposx, playerposy]`
* **T**: Target's position `[targetposx, targetposy]`
* **O**: Obstacles' positions `[[x1, y1], [x2, y2],...,[xn, yn]]`
---
## Output
**Path**: A path player can use to reach target `[[x1, y1], [x2, y2],...,[xn, yn]]`
---
## Rules
1. The point `[0,0]` is on the top-left corner of the grid.
2. Player's position will always be on the left side of the grid.
3. Target's position will always be on the right side of the grid.
4. The grid will always have at least one obstacle.
5. You can assume that no obstacle overlaps player or target position.
6. You don't necessarily need to find the min path.
7. The player can only move left, right, top and bottom not diagonally.
8. You can take the input in any convenient way.
9. You can assume that a path for the player to get to target will always exist.
10. Obviously, for each input multiple valid paths exist, choose one.
11. Assume `N > 2` so the grid will be at least `3 x 3`.
---
## Examples
Input: `9`, `[6, 0]`, `[3, 8]`, `[[0, 5], [2, 2], [6, 4], [8, 2], [8, 7]]`
Possible Output: `[[6, 0], [6, 1], [6, 2], [6, 3], [5, 3], [5, 4], [5, 5], [5, 6], [5, 7], [5, 8], [4, 8], [3, 8]]`
Input: `6`, `[1, 0]`, `[3, 5]`, `[[1, 2], [2, 5], [5, 1]]`
Possible Output: `[[1, 0], [1, 1], [2, 1], [2, 2], [2, 3], [2, 4], [3, 4], [3, 5]]`
---
**Note**
Notice that `X` is for rows and `Y` for cols. Don't confuse them with the coordinates in an image.
**Edit**
As @digEmAll pointed out, due to rules `#2` and `#3`, `playerY = 0` and `targetY = N-1`. So, if you want you can take as input only `playerX` and and `targetX` (if that makes your code shorter).
[Answer]
# JavaScript (ES6), 135 bytes
Takes input as `(width, [target_x, target_y], obstacles)(source_x, source_y)`, where *obstacles* is an array of strings in `"X,Y"` format.
Returns an array of strings in `"X,Y"` format.
```
(n,t,o)=>g=(x,y,p=[],P=[...p,v=x+','+y])=>v==t?P:~x&~y&&x<n&y<n&[...o,...p].indexOf(v)<0&&[0,-1,0,1].some((d,i)=>r=g(x+d,y-~-i%2,P))&&r
```
[Try it online!](https://tio.run/##jVDBTsMwDL3vKywhGkf1onawMRAB7cCZHUElQqVrR6euqdpqaoXYr494HUhw4mDZsd/ze84m3sVNUudVOy7tKj1k@oAltWSlvltr7KinSkeGljpSSlW0050vSPi9cYCd1u398mbfefve87rb0utdMNASo43Ky1XaPWa4k7eB50UBjUMKKDSqsdsUcUW5W1PrNXb@ivrxfpyfT2gppefVhzZtWtDg7EBH0BM8ETwTWAn6Dj5GAAs3ZbFFXcc9ltKobVzhK49/t7O8KFAoIaVjWZXZ@iFO3jFh5CKKYoI343YlqqmKvEV3nySITXTsijPBtMqVGXuJ2IZhH8i2eJbYsrFFqgq7RoECfKjUxuYlCgkcPgg5LPnRxoQgl/8zYMVfkcXx0prp9UnJSchT@VIOmpxHn6MRfyReE8wIAoILgrm7QgQ0FQRiQhNOM7rkNB9ec7oSRg5Exwq/iVMmhgNmMvCnFDro4Qs "JavaScript (Node.js) – Try It Online")
### Commented
```
(n, t, o) => // n = width of maze, t[] = target coordinates, o[] = obstacles
g = ( // g() = recursive search function taking:
x, y, // (x, y) = current coordinates of the player
p = [], // p[] = path (a list of visited coordinates, initially empty)
P = [ // P[] = new path made of:
...p, // all previous entries in p
v = x + ',' + y // the current coordinates coerced to a string v = "x,y"
] //
) => //
v == t ? // if v is equal to the target coordinates:
P // stop recursion and return P
: // else:
~x & ~y // if neither x nor y is equal to -1
&& x < n & y < n // and both x and y are less than n
& [...o, ...p] // and neither the list of obstacles nor the path
.indexOf(v) < 0 // contains a position equal to the current one:
&& [0, -1, 0, 1] // iterate on all 4 possible directions
.some((d, i) => // for each of them:
r = g( // do a recursive call with:
x + d, // the updated x
y - ~-i % 2, // the updated y
P // the new path
) // end of recursive call
) && r // if a solution was found, return it
```
[Answer]
# [R](https://www.r-project.org/), 227 bytes
```
function(N,P,G,O){M=diag(N+2)*0
M[O+2]=1
b=c(1,N+2)
M[row(M)%in%b|col(M)%in%b]=1
H=function(V,L){if(all(V==G+2))stop(cat(L))
M[t(V)]=2
M<<-M
for(i in 0:3){C=V+(-1)^(i%/%2)*(0:1+i)%%2
if(!M[t(C)])H(C,c(L,C-2))}}
try(H(P+2,P),T)}
```
[Try it online!](https://tio.run/##hVTNTttAED6zT7EVSr1bj1vbAdpGcasqUuFAQg6BS0glx3aIJce21uuSKM2Vc38k2t76bLwInV07Bg7ARvZO5uf7ZnZmLW53qV8u4yT2xYrOyjSQcZbSsohCKjOaiziVVM4jmvtyTtGy8KWIl4RgEO1aTQQbwDDxV5GAkS8uIgkn00L6QRL1skyEBV8TQukuDfxcliKil3O/gm0Y536BbFlYBsiM/wuJWynzUmIgCoqsjn5d6dnsOVJekYroroyGr8EOfMmMk9PR8HREmW3FaRgto5B3DFCsYJynRo2T@6KINIqIijJRwSioxKKvfsK0mcloKb3cL2RkMyNgBlwU5ZQZ1AD1Q0gOBjc45obUOk0FUJ0qQzhIgyzxXJiuRHbpjbjp1OSPdaKuYPhpdNTRuVK6WN7DVNQDGFT68cMTMp2J8jRurv8ZaJ9lgmHiOY1T6nRSTIAF9Umu0UxpPNN2z3O4AquMY6UCCEWWe58nFeDQ0P5RggfWBD0AfDp@dC9@TclOqNt/5246MKEPNBZqiA5SK4wFRpAdMcV@MmzDzdU1nv/N1Q/9/m1waHyrpX2@o/Wj9vj5iMdfbf2l338MNWE7TxWCeYwlK@KLlIXcdHmd4oZUz2Lpdq1tn7BNWBY@VavcMVbUtQLdQLvDBpbDtxZwHrOoI8adf3Be4hzVIjov1KBciljihGotNFS7erS0kmwIwUuaibuLQmbe7f1LDodwwtd9L4z9CzbAkl7ZpD8@Md2J55CpFzCFi0h9nUqft@K0Nf2mcqll5XfkNZBncMzXOCJ@krAzzzvEWF7ILGdqqo@5ApLsjE88l/S7XatP1JDGakLtTpuve96ZybD@LyxuvWlhNszuOGbMWy2XIOoLFd3jE37EehCwY@hZiL/ZEClW7IgNTReGHEZ8c4vfM/YeXQ7A5ri14R2H7fTYQPc54AC4QF0tHADd08K7rQaFtzjVnOjbeJ5az63zVN9WxbsPikPz7sHeA15Hgztbwd0K7TtTu7a0a0O17@Gu0iG3/wE "R – Try It Online")
Not really short, and definitely not giving the shortest path (e.g. check the first example).
It basically performs a recursive depth-first search and stops as soon as the target has been reached, printing the path.
Thanks to JayCe for the improvement in output formatting
[Answer]
# [Python 2](https://docs.python.org/2/), ~~151~~ 149 bytes
```
N,s,e,o=input()
P=[[s]]
for p in P:x,y=k=p[-1];k==e>exit(p);P+=[p+[[x+a,y+b]]for a,b in((0,1),(0,-1),(1,0),(-1,0))if([x+a,y+b]in o)==0<=x+a<N>y+b>-1]
```
[Try it online!](https://tio.run/##PY3NCoMwEITvPkWOCVkh2j9bXR9BvIc9KCgNggnVgj693dDSy3y7w85s2Nenn/PjaGCBATy6ObxXqZIWrV2IktG/RBBuFu1jgx0nDDbNqJwQh3rY3CqDKluNNmhrN93BrnuiGOqg55iUBjIFrGlEBoY1jVBulP8E93uFaCpkp2pq9mp@cxx3EPYKwhDzBKKItAbEJQ45iJy@B@fI4rczb0Qf "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~133~~ ~~131~~ 130 bytes
* -1 byte thanks to [BWO](https://codegolf.stackexchange.com/questions/171550/get-me-out-of-here/171698?noredirect=1#comment414551_171698)
```
(n!p)o=head.(>>=filter(elem p)).iterate(\q->[u:v|v@([x,y]:_)<-q,u<-[id,map(+1)]<*>[[x-1,y],[x,y-1]],all(/=u)o,x`div`n+y`div`n==0])
```
[Try it online!](https://tio.run/##XVFbbsIwEPzPKRapH3ZZ07ygFMVRL9ATGAsiJRVWEydAEgWpd0/txAUJ/8zu7O6MvT5l15@iLMeR6EVDa34qsnxF0pR/q7ItLqQoiwoaSlfKZFlbkP2ZpaLb9b/9JxED3uTuQBN2xi5hQuVYZQ1ZBlQmr6kQAwtMA9o2FkiJWVmSN97RGodjrvqjXt5m5NyXdFS66dorcBAeuEM2CCJA8KVBG4Q2CBHWFtcIVtZURGQpKSk@Rj9MYfM/6ruR0EmYQmxx63KD73ep7ZOS8bECd6VAzrcKnOKE0YOPHB85fsLY4uwQW3NjMTlIz6sypc2zze6@DkD2RCM0CDVCS4Gl0FyUbuEFiIaF@QuoLT8va/wD "Haskell – Try It Online") (with a few testcases)
A function `!` taking as input
* `n :: Int` size of the grid
* `p :: [Int]` player's position as a list `[xp, yp]`
* `o :: [[Int]]` obstacles position as a list `[[x1, y1], [x2, y2], ...]`
* `t :: [[[Int]]]` (implicit) target's position as a list `[[[xt, yt]]]` (triple list just for convenience)
and returning a valid path as a list `[[xp, yp], [x1, y1], ..., [xt, yt]]`.
As a bonus, it finds (one of) the shortest path(s) and it works for any player's and target's position. On the other hand, it's *very* inefficient (but the examples provided run in a reasonable amount of time).
## Explanation
```
(n ! p) o = -- function !, taking n, p, o and t (implicit by point-free style) as input
head . -- take the first element of
(>>= filter (elem p)) . -- for each list, take only paths containing p and concatenate the results
iterate ( -- iterate the following function (on t) and collect the results in a list
\q -> -- the function that takes a list of paths q...
[u : v | -- ... and returns the list of paths (u : v) such that:
v@([x, y] : _) <- q, -- * v is an element of q (i.e. a path); also let [x, y] be the first cell of v
u <- [id, map (+ 1)] <*> [[x - 1,y], [x, y - 1]], -- * u is one of the neighbouring cells of [x, y]
all (/= u) o, -- * u is not an obstacle
x `div` n + y `div` n == 0 -- * [x, y] is inside the grid
]
)
```
This function performs a recursive BFS via `iterate`, starting from the target and reaching the player's starting position. Paths of length \$k\$ are obtained by prepending appropriate cells to valid paths of length \$k-1\$, starting with the only valid path of length 1, that is the path `[[xt, yt]]`.
The apparently obscure expression `[id, map (+ 1)] <*> [[x - 1,y], [x, y - 1]]` is just a "golfy" (-1 byte) version of `[[x + 1, y], [x, y + 1], [x - 1, y], [x, y - 1]]`.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~79~~ 75 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
{⍺←0j¯1⋄n p t o←⍵⋄p=t:p⋄p,(-∘p∇⊣@1∘⍵)⊃s/⍨{~∨/¯1n∊9 11○⍵}¨s←o~⍨p+⍺×0j1*3⌽⍳4}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9e4CMbIOrTd81N2Sp1CgUKKQDxR51LsVyC@wLbEqANE6GrqPOmYUPOpof9S12MEQyAYq0HzU1Vys/6h3RXXdo44V@kAj8h51dFkqGBo@mt4NlK89tKIYaFR@HVBJgTbQpsPTDbIMtYwf9ex91LvZpPZ/GtiiPqAxh9YbP2qbCHRXcJAzkAzx8Az@n6ZgomCQZaBgDMQahkDCMMtQwSjLSJMLImMIlDFGlQEA "APL (Dyalog Unicode) – Try It Online")
-4 bytes by refactoring `c` thanks to @Adám.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 79 [bytes](https://codegolf.meta.stackexchange.com/a/9429/78410)
```
{⍺←0j¯1⋄n p t o←⍵⋄p=t:p⋄c←⊃s/⍨{~∨/¯1 n∊9 11○⍵}¨s←o~⍨p+⍺×0j1*3⌽⍳4⋄p,(c-p)∇c@1⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6sf9e4CMbIOrTd81N2Sp1CgUKKQDxR51LsVyC@wLbEqANLJIJGu5mL9R70rqusedazQB6pXyHvU0WWpYGj4aHo3UHntoRXFQGX5dUA1BdpAcw9PN8gy1DJ@1LP3Ue9mE5BpOhrJugWajzrakx0MH3UtAmn6nwa2rA9o@qH1xo/aJgLdFhzkDCRDPDyD/6cpmCgYZBkoGAOxhiGQMMwyVDDKMtLkgsgYAmWMUWUA "APL (Dyalog Unicode) – Try It Online")
Takes a 4-element array `N P T O` as input, where `N` is an integer and the coordinates are represented as complex numbers.
Interprets a complex number `x + yi` (`XjY` in APL's notation) as the position `(x, y)`, where `(0, 0)` is at the bottom left of the board and `x` and `y` directions are right and upwards respectively. Uses the right-hand-touching algorithm in this view, which works because both the start and the target are adjacent to the outer wall (and the minimal path is not required). The path may have multiple copies of the same coordinates when it encounters a dead end. To ensure that the player is touching the right-hand wall at start, the direction is initialized to the downwards direction `-i`.
### Ungolfed with comments
```
f←{
⍺←0j¯1
d←⍺ ⍝ direction, default down
n p t o←⍵ ⍝ decompose the inputs
p=t:p ⍝ player = target: reached the goal
turn←0j1*¯1 0 1 2 ⍝ turns to try out, right turn first
steps←o~⍨p+d×turn ⍝ possible steps from current position
chosen←⊃steps/⍨{~∨/¯1 n∊9 11○⍵}¨steps ⍝ the free spot with highest precedence
d2←chosen-p ⍝ keep track of the previous step
p,d2∇n chosen t o ⍝ move one step and recurse
}
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 229 bytes
```
.
$&$&
@@
s@
##
.#
{`(\w.)\.
$1l
\.(.\w)
r$1
(?<=(.)*)\.(?=.*¶(?<-1>.)*(?(1)$)\w)
d
}`\.(?=(.)*)(?<=\w(?(1)$)(?<-1>.)*¶.*)
u
+T`.`#`.(?=(.)*)(?<=d#(?(1)$)(?<-1>.)*¶.*)|(?<=(.)*.).(?=.*¶(?<-2>.)*(?(2)$)u#)|(?<=#r).|.(?=l#)
.(.)
$1
```
[Try it online!](https://tio.run/##bY8xDsIwDEV3X8NRZQdhKZ0pzSEYMwSpDEgVQwF1oFyrB@jFilNaBKgeLMv//fy4Od3Ol@M4CpjMZOA9XD0ggiA8IoVWOKjkaghCElqGxjigcleQsFWNykLs0Otm6/a6opIcG05kBc84AROaPKGd5Q8@9GIZ7rA5RIkYf@gKV@luSRf@Ts/n9FwNd3xT2LB0CaqRQf/PeomeakVLG8hSf1MCcFX1suqdXpQX "Retina 0.8.2 – Try It Online") Not sure whether the I/O format qualifies. Explanation:
```
.
$&$&
```
Duplicate each cell. The left copy is used as a temporary working area.
```
@@
s@
```
Mark the start of the maze as visited.
```
##
.#
```
Mark the end of the maze as being empty.
```
{`(\w.)\.
$1l
\.(.\w)
r$1
(?<=(.)*)\.(?=.*¶(?<-1>.)*(?(1)$)\w)
d
}`\.(?=(.)*)(?<=\w(?(1)$)(?<-1>.)*¶.*)
u
```
While available working cells exist, point them to adjacent previously visited cells.
```
+T`.`#`.(?=(.)*)(?<=d#(?(1)$)(?<-1>.)*¶.*)|(?<=(.)*.).(?=.*¶(?<-2>.)*(?(2)$)u#)|(?<=#r).|.(?=l#)
```
Trace the path from the exit to the start using the working cells as a guide.
```
.(.)
$1
```
Delete the working cells.
[Answer]
## JavaScript, 450 bytes
Takes input as `(n, {playerx, playery}, {targetx, targety}, [{obstaclex, obstacley}])`.
Returns an array of `{hopx, hopy}`.
```
j=o=>JSON.stringify(o);l=a=>a.length;c=(a,o)=>{let i=l(a);while(i>0){i--;if(j(a[i])==j(o)){return 1;}}return 0;}h=(p,t,o)=>{if(p.y<t.y&&!c(o,{x:p.x,y:p.y+1})){return{x:p.x,y:p.y+1};}if(p.y>t.y&&!c(o,{x:p.x,y:p.y-1})){return{x:p.x,y:p.y-1};}if(p.x<t.x&&!c(o,{x:p.x+1,y:p.y})){return{x:p.x+1,y:p.y};}if(p.x>t.x&&!c(o,{x:p.x-1,y:p.y})){return{x:p.x-1,y:p.y};}return t;}w=(n,p,t,o)=>{let r=[];r.push(p);while(j(p)!==j(t)){p=h(p,t,o);r.push(p);}return r;}
```
Here is an unobfuscated version on my mess:
```
// defining some Array's function for proper comparaisons
json = (object) => { return JSON.stringify(object) };
length = (array) => { return array.length; }
contains = (array, object) => {
let i = length(array);
while (i > 0) {
i--;
if (json(array[i]) == json(object)) { return true; }
}
return false;
}
//return next found hop
getNextHop = (player, target, obstacles) => {
//uggly serie of conditions
//check where do we have to go and if there is an obstacle there
if(player.y<target.y && !contains(obstacles, [x:player.x, y:player.y+1])) { return [x:player.x, y:player.y+1]; }
if(player.y>target.y && !contains(obstacles, [x:player.x, y:player.y-1])) { return [x:player.x, y:player.y-1]; }
if(player.x<target.x && !contains(obstacles, [x:player.x+1, y:player.y])) { return [x:player.x+1, y:player.y]; }
if(player.x>target.x && !contains(obstacles, [x:player.x-1, y:player.y])) { return [x:player.x-1, y:player.y]; }
return target;
}
//return found path
getPath = (gridsize, player, target, obstacles) => {
let path = [];
path.push(player);
//while player is not on target
while(json(player)!=json(target)) {
player = getNextHop(player, target, obstacles); //gridsize is never used as player and target are in the grid boundaries
path.push(player);
}
return path;
}
```
] |
[Question]
[
So your task is to take a 3x3 block where `-`'s mean blank spaces, and `*`'s mean filled spaces, for example:
```
-**
-*-
*-*
```
and rearrange the block so that the `*`'s form an X, like this:
```
*-*
-*-
*-*
```
**Input:**
3x3 squares like above, they can be 3 lines, an array, or however you want.
**Output:** The shortest amount of moves to rearrange into an X. Each move is flipping 2 characters that are touching, and are horizontal from each other, vertical from each other, or diagonal from each other. If it's not possible, return any impossible output, for example `999` or `-4242`. `5` is the smallest such number.
**Test Cases:**
1) Output: 1
```
-**
-*-
*-*
```
2) Output: -1
```
-*-
-*-
*-*
```
3) Output: 3
```
---
-**
***
```
4) Output: 0
```
*-*
-*-
*-*
```
**You can substitute the blank and non blank characters but be sure to include which is which in your post**
**Code Golf**
Remember this is code golf the shortest code wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
5ḶḤd3ạŒ!Ṁ€€ḅ1Ṃ
T’d3Ç-L=5Ɗ?
```
[Try it online!](https://tio.run/##y0rNyan8/9/04Y5tD3csSTF@uGvh0UmKD3c2PGpaA0QPd7QaPtzZxBXyqGFmivHhdl0fW9NjXfb/D7cDJf//j@aKNtAxBEIDBI7l0sEUNQCLoqhDUguBhjAIN8EAVW0sAA "Jelly – Try It Online")
---
Take a flat list as input.
Too bad that Jelly doesn't have "multidimensional truthy indices"... `T€ṭ€"JẎ` also works but takes 1 more byte.
---
Algorithm: There are 5 current block positions and 5 targets (destinations), the algorithm tries each of the 5! matching, and output the minimum sum of [source, destination] Chebyshev distance.
[Answer]
## [Haskell](https://www.haskell.org/), 176 132 126 104 bytes
```
w=0:1:w
m a|sum a/=5=5|1>0=sum$[a!!4|3<-sum.map(a!!)<$>[[0,1,2],[0,3,6],[2,5,8],[6,7,8]]]++zipWith(*)a w
```
[Try it online!](https://tio.run/##bY9PC4JAEMXvfYoJPFhttauuRrh@gm4dOsgelgiUsqTdEMLvbjNh2D8Y3mPgx5s3hbHHw@nUub0ABTlnIJ7Dv1SP3D4YCP6fCHuCvxHDEBER8Sd/yJA9IX6q0BARf/T45ohIPq68E68MSwQ@zQD/IglJIhJJEpMkumsUX4t1M6rAtPaGulRSyVZkXOHq5WY8jtowneOyqEzt4z5JvSzHfoIFmqGHLEYPmGQr9Jgl6FrPZvey3pWu8KcTA01XmfKMneqb27rr5gwe2OLSoGEqVFjGdg8 "Haskell – Try It Online")
---
Takes a list of integers with 1 as the non-blank character. Sums the number of non-zero even-indexed squares, then adds 1 if any of the double move patterns are found (center square and edge column/row completely filled). The last part's a bit wasteful I think, probably could be much improved over this brute-force method. Returns 5 (an impossible output) on an impossible input.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~194~~ 192 bytes
```
from itertools import*
f=lambda l,k=0:-(sum(l)!=5)or[1,0]*4!=l[:-1]and k<4and-~min(f(l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:],k+1)for a,b in combinations(range(9),2)if max(b/3-a/3,abs(a%3-b%3))<2)
```
[Try it online!](https://tio.run/##bY/NasMwEITvforNISDFMpHi5FATP4nQYdVYrbB@jKRCe@mru7abtrSUYVnmYxlmp7fyHMNpnk2KHmwZUonRZbB@iqkcKtM79PqG4NjY864h@cUTR3f9hcYkBePqcN71TnaNUBhuMF7Py2revQ3EkIWjqqWTWqnaSaxFpzePm9eLV2ysBTUxATINNsBj9NoGLDaGTBKGp4E8UHai1oDHV6KPbYPHlqHOBPdto/ctpdcTncuQS4YeZAUgOROL@M8o9oX5f5jf8V2f@FfA3xDxfc9Vpapq/WCtsL6wVemW2ynZUMCQFdD5Aw "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 123 bytes
Takes input as a 9-bit integer. Solves the puzzle by naively applying the rules, which has been proven not to be the shortest approach.
```
f=(n,k=b=-1)=>n^341?k>2?b:[3,6,9,10,17,18,20,34,36].map(m=>[1,8,8].map(M=>(x=n&(m*=M))&-x^x||f(n^m,k+1)))|b:!~b|k<b?b=k+1:b
```
[Try it online!](https://tio.run/##jY7BboJQEEX3fAXdmDd0kBkxlpIOfAFfYCThqTSKPExtGhakv04fyMamjd5Z3MxkTu49Fl/FZftxOH/6ptnt@74UZbASLT6DJCYPl5xWySLV8TrEFb4iE/ILcoQLwnCJ4Wozr4uzqiVZM0YYXddMEtWKmanakwxg5rd523WlMnmN1TMDQKfjp2/dVW861WJPse4DzyVmx3Wt0WBM7HqBs23MpTnt56fmXZWKtH2icQCckaFHGLphaGLGOOa/GSsedGUsfD9navar24Ta3v904yGIAPof "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f = recursive function taking:
n, // n = input
k = // k = number of moves, initialized to -1
b = -1 // b = best result so far, initialized to -1
) => //
n ^ 341 ? // if n does not match the target pattern:
k > 2 ? // if we've already done more than 3 moves:
b // we're not going to find a solution -> abort
: // else:
[3,6,9,10,17,18,20,34,36] // for each swap bitmask m
.map(m => // and
[1,8,8] // for each multiplier M:
.map(M => // apply the multiplier to m and
(x = n & (m *= M)) // apply the final bitmask to n -> this gives x
& -x // isolate the least significant bit of x
^ x || // if it's the only bit set,
f(n ^ m, k + 1) // then swap the bits and make a recursive call
)) | b // end of both map() loops; return b
: // else:
!~b | k < b ? b = k + 1 : b // this is a solution in k+1 moves: update b
```
**NB**: This codes performs some illegal moves beyond the top of the board when **m** is multiplied by 64. But they are simply ignored, as they can't possibly lead to a shorter solution than the best legal solution.
Below are the 9 base swap bitmasks and the target pattern. The top left corner is the most significant bit.
```
000 000 001 001 010 010 010 100 100 101
011 110 001 010 001 010 100 010 100 010 (341)
(3) (6) (9) (10) (17) (18) (20) (34) (36) 101
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ċȤ‘ḤB;U$=a¥;Ḋm2ƊẠ€SɓSn5Nȯ
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5wj3SeWPGqY8XDHEifrUBXbxENLrR/u6Mo1Otb1cNeCR01rgk9ODs4z9Tux/v///9EGOoY6BjpcCiDSEEwDWbEA "Jelly – Try It Online")**
A monadic link.
### How?
Inspired by [Bubbler's Python answer](https://codegolf.stackexchange.com/a/161574/53748); golfed to suit Jelly...
```
“ċȤ‘ḤB;U$=a¥;Ḋm2ƊẠ€SɓSn5Nȯ - Link: length 9 list of ones & zeros, X
“ċȤ‘ - list of code-page indices = [232,154]
Ḥ - double = [464,308]
B - to binary = [[1,1,1,0,1,0,0,0,0],[1,0,0,1,1,0,1,0,0]]
$ - last two links as a monad:
U - upend = [[0,0,0,0,1,0,1,1,1],[0,0,1,0,1,1,0,0,1]]
; - concatenate = [[1,1,1,0,1,0,0,0,0],[1,0,0,1,1,0,1,0,0],[0,0,0,0,1,0,1,1,1],[0,0,1,0,1,1,0,0,1]]
¥ - last two links as a dyad:
a - logical AND (vectorises)
= - equal? (vectorises)
Ɗ - last three links as a monad:
Ḋ - dequeue X (remove leftmost element)
2 - literal two
m - modulo slice (keeps the "edge-elements")
; - concatenate
Ạ€ - all? for €ach (edge-elements: no-op
- else: 1 for any cost-2 element 0 otherwise)
S - sum
ɓ - new dyadic chain ^that on the right; X on the left
S - sum X
5 - literal five
n - not equal?
N - negate (-1 if not exactly 5 1s, 0 otherwise)
ȯ - logical OR with right
```
[Answer]
# JavaScript, 85 bytes
```
s=>/^0*(10*){5}$/.test(s)*s.match(/(?=1.(..)*$|^1(..)?11.1|1.11(..)?1$)|$/g).length-1
```
This is a regex port of [Bubbler's answer](https://codegolf.stackexchange.com/a/161574/44718).
Input as a string of 0 / 1.
```
f=
s=>/^0*(10*){5}$/.test(s)*s.match(/(?=1.(..)*$|^1(..)?11.1|1.11(..)?1$)|$/g).length-1
document.write('<table>'+('<tr>'+'<td><label><input type=checkbox><span></span></label>'.repeat(3)).repeat(3)+'</table>');
document.write('Answer: <output id=o></output>');
U=()=>o.value=f(ii.map(i=>i.checked?1:0).join``);
ii=[...document.querySelectorAll('input')];
ii.forEach((i,p)=>{
i.checked=!(p%2);
i.oninput=U;
});
U()
```
```
label{display:block;position:relative;overflow:hidden;width:20px;height:20px;}
input{position:absolute;top:-200%;}
input~span{width:100%;height:100%;display:block;border:1px solid black;box-sizing:border-box;}
input:focus~span{border-color:red;}
input:checked~span{background:#ace;}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~23~~ 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ç╙╤Ü┤└åVτ┐├Y-²▼░█∩¡3ëâ
```
[Run and debug it](https://staxlang.xyz/#p=80d3d19ab4c08656e7bfc3592dfd1fb0dbefad338983&i=[1,1,1,1,1,0,0,0,0]%0A[1,0,1,0,1,0,1,1,0]%0A[1,0,1,0,1,0,1,0,1]%0A[1,0,1,0,1,0,1,0,0]&a=1&m=2)
This program takes an array of `[0, 1]` as input, and returns an integer number of moves, or an empty string if no solution is possible.
Consider this indices for the grid
```
0 1 2
3 4 5
6 7 8
```
* If there are not exactly 5 `1`s in the input, then there is no solution, so we produce no output.
* The centers of each side are the incorrect positions. These are indices 1, 3, 5, and 7. Summing the distance for each `1` in these positions will produce the final result.
* For each `1` in an incorrect position its distance is either 1 or 2. It will be 2 iff it's surrounded by other `1`s. For example, if there are `1`s at indices [0, 1, 2, 4], then the distance for the incorrect `1` is 2.
* With this in mind, consider this pseudo-code for getting the distance contributed to the result by index 1.
1. Read 4 bits from indices [1, 0, 2, 4]. This puts the incorrect position in the most significant position.
2. Convert these bits to a number `b` from 0 to 15.
3. When `0 <= b <= 7` the distance is 0. When `8 <= b <= 14` the distance is 1. When `b == 15` the distance is 2. This can be calculated using integer division by `b * 2 / 15`.
So the total distance can be calculated by repeating this process 4 times and rotating the grid in between.
```
1#5=4* if the number of 1s is 5, then 4, else 0
D repeat the rest of the program that many times
x push the value in the x register, which is initially the input
3/ split into 3 rows
rM rotate 90 degrees
$X flatten back into single array, and save the "rotated" array in the X register
A|2E get the digits of 2^10 i.e. [1,0,2,4]
@ read the bits from the current rotation at indices [1,0,2,4]
:b convert bits to integer
H15/ double, then divide by 2
+ add to running total
```
[Run this one](https://staxlang.xyz/#c=1%235%3D4*%09if+the+number+of+1s+is+5,+then+4,+else+0%0AD+++++%09repeat+the+rest+of+the+program+that+many+times%0A++x+++%09push+the+value+in+the+x+register,+which+is+initially+the+input%0A++3%2F++%09split+into+3+rows%0A++rM++%09rotate+90+degrees%0A++%24X++%09flatten+back+into+single+array,+and+save+the+%22rotated%22+array+in+the+X+register%0A++A%7C2E%09get+the+digits+of+2%5E10+i.e.+[1,0,2,4]%0A++%40+++%09read+the+bits+from+the+current+rotation+at+indices+[1,0,2,4]%0A++%3Ab++%09convert+bits+to+integer%0A++H15%2F%09double,+then+divide+by+2%0A++%2B+++%09add+to+running+total&i=[1,1,1,1,1,0,0,0,0]%0A[1,0,1,0,1,0,1,1,0]%0A[1,0,1,0,1,0,1,0,1]%0A[1,0,1,0,1,0,1,0,0]&a=1&m=2)
[Answer]
# Excel, ~~86~~ 81 Bytes
```
=SUM(B1,A2,B3,C2)+B2*(AND(A1:A3)+AND(A1:C1)+AND(C1:C3)+AND(A3:C3))/(SUM(A1:C3)=5)
```
**Old:** *When the 'impossible' output was `-1`*
```
=IF(SUM(A1:C3)=5,SUM(B1,A2,B3,C2)+B2*(AND(A1:A3)+AND(A1:C1)+AND(C1:C3)+AND(A3:C3)),-1)
```
Uses `1` for filled and `0` for empty, input in range `A1:C3`. ~~Possible to golf further if we can return values other than `-1` for "impossible".~~ Returns a `#DIV/0!` error on impossible grids
Operates on the same logic as [Bubbler's Python answer](https://codegolf.stackexchange.com/a/161574/78385).
] |
[Question]
[
There's already a comprehensive list of tips for python [here](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python), so what I'm asking for are tips that specifically apply to using the `numpy`, `scipy` or `pylab` libraries.
These can be either ways to shorten code already using `numpy`, or ways to shorten common python operations by using these libraries.
One tip per answer, please.
[Answer]
# Make use of Numpy's [broadcasting](https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html)
Broadcasting means replicating a multidimensional array along some of its singleton dimensions to match the size of another array. This happens automatically for Numpy arrays when arithmetic operators are applied to them.
For example, to generate a 10×10 multiplication table you can use
```
import numpy
t=numpy.arange(1,11)
print(t*t[:,None]) # Or replace t[:,None] by [*zip(t)]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PzO3IL@oRCGvNLegkqvEFkzrJRYl5qWnahjqGBpqchUUZeaVaJRolURb6fjl56XGav7/DwA)
Here `t` is created as the Numpy array `[1, 2, ..., 10]`. This has shape (10,), which is equivalent to (1,10). The other operand array, `t[:,None]`, has size (10,1). Multiplying the two arrays implicitly replicates them, so they behave as if they both had shape (10,10). The result, which also has shape (10,10), contains the products for all pairs of entries in the original arrays.
[Answer]
# Use r\_[...] instead of range(...)
Numpy provides matlab like syntax for array creation using `r_[...]`. Any slice notation in between the brackets is interpreted as an array with the range indicated. So, for instance
```
r_[:30:4]
```
is equivalent to
```
arange(0,30,4)
```
and for most uses can replace
```
range(0,30 4)
```
It can also handle more complex expressions.
For example to get indices from 0 up to 10 and back down again,
```
r_[:10,10:-1:-1]
```
[Answer]
# The shorter than shortest infinite for comprehension
If numpy is \*-imported then using [this "feature"](https://stackoverflow.com/q/69878231/15752941) of `numpy.r_`/`numpy.c_` an infinte counter is as cheap as:
```
for[i]in r_:print(i)
```
This is significantly shorter than [this](https://codegolf.stackexchange.com/a/237171/107561) pure Python trick and has the added benefit of actually creating a proper counter.
This can also be used for a cheaper `enumerate`:
```
S="abcde"
for x,[i]in zip(S,r_):print(i,x)
```
If you can live with a "boxed" counter, i.e. [0],[1],[2],... rather than 0,1,2,... then you can save the brackets around `i`.
The boxes can even be useful: For example, if we have set up a loop anyway, then we can as a byproduct create a reversed "range" of the same length as the looped over sequence S:
```
C=[]
for e,C[:0]in zip(S,r_):f(e)
```
If for some reason you need double boxes [[0]],[[1]],[[2]],... use `c_` instead of `r_`.
[Answer]
# Don't forget the matrix class
It may be aesthetically challenged and semi-deprecated since all but forever but it can be useful for golfing.
Here is an example [How to solve the LCM in 50 bytes of Python](https://codegolf.stackexchange.com/q/237855/107561) where on a non numpy specific challenge it allows us to outgolf @dingledooper's extremely clever pure Python approach by ~10%. And that's counting the numpy import and without requiring us to be particularly smart:
```
from numpy import*
print(lcm(*mat(input()).A1))
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1chrzS3oFIhM7cgv6hEi6ugKDOvRCMnOVdDKzexRCMzr6C0RENTU8/RUFPz/38TM2NjcwUgaWQOAA "Python 3 – Try It Online")
This shows off three useful features:
1. Short constructor name `mat` although not as short as `r_` or `c_`
2. Hilariously graceful input parser. For example, it will accept
```
mat("""[1 2]\t[3,4];5 6 7
8""")
```
without complaint.
3. a handful of very short-named attributes, viz. `A,A1,T,H,I` which are the underlying array object,the same flattened,the transpose,the conjugate transpose and the pseudo inverse.
Finally, there is one more useful feature that we didn't use in the example:
4. Overloaded `*` operator. That in itself doesn't gain us much over the `@` operator for standard numpy arrays but for example taking the matrix power can be done using `**` much shorter than `linalg.matrix_power`.
] |
[Question]
[
An [Izhikevich neuron](https://www.izhikevich.org/publications/spikes.pdf) is a simple yet quite effective model of a biological neuron, designed for use in a discrete time-stepping simulation. In this golfing challenge, you will be implementing this model.
**Parameters**
This model involves only 7 variables organized into 2 differential equations, compared to the dozens of parameters of a physiologically accurate model.
* `v` and `u` are the two state variables of the neuron. Here, `v` is the "fast" variable representing the cell potential over time, and `u` is the "slow" variable representing certain membrane properties. The `v` variable is the most important one, as this is the output of the simulation.
* `a`, `b`, `c`, and `d` are fixed constants that describe the properties of the neuron. Different types of neurons have different constants, depending on the desired behavior. Notably, `c` is the reset potential, which is the membrane potential the cell returns to after spiking.
* `I` represents the input current to the neuron. In network simulations, this will change over time, but for our purposes we will treat `I` as a fixed constant.
**The Model**
This model has very simple pseudocode. First, we take the constant values of `abcd` and use them to initialize `v` and `u`:
```
v = c
u = b * c
```
Next, we loop through the simulation code as many times as desired. Each iteration represents 1 millisecond of time.
```
for 1..t:
if v >= 30: # reset after a spike
v = c
u = u + d
v += 0.04*v^2 + 5*v + 140 - u + I
u += a * (b*v - u)
print v
```
Certain real-world implementations include additional steps for numerical accuracy, but we aren't including those here.
**Input**
As input, your program/function should take the values of `a`, `b`, `c`, `d`, `I`, and `t` (the number of time steps to simulate). Once set, none of these parameters will be changing during our simple simulation. The order of input does *not* matter: you can specify the order in which your program takes these parameters.
**Output**
Output will be a list of numbers representing the cell's membrane potential (given by variable `v`) over the course of the simulation. The list can be in any appropriate format.
You have the choice of whether to include the 0th value of the simulation (the initial configuration before any time has passed) in your output. For example, for an input of `0.02 0.2 -50 2 10 6` (for `a b c d I t`), an output of either
```
-50
-40
-16.04
73.876224
-42.667044096
-25.8262335380956
29.0355029192068
```
or
```
-40
-16.04
73.876224
-42.667044096
-25.8262335380956
29.0355029192068
```
is acceptable.
Your values do *not* have to be exactly the same as those above, depending on how your language handles floats.
**Reference Implementation**
Here is a [TIO implementation](https://tio.run/##PY29DoMwDIT3PIWFPIRgokBhorDzDl34lZAQRQiyVDx7GkdVJQ93vu/sfTrW0jmJHWFPOBCOhC3hGUMNk@1W@WziSgi03uNQCbxY9KCCE/P7kJnWnv8IgGWWHmxqeJjgAf69YEL3ggRw5M0tApDUYLQpFFqlch@WipeQFQbSH94yztL3O/9bYs8QxzFH@7FsJ0RoX1tUids5fzAno3NKS0M5ZcaP@QI) I wrote in Perl to demonstrate the model. The parameters are that of a "chattering" neuron from the paper linked above, and this serves as a demonstration of how this model is able to recreate some of the more complex properties of neurons, such as alternating between states of high and low activity. If you look at the output, you can see where the neuron immediately spikes several times, but then waits a while before spiking several more times (despite the cell input voltage `I` being constant the whole time).
[Answer]
# [R](https://www.r-project.org/), ~~110~~ 99 bytes
Anonymous function that takes 6 arguments. Nothing fancy, just a straightforward port of the reference implementation. The updating of `u`, `v`, and the printing of `v` have all been combined into a single line, thanks to the fact that R's `print` returns the value that is being printed, so you can use it in assignment. Many thanks to Giuseppe for saving 11 bytes!
```
pryr::f({v=c;u=b*c;for(i in 1:t){if(v>=30){v=c;u=u+d}
u=a*b*(v=print((.04*v+6)*v+140+I-u))-a*u+u}})
```
[Try it online!](https://tio.run/##LcqxDoMgEIDh3adgvAMhR2sdNNe9j6E2JCzWEI@kMTw7Zejyf8ufauB6pG@apgBX5m0WXvU2h0@CqOKu/HTiFQPkJ98J/4eYd@mEF71qyHykuJ8AjgadzYgtfiDzsoJoFy1GSsEaugDk6NYrci32Qb1q@saI9Qc "R – Try It Online")
[Answer]
# [Clean](https://clean.cs.ru.nl), ~~150~~ ~~145~~ ~~140~~ 138 bytes
```
import StdEnv
$a b c d i t=map snd(iterate(\(u,v)#(w,n)=if(30.0<v)(c,u+d)(v,u)
#y=0.04*w*w+6.0*w+140.0-n+i
=(a*b*y-a*n+n,y))(b*c,c))%(0,t)
```
[Try it online!](https://tio.run/##JU9BasMwELz7FQtJYVeWg@OkOVW39lDILdde1pJTBNYmJLKNP191Sw8zzAwMzPhxYCnpFqZxgMRRSkz32yPDJYcPmastQw8eAkTILvEdnhIw5uHBecAvnOxMG1yskItXPLS79m0m9HaqA@FsJ6o2q9P0aBaz1Kddq7w/atBIHSuHbHqzNmykFrsSYW@89UQv2NpM5ZJZlzjYgjY6pQ6aV5XQKfZ/4lR@/HXk72dpPs/lfRVO0f8bPXCO/S8 "Clean – Try It Online")
Defines the function `$ :: Real Real Real Real Real Int -> [Real]`, implementing the algorithm as described in the OP, starting from the 0th term.
[Answer]
# [Python 2](https://docs.python.org/2/), 100 bytes
```
a,b,c,d,I,t=input();v=c;u=b*c
exec"if v>=30:v=c;u+=d\nv=v*v/25+6*v+140-u+I;u+=a*(b*v-u);print v\n"*t
```
[Try it online!](https://tio.run/##HYlBDoIwEADvvoJwgnaLSwUONuudP3ChBWMvtTHtRl9f0cMkk5n4SY9n0KWsYMHBBjMk8iHm1LSGyZlMVrjT/t5d7e8V3@iC13@XtC2BiQWf9SgnwbIfUGU5/9YqGitY5dbElw@p4iXUIpWCHWrAToMaDwV90CNMXw "Python 2 – Try It Online")
Saved 2 bytes thanks to [user71546](https://codegolf.stackexchange.com/users/71546/user71546).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~107~~ ... ~~103~~ 101 bytes
Contributed by @apsillers
```
(a,b,c,d,I,t)=>[...Array(t)].map(_=>(v<30||(v=c,u+=d),v=v*(v/25+6)+140-u+I,u+=a*(b*v-u),v),u=b*(v=c))
```
[Try it online!](https://tio.run/##FctBDoIwEEDR60zb6ViquNGSuOQMxphSwGiQEqCTmHB3hPV//@PZT2F8D7PuY92srVvBY4UBayxxFq64E9FtHP0PZvGgrx/g6Qrg69EsC7ALmJSrBbJjCXywuToLlZ2MTqrck5dQSdZpEwKTq@T@CLFeQuyn2DXUxRe0QMYiWdS5QYuZwfNG/g "JavaScript (Node.js) – Try It Online")
**Original Approach: ~~105~~ 103 bytes. -1 byte Thanks Arnauld, and -2 bytes Thanks @Kamoroso94.**
```
(a,b,c,d,I,t)=>{for(u=b*(v=c);t--;){v<30||(v=c,u+=d);v=v*(v/25+6)+140-u+I;u+=a*(b*v-u);console.log(v)}}
```
[Try it online!](https://tio.run/##FcpLEoMgEADR6zAyGCTRDSF7j8FHU0lZYinMRj07Mdt@/bVkN79@liTmGIYymsIsOvQYsMcE5rWPcWXZuIqR8aCTEBp2et7lcfwLZm4CaDJ0DTfV8g5485Ai815fZCvmKhIZtI/zFqehnuKbEZxn0SOrpcJaoWglKmwkdlB@ "JavaScript (Node.js) – Try It Online")
**Or if popping alerts is OK, then ~~101~~ ... ~~99~~ 97 bytes (-1 byte Thanks Arnauld, -2 bytes Thanks @Kamoroso94):**
```
(a,b,c,d,I,t)=>{for(u=b*(v=c);t--;){v<30||(v=c,u+=d);v=v*(v/25+6)+140-u+I;u+=a*(b*v-u);alert(v)}}
```
```
var u, v;
var f =
(a,b,c,d,I,t)=>{for(u=b*(v=c);t--;){v<30||(v=c,u+=d);v=v*(v/25+6)+140-u+I;u+=a*(b*v-u);alert(v)}}
function run() {
f(...["a", "b", "c", "d", "I", "t"].map(x => document.getElementById(x).value * 1));
}
```
```
a = <input id="a" value="0.02"><br>
b = <input id="b" value="0.2"><br>
c = <input id="c" value="-50"><br>
d = <input id="d" value="2"><br>
I = <input id="I" value="10"><br>
t = <input id="t" value="6"><br>
<input type="button" value="Run" onclick="run()">
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 94 bytes
```
->a,b,c,d,i,t{v=c
u=b*c
t.times{v>=30?(v=c;u+=d):0
v+=0.04*v**2+5*v+140-u+i
u+=a*(b*v-u)
p v}}
```
[Try it online!](https://tio.run/##DcpBCsIwEEDRfU7hsp2ZhGlsN8rUg4iLJrWQhSCaDEjp2WPg7/77lPCrm1Q7LxQo0kqJ8q4STZEA0WSX0@v53XWWM9@6Nq4FZe0vbBSFHY@gAB4nUBxGtgWTaWCBLoDa0pv3SY@jbvdGPbHzZCcmTwO3@FH/ "Ruby – Try It Online")
Another straightforward port of the reference implementation, a lambda accepting 6 arguments.
[Answer]
# [Haskell](https://www.haskell.org/), ~~112~~ 111 bytes
```
(a#b)c d i t|let r(v,u)|v>=30=r(c,u+d)|p<-0.04*v^2+6*v+140-u+i=(p,u+a*(b*p-u))=fst<$>take t(iterate r$r(c,b*c))
```
[Try it online!](https://tio.run/##FcxBDoMgEADAr2yih10Qg9R6Ep/SBJWmRGsIAif/Tu15kvmYc7P7XgqaaqYFVnAQr91GCJibRFee9EPqgEuT@EqXH4VsZc/yS/GBZd71UiTuNPrbDcOZeZGI9PuMYz1Fs1mI6KINJloI9f@Z2UJUvsYdoMEHd0SoAe9VVbJVhOIpSUEnYSg/ "Haskell – Try It Online")
Does not output the zero case. Assumes that `c` is never `>=30` since that wouldn't make sense.
~~Never thought I'd have to use a `where` clause in a code golf but there are just too many variables.~~
EDIT: Thanks @Lynn for taking off a byte! I forgot that you can put `let` statements in guards. Sure kills the readability though
[Answer]
# [Element](https://github.com/PhiNotPi/Element), 81 bytes
```
_a;_b;_3:b~*u;_d;_I;_'[3:\.04*5+*140+u~-+I~++4:\
.`30<!b~*u~-+a~*u~+[d~+]u;[#2:]]
```
[Try it online!](https://tio.run/##FcoxDoQgEEDRfm5hLDZhAhkBLZi9gGdAMmqk291KWq7OSvWTl58/@Zt/d2tysJwsLpxVFZaLZWV5RRc2Q17NqCZPWKrGtSL6sIHZHb2Hfj949GC8KqbCcbQhpdYMWTAW9ExgYSJY/g "Element – Try It Online"), [Esolangs page](http://esolangs.org/wiki/Element)
**Explanation:**
```
_a;_b;_3:b~*u;_d;_I;_'[ ... ]
```
This part of the program takes input. It stores constants `a`, `b`, `d`, and `I` into variables. The input for `c` is never stored in a variable, but rather remains on the main stack throughout execution. Three copies are made: one on top for initializing `u`, one in the middle to serve as the initial `v`, and one on the bottom to serve as the constant `c`. The input for `t` is thrown immediately onto the control stack to serve as the basis of the FOR loop (the `[...]`) surrounding the rest of the program.
```
3:\.04*5+*140+u~-+I~++4:
```
This part of the program takes the current value of `v` and calculates the new value, and then four copies of the new `v` value are made.
```
\
.`
```
The first copy of `v` has a newline appended and is printed.
```
30<!
```
The second copy of `v` is used to test if the neuron has spiked. The result of this test is put on the control stack for later use.
```
b~*u~-+a~*u~+
```
This part computes the "delta `u`", meaning the amount to add to `u`.
```
[d~+]
```
This IF block adds `d` to the above sum if the neuron is spiking. This combines what would normally be two assignments into a single assignment.
```
u;
```
This stores the updated value of `u`.
```
[#2:]
```
This IF block is a continuation of the above IF block. If the neuron is spiking, delete the current value of `v` (which is now on the top of the main stack), and replace it with a duplicate of `c` (which has been on the bottom of the main stack this entire time).
And that's basically all there is to it. One minor note is that this thing leaks memory: it takes an extra `"#` in there to delete the top of the control stack (the evaluated IF condition) after each loop iteration.
Although I wouldn't call Element the most graceful golfing language, this challenge does allow me to showcase an interesting feature: due to the division between the main stack and control stack, I can take an IF statement and split the condition and body into multiple parts, interlaced with unconditional code.
[Answer]
# MATLAB, 111 bytes
```
function z(a,b,c,d,I,t)
v=c;u=b*c;for i=1:t if v>=30 v=c;u=u+d;end
v=.04*v^2+6*v+140-u+I
u=u+a*(b*v-u);
end
end
```
Pretty simple implementation, can probably be further improved.
] |
[Question]
[
m|Y bR|ain is We|iRd. F(o)R T(h)E La|sT fi(v)e YE|ars O|R s|o, (I) ha|ve C(u)T wO|rds in h(a)lf wh|En (I) s(e)e Th|em. Wh|EN I started Do|ing it, it To|oK a meN|TaL effort - B(u)T I almost cou(l)dn't N(o)T d|o it. N(o)w, I d|o it in the back of my head, a(n)d hardly ev|en not|iCe it. However, I thought this wo|uld make a great challenge.
# Definitions
For this challenge, each letter is given a point score, based on my judgement of its width in a sans-serif font. You will use this width to cut a word into two halves of equal width. The characters that this challenge will use are the alphabet in lower and upper cases, apostrophe, and hyphen.
```
Width Characters
1 i l I '
2 f j r t -
3 a b c d e g h k n o p q s u v x y z
4 m w A B C D E F G H J K L N O P Q R S T U V X Y Z
5 M W
```
For my explanations and test cases, `|` denotes the location in which a word can be cleanly split in half. `(` and `)` on either side of a letter indicate that that letter will be split in half to create a clean split.
# Input
Input will consist of a single "word" (which is not required to be in the dictionary). You can take this word in whatever text input you would like (String, char array, etc.). This word will only contain letters, `'`, and `-` (see above table). Because of what you will do with this word (see below), case of input is left to the developer's discretion. Trailing newlines allowed if needed.
# The Task
Permutate through all forms of the input (all letters at all possible upper or lower case positions). For example, for input `it's`, the below is all permutations:
```
it's
it'S
iT's
iT'S
It's
It'S
IT's
IT'S
```
To split a permutation of a word in half, the points on one side of the word must be the same as the points of the other side of the word. However, if a letter is stuck in between two even sections, you can also cut a letter cleanly in half.
Please note that "half" does not mean that you have moved halfway into the string. "Half" means that the points on both sides are equal.
Examples:
`W` is 5 points. `i` is 1 point. Splitting the permutation `Wiiiii` in half will result in `W | iiiii`, with 5 points on each side of the `|`.
`T` is 3 points. Splitting the permutation `TTTT` in half will result in `TT | TT`, with 6 points on each side of the `|`.
`w` is 4 points. a is 3 points. Splitting the permutation `waw` in half will result in `w (a) w`, with 5.5 points on each side. The points from `a` are distributed to both sides, as `a` is split in half.
# Output
Your output is an integer of the number of unique permutations of the input that can be cleanly split in half. Trailing newlines allowed if needed.
# Test Cases
I will be outputting all valid permutations of the input for the test cases. Remember that that is not part of the specs for you.
In my intermediate output, the numbers indicate the point value of the letter above them, so the output is a bit easier to visualize.
```
Input: a
( a )
3
( A )
4
Output: 2
Input: in
Output: 0
Input: ab
A | B
4 4
a | b
3 3
Output: 2
Input: abc
A ( B ) C
4 4 4
A ( b ) C
4 3 4
a ( B ) c
3 4 3
a ( b ) c
3 3 3
Output: 4
Input: will
W ( I ) L l
5 1 4 1
W ( I ) l L
5 1 1 4
W ( i ) L l
5 1 4 1
W ( i ) l L
5 1 1 4
w I | L l
4 1 4 1
w I | l L
4 1 1 4
w i | L l
4 1 4 1
w i | l L
4 1 1 4
Output: 8
Input: stephen
S T E ( P ) H E N
4 4 4 4 4 4 4
S T E ( p ) H E N
4 4 4 3 4 4 4
S T E | p h e n
4 4 4 3 3 3 3
S T e ( P ) H E n
4 4 3 4 4 4 3
S T e ( P ) H e N
4 4 3 4 4 3 4
S T e ( P ) h E N
4 4 3 4 3 4 4
S T e ( p ) H E n
4 4 3 3 4 4 3
S T e ( p ) H e N
4 4 3 3 4 3 4
S T e ( p ) h E N
4 4 3 3 3 4 4
S t E ( P ) H e n
4 2 4 4 4 3 3
S t E ( P ) h E n
4 2 4 4 3 4 3
S t E ( P ) h e N
4 2 4 4 3 3 4
S t E ( p ) H e n
4 2 4 3 4 3 3
S t E ( p ) h E n
4 2 4 3 3 4 3
S t E ( p ) h e N
4 2 4 3 3 3 4
S t e ( P ) h e n
4 2 3 4 3 3 3
S t e p | H E N
4 2 3 3 4 4 4
S t e ( p ) h e n
4 2 3 3 3 3 3
s T E ( P ) H E n
3 4 4 4 4 4 3
s T E ( P ) H e N
3 4 4 4 4 3 4
s T E ( P ) h E N
3 4 4 4 3 4 4
s T E ( p ) H E n
3 4 4 3 4 4 3
s T E ( p ) H e N
3 4 4 3 4 3 4
s T E ( p ) h E N
3 4 4 3 3 4 4
s T e ( P ) H e n
3 4 3 4 4 3 3
s T e ( P ) h E n
3 4 3 4 3 4 3
s T e ( P ) h e N
3 4 3 4 3 3 4
s T e ( p ) H e n
3 4 3 3 4 3 3
s T e ( p ) h E n
3 4 3 3 3 4 3
s T e ( p ) h e N
3 4 3 3 3 3 4
s t E ( P ) h e n
3 2 4 4 3 3 3
s t E p | H E N
3 2 4 3 4 4 4
s t E ( p ) h e n
3 2 4 3 3 3 3
s t e P | H E N
3 2 3 4 4 4 4
s t e p | H E n
3 2 3 3 4 4 3
s t e p | H e N
3 2 3 3 4 3 4
s t e p | h E N
3 2 3 3 3 4 4
Output: 37
Input: splitwords
S P L I T | W O r d s
4 4 4 1 4 5 4 2 3 3
<snip>
s p l i t w | o R d S
3 3 1 1 2 4 3 4 3 4
Output: 228
Input: 'a-r
' a ( - ) R
1 3 2 4
' a | - r
1 3 2 2
Output: 2
Input: '''''-
' ' ' ( ' ) ' -
1 1 1 1 1 2
Output: 1
```
# Victory
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. You must be able to output all test cases (so, all inputs up to 10 characters) in a reasonable amount of time. Do not artificially cap your input.
# ~~Bounty~~
I do not know if this is in the realm of possibility. However, you're golfers - you'll do anything for rep. I am offering a 200 rep bounty (I'll start it once this bounty condition is fulfilled, as it seems basically impossible to me) for a program that outputs the correct output for `antidisestablishmentarianism` in under 15 seconds on an average computer (aka mine). Please note that this test case must not be hard coded in any way.
@DigitalTrauma crushed my bounty, coming in well under two seconds. Check out his answer [here](https://codegolf.stackexchange.com/a/118049/65836).
[Answer]
# c, 378 bytes; about 0.6s for `antidisestablishmentarianism`
**Updated answer**. I read @JonathanAllan's comment about `i`s, and at first I didn't understand this optimization, but now I see that since both `i` and `I` have a width of 1, then we can count the associated permutations twice with only having to validate once. Previously my solution used multiple threads to spread the load over multiple CPUs and with that I was just about able to go through all 228 possibilities on my machine. Now with the `i` optimization there is no need to mess with threads - a single thread does the job easily within the time restriction.
Without further ado - golfed c function:
```
char m[128]={[39]=10,[45]=20};f(s,l,p)char *s;{m[65]?:bcopy("PPPPPPPPPPPdPPPPPPPPPdPPP <<<<<(<<(<P<<<<(<(<<P<<<",m+65,58);int g,h,u=0,v=0,x=0,y=0,c=0;if(p<l){g=s[p];if(g>64&&g-'i'){s[p]-=32;c+=f(s,l,p+1);}s[p]=g;c+=((g=='i')+1)*f(s,l,p+1);}else{for(l--,p=0,g=m[s[p]],h=m[s[l]];p<=l;){y=v;x=u;if(u+g>v+h){v+=h;h=m[s[--l]];}else{u+=g;g=m[s[++p]];}}c=u==v||y==x;}return c;}
```
The recursive function `f` takes 3 parameters - a pointer to the input string, the string length and the offset in the string to start processing (should be 0 for top-level call). The function returns the number of permutations.
[Try it online](https://tio.run/nexus/c-gcc#XVLRbpswFH3Pcz7AYmqDg9lI2kRdjbtPWB/2RtBEjAOWjIOwSZNRPruvy2ygCdmVjO45nHuPfe0zzZMKFNFi@RSTJnr4HpNFgKLHVUyWQYt3rkIClbBTzRVuimi9in88b@m@PLnO6xBTs9JP0GWgi9CGG4ZTN5y@9rlBNnNQ4a1XaPUEMZcaZChHNQnQwayjWSezKAkw37llKGCTERWVsYXZy/rx/j7zZ3wGG0v65GGJqUeGrXoLiFvLk8yyrpsRYrWGn48lTCjW7PaVK3wflcYuI0Vk62KUd5mIY1yGRGDYnMgBH0lt7Wsvezl4OWwOHslxr/R9q@071p7x7Vt5XmnplpKakMP7@4mQI24rputKAorb8xcuqahTBkKlU77/mr9MxlTFZWa5iR1QkXAJXJslVUYR6C9kbsABgmZih21/cnxJS1YVv6nUPdPrNVOaJoqpKAZkKLPhJA66Ai7HKNneIjqGb1yIMVaalTm7qVel4PptX6VqzM4Sv7rBNvwbJ6l5ys1edbIVXOUFkzqpeCK5KpxO1vZH6z7mJs14zKECDDgIgav4H7bfuZcTQ/AN/M9FQQyh0XseHA1jeOu6Mt3MN63LUQWP4cjVxuecjdq8L10hWySYtDlEIDD6q9bcqd65zq@hH9g4d2rjPANpqu/SjRkcGHuhS/fBtb16Dw8pwJN2cv5LdyLJ1Nn/ufyQe58mNGf/AA). TIO seems to typically run through all testcases (including `antidisestablishmentarianism` in under 2 seconds.
Note that there are some unprintables in the string that is `bcopy()`ed to `m[]`. The TIO seems to handle these correctly.
Ungolfed:
```
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
int width_tbl[] = {
['\''] = 1,
['-'] = 2,
['A'] = 4,4,4,4,4,4,4,4,1,4,4,4,5,4,4,4,4,4,4,4,4,4,5,4,4,4,
['a'] = 3,3,3,3,3,2,3,3,1,2,3,1,4,3,3,3,3,2,3,2,3,3,4,3,3,3
};
int
f (char *str, int len, int pos) {
int lidx, ridx;
int tot_width = 0;
int lwidth, rwidth;
int tot_lwidth = 0, tot_rwidth = 0;
int prev_tot_lwidth = 0, prev_tot_rwidth = 0;
char tmp;
int perm_cnt = 0;
if (pos < len) {
tmp = str[pos];
if (isalpha(tmp) && (tmp != 'i')) {
str[pos] = toupper(str[pos]);
perm_cnt += f(str, len, pos+1);
}
str[pos] = tmp;
perm_cnt += ((tmp == 'i') + 1) * f(str, len, pos+1);
} else {
//puts(str);
lidx = 0;
ridx = len - 1;
lwidth = width_tbl[str[lidx]];
rwidth = width_tbl[str[ridx]];
while (lidx <= ridx) {
prev_tot_rwidth = tot_rwidth;
prev_tot_lwidth = tot_lwidth;
if (tot_lwidth + lwidth > tot_rwidth + rwidth) {
tot_rwidth += rwidth;
rwidth = width_tbl[str[--ridx]];
} else {
tot_lwidth += lwidth;
lwidth = width_tbl[str[++lidx]];
}
}
if (tot_lwidth == tot_rwidth) {
perm_cnt = 1;
} else if (prev_tot_rwidth == prev_tot_lwidth) {
perm_cnt = 1;
}
}
return perm_cnt;
}
int main (int argc, char **argv) {
int i;
int perm_cnt;
if (argc > 0) {
char *str = strdup(argv[1]);
assert(str);
perm_cnt = f(str, strlen(str), 0);
printf("n = %d\n", perm_cnt);
}
return 0;
}
```
I have a mid-2015 MacBook Pro running MacOS 10.12.4. The compiler is the default MacOS clang. I am compiling with:
```
cc splitwords.c -O2 -o splitwords
```
Running all testcases, including `antidisestablishmentarianism` gives:
```
$ time ./splitwords
Testcase "a": n = 2
Testcase "in": n = 0
Testcase "ab": n = 2
Testcase "abc": n = 4
Testcase "will": n = 8
Testcase "stephen": n = 37
Testcase "splitwords": n = 228
Testcase "'a-r": n = 2
Testcase "'''''-": n = 1
Testcase "antidisestablishmentarianism": n = 83307040
real 0m0.573s
user 0m0.564s
sys 0m0.003s
$
```
This is by no means optimal. The algorithm simply brute-forces its way through all possibilities (modulo `i` - see comments above), and counts the words that may be split according to the criteria.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~75~~ ~~74~~ ~~73~~ 70 bytes
```
~~lfsm}sT-Bysded.\_Tm.n]d\*Fmm?k|qd\i+4}d"mw"|}d"il'"h|}d"fjrt-"+2}d"mw"-2}d"'-~~
~~lfsm}sT-Bysded.\_Tm.n]d\*Fmm?k|qd\i+4}d"mw"|x}Ld+c"mw il' fjrt-")G1 4-2}d"'-~~
~~lfsm}sT-Bysded.\_Tm.n]d\*Fm<,|x}Ld+c"mw il' fjrt-")G1 4|qd\i+4}d"mw"-2}d"'-~~
lfsm}sT-Bysded._Tm.n]d*Fm<,|x}Ld+c"mw il' fjrt-")G1 4|qd\i+4}d"mw"h}dG
```
[Try it online!](http://pyth.herokuapp.com/?code=lfsm%7DsT-Bysded._Tm.n%5Dd%2aFm%3C%2C%7Cx%7DLd%2Bc%22mw+il%27+fjrt-%22%29G1+4%7Cqd%5Ci%2B4%7Dd%22mw%22h%7DdG&test_suite=1&test_suite_input=%22a%22%0A%22in%22%0A%22ab%22%0A%22abc%22%0A%22will%22%0A%22stephen%22%0A%22splitwords%22%0A%22%27a-r%22%0A%22%27%27%27%27%27-%22&debug=0)
For the love of God, please don't even try `antidisestablishmentarianism` in the interpreter. You'll crash it.
## Explanation
```
lfsm}sT-Bysded._Tm.n]d*Fm<,|x}Ld+c"mw il' fjrt-")G1 4|qd\i+4}d"mw"h}dG
```
Let us break down this code into X parts.
### The first part: generating cased versions and mapping to the values
```
m<,|x}Ld+c"mw il' fjrt-")G1 4|qd\i+4}d"mw"h}dG
```
Let us be clear here. In **no** part of the process are letters capitalized. We just need to map one letter to two values (and the punctuation marks to one value), without the need of capitalizing them. We'll be deciding for which characters we will be needing two values, and for which characters we will be needing one:
```
m<,|x}Ld+c"mw il' fjrt-")G1 4|qd\i+4}d"mw"h}dGQ Q implicitly appended
m Q for d in Q:
}dG d in alphabet?
h +1 (T/F as 1/0)
< take the first ^ elements of the following array
for d in alphabet, it will take 2 elements;
for d being ' or -, it will take 1 element.
, pair up the following two values
|x}Ld+c"mw il' fjrt-")G1 4 this is the first value
|qd\i+4}d"mw" this is the second value
```
As you see, even the first part is too long.
The first value is for lowercase version, which includes `'` and `-`. The second value is for uppercase version, with `'` and `-` will not take.
The first value:
```
|x}Ld+c"mw il' fjrt-")G1 4
"mw il' fjrt-" does what it says on the tin
c ) split on spaces, creating an
array with three elements
+ G append another element, which
is the alphabet, as a fail-safe;
now the array has 4 elements
}Ld check if d is in each array
as with above, True becomes 1
and False becomes 0 (T/F as 1/0)
x 1 find the first occurrence of 1
| 4 logical or with 4. If it was 0,
it would become 4 now.
```
The first string contains `"mw"` at index 0. It has a value of 4, which explains the need of the logical or. Note that Pyth uses 0-indexing. Also, the space before the `4` is to separate it from `1`.
The second value (uppercase):
```
|qd\i+4}d"mw"
qd\i d=="i"
| logical OR
}d"mw" is d in "mw"? That is, is d "m" or "w"?
+4 +4
```
If `d` is `"i"`, then it gives `1` on the first step. Otherwise, it continues. If `d` is `"m"` or `"w"`, then the third step gives `1`, which is added to `4` to give `5`. If `d` is not `"m"` or `"w"`, then the third step gives `0`, which is added to `4` to give `4`.
## The second part: getting the job done
```
lfsm}sT-Bysded._Tm.n]d*F
```
This is prepended to the first part, which technically is not separated from the second part (it is still one command). So, the value from the first part is passed to the right.
Recap: in the first part, we mapped the letters to their possible values (lowercase and uppercase for letters, just one value for the two punctuation marks). For input `"ab"`, one would get `[[3,4],[3,4]]`.
To generate the different cased versions (which should have been done in the first part, but that would overflow), we use the Cartesian product repeatedly, and then flatten the result. Problems arise when there is only one letter (first testcase), because the Cartesian product would not give us an array, and the flatten command (`.n`) is overflowed to give strange results to numbers. We'll see how I circumvented this issue.
```
lfsm}sT-Bysded._Tm.n]d*F
*F reduce by Cartesian product
m d for d in each unflattened version:
] [d] (wrap in array)
.n flatten
f filter for resulting arrays as T
._T all prefixes of T
m for d in each prefix:
sd find the sum of d
y double
-B ed [above, above - last element of d]
}sT is the sum of T in the above array of 2 elements?
s sum the 1/0 generated in each prefix
any non-zero value is regarded as truthy
l length
```
If it is a split in the middle by `|`, then the prefix would have the sum doubled being the sum of the total.
If it is split by `()`, then the prefix sum doubled minus the value in parentheses would be the sum of the total.
[Answer]
## JavaScript (ES6), ~~199~~ ~~169~~ 167 bytes
Expects the input string in lower case. Too slow for the bounty.
```
f=(s,r=[],t=R=0,i=3,x=parseInt("k1048cccctt"["i'l-fjrtmw".search(c=s[0])+1],36)+8>>i&7)=>x&&(c?(i&&f(s,r,t,0),f(s.slice(1),[x,...r],t+x)):R+=r.some(x=>t==x|!(t-=2*x)))
```
### Test cases
```
f=(s,r=[],t=R=0,i=3,x=parseInt("k1048cccctt"["i'l-fjrtmw".search(c=s[0])+1],36)+8>>i&7)=>x&&(c?(i&&f(s,r,t,0),f(s.slice(1),[x,...r],t+x)):R+=r.some(x=>t==x|!(t-=2*x)))
;[ "a", "in", "ab", "abc", "will", "stephen", "splitwords", "'a-r", "'''''-" ]
.map(
s => console.log(s, '->', f(s))
)
```
[Answer]
## C, ~~403~~ 394 bytes,
Thanks Kevin!
```
r;char*g[]={"","ilI'","fjrt-","","mw","MW",0},**p,b[99];q(c){for(p=g;*p;p++)if(strchr(*p,c))return p-g;return c>='a'&&c<='z'?3:4;}f(char*w,int l){int i,n,c,t,x,y;if(*w){for(i=0;i<2;i++)x=tolower(*w),y=toupper(*w),!i||x!=y?b[l]=i%2?x:y,b[l+1]=0,f(w+1,l+1):0;}else{t=0;for(c=0;c<2;c++)for(i=0;i<l;i++){x=y=0;for(n=0;n<l;n++)c==0||n!=i?((n<i)?(x+=q(b[n])):(y+=q(b[n]))):0;t|=x==y;}r+=t;}return r;}
```
[Try it online](https://tio.run/nexus/c-gcc#RZDBbsIwDIbP4ymgEjRpg1TYLjR4Pe@w8w5dDxBayBTSkAa1XdtnZ@5AQor8@3csf05ulovTzgbHNIPO85gn1YePUvxYt0TFc64xfH55LBpYEBi2TzebjF@IoF1RWmLgyAPDTRhSWZDKWXGyBNsEpTZ3V6unZnnkj1S8g7/zFwuxBf/XT17jNz4U5H@Dmkntpop2o0immWCONazlODWo7ywJEZfbNZcIa8CVqqxzO96yFt3VmIebyb5vZtAm@1RlIOfrpIlbXFyFqwwiVpA6XDE0NI74kKsq7xxOHgkCVSBBIOFJVP/EroH20aZRNZY1lgVA1Pd6BjIhRG8lTUgTwoXsU51RGpP2aUae66EBaPlgQ3AY7x9j@XAbH37eSU3opJu8GIu@IN788K09NsWsMkq6urSHCn1EKZ8Mtz8)
Ungolfed code:
```
int getwidth(int c)
{
char **p, *g[] = { "", "ilI'", "fjrt-", "", "mw", "MW", 0};
for (p=g; *p; p++)
{
if (strchr(*p,c))
return p-g;
}
return c >= 'a' && c <= 'z' ? 3 : 4;
}
int test(char* w, int l)
{
int i, n, c, t, x, y;
if (*w)
{
for (i=0;i<2; i++)
{
x = tolower(*w);
y = toupper(*w);
if (!i || x != y)
{
b[l] = i % 2 ? x : y;
b[l + 1] = 0;
test(w + 1, l+1);
}
}
}
else
{
t = 0;
for (c=0; c<2; c++)
{
for (i=0; i<l; i++)
{
x = 0;
y = 0;
for (n=0; n<l; n++)
{
if (c == 0 || n != i)
{
if (n < i)
x += getwidth(b[n]);
else
y += getwidth(b[n]);
}
}
t |= x == y;
}
}
r += t;
}
return r;
}
```
] |
[Question]
[
You're given a **n-by-m** matrix of integers, where **n,m > 3**. Your task is to find the **3-by-3** sub-matrix that has the lowest mean, and output this value.
**Rules and clarifications:**
* The integers will be non-negative
* Optional input and output format
* The output must be accurate up to at least 2 decimal poins (if it's non-integer)
* The submatrices can be made up of arbitrary columns and rows
**Test cases:**
```
1 0 4 0 1 0
1 0 4 0 1 0
4 3 4 3 4 3
1 0 4 0 1 0
Minimum mean: 0 (We have chosen columns 2,4,6 and rows 1,2,4 (1-indexed)
-----------------------------
4 8 9 7
5 10 1 5
8 5 2 4
8 3 5 10
6 6 3 4
Minimum mean: 4.2222
-----------------------------
1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5
Minimum mean: 0.11111
-----------------------------
371 565 361 625 879 504 113 104
943 544 157 799 726 832 228 405
743 114 171 506 943 181 823 454
503 410 333 735 554 227 423 662
629 439 191 707 52 751 506 924
Minimum mean: 309.56
```
[Answer]
## Mathematica, ~~77~~ 50 bytes
```
±x_:=x~Subsets~{3}
Min[Mean/@Mean/@±#&/@±#]&
```
`` is Mathematica's transposition operator (and is rendered as a superscript T in Mathematica).
This answer first defines a helper operator `±` which returns all 3-element subsets of a list, and then evaluates to an unnamed function which uses this operator to solve the problem.
This is done by first computing all 3-element subsets of the matrix's rows. Then for each such subset, we transpose it and compute *its* 3-element subset of rows. This gives us all possible 3x3 submatrices (although they are transposed). We then compute the mean on all of them and find the overall minimum.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes
```
œc3S€Zµ⁺FṂ÷9
```
[Try it online!](https://tio.run/nexus/jelly#dZA9TsNAEIX7PcUcIEL7v/YFaGiQkCjonMiICEisOCDRhTS0SLRQ0VIhUBLoYnEQ@yLGb2IsLEGxszPfvp15u/XXw8gcVcuXk@17dfuxX26WxSquy8@3cv3a4O2muD9t9nLzXC0eq8XTMRV3TU0HVK5XDaLDZJanND9LaTzJruYDukwyLi/Gk3NKhtPrdEB5miWzZJ7S8IbyLBml@V5dKyKSzbLtzrX4m6IyLe32f7QspgghRgjC4QwCVpATfAhKGsHugPmhSgqP3HfUim5Yt4Rs7/eJbO/0SWezRyS7ESagufOYbTxyr5FHAQ9wEheVMuzMitgic5apC3hhDF3Q8BsZWNIaL7LSicBqpVi9myOh23VREUik@U@dFU5yxp9lDPJg4MQ5y10xzbLaey28xlxrEFWMTkEG/kR4CO7XNG2/AQ "Jelly – TIO Nexus")
# How it works
```
œc3S€Zµ⁺FṂ÷9 Main link. Argument: M (matrix)
œc3 Yield all combinations of 3 rows.
S€ Map column-wise sum over the combinations.
Z Zip, transposing rows and columns.
µ Combine all links to the left into a chain.
⁺ Duplicate the chain, executing it twice.
F Flatten.
Ṃ Take the minimum.
÷9 Divide it by 9.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~21~~ 16 bytes
```
2Fvyæ3ùO})ø}˜9/W
```
[Try it online!](https://tio.run/nexus/05ab1e#@2/kVlZ5eJnx4Z3@tZqHd9SenmOpH/7/f3S0iY6ChY6CpY6CeayOQrSpjoKhARDrKJiCuEAZoIiRjoIJlGcMFjA0AHHNdBTMwCImsbEA "05AB1E – TIO Nexus")
**Explanation**
* For each row, get the sum of each ordered subset of size 3
* Transpose the resulting matrix
* For each row, get the sum of each ordered subset of size 3
* Flatten the resulting matrix
* Divide by 9
* Get the minimum
[Answer]
# [Haskell](https://www.haskell.org/), 90 bytes
```
import Data.List
t r=[a+b+c|[a,b,c]<-subsequences r]
s=(/9).minimum.(t=<<).transpose.map t
```
[Try it online!](https://tio.run/nexus/haskell#HcmxDoIwFEbhnafo4ADht4oCQkI3R9@g6VBIhw4ttfey@e6Ibt/J2X1Ia2bxtGzlyxMXLLLStp7r5aMtZixmOtM2k3tvLi6ORDYFqfIyVjL46MMWZMlqmirJ2UZKKzkZbBK8B@ujStlHPpHWLQaMeBjoDs0VDbqDAzrc0P51x28c7NEf0RqzfwE "Haskell – TIO Nexus")
[Answer]
# [Bean](https://github.com/patrickroberts/bean), 198 bytes
Hexdump:
```
00000000 bc 81 bd a0 65 40 a0 5d dd a0 68 50 80 a0 77 20 ¼.½ e@ ]Ý hP. w
00000010 80 01 dd a0 66 25 3b 52 cc cb c0 50 84 a0 5d 20 ..Ý f%;RÌËÀP. ]
00000020 66 87 4c cc a0 68 8b 20 66 8c 25 3b cd d0 84 a0 f.LÌ h. f.%;ÍÐ.
00000030 5d 20 66 80 4e a0 66 81 4c d3 a0 65 a0 5d a0 68 ] f.N f.LÓ e ] h
00000040 4c a0 66 8c 25 3a 8b 25 3a 50 84 a0 5d 20 66 bd L f.%:.%:P. ] f½
00000050 a0 6e 43 a5 39 a5 3a a5 3b 00 bd a0 5f 43 cf 20 nC¥9¥:¥;.½ _CÏ
00000060 6e 00 3d a0 69 20 12 b6 a7 36 a7 26 4d a0 69 80 n.= i .¶§6§&M i.
00000070 53 d0 80 a0 1f 20 80 45 a0 69 53 d0 80 a0 6e 20 SÐ. . .E iSÐ. n
00000080 80 8b 40 a0 6f a0 75 4c a0 6f 8b 53 d0 80 a0 5f ..@ o uL o.SÐ. _
00000090 20 80 8b 40 a0 6f a0 74 4c a0 6f 8b 50 84 d0 84 ..@ o tL o.P.Ð.
000000a0 a0 77 20 75 20 74 4c d3 a0 65 a0 5f 50 80 a0 43 w u tLÓ e _P. C
000000b0 20 80 01 81 25 3b 4c d3 a0 65 20 6e 81 25 3b 26 ...%;LÓ e n.%;&
000000c0 4c a0 69 8e 25 42 L i.%B
000000c6
```
Equivalent JavaScript:
```
// indices array increment function
var i=(a,l=$.length,j=2)=>++a[j]>=l+j-2?a[j]=j&&i(a,l,j-1)+1:a[j],
// row indices
r=[0,1,2],
// column indices
c=[...r],
// minimum sum
m=Infinity;
do{
do{
// calculate sum of current row/column indices and keep minimum
m=Math.min(m,
(r.reduce((s,y)=>s+c.reduce((s,x)=>s+$[y][x])))
)
// until column indices loop
}while(i(c,A.length)!=2)
// until row indices loop
}while(i(r)!=2)
// output mean
m/9
```
### [Try demo here](https://patrickroberts.github.io/bean/#h=vIG9oGVAoF3doGhQgKB3IIAB3aBmJTtSzMvAUISgXSBmh0zMoGiLIGaMJTvN0ISgXSBmgE6gZoFM06BloF2gaEygZowlOoslOlCEoF0gZr2gbkOlOaU6pTsAvaBfQ88gbgA9oGkgEranNqcmTaBpgFPQgKAfIIBFoGlT0ICgbiCAi0Cgb6B1TKBvi1PQgKBfIICLQKBvoHRMoG+LUITQhKB3IHUgdEzToGWgX1CAoEMggAGBJTtM06BlIG6BJTsmTKBpjiVC&i=WzEsMCw0LDAsMSwwXQpbMSwwLDQsMCwxLDBdCls0LDMsNCwzLDQsM10KWzEsMCw0LDAsMSwwXQ==&f=0&w=1)
] |
[Question]
[
Imagine this, we have an environment with a global scope containing just a single object, called `codegolf`. This object has a single child called `stackexchange`, which has a property called `com`.
Accessing this property would look like `codegolf.stackexchange.com`.
### The challenge
The input of your program/function will be a string trying to access a property on the global scope. Whenever this property is found, you shall print/return a truthy value. If the property isn't found, a falsy value shall be printed/returned. The catch: when you try to access a property on a non-existant object, your program should throw any kind of error¹.
To make things a bit easier, you may assume that input will always be `[a-z.]`, it will never be empty, it will never have repeating `.`'s and it will never start or end with a `.`. So `codegolf.` is an invalid input.
### Test cases
```
codegolf.stackexchange.com => 1 // or any other truthy value
codegolf.stackexchange.net => 0 // or any other falsy value
codegolf.stackexchange => 1
codegolf.foo => 0
codegolf => 1
foo => 0
codegolf.com => 0
codegolf.constructor => 0
codegolf.foo.bar => Error (since foo is undefined)
codegolf.stackexchange.com.foo => Error (since com is a value, not an object)
codegolf.stackexchange.com.foo.bar => Error
foo.stackexchange.com => Error
foo.bar => Error
foo.bar.baz => Error
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in bytes wins
¹ if (and only if) your language of choice doesn't support errors **at all**, you must output something which makes it clear that this is an error. For example, if you use 1 for truthy and 0 for falsy, you may use "e" for an error. Be consistent in your return values and explain the behaviour in your post.
[Answer]
# JavaScript, 135 bytes
```
v=>(c=(p,i)=>new Proxy({}, {get:(o,q)=>(r=q==p[i]?c(p,i+1):o.$,i==3?r||z:r)}),x=c(["codegolf","stackexchange","com"],0),!!eval("x."+v))
```
Reworked the first attempt to prevent builtin keys being accessible, at this point its going to be better to use a different approach, but hey!
Returns true for valid, false for missing and errors on error.
[Answer]
## JavaScript (ES6), 87 bytes
Returns `false`/ `true` or throws `ReferenceError`.
```
s=>s.split`.`.map((w,i)=>e|['codegolf','stackexchange','com'][i]!=w&&e++,e=0)&&e>1?X:!e
```
```
let f =
s=>s.split`.`.map((w,i)=>e|['codegolf','stackexchange','com'][i]!=w&&e++,e=0)&&e>1?X:!e
console.log(f('codegolf.stackexchange.com')); // => true
console.log(f('codegolf.stackexchange.net')); // => false
console.log(f('codegolf.stackexchange')); // => true
console.log(f('codegolf.foo')); // => false
console.log(f('codegolf')); // => true
console.log(f('foo')); // => false
console.log(f('codegolf.com')); // => false
console.log(f('codegolf.foo.bar')); // => Error
```
### Probabilistic version, 78 bytes (non-competing)
Because all properties are guaranteed to match `[a-z]`, we can give this a try:
```
s=>s.split`.`.map((w,i)=>e|[162,6,2][i]-parseInt(w,36)%587&&e++,e=0)&&e>1?X:!e
```
Apart from the fact that `587` is a prime and leads to rather short values for the words we are interested in, this is a rather random modulo choice.
Although it does pass all test cases, it is of course likely to return false-positives.
```
let f =
s=>s.split`.`.map((w,i)=>e|[162,6,2][i]-parseInt(w,36)%587&&e++,e=0)&&e>1?X:!e
console.log(f('codegolf.stackexchange.com')); // => true
console.log(f('codegolf.stackexchange.net')); // => false
console.log(f('codegolf.stackexchange')); // => true
console.log(f('codegolf.foo')); // => false
console.log(f('codegolf')); // => true
console.log(f('foo')); // => false
console.log(f('codegolf.com')); // => false
console.log(f('codegolf.foo.bar')); // => Error
```
[Answer]
## Batch, ~~269~~ 231 bytes
```
@echo off
set/ps=
set w=1codegolf
for %%a in (%s:.= %)do call:l %%w
echo %w:~0,1%
exit/b
:g
if
:l
if %w:~-1%==. goto g
if not %1==%w% set w=0.&exit/b
set w=1com
if %1==com set w=1.
if %1==codegolf set w=1stackexchange
```
Takes input on STDIN; throws a syntax error for an invalid property. Works by using `w` as a state machine. If `w` ends with a `.` this means that the next property access is invalid. Edit: Saved 17 bytes by using the syntax error to abort the batch script. Saved 21 bytes by realising that one of my assignments could be unconditional.
[Answer]
# Javascript, ~~84~~ 82 bytes
Not short enough to win, but since I am a beginner I thought it would be fun to share it. Maybe someone has a suggestion for improvement.
```
s=>s.split`.`.length>3&&e||!!eval('codegolf={stackexchange:{com:true}};window.'+s)
```
It passes all the tests in the question, returns `true` for existing value, `false` for non-existent and it throws an error if you try to get a property of a non-existent or non-object variable. However I now realize that this solution has some issues as well. As pointed out by @Florent in the comments it returns true when string prototype properties such as `.toString` are called.
**Edit**: 2 bytes shorter thanks to @MamaFunRoll
Test snippet:
```
var f =
s=>s.split`.`.length>3&&e||!!eval('codegolf={stackexchange:{com:true}};window.'+s)
console.log(f('codegolf.stackexchange.com')) //true
console.log(f('codegolf.stackexchange.net')) //false
console.log(f('codegolf.stackexchange')) //true
console.log(f('codegolf.foo')) //false
console.log(f('codegolf')) //true
console.log(f('foo')) //false
console.log(f('codegolf.com')) //false
console.log(f('codegolf.foo.bar')) // TypeError
console.log(f('codegolf.stackexchange.com.foo')) //ReferenceError
console.log(f('codegolf.stackexchange.com.foo.bar')) //ReferenceError
console.log(f('foo.stackexchange.com')) // TypeError
console.log(f('foo.bar')) // TypeError
console.log(f('foo.bar.baz')) // TypeError
```
[Answer]
# JavaScript, 173 bytes
```
function d(a){var b="codegolf",u="stackexchange",c=a.split("."),e="e";return c.length==1?c[0]==b:c.length==2?c[0]==b?c[1]==u:e:c.length==3?c[0]==b?c[1]==u?c[2]=="com":e:e:e}
```
Works with IE 10, so should work on major modern browsers.
**[Try it here (+ ungolfed)](https://repl.it/Ebkr/1)**
[Answer]
# C#, 155 bytes
Wasn't going to be the shortest but thought it would be fun give it a go in C#...
```
bool f(string s){var a=s.Split('.');int e=0,l=a.Length-1,i=l;for(;0<=i;i--){e+=a[i]!=new[]{"codegolf","stackexchange","com"}[i]?i<l?s[-1]:1:0;}return e<1;}
```
* Splits the string and reverse iterates through the result.
* A non matching element more than 1 iteration deep, errors (throwing an `IndexOutOfRangeException` by accessing a char at -1 position in the string).
* Otherwise, returns false if any elements didn't match.
[.NET Fiddle](https://dotnetfiddle.net/0Na727)
[Answer]
# Ruby, ~~84~~ 80 bytes
Anonymous function which returns `true` or `false`, or divides by zero to raise error:
```
->s{k=1;s.split(?.).zip(%w[codegolf stackexchange com]){|i,o|1/0if !k;k=i==o};k}
```
[Try it online](https://repl.it/Ebus/1)
[Answer]
# C, 98 ~~112~~ 113 bytes
```
f(char*a){char*c="codegolf.stackexchage.com";while(*c&&*c==*a)++a,++c;return strchr(a,46)?*(a=0):!(*a|*c&*c-46);}
```
ungolfed
```
f(char*a){char*c="codegolf.stackexchage.com";
while(*c&&*c==*a)++a,++c;
return strchr(a,46)?*(a=0):!(*a|*c&*c-46);
}
f(codegolf.stackexchage.com)=1
f(codegolf.stackexchage.net)=0
f(codegolf.stackexchage)=1
f(codegolf.foo)=0
f(codegolf)=1
f(foo)=0
```
for the below it has to seg fault
```
f(codegolf.stackexchage.com.foo)
f(foo.bar)
f(foo.bar.baz)
f(codegolf.foo.bar)
f(foo.v)
```
[Answer]
# Java, ~~187~~ 138 bytes
Version 2.0(**138** bytes):
Idea shamelessly stolen from @Jamie.
```
l->{for(String []a=l.split,int l=i=a.length-1,e=0;i>=0;e+=a[i]!=new String[]{"codegolf","stackexchange","com"}[i]?i<l?s[-1]:1:0)return e;}
```
Version 1.0(**187** bytes):
```
l->{String[]a=l.split(".");return a[0].equals("codegolf")?(a.length<2?1:(a[1].equals("stackexchange")?(a.length<3?1:(a[2].equals("com")?1:0)):(a.length<3?0:a[-1]))):(a.length<2?0:a[-1]);}
```
Explanation of the return part:
```
return a[0].equals("codegolf")?(a.length<2?1:(a[1].equals("stackexchange")?(a.length<3?1:(a[2].equals("com")?1:0)):(a.length<3?0:a[-1]))):(a.length<2?0:a[-1]);
return ;
a[0].equals("codegolf")? :
(a.length<2? : ) (a.length<2? : )
1 (a[1].equals("stackexchange")? : ) 0 a[-1]
(a.length<3? : ) (a.length<3? : )
1 (a[2].equals("com")? : ) 0 a[-1]
1 0
```
] |
[Question]
[
The task is to display ascii table for a given array.
### Input
The input is an 2D matrix. The matrix's row length is same with the length of an array. Alternatively, you can take input of an 2D matrix with the first row is a header. The outer dimension is the row.
Example Input:
```
[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]
```
### Output
The output of a table looks like below.
```
+---------------------+-------------------+------------+------------+------------+------------+
| License | 2008-05-08 | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2 | 58.69% | 52.2% | 42.5% | 33% | 23% |
| GPLv3 | 1.64% | 4.15% | 6.5% | 12% | 9% |
| LGPL 2.1 | 11.39% | 9.84% | ? | 6% | 5% |
| LGPL 3.0 | ? (<0.64%) | 0.37% | ? | 3% | 2% |
| GPL family together | 71.72% (+ <0.64%) | 66.56% | ? | 54% | 39% |
+---------------------+-------------------+------------+------------+------------+------------+
```
Each cell has exactly one space on the left and at least one space on the right, padded until the bars aligned. However, at least one cell has only one space on its right.
### Test cases
```
Input:
[["Hello", "World", "!!!"],["aa", "bbbbbbbbb", "CcC"], ["Pyth", "CJam", "GolfScript"]]
Output:
+-------+-----------+------------+
| Hello | World | !!! |
+-------+-----------+------------+
| aa | bbbbbbbbb | CcC |
| Pyth | CJam | GolfScript |
+-------+-----------+------------+
```
### Example submission
```
function ascii_table(array, header) {
var lengths = array[0].map(function(_, i) {
var col = array.map(function(row) {
if (row[i] != undefined) {
return row[i].length;
} else {
return 0;
}
});
return Math.max.apply(Math, col);
});
array = array.map(function(row) {
return '| ' + row.map(function(item, i) {
var size = item.length;
if (size < lengths[i]) {
item += new Array(lengths[i]-size+1).join(' ');
}
return item;
}).join(' | ') + ' |';
});
var sep = '+' + lengths.map(function(length) {
return new Array(length+3).join('-');
}).join('+') + '+';
if (header) {
return sep + '\n' + array[0] + '\n' + sep + '\n' +
array.slice(1).join('\n') + '\n' + sep;
} else {
return sep + '\n' + array.join('\n') + '\n' + sep;
}
}
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins!
[Answer]
## vim, ~~139~~ ~~138~~ 134
```
$x0xqq%ls<cr><esc>@qq@q:se nosol|%s/,/\t/g|%s/]/\t./|%!column -t -s'<C-v><Tab>'<cr>qwf";;h<C-v>GI|<esc>@wq@wll<C-v>Gls|<esc>0<C-v>Gs| <esc>:%s/"//g<cr>Yp:s/[^|]/-/g|s/|/+/g<cr>YggpkP
```
Accepts input in the form shown in the test cases. May or may not be valid, as this relies on the input string never containing any `"`, `,`, `]`, or `|` characters.
If the input has to be able to contain `]`s, then `:%s/]/\t./<cr>` can be replaced with `qe$s<Tab>.<esc>j@eq@e` for 2 extra chars. There is no easy way to allow `",|` in the input.
Must be run in a Unix environment, as it relies on the `column` command line tool.
Slightly outdated explanation (by one revision, but that was just a bit of rearranging):
```
:se nosol<cr> we need this later: G in visual block shouldn't go to BOL
$x0x delete the surrounding pair of brackets
qq record a macro
%ls<cr><esc> put each element of the big array on its own line
@qq recurse
@q play back the macro until EOF
:%s/,/\t/g<cr> replace all remaining commas with tabs
:%s/]/\t./<cr> replace the ] at the end of lines with tabs and a dot
we need this for the line at the right edge of the table
:%!column -t run the whole file through `column' on tabs
-s'<C-v><Tab>
'<cr>
qw record another macro
f";; go forward 3 "s--that is, to the next "column"
h go back to the middle of the column
<C-v>GI|<esc> insert a line behind the cursor from top to bottom
@wq recurse
@w play back until EOF
ll move right before the line of dots we added earlier
<C-v>Gl select the dots
s|<esc> replace with a line (top to bottom)
0<C-v>G select all the opening brackets
s| <esc> again, (the leftmost) line
:%s/"//g<cr> kill all the quotes around the data
Yp duplicate bottom line
:s/[^|]/-/g<cr> replace everything that's not a line with a dash
:s/|/+/g<cr> now replace the lines with plus signs
YggpkP put the separators before and after the first line
```
Thanks [smpl](https://codegolf.stackexchange.com/users/41496/smpl) for a byte!
[Answer]
# JavaScript (ES6), 210 ~~212 219~~
**Edit** 2 bytes saved thx @Neil
```
a=>(J=(m,j)=>j+m.join(j)+j,a.map(r=>r.map((c,i)=>s[i]>(l=c.length)?0:s[i]=l),s=[]),t=J(s.map(n=>'-'.repeat(n+2)),'+'),z=a.map(r=>J(r.map((c,i)=>' '+c+' '.repeat(s[i]+1-c.length)),'|')),z[0]+=`
`+t,t+J(z,`
`)+t)
```
**TEST**
```
F=a=>(
J=(m,j)=>j+m.join(j)+j,
a.map(r=>r.map((c,i)=>s[i]>(l=c.length)?0:s[i]=l),s=[]),
t=J(s.map(n=>'-'.repeat(n+2)),'+'),
z=a.map(r=>J(r.map((c,i)=>' '+c+' '.repeat(s[i]+1-c.length)),'|')),
z[0]+='\n'+t,
t+J(z,'\n')+t
)
Z=[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]
O.textContent=F(Z)
```
```
<pre id=O></pre>
```
[Answer]
# CJam, 58 bytes
Anyone know trick of golfing in CJam?
```
q~z_{:,:e>)}%_{)'-*'++}%'+\+N+@@.{f{Se]"| "\+}}z'|N+f+1$f+
```
[Answer]
# Python 2, 190
This solution makes use of list comprehensions and generator expressions. It accepts a list of lists, and returns a string in the required format.
```
def b(i):
d=[max(map(len,c))for c in zip(*i)]
a='+'+''.join('-'*h+'--+'for h in d)
e=['|'+''.join(' '+f.ljust(h)+' |'for h,f in zip(d,j))for j in i]
return'\n'.join([a,e[0],a]+e[1:]+[a])
```
The code before the minifier:
```
def mktable(data):
sizes = [max(map(len, column)) for column in zip(*data)]
divider = '+' + ''.join('-'*size+'--+' for size in sizes)
lines = ['|' + ''.join(
' ' + value.ljust(size) + ' |' for size, value in zip(sizes, row)
)
for row in data]
return '\n'.join([divider, lines[0], divider] + lines[1:] + [divider])
data = [
["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],
["GPLv2","58.69%","52.2%","42.5%","33%","23%"],
["GPLv3","1.64%","4.15%","6.5%","12%","9%"],
["LGPL 2.1","11.39%","9.84%","?","6%","5%"],
["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],
["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]
]
table = mktable(data)
print table
```
which outputs:
```
+---------------------+-------------------+------------+------------+------------+------------+
| License | 2008-05-08 | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2 | 58.69% | 52.2% | 42.5% | 33% | 23% |
| GPLv3 | 1.64% | 4.15% | 6.5% | 12% | 9% |
| LGPL 2.1 | 11.39% | 9.84% | ? | 6% | 5% |
| LGPL 3.0 | ? (<0.64%) | 0.37% | ? | 3% | 2% |
| GPL family together | 71.72% (+ <0.64%) | 66.56% | ? | 54% | 39% |
+---------------------+-------------------+------------+------------+------------+------------+
```
[Answer]
# MATLAB, ~~244 239 229~~ 226
```
a=eval(regexprep(input(''),{'], *?[','[[',']]','"'},{';','{','}',''''}));s=size(a);c=repmat(' | ',s(1),1);b=c;for i=1:s(2)
x=char(a{:,i});b=[b x c];end
h=b(1,:);r=h*0+'-';r(h=='|')='+';b=[r;h;r;b(2:end,:);r];disp(b(:,2:end-1))
```
Explanation to follow.
---
Test case:
Input:
```
'[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]'
```
Output:
```
+---------------------+-------------------+------------+------------+------------+------------+
| License | 2008-05-08 | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2 | 58.69% | 52.2% | 42.5% | 33% | 23% |
| GPLv3 | 1.64% | 4.15% | 6.5% | 12% | 9% |
| LGPL 2.1 | 11.39% | 9.84% | ? | 6% | 5% |
| LGPL 3.0 | ? (<0.64%) | 0.37% | ? | 3% | 2% |
| GPL family together | 71.72% (+ <0.64%) | 66.56% | ? | 54% | 39% |
+---------------------+-------------------+------------+------------+------------+------------+
```
[Answer]
# Ruby, ~~129~~ ~~126~~ ~~127~~ 126 characters
```
->a{t=?|
a.transpose.map{|c|t+=" %-#{c.map(&:size).max}s |"}
[d=(t%a[0].map{p}).tr('| ','+-'),a.map{|r|t%r}.insert(1,d),d]*$/}
```
Sample run:
```
2.1.5 :001 > puts ->a{t=?|;a.transpose.map{|c|t+=" %-#{c.map(&:size).max}s |"};[d=(t%a[0].map{p}).tr('| ','+-'),a.map{|r|t%r}.insert(1,d),d]*$/}[[["License","2008-05-08","2009-03-11","2011-11-22","2013-08-12","2015-11-19"],["GPLv2","58.69%","52.2%","42.5%","33%","23%"],["GPLv3","1.64%","4.15%","6.5%","12%","9%"],["LGPL 2.1","11.39%","9.84%","?","6%","5%"],["LGPL 3.0","? (<0.64%)","0.37%","?","3%","2%"],["GPL family together","71.72% (+ <0.64%)","66.56%","?","54%","39%"]]]
+---------------------+-------------------+------------+------------+------------+------------+
| License | 2008-05-08 | 2009-03-11 | 2011-11-22 | 2013-08-12 | 2015-11-19 |
+---------------------+-------------------+------------+------------+------------+------------+
| GPLv2 | 58.69% | 52.2% | 42.5% | 33% | 23% |
| GPLv3 | 1.64% | 4.15% | 6.5% | 12% | 9% |
| LGPL 2.1 | 11.39% | 9.84% | ? | 6% | 5% |
| LGPL 3.0 | ? (<0.64%) | 0.37% | ? | 3% | 2% |
| GPL family together | 71.72% (+ <0.64%) | 66.56% | ? | 54% | 39% |
+---------------------+-------------------+------------+------------+------------+------------+
```
] |
[Question]
[
Write a program that takes an input string of length 2 or more characters and adds the string `~BOO!~` (that string has a leading and ending space) in a *uniformly random* spot in the string that is not on either end.
---
**Disallowed sample inputs**: `2` or (an empty input)
**Disallowed sample outputs**: `Hello ~BOO!~` or `~BOO!~ Hello` for the input `Hello`
**Sample input**: `Hello, World!`
**Sample outputs**: `Hel ~BOO!~ lo, World!` or `Hello, Worl ~BOO!~ d!`
---
This is code golf, fellas. Standard rules apply. Shortest code in bytes wins.
---
Congratulations to **Dennis** for having the shortest, spookiest program! Happy Halloween!
[Answer]
# Pyth, ~~19~~ 18 bytes
```
j" ~BOO!~ "cz]OtUz
```
*Thanks to @Jakube for golfing off 1 byte!*
[Try it online.](https://pyth.herokuapp.com/?code=j"+~BOO%21~+"cz%5DOtUz&input=Hello)
### How it works
```
(implicit) Store the input in z.
Uz Compute [0, ... len(z)-1].
t Remove the first element.
O Select an integer, pseudo-randomly.
] Wrap it in an array.
cz Split the input string at that point.
j" ~BOO!~ " Join the split string, using " ~BOO!~ " as separator.
```
[Answer]
# GML, 91 bytes
```
s=get_string("","")
show_message(string_insert(" ~BOO!~ ",s,irandom(string_length(s)-2)+1);
```
Simple enough - get a string, insert the substring into it, output the string. Done.
[Answer]
# Python 3, 60 bytes
```
s=input();n=1+hash(s)%(len(s)-1);print(s[:n],'~BOO!~',s[n:])
```
Note:
The modulo of `hash()` will be uniformly distributed over the length of the string. If you think that's bending the rules, note that because of python's hash randomization, this is *actually* random: repeated executions with the same input will give different results.
[Answer]
# CJam, 20 bytes
```
l_,(mr)/(" ~BOO!~ "@
```
[Try it online](http://cjam.aditsu.net/#code=l_%2C(mr)%2F(%22%20~BOO!~%20%22%40&input=Hello%2C%20World!)
Explanation:
```
l Get input.
_, Calculate length.
( Decrement, since the number of possible positions is 1 less than length.
mr Generate random number between 0 and length-2
) Increment, giving random number between 1 and length-1.
/ Split. Note that this splits repeatedly, but this will not do any harm.
We will only really use the first split.
( Peel off the first fragment after the split.
" ~BOO!~ "
Push the magic string.
@ Rotate the list with the remaining fragments to the top.
```
[Answer]
## Pip, 19 bytes
Takes input from the command-line. If the input has spaces or other special characters, it will need to be placed in quotes.
```
a^@1RR#aJ" ~BOO!~ "
```
Explanation:
```
a Command-line arg
^@ Split at index...
1RR#a ...random integer >= 1 and < length(a) (Python randrange)
J" ~BOO!~ " Join on that string and autoprint
```
[Answer]
# Julia, 70 bytes
```
print((s=readline())[1:(r=rand(2:length(s)-2))]," ~BOO!~ ",s[r+1:end])
```
Ungolfed:
```
# Read a line from STDIN
s = readline()
# Define a random integer within the bounds of s
r = rand(2:length(s)-2)
# Print to STDOUT with boo in there somewhere
print(s[1:r], " ~BOO!~ ", s[r+1:end])
```
[Answer]
## APL, 27 bytes
```
{(-⌽' ~BOO!~ ',⍵⌽⍨⊢)?¯1+⍴⍵}
```
APL doesn't have an insert function, so we rotate the string instead.
```
{ } ⍝ Monadic function:
?¯1+⍴⍵ ⍝ Place to insert string, let's say it's X
( ) ⍝ Monadic train:
⍵⌽⍨⊢ ⍝ Rotate input by X (⊢) to the left
' ~BOO!~ ', ⍝ Concatenate ' ~BOO!~ '
- ⍝ -X
⌽ ⍝ Rotate that by X to the right
```
**[Example input on TryAPL](http://tryapl.org/?a=%7B%28-%u233D%27%20%7EBOO%21%7E%20%27%2C%u2375%u233D%u2368%u22A2%29%3F%AF1+%u2374%u2375%7D%27Walking%20along%20unsuspectingly...%27&run)**
[Answer]
# Lua, 75 bytes
```
s=io.read()m=math.random(2,#s/2);return s:sub(1,m).." ~BOO!~ "..s:sub(m,#s)
```
[Answer]
## Python 3, 79 bytes
```
from random import*;s=input();n=randint(1,len(s)-1);print(s[:n],'~BOO!~',s[n:])
```
[Try it online](http://ideone.com/YHYs4R)
Pretty self-explanatory - read a string, pick a random integer between 1 and the length of the string, and print the string with `' ~BOO!~ '` inserted.
[Answer]
# Perl, 35 bytes
34 bytes code + 1 byte command line
```
$-=rand y///c-2;s/..{$-}\K/~BOO!~/
```
Usage:
```
perl -p entry.pl
```
[Answer]
# C#, 125 bytes
```
using System;class X{static void Main(string[]a){Console.Write(a[0].Insert(new Random().Next(a[0].Length-2)+1," ~BOO!~ "));}}
```
Expanded:
```
using System;
class X
{
static void Main(string[] a)
{
Console.Write(a[0].Insert(new Random().Next(a[0].Length - 2) + 1, " ~BOO!~ "));
}
}
```
This solution assumes that the string is passed in as the first command-line parameter. This is not usual for C# (stdin is more normal), so I’ve also included a solution that uses normal stdin:
# C#, 139 bytes
```
using System;class X{static void Main(){var x=Console.In.ReadToEnd();Console.Write(x.Insert(new Random().Next(x.Length-2)+1," ~BOO!~ "));}}
```
Expanded:
```
using System;
class X
{
static void Main()
{
var x = Console.In.ReadToEnd();
Console.Write(x.Insert(new Random().Next(x.Length - 2) + 1, " ~BOO!~ "));
}
}
```
[Answer]
# MATLAB, 69 bytes
```
i=input('');a=randi(nnz(i)-1,1);disp([i(1:a) ' ~Boo!~ ' i(a+1:end)]);
```
Inserting a string mid string at a given index in MATLAB is costly in terms of bytes. If there was a simple way to do it, I could save a fair amount by moving to an anonymous function, but I can't find one. Ah well.
Basically it gets a random number between 1 and the length of the string minus 1. Then it displays everything up to and including that index, followed by the `~Boo!~`, and then everything after the index to the end.
---
It also works with **Octave**, so you can try it out online [here](http://octave-online.net/).
[Answer]
# Vitsy, 19 Bytes
Note that `z` and `Z` were edited today, but not for this challenge.
```
I1-R1+\i" ~OOB~ "zZ
I1- Get the length of the input, minus 1
R Push a random number from 0 to the top item of the stack.
1+ Add one to it - this is now a random number from 1 to input
length - 1.
\i Get that many items of input.
" ~OOB~ " Push ' ~BOO~ ' to the stack.
z Get the rest of the input.
Z Output it all.
```
[Answer]
# Bash/GNU, 61 bytes
```
echo $1|sed "s/.\{`shuf -i1-$((${#1}-1)) -n1`\}/\0 ~BOO!~ /"
```
Takes input string as argument
[Answer]
# Ruby, 46 bytes
```
$><<gets.insert(rand(1..$_.size-2),' ~BOO!~ ')
```
[Answer]
# JavaScript, 79
```
r=Math.random()*((x=prompt()).length-1)+1;x.substr(0,r)+" ~BOO!~ "+x.substr(r);
```
It's for the browser console; have fun just popping that in.
[Answer]
# Java 8, ~~158~~ 154 bytes
```
interface M{static void main(String[]a){int i=a[0].length()-2;System.out.println(a[0].substring(0,i=1+(i*=Math.random()))+" ~BOO!~ "+a[0].substring(i));}}
```
[Try it here.](https://tio.run/##Xcu7DoIwFADQXylMrTyCroTFyYUwMDgQhitUuFhaAhcSQ@DXK2F0P6eDBQIzSN3VH2tRkxzfUEmWrhMBYcUWgzXrATXPaUTdFCWI9XAMEyiiMlRSN9RyEdzi/DuR7EMzUzgclJTmJ5nm13ReHvmYXD2OlyQFasMRdG16LoTwXLbfs8zZmev9HRQi3jZr7UMqZXz2NKOqnR8)
EDIT: Only now reading program instead of the default function/program in the challenge description.. So added the bordercode with interface and main method.
If a function would be allowed it would be (**~~99~~ 95 bytes**)
```
s->{int i=s.length()-2;return s.substring(0,i=1+(i*=Math.random()))+" ~BOO!~ "+s.substring(i);}
```
[Try it here.](https://tio.run/##1ZKxbsMgEIb3PMXFE8QxartartR06ZJk6NCh6kBsmpDiw4JzpCp2Xt0lEYq6VM5adEIc9x3/j2AvDzKzjcJ99TWURnoPS6nxOAHQSMp9ylLB6pwCvJLTuIWSxYXnedjvJ2HyJEmXsAKEAgafPR5DN@jCC6NwSzvGs4fcKWodghe@3fjLEexurov7lOlZsZS0E05iZWvGOU8TOC3W6@kJkvR3g@Z5P5xlQzTtxgTRqH2wuoI6eI/23j9A8mj825OqhW1JNKFEBhmKkiUvyhg7hzfrTDVN@OU6f9NPi@dRZnYdo2godTdojiJd96@Q67Py@Hv64Qc)
**Explanation:**
```
s->{ // Method with String as both parameter and return-type
int i=s.length()-2; // The length of the input - 2
return s.substring(0,i=1 // Return the first part of the input from index 0 to 1
+(i*=Math.random())) // + a random integer between 0 and length-2
+" ~BOO!~ " // appended with the literal " ~BOO!~ "
+s.substring(i); // appended with the rest of the input-String
} // End of method
```
[Answer]
# [Chaîne](http://conorobrien-foxx.github.io/Cha-ne/?code%3D%7Bil1-R1%2B%60%7D%20~BOO!~%20%7B%3C%24%2F%7D||input%3D%22Hello%2C%20World!%22), 23 bytes
```
{il1-R1+`} ~BOO!~ {<$/}
```
[Answer]
# TeaScript, 30 bytes
```
xh(j=N(xn-1)+1)+' ~BOO!~ '+xS(j)
```
Very straight forward.
[Answer]
## CJam, 19 bytes
```
q_,mr)/(" ~BOO!~ "@
```
] |
[Question]
[
Does anyone have any [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") tips for golfing in [Processing](http://processing.org)? It is a graphical extension of java, and is somewhat difficult to golf.
[Answer]
* If no animation is required, you can skip the `void draw()` and put everything into `void setup()`.
* Initialising the size of the canvas is sometimes not necessary - it will be initialised to `(100, 100)` by default.
* If you need to use `height` and `width` in your code, it is usually shorter to use their numeric values instead. For example, with a canvas of size `(100, 100)`, using `99` to replace `height` and `width` can save you 7 bytes.
[Answer]
If you only run code in the setup method then you don't need write the method outline. For example you can write:
```
rect(10,10,90,90);
```
instead of
```
void setup {
rect(10,10,90,90);
}
```
And as long as you don't use any other methods then everything will be put in the setup method before running
[Answer]
# White `#FFFFFF`
Related: [Colour Notation](https://codegolf.stackexchange.com/a/101955/41805)
Instead of using this for white:
```
color(255) //10 bytes
```
you can do this:
```
color(-1) //9 bytes
```
and save 1 byte.
[Answer]
# Colours `(R, G, B)` notation
### Hexadecimal colours
Processing is very flexible in colour format.
```
fill(255,255,0); //16 bytes
```
can be written using hexadecimal notation as
```
fill(#ffff00); //14 bytes (2 bytes saved)
```
### Grayscale
Here is a special usage for colours if all the Red, Green and the Blue values are the same (white):
```
fill(255,255,255); //18 bytes
fill(#ffffff); //14 bytes
fill(255); //10 bytes
```
All the three parameters can be shortened into one parameter containing the grayscale value: from `0` black to `255` white.
This can be extended for alpha as well:
```
fill(175,175,175,50); //translucent gray
fill(175,50); //8 bytes shorter
```
Both mean the same colour, but the latter way is shorter by 8 bytes.
### Alpha
Although obvious, it should be stated that the alpha parameter in specifying colours is optional since colours are defaulted to an alpha value of `255` (100% opaque).
# Summary: Color formats
Use the shortest colour format to express your colour (remember to leave out unnecessary bits -depending on the context of the program- for example: alpha or grayscale)
`R`: Red
`G`: green
`B`: blue
`A`: alpha
`g`: grayscale
```
RRR,GGG,BBB
#RRGGBB
ggg
RRR,GGG,BBB,AAA
ggg,AAA
```
[Answer]
## Abbreviate constants
If you're ever using one of the all-caps keywords in Processing (such as `DIFFERENCE` or `TRIANGLE_FAN`), see if the number they correspond to is shorter.
For example, `DIFFERENCE` is just an `int` that's equal to 32. Instead of using `DIFFERENCE` [here](https://codegolf.stackexchange.com/a/107082/34793), I could write `32`, saving 8 characters.
[Answer]
# Shorter alternative to `void keyPressed(){}`
```
void draw(){}void keyPressed(){foo;} //36 bytes
void draw(){if(key>0)foo;} //26 bytes
```
The `void draw(){}` is needed by default in order for `key` to be updated. If the user hasn't pressed a key since the start of the program, `key` is given a value of `0`. By checking if it is more than `0` (ie the user has pressed a key), we have golfier code and save 10 bytes.
[Answer]
# Setting and committing pixels using set()
It's more efficient to set pixels via [pixels[]](https://processing.org/reference/pixels.html):
```
pixels[0] = color(255)
updatePixels();
```
However, that requires `updatePixels()` and also using an index which depending on the scenario will require converting an x,y position to a pixel index.
To keep things short, even though it's less CPU efficient (as each call updates the whole buffer), [set()](https://processing.org/reference/set_.html) allows a pixel to set and committed to buffer straight away in one call.
```
set(0,0,color(255));
```
] |
[Question]
[
The task is to count the number of disjoint `11` blocks in a 64-bit word, using the minimum number of straight-line instructions. That is, how many nonoverlapping neighbored pairs of 1-bits can be found.
## Examples
(imagine leading zeros to fill up to 64 bits)
```
Input Output
111111 3
1110111 2
11110010111 3
```
Here is a possible implementation (that would not be a valid answer since it uses a loop and a condition):
```
uint64_t f(uint64_t x) {
uint64_t n = 0;
while (x)
if ((x & 3) == 3)
++n, x >>= 2;
else
x >>= 1;
return n;
}
```
## Scoring
The goal is to minimize the number of instructions. Instructions allowed are only the basic bitwise and arithmetic operators (`|`, `&`, `^`, `+`, `-`, `~`, `<<`, `>>` (arithmetic shift)) plus `popcount` (count the number of bits set in a word), `clz` (count leading zeroes), and `ctz` (count trailing zeroes). Also, `*` and `/` are allowed with a cost of 5 and 25 instructions, respectively. Using 64-bit constants is free. No loops, conditions, function calls etc. are allowed. Example of a three-instruction function that makes it easy to count the number of instructions:
```
uint64_t f(uint64_t x) {
uint64_t t0 = x ^ 0xff00ff00ff00ff00;
uint64_t t1 = t0 - 1;
uint64_t t2 = popcount(t1);
return t2;
}
```
but it's also fine to present it in more readable form.
**EDIT:** now also allowing `clz`, `ctz`, `*`, and `/`.
[Answer]
# 5 ops
```
E = int('01'*32, 2) # ...01010101
def f(n):
r = (n ^ E) + E # 2 ops
t = n & (E ^ r) # 2 ops
return popcount(t) # 1 op
```
[Try it online!](https://tio.run/##XY/BisMwDETv/oqBQmOnIdQplBLIMb@x4G6drmErG8Ut7Ndn5Wx72KKT9EajUfrJX5EOp8RLiukz3iljwLe7nS8O1J8DaTLtOteVrcwyCg6l2duqPnQNOgNs0Lbt3v6VUhc/YZK9XoFFrgkfGA12GIEi7hDTrFAuEbbQo3A2/xj7fGfCK5PORpgVtmzw8Bym4FlNkcUgENjR1euuru2xHM2Or764v8WX/Apunj3nNR@G4aVtJGXzbJoVGvXuL78V98Tlf3qqll8 "Python 3.8 (pre-release) – Try It Online")
**6 ops**
```
E = int('01'*32, 2) # ...01010101
O = int('10'*32, 2) # ...10101010
def f(n):
r = (n << 1) | E # 2 ops
t = n & (O ^ (r - n)) # 3 ops
return popcount(t) # 1 op
```
[Try it online!](https://tio.run/##XZDNasMwEITveooBQy0Z11g2lBLiY855g4LSyKkhXYm1Egj03V3JPxdLp9V8Gs3Iv8KPo/bT8@Sd/3YPCuhwN7@XqwEdLgNJUtV8LnOdq@kU5SENtc6LtinRKCBDVVW1XrY4b4iud8hK1EJcbY8@Wh8EOOKScDxCK/zhhGVlaOD8KJACEd4gz/iCZLyD1GzYLjrb8GDCFl8Gtd7XUZ8yPC0P/WBZ9I6j0UBgQzcrm6LQHylAMHyz6ZVd21hXwIyj5TBnRddtbBkTl@tQzqISe/9YNLl7Tn9BKzX9Aw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# 11 ops
```
uint64_t f(uint64_t x) { // 11111011110
uint64_t notx = ~x; // odd ^ even // 00000100001
uint64_t bit = notx & (x>>1); // 00000100001
uint64_t odd = bit & 0x5555555555555555; // 00000000001
uint64_t even = ~bit | 0x5555555555555555;// 11111011111
uint64_t cov1 = notx; // odd ^ even // 00000100001
uint64_t cov2 = odd + even; // 11111100000
uint64_t cov = cov1 ^ cov2; // 11111000001
uint64_t mask = cov ^ 0x5555555555555555; // 01010010100
uint64_t res = mask & x; // 01010010100
return __builtin_popcountll(res); // (4)
}
```
[Try it online!](https://tio.run/##fZJhb8IgEIa/8ysuWWJqlkXQzkTR/hQbpWySVWha6kg299fdgZu2He4@XNuD570XeqKqnl6FOD8oLcq2kLBSprG13B4ycquJxhZK225pp2wjsXJucWGe5hZekuurG8MHRGMyAeaDhkR86UppYx2s4ctxv80UBWxAHqXuwtQHC6kPox9kg8QIEpdlbMyHne/Cvtc6SIyAuudB8BtMI3CwiLY9/hnDe2cewMIc2Y/v@Kn/s43wFGHPPAaG37ntANM/MLKh/yYo3YNjZz5sm7cLjXDsxrxt5k2H1Idr2SAbJEbgeHRIhnAtbVtryPNdq0qrdF6ZSphW27JMUK/zrxFO0jE5nbEdNlE6wWHsG3A8fL/vVSkhwdleLoXSkGVhcMmv0mXBtBZWK5xuXMNnKEpdlBeNU9cd5dh2PiOMLQhbpDMypSwl8ymZsW8 "C++ (gcc) – Try It Online")
[Verify through 0..65535](https://tio.run/##jZJtb4IwEMff8yluLpo2sgg@vanwUSRaCmuGhUBxTTb31d21ZCqKye7F0Rz3u/tfe7yq3nLOz69S8aJNBWxk2eha7A6xd43xRqdS6dvQXupGYOTc4o/1MtGQkcvRUPiCQZvNILQWOOfZ0IXCkhDBj4EJEBPHIWWPcGAtdK4Pl2mKsC0xgcCs7oxd4WAAFkehbGuLfw/hPdl3MC@PodPNbA@rY9sV/I9shOcIW2rqKPbkwhwcPMDIuv5bV@kZPDTzYdd8dDTCQzdmZYdWtHN9uBYNsq7EBAwbfOd7uBa6rRUkyb6VhZYqqcqKl63SRUGw3s1rI0yW1Dtddyvv71ZfjH26gLnY57ssBG4P9f5qyQwIsSu1oBBF6L1bmdOp8sFAHEcwZ5c/omhEL63LCNntHIp5Jw8l4C1IRR5EmS45K2uUEwUMzGa9Wi3WDHviCDIjGcp8iXL0FKoauYyMMjIuWuqDMJXgWqQwTn3IhcbvCIXiGdN9sCjtqcH5T@df)
[Answer]
# 28 ops
```
uint64_t f(uint64_t x) {
uint64_t a = x & (x >> 1);
uint64_t b = a & (~a >> 1 | a >> 2);
uint64_t c = b & (~b >> 1 | b >> 4);
uint64_t d = c & (~c >> 1 | c >> 8);
uint64_t e = d & (~d >> 1 | d >> 16);
uint64_t f = e & (~e >> 1 | e >> 32);
return popcount(f);
}
```
[Try it online!](https://tio.run/##bZHRToQwEEXf@xWTmBh40IgQ4i7Ir5jSFm3CFgIlNlnx19dhauuK9oXJvecOza0Yx7tXIS432oh@kQpqPcx2UvzUsB9NzFZqY6@lVttZocIWNMrixcI4jGJYjE2i4lI4M8CD8ePRJ@qyaMCc3VqRMym7TAbMvY@mFVsvMd/9syoqHJ7BwS0kDpoGsrT6bbdo883@5OTDB9DwuAcFgi2BbQBpKPagRFAQKAJIw9MeVAhKAmUA/VDuyQ5JRaQKJA15uOV3PbHajgrCOJy4NsmfUpyPvb/pXkFCtQtttpWxwPgeuNFCXWPL6OGXRGVk73es1xd42H5b5izLDiw7FPkX "C++ (gcc) – Try It Online")
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
An Elf is hopping on a chessboard which extends infinitely in all four directions. They move like a generalized chess Knight: on each step, they move `X` units horizontally and `Y` units vertically, or `Y` units horizontally and `X` units vertically. (`(X,Y) = (1,2)` would give regular Knight's moves.)
The Elf plays the game "Self-trapping Elf". In this game, the Elf starts at position `(0,0)` and hops around. They cannot hop into any cell already hopped on, including the starting cell. The objective is to trap themselves in the fewest number of steps possible.
**Task:** Given the values of `X` and `Y` (`0 < X < Y`), output the sequence of coordinates that the Elf should visit, so that they can trap themselves in exactly **15** moves.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
Some explanation can be found [in this Puzzling post](https://puzzling.stackexchange.com/q/104038/71652). There are many ways to achieve this: (the worked out examples are for `(X, Y) = (1, 2)`)
* Choose any position (X) one move away from the origin (O). We will step all 8 cells reachable from X and then move into it.
```
. O . A .
G . . . B
. . X . .
F . . . C
. E . D .
```
* For almost any pair of cells out of `OABCDEFG`, there is exactly one way to move from one cell to the other in 2 steps without going through X.
The following are valid solutions to the problem:
```
. . . . 1 . . . .
. . . . . . . 3 .
. . . 0 . 2 . . .
. . e . . . 4 . .
d . . . f . . . 5
. . c . . . 6 . .
. . . a . 8 . . .
. b . . . . . 7 .
. . . . 9 . . . .
. 0 b 6 .
a 5 . 1 c
. . f . 7
4 9 . d 2
. e 3 8 .
```
The actual output for the first answer would be
```
[(1, 2), (2, 0), (4, 1), (3, -1), (5, -2), (3, -3), (4, -5), (2, -4),
(1, -6), (0, -4), (-2, -5), (-1, -3), (-3, -2), (-1, -1), (1, -2)]
```
You may include or exclude the starting position of `(0, 0)`.
[Answer]
# JavaScript (ES6), 79 bytes
Expects `[Y, X]`. The path is hardcoded.
```
V=>[p=[0,0],..."763145621057234"].map(d=>p=p.map((v,k)=>v+V[d&1^k]*~-(d>>k&2)))
```
[Try it online!](https://tio.run/##XY/LasMwEEX3/YrBi3gmUYTtxM4iSNBFv6CQjaqC8SNV/JCRjYkh9NdTNbRddHdn5gyHe8nnfCycGaZtb8vqXov7SUg1CBWxSDPOeXDIdvE@zZI4Sg/Jbh9o3uUDlkIOYnhEnFlDQs6bkypX8Xuj159bLKVsVgkR3V01goAaVcIg1nR86vyo9BH8gdfWveTFB6K6Mlg0A0MgJGCnFthAoj36F283eHYuXzAlXpu2xYAHROr6Cxo@2dfJmf6McUZeVNh@tG3FW3tGL/u3Cd/60L92jw7u2@r4xZoeQwiJfqJnfIUv "JavaScript (Node.js) – Try It Online")
Or **[78 bytes](https://tio.run/##XY/LasMwEEX3/YrBi3imUYTt1M4iSNBFv6CQjaqC8SNV/JCRjYkh9NddNbRddHdn5gyHe8nnfCycGaZdb8tqrcV6ElINQkUs0oxzHhyyffyUZkkcpYdkH2je5QOWQg5iuEecWUNCztuTKjfxe6MfP3dYStlsEiJaXTWCgBpVwiDWdHzo/Kj0EfyB19a95MUHoroyWDQDQyAkYKcW2EKiPfoXbzd4di5fMCVem7bFgAdE6voLGj7Z18mZ/oxxRl5U2H60bcVbe0Yv@7cJ3/rQv3b3Du7b6vjFmh5DCIl@omd8hS8)** if we don't output the starting position.
### Encoding
The directions are encoded with 3-bit values, using the following scheme:
```
d | as binary | (dx,dy)
---+-----------+---------
0 | 0 0 0 | (-Y,-X)
1 | 0 0 1 | (-X,-Y)
2 | 0 1 0 | (+Y,-X)
3 | 0 1 1 | (+X,-Y)
4 | 1 0 0 | (-Y,+X)
5 | 1 0 1 | (-X,+Y)
6 | 1 1 0 | (+Y,+X)
7 | 1 1 1 | (+X,+Y)
| | |
| | +--> if set, use X for |dx| and Y for |dy|
| | (if cleared, do it the other way around)
| +----> sign of dx (positive if set)
+------> sign of dy (positive if set)
```
### Commented
```
V => // V[] = input vector [ Y, X ]
[ p = [0,0], // p[] = current position, initialized to [ 0, 0 ]
... // this is also the 1st direction (zero'ish)
"763145621057234" // <-- = the directions for the next 15 moves
] //
.map(d => // for each direction d:
p = // update the position:
p.map((v, k) => // for each coordinate v at index k:
v + // add to v
V[d & 1 ^ k] * // either V[0] or V[1] according to bit #0
~-(d >> k & 2) // multiplied by either -1 or +1
// according to bit #1 or bit #2
) // end of inner map()
) // end of outer map()
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 by using `ṃ` - I really should know to use this since I actually implemented this atom! >.<
-1 altering valid move generation code.
-2 compressing in a way so as not to need valid move construction.
```
;N“©Ȯṅ!ı|⁺⁸’ṃs2+\
```
A monadic Link that accepts the pair `[Y, X]` and yields a list of coordinates.
**[Try it online!](https://tio.run/##ATAAz/9qZWxsef//O07igJzCqciu4bmFIcSxfOKBuuKBuOKAmeG5g3MyK1z///9bMiwgMV0 "Jelly – Try It Online")** Or try it with a [formatted output](https://tio.run/##AU8AsP9qZWxsef//O07igJzCqciu4bmFIcSxfOKBuuKBuOKAmeG5g3MyK1z/w4fCqy9DK8aKxZLhuazigqzDlyJKJFN6MFpv4oCdLkf//1s1LDJd "Jelly – Try It Online").
### How?
```
;N“©Ȯṅ!ı|⁺⁸’ṃs2+\ - Link: pair of integers, [Y, X] (1 < X < Y)
N - negate -> [-Y, -X]
; - concatenate -> [-Y, -X, Y, X]
“©Ȯṅ!ı|⁺⁸’ - base 250 number = 477042125414097387
ṃ - (that) base decompress ([-Y, -X, Y, X])
-> convert to base 4 using [-Y, -X, Y, X] as digits [1, 2, 3, 0]
s2 - split into twos
\ - cumulative reduce by:
+ - addition (vectorises)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
F²⊞υN≔⟦υ⮌υ⟧θ≔⁺θ±θθ≔⁺θEθEι⎇μλ±λθIΦΣEθ⟦E§θ⊖κ⁺λ§ιμι⟧κ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVA7CgIxEO09RbCaQCy0EqxEEbZQFrVbtojrqMEkuvmInsVGUNEreRYbE7-NU8ww8-a9N8z-Wiy4KVZcHg5n72a15u0-WxkCDUpSbxfgGUn02ruBVxM0QGmr0rZWzDVkARriBo1F8DRnpPxhqfQWSkYGOOcOoaT0L9zn608RjIzRaG52oBiRX6qkMV7s1AjtoMOtg56QLpwz8greIlmsbZfoKW5j38XCoELtcArLqPA0DcKfneContIijzns0NbJTgr7fsQlq9Y2spof66TxmjwA) Link is to verbose version of code. Explanation:
```
F²⊞υN
```
Input `X` and `Y`.
```
≔⟦υ⮌υ⟧θ≔⁺θ±θθ≔⁺θEθEι⎇μλ±λθ
```
Generate all of the positions one step away from the origin.
```
IΦΣEθ⟦E§θ⊖κ⁺λ§ιμι⟧κ
```
Output the positions and in between each pair of positions also output the other position one step away from both.
If string input and complex output is acceptable, then for ~~38~~ 36 bytes:
```
F+-F⁴⊞υ×I⪫⟦θιηj⟧ωXI1jκΦΣEυ⟦⁺ι§υ⊖κι⟧κ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY7NCoJAFIX3PcVlVndoXBgtAldRBAWBUDtxYTri6Kg1P9m7tEioqFfqbdJsd_jO4eNc33EWqbiOZNs-rUmd2eeW1gqQjB1C4RenFHyrM7QM9qLkGheRNripRYXBiYFgkDEgOQkZNJQy8OuGq2FE3Jx0pKCUeiNficrgSkjT1Ttb4jY69tLAl1Zjp5mbdZXwS8-WPFa85JXhCRa9VIR0EHkPfYj1_-wrIM5ZkvDuwmQgXw) Link is to verbose version of code. Explanation:
```
F+-F⁴⊞υ×I⪫⟦θιηj⟧ωXI1jκ
```
Generate all positions one step away from the origin.
```
ΦΣEυ⟦⁺ι§υ⊖κι⟧κ
```
Output the positions and in between each pair of positions also output the other position one step away from both.
[Answer]
# [Python](https://www.python.org) NumPy, 93 bytes (@alephalpha)
```
lambda p:cumsum(kron([p,-p,*conj([p,-p])],[1,-1,1j,-1j])[-(r_[:14,15]^1)])
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5NTsMwEEb3OYWXM66NMGpRVckncQ0KJS5x4x9cW4orbsImEoI7cRsa0s3M6Gn0fe_zJ9b8Fvz0ZeT-u2TDt796aN3La0vi7lDcuTg4peBBRcYjo4fg7XJr1EwJxgUT9jqtRsUhPaudWDOx0U8CNTYmBUd8cbGS3sWQMr2VfIzyYbWxTZUGRmxi6n2GyobOQ_H9e-nmqHtWNaKU4pG1wwCqKi706kKFpfREek9uP8SERBbQ-mMHa_wnl5nAyMa72boc29wBXq1wcZimZf8B)
### [Python](https://www.python.org) NumPy, 96 bytes
```
lambda p:cumsum(kron([p,q:=p-2*p.real,-q,-p],[1,-1,1j,-1j])[-(r_[:14,15]^1)])
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5LTsMwGIT3OYWXtvu7wlWLUCSfxBgwJW7j-hUTS3HFTdhEQnAnbkNLupmRPo1m5vMn1fEYw_xlxON3GQ17-H1x2r--aZTaffHvxeNTjgHLBEMrEtvQtM6ddsAGYEmB5MA4cHtRq4hkOD_Llm-B79QTJ4o0JkePQvGpot6nmEd62_mYxGa1s00VBk-kSbkPI67guoBL6IfSXavuoCpChOD3oJ3DskrG1epMuaX0hPqAbhlkYkYL0OHQ4S35J-crwRNM630Mthz02GFyeUWWD_O8-B8)
Uses complex numbers.
This works essentially by hopping from the trapping square to each of the eight reachable squares and back an then swapping moves 2 and 3, 4 and 5, 6 and 7 (1-based) and so on.
Unfortunately not very short.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 63 bytes
```
t->Vec(((u=conj(s=t/(I-x^2)%y=x^8)+s*y)*x^3-u+t)/(1-x)%y^2+u%x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN-1LdO3CUpM1NDRKbZPz87I0im1L9DU8dSvijDRVK20r4iw0tYu1KjW1KuKMdUu1SzT1NQx1K4BScUbapaoVmhBjNhYUZeaVaKRpGCpoKxhpeWpCxRcsgNAA)
Takes a complex number (`X+Y*I`) and outputs a list of complex numbers.
Implements the algorithm in [@Neil's Charcoal answer](https://codegolf.stackexchange.com/a/255098/9288) using polynomial magics.
```
. . d . 1 . .
. . 0 . c . .
. e . . . 2 b
. . . f . . .
. 6 . . . a 3
. . 8 . 4 . .
7 . 5 . 9 . .
```
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 71 bytes
```
t->s=0;[s+=a|a<-[-v=I*t,t,t,v,v,-t,-u=conj(t),-v,w=I*u,u,u,-w,-w,-u,w]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN91LdO2KbQ2so4u1bRNrEm10o3XLbD21SnRAsAwIdUt0dEttk_PzsjRKNHV0y3TKgdKlOiCoWw5GpTrlsbEQ4zYWFGXmlWikaRgqaCsYaXlqakLEFyyA0AA)
Gives the same result as above, but the directions are hardcoded.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 37 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{-∘⊃⍨{,⍉↑⍵(2+/⍵)}{∊⍵,¨2⌽⌽+⍵}⍵×0j1*⍳4}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q9Z91DHjUVfzo94V1TqPejsftU181LtVw0hbH0hp1lY/6ugCMnQOrTB61LMXiLSBvFogPjzdIMtQ61HvZpNaAA&f=40pTMMwy4kpTMMoyBgA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Input a complex number `yJx`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
(ì•Ct-V₂‹Sθ•sÅв2ôÅ»+
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/255122/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f9f4/CaRw2LnEt0wx41NT1q2Bl8bgeQX3y49cImo8NbDrce2q39/3@0kY5hLAA) or [try it online pretty-printed](https://tio.run/##yy9OTMpM/f9f4/CaRw2LnEt0wx41NT1q2Bl8bgeQX3y49cImo8NbDrce2q39v/bwjnNbww@3aAMZh1aCOcWHFxzdUZtwbou63qF1ZS6VF/YeXnF0n0@Q3tGFfodXVJ7bcXwuUOz43NpDu/9HG@kYxgIA).
**Explanation:**
```
( # Negate the values in the (implicit) input-pair: [-Y,-X]
ì # Prepend it in front of the (implicit) input-pair: [-Y,-X,Y,X]
•Ct-V₂‹Sθ• # Push compressed integer 856559820693157436
s # Swap so earlier quadruplet is on top again
Åв # Convert 856559820693157436 to custom base [-Y,-X,Y,X],
# which basically converts it to base 4, and indexes into the quadruplet
# (unlike Jelly, 05AB1E uses 0-based indexing, so [-Y,-X,Y,X] → [0,1,2,3])
2ô # Then split this list into pairs
Å» # Cumulative left-reduce it, keeping all intermediate results:
+ # Add the values at the same positions in the pair together
# (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 `•Ct-V₂‹Sθ•` is `856559820693157436`.
] |
[Question]
[
Let \$S \subset \mathbb N\_{\geq0}\$ be a subset of the nonnegative integers, and let $$
S^{(k)} = \underbrace{S + S + \dots + S}\_{k\ \textrm{times}} = \{ a\_1 + a\_2 + \dots + a\_k : a\_i \in S\}.
$$
For example, $$\begin{align}
\{1,2,3\}^{(2)}
&= \{1+1, 1+2, 1+3, 2+1, 2+2, 2+3, 3+1, 3+2, 3+3\}\\
&=\{2,3,4,5,6\}
\end{align}$$
If \$S\$ contains \$n\$ elements, then \$S^{(k)}\$ contains at most \$\binom{n+k-1}{k} = \frac{(n + k - 1)!}{(n-1)!k!}\$ distinct elements. If \$S^{(k)}\$ contains this number of distinct elements, we call it \$k\$-maximal. The set \$S = \{1,2,3\}\$ given in the example above is *not* \$2\$-maximal because \$1 + 3 = 2 + 2\$.
## Challenge
Given a positive integer `k`, your task is to return the lexicographically earliest infinite list of nonnegative integers such that for every \$n\$ the set consisting of the first \$n\$ terms of \$S\$ is \$k\$-maximal.
You can return a literal (infinite) list/stream, you can provide function that takes a parameter `i` and returns the \$i\$th element of the list, or you can give any other reasonable answer.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins.
### Test Data
```
k | S^(k)
---+------------------------------------------------------------
1 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
2 | 0, 1, 3, 7, 12, 20, 30, 44, 65, 80, 96, ...
3 | 0, 1, 4, 13, 32, 71, 124, 218, 375, 572, 744, ...
4 | 0, 1, 5, 21, 55, 153, 368, 856, 1424, 2603, 4967, ...
5 | 0, 1, 6, 31, 108, 366, 926, 2286, 5733, 12905, 27316, ...
6 | 0, 1, 7, 43, 154, 668, 2214, 6876, 16864, 41970, 94710, ...
```
For \$k=2\$ , this should return OEIS sequence [A025582](https://oeis.org/A025582).
For \$k=3\$ , this should return OEIS sequence [A051912](https://oeis.org/A051912).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 102 bytes
```
(k,a=[],n=-1,g=_=>(h=(c,u,p)=>c?a.every(v=>v<p||h(c-1,v+u,v)):h[u]^=1)(k,a.push(++n))?n:g(a.pop()))=>g
```
[Try it online!](https://tio.run/##PY5NisMwDIX3PYWWEnbDZDOLpkoPEjIleJy/BtsksWGY9uypQmkX4iE9fU8am9QsZh7CenT@124tb3jTDVe1dnzMdcdXLrFnNDrqQFyaS5PZZOc/TFymc7jfezSymFTUiejUV7H@4Zz2lCzEpUelHNHFnTqUgQ9IJDHd1voZcLIrDMCQFyJnhm9RpQj@DwC7l8RrcSANPq4hrov0VV2I@8FHGX0VIi98fOPwRl5fJLm7cw8p493iJ5tNvsPhEy32Y3sC "JavaScript (Node.js) – Try It Online")
Invoke `f(k)`, it returns a function `g`. Each time you invoke `g()`, you will get the next value of `k`-th sequence.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
»*@Żœcḷœċ§QƑɗƇḢ
```
[Try it online!](https://tio.run/##y0rNyan8n5lXUFpipZCpo5DNlambnJ@blJmXWJKZn1eskJ@mUJSYl55qoJGbWKGRqZOtpZWpqWmtkJaZU5JapJGWX6SQmJOjUFCUmpZZkVpspVBcmgvWla1bhGJQYlGqQkpmcUlmXnIJWH9Rccn/Q7u1HI7uPjo5@eGO7UcnH@k@tDzw2MST04@1P9yx6P///yb/jQA "Jelly – Try It Online")
Takes `i` and `k` and returns the first `i` elements of the `k`th sequence. Extremely slow.
The `i`th term (1-indexed) cannot exceed `1+k+..+k**(i-2)` since the `k`-combinations without replacement of the set `0, 1, 1+k, 1+k+k**2, ..., 1+k+...+k**(i-2)` has distinct sums (because each added term is strictly larger than the previously existing maximum sum) and, as the terms strictly smaller than the bound emerge, the bound for the next term will only go lower. This bound can be relaxed to `max(i, k**i)` by considering the cases where `k=1` and `k>=2`.
```
»*@Żœcḷœċ§QƑɗƇḢ Dyadic link. Left = i (#terms to return), Right = k
»*@ bound = max(i, k**i)
Żœcḷ All i-combinations of 0..bound
ƇḢ Filter and take the first sequence satisfying...
œċ§QƑɗ All k-combinations without replacement have distinct sums
```
[Answer]
# JavaScript (ES6), 113 bytes
Expects `(k)(n)` and returns the first \$n\$ terms of \$S^{(k)}\$ in reverse order.
```
k=>n=>(g=a=>(h=(a,k,s)=>k?a.every((v,i)=>h(a.slice(i),k-1,v-~s)):h[s]^=1)(a,k)?n--?g([0,...a]):a:g(a,a[0]++))([])
```
[Try it online!](https://tio.run/##bctLCsMgFIXheVdyL1FJ@oSAyULEwiU1JjVoiUXopFu3trNCJmfwHf47JYrDOj@e3IebyaPMTnZedmAllZ0kEHMsouxcT8Iks74AEpsLTEAiLvNgYEbmeMMSf0fEdlJRX2WD3xJ7z3lvQdVMCEEaW2ptOUjVuqoQQWnMQ/AxLEYswcIIJbwg7v5xv4WHLTxu4WkLzz/MHw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 70 bytes
```
NθNη≔⁰ζW‹Lυη«⊞υζ≦⊕ζ≔EΦEXLυθ﹪Eθ÷κXLυνLυ¬⊙κ∧ν›μ§κ⊖νΣEκ§υμε¿⊙ε⊖№εκ≔⊟υε»Iυ
```
[Try it online!](https://tio.run/##ZU9Na8MwDD03v8JHGzzYobeeQstGoC2B/QIv0RoTR05iu90H@@2ZlIauYwcJPb2nJ6lqzFh546apwD7FY@peYZSD2mT3uCGch2BPKB@1@CR0aawDIfcQAiU8xUYmpUWjlPjKVmUKhK/K1cH0y2yB1QgdYIR64RaCJPLJukiruCz9hao724Hi4Ovk/MwPWhQYd/Zsa5CtFv/0qBTlW4PB0UeZ4wfLc6wlavE8guGNHXVigTW8M7mD242SbdQ8/ZK6eXP7q6X3uisJ/Il9E7M//LXY@oSRmy1rxfJv6fv5Tp78zsrRkmZrQuRbN9O0Fuvp4ex@AA "Charcoal – Try It Online") Link is to verbose version of code. Takes `k` and `n` as input and outputs the first `n` terms. Explanation:
```
NθNη
```
Input `k` and `n`.
```
≔⁰ζ
```
Start with a first trial term of `0`.
```
W‹Lυη«
```
Repeat until enough terms have been collected.
```
⊞υζ
```
Push the next trial term to the list of terms.
```
≦⊕ζ
```
Increment the trial value.
```
≔EΦEXLυθ﹪Eθ÷κXLυνLυ¬⊙κ∧ν›μ§κ⊖νΣEκ§υμε
```
Calculate all of the sums of combinations with replacement of the terms including the trial term.
```
¿⊙ε⊖№εκ≔⊟υε
```
If there are any duplicates then remove the trial term from the list.
```
»Iυ
```
Output the resulting list.
63 bytes by porting @ovs's Python answer:
```
NθNη≔±¹ζ≔E⊕θ¬κεW‹ⅉη«≦⊕ζ≔⟦⟧δFε⊞δ|κ×∨⌈δ⁰X²ζ¿¬&§ε±¹×§δ±²X²ζ«≔δε⟦Iζ
```
[Try it online!](https://tio.run/##ZY89a8MwEIZn@1doPIELbcjWye1kaBwPWUrIoFqXSMSSU0muQ0p@u3oidhuoQHBf73P3tkq4thddjJU9DaEezAc6@OTP@X2uKC@91wcLNR5EQHjiBbv8VVfiBJVtHRq0ASUBClb3AY6cAqS5UekOGbyh9/AOVFScs@88I@GEuJPf0NnU2O4KJlO@7x0D5KwZvAIaetFh1B7XDo4F22iDHiheibM2gwFJSx7pN/1IDhaJSY8wes8g3TbJSyuhDJWVeAakq2d/fGbOTfnbXPB/3ORlPljeLGdZ47QNsH0VPsCF71Ltml9jXLJlfPjqfgA "Charcoal – Try It Online") Link is to verbose version of code. Takes `k` and `n` as input and outputs the first `n` terms. Explanation:
```
NθNη
```
Input `k` and `n`.
```
≔±¹ζ
```
Start the trial term at `-1` so that `0` can be considered with an initial increment on the first pass.
```
≔E⊕θ¬κε
```
Start with a list of `1` and `k` `0`s, which are bitmasks representing the sets of sums of `i` elements of the empty set; the first set is the set of sums of zero elements which is always `{0}` while the others are empty sets.
```
W‹ⅉη«
```
Loop until `n` terms have been printed.
```
≦⊕ζ
```
Increment the next trial term.
```
≔⟦⟧δFε⊞δ|κ×∨⌈δ⁰X²ζ
```
Using the bitmasks from the terms so far, calculate the bitmasks for the sets of sums of `i` elements from them plus the current trial term.
```
¿¬∧ζ&§ε±¹×§δ±²X²ζ«
```
If there are no collisions between the sums of `k` elements excluding the current trial term and the sums of `k` elements including the current trial term at least once, then...
```
≔δε
```
... save the new bitmasks, and...
```
⟦Iζ
```
... output the current trial term on its own line.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~130~~ ~~106~~ 105 bytes
Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for pointing out a mistake.
Saved a lot of bytes by looking at [@AZTECCO's Haskell answer](https://codegolf.stackexchange.com/a/236522/64121) and realizing I don't need to keep track of the maximum number of unique sums.
```
def f(k):
r=1,*[0]*k;j=-1
while 1:
j+=1;d=0;w=[d:=i|d<<j for i in r]
if r[k]&w[-2]<<j<1:yield j;r=w
```
[Try it online!](https://tio.run/##JY5LDoIwFAD3nOKt5GNJqC40lHoRwsLYVl4LtHk0ISTeHUHXM5lMWGPvp@s90LYpbcBkLq8TIMlZ0VZd4YSVJU9g6XHQwHcE9iy5ULISi2xVLfGjmsaC8QQIOAF1u4MGqHXdaWnLS7fjhtcr6kGBFSSXzZAfAaOm6P0wA47BUwScB3zpJDlS7pd6Tm@dcXY7liAQTjFzLC0fKSv@cnb8MuBVnm9f "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
m‚àÝI.Æ.Δ¹ã€{ÙODÙQ
```
Port of [*@Bubbler*'s Jelly answer](https://codegolf.stackexchange.com/a/236478/52210), but lacking a `k-combinations without replacement` builtin.
First input is \$k\$, second input is \$i\$. Outputs the first \$i\$ elements of the \$k^{th}\$ sequence.
[Try it online.](https://tio.run/##ASsA1P9vc2FiaWX//23igJrDoMOdSS7Dhi7OlMK5w6Pigqx7w5lPRMOZUf//Mgo0)
**Explanation:**
```
m # Push the first (implicit) input to the power of the second
# (implicit) input: k**i
‚ # Pair it together with the second (implicit) input: [i,k**i]
à # Pop and push the maximum
Ý # Pop and push a list in the range [0,max(i,k**i)]
I.Æ # Pop and get all i-element combinations of this list
.Δ # Find the first list which is truthy for:
# Get all k-combinations without replacement:
¹ã # Take the current list to the cartesian power of the first input k
€{ # Sort each inner list
Ù # Uniquify this list of lists
O # Get the sum of each inner list
# Check that all sums are unique:
D # Duplicate the list of sums
Ù # Uniquify the copy
Q # Check if both lists are still equal
# (after which the result is output implicitly)
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~109~~ 103 bytes
```
s#k=sum<$>mapM(\_->s)[1..k]
f=([0]!)
(n:s)!k|any(`elem`s#k)$map(+n)$s#(k-1)=(n+1:s)!k|1>0=n:(n+1:n:s)!k
```
[Try it online!](https://tio.run/##pZDNboJAFIX3PMU1shiiEO78giksu@uqS7WVBaZmhBqxiU18d3rvEHmBknDuDHPOdzJ8NYNvz@dxHJa@Gn66l7jumsub2H2m9ZBsMcv8PjpWYpvvF0kk@s2QLPyj6X/FoT233YFiSUwJseqTeFgKn2JSiX6FkxHrvOo3YT9Fx6459VBxB4jdPa0v11N/g/jW@BbKGI5wD616P3p4wPuH8EmUpukq/ccTARIrXwOuQa4BFL2gWQwL2KAuKBTTKMNACmVZFkUgZwKn2YuMkjn7VFCtJ9oELcI3KO2ToGYC@ZApigkOA4uzEkO5coFgHB@DY@xE0DOBDJJzhhZoAstytjB8F9QTzuZ8okvrngQzE8inaGBOMWU5VUpSKQteG6coirLMuckpnG9hZwJBNZsMdVlulxJ5WTgyoy0sbTSWjtylds8/@fp9hT8 "Haskell – Try It Online")
* thanks to @Ovs for suggesting using sum<$>.. instead of map(sum)..
Essentially we search next term by checking if the sums with it creates only new sums.
* f returns an infinite list of *k* using an initial set [0] applied to (!)
* (n:s)!k finds all next terms indefinitely
*|any(`elem`s#k)$...* if any of ... Are in s#k try next *n*
... *map(+n)$s#(k-1)* permutations of k-1 + n
else we add *n* to the set and we search next terms
* s#k returns all permutations of *s* of length *k* summed.
Stolen from [this answer of Laikoni](https://codegolf.stackexchange.com/a/165682/84844)
[Try k=5](https://tio.run/##PUzLbsMgELzzFRvFB5BtBLZ5OCo99tYvcK2Gg6NEYBqF9FAp/@4ujdTLzmNn5uxzWGLctrwPbvVXyN9rhfhOPz7b18wmyXmYycnRScw7Rmg6ZLYLD59@6HGJy3rEIisNWidW5T0NrWSOplo@g/GlzXU9pdmlw58b0d1Wf0ng4Hq7pDtUdx8WMBWcQG0ECCh4gGhANqAb6BGksEg0Khg7vF1nC1em7/HZjUKhZ3qJJuecEND/C6aBoYTUgGvalq4s1BoMS201ikGOBtPjYKR4Lrx93eAX "Haskell – Try It Online")
[Try k=6](https://tio.run/##PUzLbsMgELzzFRvFB5BtxPoBOCo99tYvcK2Gg6NEYBqF9FAp/@6uG6mXncfOzNnnMMe4rnkf3OKvkL@XgvCdf3zWr1mMKGWY2MnxUU07wXg6ZLELD59@@HGO83KkotgavEyiyHseahSOpxKfwfhS57Ic0@TS4c@N5K6LvyRwcL1d0h2Kuw8z6AJOoFcGDHp4gKoAK9AVtASoLBFNCoaGbtPYjfembenZDKonz7RIppSSMdD/C6aCbgv1Ha1pu3Vxo9ZQGLXVJDocDKWHzqB6Lrx93eAX "Haskell – Try It Online")
] |
[Question]
[
# Challenge
Write a program that compresses and decompresses ASCII text losslessly. It should be specialized to work well with palindromes, including case-insensitive and punctuation-insensitive palindromes. The best compression with the smallest source wins.
## Scoring
`total_bytes_saved / sqrt(program_size)` - Highest score wins
`total_bytes_saved` is how many bytes smaller the compressed strings are than the originals, total across the test cases below. `program_size` is the size in bytes of the source code of both the compression and decompression programs. Code shared between the two need only be counted once.
For instance, if there are 10 test cases and a 100 byte program saved 5 bytes on 7 test cases, 10 each on 2 of them, but the last test case was 2 bytes longer, the solution would score 5.3. (`(7 * 5 + 10 * 2 - 2) / sqrt(100) = 5.3`)
## Test Cases
* `tacocat`
* `toohottohoot`
* `todderasesareddot`
* `amanaplanacanalpanama`
* `wasitacaroracatisaw?`
* `Bob`
* `IManAmRegalAGermanAmI`
* `DogeeseseeGod`
* `A Santa at NASA`
* `Go hang a salami! I'm a lasagna hog.`
## Rules
1. Standard loopholes apply.
2. The compression must work on all printable ASCII (bytes 32-126, inclusive) text strings, not just palindromes. It doesn't actually have to save space for any inputs, however.
3. Output can be any sequence of bytes or characters, regardless of its implementation or internal representation (strings, lists, and arrays are all fair game, for instance). If encoding to UTF-8, count bytes, not characters. Wide strings (e.g. UTF-16 or UTF-32) are not allowed unless the only codepoints possibly used are between 0 and 255.
4. Compression/Decompression builtins are not allowed.
For the sake of our own enjoyment, post the compressed strings with your source code.
**UPDATE 1:** Scoring changed from `total_bytes_saved / program_size` to `total_bytes_saved / sqrt(program_size)` in order to give more weight to better compression and less weight to aggressive golfing. Adjust your scores accordingly.
**UPDATE 2:** fixed `wasitacaroraratisaw?` to be `wasitacaroracatisaw?`
[Answer]
## JavaScript (ES6), 3.143 (81 bytes saved, 664 byte program)
```
R='replace',S=String.fromCharCode,T=c=>c.charCodeAt(),U='toUpperCase',V='0000000',W=(a,b,c=2)=>a.toString(c).slice(b),X=x=>'0b'+x,Y=a=>[...a].reverse().join``,Z=/[^]/g
C=s=>S(...((Y(q=s[U]()[R](/[^A-Z]/g,m=''))==q?(q=q.slice(0,p=-~q.length/2),p%1&&10):11)+q[R](Z,x=>W(T(x),2))+111+s[R](Z,c=>/[a-z]/.test(c)?W("00",m,m=1):m+(/[A-Z]/.test(c,m='')?"01":W(c<'!'?2:T(c)+384)))+V).match(/(?!0+$).{8}/g).map(X))
D=s=>{s=s[R](Z,c=>W(256+T(c),1))+V;M=r=>(s=s[R](p=s.match(`^${r}|`)[0],''),p);for([,a]=M`1.|0`,t=u=i='';!M`111`;)t+=W(X(M`.{5}`)-~8,0,36);for(t+=W(Y(t),a?a/0:1);p;)u+=M`0(?=00)|00?1`?(c=t[i++])?+p[1]?c[U]():c:'':M`10`?' ':M`11`&&S(X(M`.{7}`));return u+W(t,i)}
```
Now that I'm fairly satisfied with this program (and the scoring system), I'll write a bit of an explanation.
The basic idea is to compress the input into a string of bits, then compress each set of 8 bits into a byte. For the purposes of explanation, I'll just manipulate the bit string.
The bit string can be separated into several sections:
```
input -> Taco Cat.
output -> 0101000000100011011111110100001100100011101011100000000
0 | 10100 00001 00011 01111 111 | 01 00001 10 01 0001 110101110
header | letter data | styling data
```
The header is a very simple mapping:
```
0 -> odd-length palindrome
10 -> even-length palindrome
11 -> non-palindrome
```
Letter data is also fairly simple. First, all non-letters are extracted from the string, and all letters are converted to uppercase. If the resulting string is a palindrome, the reversed half is stripped. Then this mapping is applied:
```
A -> 00001
B -> 00010
C -> 00011
D -> 00100
...
Z -> 11010
```
This section is terminated with `111`. After that comes the styling data, which stores upper/lower-case data and non-letters. This works like so:
```
01 -> next letter as uppercase
0...01 (n 0s) -> next (n-1) letters as lowercase
10 -> space
11xxxxxxx -> character with code point 0bxxxxxxx
```
So going through the example shown above, we have
```
header: 0 -> palindrome
letter data: 10100 00001 00011 01111 111 -> taco
styling data:
01 -> T
00001 -> aco
10 -> <space>
01 -> C
0001 -> at
110101110 -> .
```
When the end of the bit string is reached, all remaining characters from the letter data are appended to the result. This saves us from having to do one last `000...001` and allows us to truncate these bits from the string.
Going through the test cases:
```
tacocat -> 3 bytes (-4)
24 bits: 010100000010001101111111
toohottohoot -> 5 bytes (-7)
35 bits: 10101000111101111010000111110100111
todderasesareddot -> 7 bytes (-10)
49 bits: 0101000111100100001000010110010000011001100101111
amanaplanacanalpanama -> 8 bytes (-13)
59 bits: 00000101101000010111000001100000110000001011100000100011111
wasitacaroracatisaw? -> 11 bytes (-9)
84 bits: 010111000011001101001101000000100011000011001001111111000000000000000000001110111111
Bob -> 2 bytes (-1)
16 bits: 0000100111111101
IManAmRegalAGermanAmI -> 13 bytes (-8)
98 bits: 00100101101000010111000001011011001000101001110000101100111010100010100101000001010100000010100101
DogeeseseeGod -> 7 bytes (-6)
54 bits: 000100011110011100101001011001100101111010000000000101
A Santa at NASA -> 8 bytes (-7)
63 bits: 100000110011000010111010100000011110110010000011000011001010101
Go hang a salami! I'm a lasagna hog. -> 20 bytes (-16)
154 bits: 1000111011110100000001011100011100001100110000101100000010110101001111010011000000110001100000000111010000110011101001110011000110000000001100000111010111
```
[Answer]
# Python 2: 2.765 (70 bytes saved, 641 byte program)
I changed my approach a little. It now works well on imperfect palindromes. There are no compressed strings that will be longer than the input. Perfect even-length palindromes will always compress to 50% the original size.
```
A=lambda x:chr(x).isalpha()
def c(s):
r=bytearray(s);q=len(r);L=0;R=q-1;v=lambda:R+1<q and r[R+1]<15
while L<=R:
while not A(r[L])and L<R:L+=1
while not A(r[R])and R:
if v()and r[R]==32:r[R]=16+r.pop(R+1)
R-=1
j=r[L];k=r[R]
if A(j)*A(k):
if L!=R and j&31==k&31:
r[L]+=(j!=k)*64;r[R]=1
if v():r[R]+=r.pop(R+1)
else:r[L]|=128;r[R]|=128
L+=1;R-=1
while r[-1]<16:r.pop()
return r
def d(s):
r='';t=[]
for o in s:
if 15<o<32:r+=' ';o-=16
while 0<o<16:r+=chr(t.pop());o-=1
if o==0:continue
if 127<o<192:o-=64;t+=[o^32]
elif o>192:o-=128
elif A(o):t+=[o]
r+=chr(o)
while t:r+=chr(t.pop())
return r
```
# Results
```
'tacocat' <==> 'tac\xef'
4/7 (3 bytes saved)
'toohottohoot' <==> 'toohot'
6/12 (6 bytes saved)
'todderasesareddot' <==> 'todderas\xe5'
9/17 (8 bytes saved)
'amanaplanacanalpanama' <==> 'amanaplana\xe3'
11/21 (10 bytes saved)
'wasitacaroracatisaw?' <==> 'wasita\xe3ar\xef\x09?'
12/20 (8 bytes saved)
'Bob' <==> '\x82\xef'
2/3 (1 bytes saved)
'IManAmRegalAGermanAmI' <==> 'I\x8d\xa1n\x81m\x92e\xa7\xa1\xec'
11/21 (10 bytes saved)
'Dogeeseseegod' <==> '\x84ogees\xe5'
7/13 (6 bytes saved)
'A Santa at NASA' <==> 'A S\xa1\xaeta\x12\x14'
9/15 (6 bytes saved)
"Go hang a salami! I'm a lasagna hog." <==> "\x87o hang a salam\xa9!\x11'\x01\x11\x17\x13."
24/36 (12 bytes saved)
```
And as a bonus, it saves 6 bytes on my incorrect palindrome I had before.
```
'wasita\xe3ar\xef\x02\xf2\x06?' <==> 'wasitacaroraratisaw?'
6 bytes saved
```
# Explanation
Decompression uses a stack. Codepoints from 32-127 are treated literally. If a character is a letter, a value is pushed onto the stack as well. Values 128-192 are used for case flipped letters, so the caseflipped letter (`o^32` because of how ASCII is laid out) gets pushed onto the stack and the normal letter gets added to the string. Values 192-255 are used to add letters without pushing to the stack, so this is used when letters do not match and for the middle letter in odd-length palindromes. Codepoints 1-15 indicate that the stack should be popped that number of times. Codepoints 17-31 are similar, but they print a space first before popping from the stack. There is also an implicit "pop until empty" instruction at the end of an input.
The compressor works from both ends and folds in matching letters as values 1-31. It skips over non-letters. When the letters match but the case does not, it adds 64 to the left letter and increments the right letter. This allows it to save space on `IManAmRegalAGermanAmI`. At the middle or when the letters do not match, it ors 128 to both sides. I can't add there because I need to avoid the special case where `left == right`. When folding neighboring pop markers on the right side, I have to check that the neighboring one won't overflow into codepoint 16 because I need that for spaces. (This is not actually an issue for any of the test case strings)
**EDIT 1**: No more ungolfed version.
[Answer]
# Python3, 1.833 (25 bytes saved, 186 byte program)
Just simple 0-order equal-probability entropy coding. No palindrome-specific optimizations.
```
def C(s):
u=0
for c in s:u=u*96+ord(c)-31
return u.to_bytes((u.bit_length()+7)//8,'big')
def D(a):
u,s=int.from_bytes(a,'big'),''
while u:s,u=s+chr((u%96)+31),u//96
return s[::-1]
```
[Answer]
# Java 8, score: 1.355 (20 bytes saved / 218 (107+111) bytes)
Compress function (contains three unprintable ASCII characters):
```
s->{int l=s.length();return s.contains(new StringBuffer(s).reverse())?s.substring(l/2)+(l%2<1?"":""):s;}
```
Decompress function (contains two unprintable ASCII characters):
```
s->{return s.contains("")?new StringBuffer((s=s.replaceAll("","")).substring(s.length()&1^1)).reverse()+s:s;}
```
**Explanation:**
[Try it online.](https://tio.run/##nVRRb9NADNZe9yvMScCdSlNtT2hlVN0K0x62BwpPDCQ3cdNsyV10vrZM0377cLq0adoJEJUaxWef/X3@7NziAruuJHub3D3FOTLDFWb24RAgs4H8FGOC88oEGAef2RRiXb@w6cv5Yyt01ApNdkKfADhgyGI4hxhOq0jo9eDaBSjRB3BTCDOCyX2gbuzmNhxy9@ODZIf8lKOcbBpm2vQ9hbm3wFHsbBC0rC0t65pn8@mUvGYTeVqQZ9LGDDji@YRXfp33jk1H56@PPxwN1IE6UQcHypxw//GwD3u/P4PbsBlB8s9s9sELCjPYY6BZKHsqc2nrMM@rqHdKGbNFpWnJm6OfR2aLcof/i5HoU84nuTCqiS1clkAhKGshv/9AE2beLRk@/YqpDJmzz4oH4qBVwNjFGNRK7s2hczMXgjzcnidJyCMTo6ck2XVjgRalARZj@eelPApshyyRMymK3nn0AplxOWhHnLlJ@@DyCu2w@EIp5sML8kVlXbZDRi4lElREFy5pu4YwRtENMMD1cDxsOy8czFDGHYExxyJ7BZdvC7FkrzC1CDOXRmqzNc38rNq8SrHZl5e7XK2CiH8milXjkVJYvWr17evn7ntl6oHot/bVFaUnZkpO4yjWXCOuUjWu54yN/bfU9xyoiNw8RKUUCZo7CrTqrLGJVU0VmxNQnZ0qa99W9epqY3WkmHR5QUl1W69zdnfymJpI64NDW2yTKNGNaV5GnlutbsJNGG3dBExl5CE4kAmAbLpBKjr0mhJiwdL5O65gbleuFX58@g0)
Only compresses perfect palindromes.
```
s->{ // Method with String as both parameter and return-type
int l=s.length(); // Get the length of the input
return s.contains(new StringBuffer(s).reverse())?
// If the input is a palindrome:
s.substring(l/2) // Only return the second halve of the String
+(l%2<1?"":"") // + either one (if even) or two (if odd) unprintables
: // Else:
s;} // Simply return the input again
s->{ // Method with String as both parameter and return-type
return s.contains("")? // If the input contains an unprintable:
new StringBuffer((s=s.replaceAll("",""))
// Remove the unprintables
.substring(s.length()&1^1))
// And take either the full string (if even),
// or minus the first character (if odd)
.reverse() // And reverse that part
+s // And append the rest of the input (minus the unprintables)
: // Else:
s;} // Simply return the input again
```
] |
[Question]
[
# Problem
Draw a hexagon chain `x` long, each with side of `y` length
# Input
`x` - the length of the chain <= 50
`y` - the length of each side <= 50
# Examples
`x=1,y=1`
```
_
/ \
\_/
```
`x=4,y=1`
```
_ _
/ \_/ \_
\_/ \_/ \
\_/ \_/
```
`x=3,y=2`
```
__ __
/ \ / \
/ \__/ \
\ / \ /
\__/ \__/
\ /
\__/
```
# Rules
* The shortest valid answer in bytes wins.
* Leading and trailing newlines allowed.
* Trailing white space allowed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
NθFN«M∧﹪ι²⊗θ↓P×_θ←↖θ→↗θ×_θ↓↘θ←P↙θ↗
```
[Try it online!](https://tio.run/##fY67CsIwGIXn9ilCpwTqori0k@AiWCmis/SS2kCav8akDuKzx6REaREcz@E7l6otZAUFN2Yneq0OuiupxDeShg1IhKcmIegZBhkMFG9EjTOoNQfMYrQkMdqCLjmtbdKKZAsPYSuCTHPFesmEwifW0TuOLlGMLJP6omRPG@VUPkLJuXeGQ77EkV3bOTI6nsn/lX9u@KST0@z8weTrSP4c8cPWeBmzCtdmMfA3 "Charcoal – Try It Online") Link is to verbose version of code. Takes the parameters in the order size, count. Explanation:
```
Nθ
```
Input the hexagon size.
```
FN«
```
Loop over the input number of hexagons.
```
M∧﹪ι²⊗θ↓
```
On alternate hexagons, move down a whole hexagon, so that the next hexagon is drawn to the lower right rather than the upper right.
```
P×_θ
```
Draw the bottom.
```
←↖θ
```
Draw the lower left side.
```
→↗θ
```
Draw the upper left side.
```
×_θ
```
Draw the top.
```
↓↘θ
```
Draw the upper right side.
```
←P↙θ
```
Draw the lower right side.
```
↗
```
Assume the next hexagon is to the upper right.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~254~~ 224 bytes
```
def f(n,w):
a=w*2
for j in range(1+w*3):print''.join([[[' ',[' /'[i%w==-j%w],' \\'[i%w==~-j%w]][i/a+~-j/w&1]][(j>0)*(i/w>=(j>a))*((i/w/n<2)or(n%-2<~-j/w<3-n%2))],' _'[(j+i/w%4/2*w)%a<(i<n*a)]][i/w%2]for i in range(-~n*a)])
```
[Try it online!](https://tio.run/##RU5LbsIwEN3nFN4YzzhO3RhQK@RwERNVlorBWUxQhDRiw9WDEyp1M@8zv3d73K8juXn@PSeRgAzjoRKxY@0qkcZJDCKTmCJdztDWrLd4uE2Z7kp9DGMmCCEooUwpVoUsueuaQXJvlDid/ozn6vQh21gXbnnTFgXD8RM1ZMvHrvCIRSzKknc4TkCycX4d99uGpENcjv6osliXMbmzTjPK6CF70hHXByxdv4TO/6Gb59rFOUFrWqwS7N7wbdwC@zd8mT3OLw "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), ~~264~~ 229 bytes
```
def f(n,w):
c=2*w;r=[[' ']*(-~n*c)for _ in' '*(1+w*3)]
for i in range(w):
for j in range(n):a=i+j*2*w;b=j%2*w;r[b][w+a],r[c+b][w+i+j*c],r[b+w-i][a],r[b+c-i][a+c],r[b+w-~i][a],r[b-~i][a+c]=r'__//\\'
for l in r:print''.join(l)
```
[Try it online!](https://tio.run/##TY7NCoMwEITvPkUuJb9W1JaCJU8Sg2hq2ohECULoxVe3GkF7m/lmd3bH7/QZbLYsr1YDjSzzuIiA4hnxT8eFgABKguLZEoX14EAFjF0ZQSn1JMcyAhs1KwWutu8Whf0AuxNaXNTc0I5stQ3vLqFeNFJ4WkvmhKJBbyNq8w31sZGi3rUKmh7JfES7XBPuYFUlSVnC/aM@HC9GZ@wE4bUbjEU9XjRKWYqjgCONbv8mZ9lpHuyOlx8 "Python 2 – Try It Online")
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~32~~ 31 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ā.{e╚øΚe╔*ο⁴↔±┼┼╬±fe«*If2%e*I╬5
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTAxLiU3QmUldTI1NUElRjgldTAzOUFlJXUyNTU0KiV1MDNCRiV1MjA3NCV1MjE5NCVCMSV1MjUzQyV1MjUzQyV1MjU2QyVCMWZlJUFCKklmMiUyNWUqSSV1MjU2QzU_,inputs=MTUlMEE1,v=0.12)
Explanation:
```
ā push an empty array - the canvas
.{ repeat input times
e╚ push a diagonal the length of the variable E (by default: next input)
øΚ prepend a line to it
e╔*ο push ["_"*E]
⁴ copy that diagonal
↔± and reverse it horizontally
┼┼ add the 3 parts together
╬± and palindromize vertically - one hexagon is finished
fe«*I push counter*E*2 + 1 (the counter is 0-based)
f2%e*I push counter%2 * E + 1
╬5 at [counter*E*2+1; counter%2*E+1] insert the hexagon in the canvas
```
[Answer]
# Befunge, ~~230~~ ~~228~~ 225 bytes
```
+\#<*:0< vp93*p92+1*3:p91:&+1p
>1+:29g-!#@_>:1-19g+:19g/1-:2*49p2%!2*:1+59p19g*\19g%+69p01v
,>*19g3*79g-1-69g-!2*49g1+0g2%*79g69g-!49g0g2%*++4g,1+:39g-v
^^3*!-*g95g91+1g96!-g95%4p04p01:`\g90p05`0::/g91:p97%*4g91:_$55+
\/_
```
[Try it online!](http://befunge.tryitonline.net/#code=KyYjOTIjPCo6MDwgdnA5MypwOTIrMSozOnA5MTomKzFwCj4xKzoyOWctISNAXz46MS0xOWcrOjE5Zy8xLToyKjQ5cDIlITIqOjErNTlwMTlnKlwxOWclKzY5cDAxdgosPioxOWczKjc5Zy0xLTY5Zy0hMio0OWcxKzBnMiUqNzlnNjlnLSE0OWcwZzIlKisrNGcsMSs6MzlnLXYKXl4zKiEtKmc5NWc5MSsxZzk2IS1nOTUlNHAwNHAwMTpgXGc5MHAwNWAwOjovZzkxOnA5NyUqNGc5MTpfJDU1KwogXC9f&input=MyAy)
[Answer]
# JavaScript (ES6), 215 bytes
Takes input in currying syntax `(y)(x)`.
```
y=>(F=(x,c=!(p=y-1,w=x*y*2+y,a=[...(' '.repeat(w++)+`
`).repeat(3*y+1)],g=(d,k)=>k!=y?g(d,-~k,a[p+=d]='_\\/'[c%3]):c++))=>x--?F(x,g(1),g(w+1),p++,g(w-1),g(-1),p+=w,g(~w),p--,g(1-w),p+=(c/6&1?w:-w)*y-w+y*2):a.join``)
```
### Demo
```
let f =
y=>(F=(x,c=!(p=y-1,w=x*y*2+y,a=[...(' '.repeat(w++)+`
`).repeat(3*y+1)],g=(d,k)=>k!=y?g(d,-~k,a[p+=d]='_\\/'[c%3]):c++))=>x--?F(x,g(1),g(w+1),p++,g(w-1),g(-1),p+=w,g(~w),p--,g(1-w),p+=(c/6&1?w:-w)*y-w+y*2):a.join``)
O.innerText = f(3)(7)
```
```
<pre id=O></pre>
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 25 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
ø╶{╷⁷«×¹2%⁷×╵⁷⇵_× ⁷/∔×╬│╋
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JUY4JXUyNTc2JXVGRjVCJXUyNTc3JXUyMDc3JUFCJUQ3JUI5JXVGRjEyJXVGRjA1JXUyMDc3JUQ3JXUyNTc1JXUyMDc3JXUyMUY1XyVENyUyMCV1MjA3NyV1RkYwRiV1MjIxNCVENyV1MjU2QyV1MjUwMiV1MjU0Qg__,i=MTElMEEz,v=1)
Explanation (some characters have been changed to look monospace):
```
ø╶{╷⁷«×¹2%⁷×╵⁷⇵_× ⁷/∔×╬│╋
ø push an empty canvas
╶{ for 1..input
╷ decrease (so this starts with 0)
⁷«× multiply by X*2; X coordinate of new hexagon done
¹2% push 0-indexed counter%2
⁷× multiply by X
╵ and increment; Y coordinate done
⁷⇵ push ceil(X/2), saving the remainder
_× repeat "_" that many times
⁷/ push " " and an ASCII diagonal with size X
∔ prepend verticall the space before the diagonal
done so there's space for the underscores
× and append the underscores horizontally to the diagonal
╬│ quad-palindromize with Y overlap of 1
and X overlap of the remainder taken before
╋ and at the before defined coords ((I-1)*X*2; (i%2)*X + 1)
insert the hexagon in the canvas
```
] |
[Question]
[
***UPDATE***:
**The gist-files are updated (including new submissions) as the Controller.java did not catch Exceptions (only errors). It does now catch errors and exceptions and also prints them.**
*This challenge consists of two threads, this is the cat thread, the catcher thread can be found [here](https://codegolf.stackexchange.com/questions/51030/assymetrical-koth-catch-the-cat-catcher-thread).*
The controller can be downloaded [here](https://gist.github.com/flawr/7f2ad5d6f20e84e9d52b).
This is an asymmetrical KOTH: Each submission is either a *cat* or a *catcher*. There are games between each pair of each a cat and a catcher. The cats and the catchers have separate rankings.
## Catcher
There is a cat on a hexagonal grid. Your task is to catch it as fast as possible. Every turn, you can place a water bucket on one grid cell in order to prevent the cat from being able to go there. But the cat is not (perhaps) that dumb, and whenever you place a bucket, the cat will move to another grid cell. Since the grid is hexagonal, the cat can go in 6 different directions. Your goal is to surround the cat with water buckets, the faster the better.
## Cat
You know the catcher wants to catch you by placing water buckets around you. Of course you try to evade, but as you are a lazy cat (as cats are) you exactly take one step at the time. This means you cannot stay on the same place you, but you have to move to one of the six surrounding spots. Whenever you see that the catcher placed a new water bucket you go to another cell. Of course you try to evade as long as possible.
## Grid
The grid is hexagonal, but as we do not have hexagonal data structures, we take a `11 x 11` square 2d array and mimic the hexagonal 'behavior' that the cat can only move in 6 directions:

The topology is toroidal, that means if you step on a cell 'outside' of the array, you will just be transferred to the corresponding cell on the other side of the array.
## Game
The cat starts out at given position in the grid. The catcher can do the first move, then the cat and its catcher alternate moves until the cat is caught. The number of steps is the score for that game. The cat tries to get a score as great as possible, the catcher tries to get a score as low as possible. The average sum over all the games you participated in will be the score of your submission. There are two separate rankings, one for the cat, one for the catchers.
# Controller
The given controller is written in Java. As a catcher or a cat you each have to each complete implement a Java class (there are already some primitive examples) and place it in the `players` package (and update the list of cats/catchers in the Controller class), but you also may write additional functions within that class. The controller comes with each two working examples of simple cats/catcher classes.
The field is a `11 x 11` 2D- `int` array that stores the values of the current states of the cells. If a cell is empty, it has value `0`, if there is a cat it has value `-1` and if there is a bucket there is a `1`.
There are a few given functions you can use: `isValidMove()`/`isValidPosition()` are for checking whether your move (cat) / position (catcher) is valid.
Each time it is your turn, your function `takeTurn()` is called. The argument contains the a copy of the current grid an has methods like `read(i,j)` for reading the cell at `(i,j)`, as well as `isValidMove()/ isValidPosition()` that checks the validity of your answer. This also manages the wrapping over of the toroidal topology, that means even if the grid is only 11 x 11, you still can access the cell (-5,13).
The method should return a `int` array of two elements, which represent possible moves. For the cats these are `{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}` which represent the relative position of where the cat wants to go, and the catchers return the absolute coordinates of where they want to place a bucket `{i,j}`.
If your method produces an invalid move, your submission will be disqualified. The move is considered as invalid, if at your destination is already a bucket or the move is not allowed / destination already occupied (as a cat), or if there is already a bucket/cat (as a catcher). You can check that before hand with the given functions.
Your submission should work reasonably fast. If your method takes longer than 200ms for each step it will also be disqualified. (Preferably much less...)
The programs are allowed to store information between the steps.
## Submissions
* You can make as many submissions as you want.
* Please do not significantly alter submissions you've already submitted.
* Please each submissions in a new answer.
* Each submission should preferably have it's unique name.
* The submission should consist of the code of your class as well as a description that tells us how your submission works.
* You can write the line `<!-- language: lang-java -->` before your source code in order to get automatic syntax highlighting.
## Scoring
All *cats* will compete against all *catchers* the same number of times. I'll try to update the current scores frequently, the winners will be determined when the activity has decreased.
This challenge is inspired by [this old flash game](http://www.gamedesign.jp/flash/chatnoir/chatnoir.html)
Thanks @PhiNotPi for testing and giving some constructive feedback.
## Current Scores (100 Games per pairing)
| Name (Catcher) | Score | Rank | Author |
| --- | --- | --- | --- |
| RandCatcher | 191962 | 8 | flawr |
| StupidFill | 212688 | 9 | flawr |
| Achilles | 77214 | 6 | The E |
| Agamemnon | 74896 | 5 | The E |
| CloseCatcher | 54776 | 4 | randomra |
| ForwordCatcher | 93814 | 7 | MegaTom |
| Dijkstra | 47558 | 2 | TheNumberOne |
| HexCatcher | 48644 | 3 | randomra |
| ChoiceCatcher | 43834 | 1 | randomra |
| Name (Cat) | Score | Rank | Author |
| --- | --- | --- | --- |
| RandCat | 77490 | 9 | flawr |
| StupidRightCat | 81566 | 6 | flawr |
| SpiralCat | 93384 | 5 | CoolGuy |
| StraightCat | 80930 | 7 | CoolGuy |
| FreeCat | 106294 | 3 | randomra |
| RabidCat | 78616 | 8 | cain |
| Dijkstra's Cat | 115094 | 1 | TheNumberOne |
| MaxCat | 98400 | 4 | Manu |
| ChoiceCat | 113612 | 2 | randomra |
[Answer]
# FreeCat
Chooses the move which would give it the most possible paths after 3 steps if the field wouldn't change.
FreeCat vs Achilles:

```
package players;
/**
* @author randomra
*/
import java.util.Arrays;
import main.Field;
public class FreeCat implements Cat {
final int[][] turns = { { -1, 1 }, { 0, 1 }, { -1, 0 }, { 1, 0 },
{ 0, -1 }, { 1, -1 } };// all valid moves
final int turnCheck = 3;
public String getName() {
return "FreeCat";
}
public int[] takeTurn(Field f) {
int[] pos = f.findCat();
int[] bestMove = { 0, 1 };
int bestMoveCount = -1;
for (int[] t : turns) {
int[] currPos = { pos[0] + t[0], pos[1] + t[1] };
int moveCount = free_count(currPos, turnCheck, f);
if (moveCount > bestMoveCount) {
bestMoveCount = moveCount;
bestMove = t;
}
}
return bestMove;
}
private int free_count(int[] pos, int turnsLeft, Field f) {
if (f.isValidPosition(pos) || Arrays.equals(pos, f.findCat())) {
if (turnsLeft == 0) {
return 1;
}
int routeCount = 0;
for (int[] t : turns) {
int[] currPos = { pos[0] + t[0], pos[1] + t[1] };
int moveCount = free_count(currPos, turnsLeft - 1, f);
routeCount += moveCount;
}
return routeCount;
}
return 0;
}
}
```
[Answer]
# [Dijkstra's](https://codegolf.stackexchange.com/a/51153/32700) Cat
He learned and applies his master's master algorithm. Note that he is dependent on some of the methods in his corresponding catcher's class.
Dijkstra's Cat vs Hexcatcher(needs updated):

```
package players;
import main.Field;
import players.Dijkstra; //Not needed import. Should already be available.
/**
* @author TheNumberOne
*
* Escapes from the catcher.
* Uses Dijkstras methods.
*/
public class DijkstrasCat implements Cat{
private static final int[][] possibleMoves = {{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}};
@Override
public String getName() {
return "Dijkstra's Cat";
}
@Override
public int[] takeTurn(Field f) {
int[] me = f.findCat();
int[] bestMove = {-1,1};
int bestOpenness = Integer.MAX_VALUE;
for (int[] move : possibleMoves){
int[] newPos = Dijkstra.normalize(new int[]{me[0]+move[0],me[1]+move[1]});
if (!f.isValidMove(move)){
continue;
}
int openness = Dijkstra.openness(newPos, f, true)[1];
if (openness < bestOpenness || (openness == bestOpenness && Math.random() < .5)){
bestOpenness = openness;
bestMove = move;
}
}
return bestMove;
}
}
```
**How he works:**
He tries to find the move that minimizes the stringiness of the board in relation to himself. For more information, see the corresponding catcher's post.
**With update:**
He now avoids the strange geometric shapes that the water buckets sometimes form.
[Answer]
# MaxCat
I tried implementing the Minimax algorithm. However, it doesn't perform very well because of the limited time. **Edit:** It now uses multithreading, but (atleast on my computer) I can't set the depth any higher. Otherwise a timeout occurs. Using a PC with 6 or more cores, this submission would be much better :)
MaxCat vs Dijkstra:

```
package players;
import java.util.ArrayList;
import java.util.List;
import main.Field;
public class MaxCat implements Cat {
final int[][] turns = { { -1, 1 }, { 0, 1 }, { -1, 0 }, { 1, 0 }, { 0, -1 }, { 1, -1 } };
public String getName() {
return "MaxCat";
}
public int[] takeTurn(Field f) {
List<CatThread> threads = new ArrayList<>();
int[] pos = f.findCat();
for (int[] turn : turns) {
if(f.read(pos[0]+turn[0], pos[1]+turn[1]) == Field.EMPTY){
CatThread thread = new CatThread();
thread.bestMove = turn;
thread.field = new Field(f);
thread.start();
threads.add(thread);
}
}
for (CatThread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {}
}
int best = Integer.MIN_VALUE;
int[] bestMove = { -1, 1 };
for (CatThread thread : threads) {
if (thread.score > best) {
best = thread.score;
bestMove = thread.bestMove;
}
}
return bestMove;
}
class CatThread extends Thread {
private Field field;
private int[] bestMove;
private int score;
private final int DEPTH = 3;
@Override
public void run() {
score = max(DEPTH, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
int max(int depth, int alpha, int beta) {
int pos[] = field.findCat();
if (depth == 0 || field.isFinished()) {
int moveCount = 0;
for (int[] turn : turns) {
if(field.read(pos[0]+turn[0], pos[1]+turn[1]) == Field.EMPTY)
moveCount++;
}
return DEPTH-depth + moveCount;
}
int maxValue = alpha;
for (int[] turn : turns) {
if(field.read(pos[0]+turn[0], pos[1]+turn[1]) == Field.EMPTY) {
field.executeMove(turn);
int value = min(depth-1, maxValue, beta);
field.executeMove(new int[]{-turn[0], -turn[1]});
if (value > maxValue) {
maxValue = value;
if (maxValue >= beta)
break;
}
}
}
return maxValue;
}
int min(int depth, int alpha, int beta) {
if (depth == 0 || field.isFinished()) {
int moveCount = 0;
for (int[] turn : turns) {
int pos[] = field.findCat();
if(field.read(pos[0]+turn[0], pos[1]+turn[1]) == Field.EMPTY)
moveCount++;
}
return -depth - moveCount;
}
int[][] f = field.field;
int minValue = beta;
List<int[]> moves = generateBucketMoves();
for (int[] move : moves) {
f[move[0]][move[1]] = Field.BUCKET;
int value = max(depth-1, alpha, minValue);
f[move[0]][move[1]] = Field.EMPTY;
if (value < minValue) {
minValue = value;
if (minValue <= alpha)
break;
}
}
return minValue;
}
private List<int[]> generateBucketMoves() {
int[][] f = field.field;
List<int[]> list = new ArrayList<>();
for (int i = 0; i < f.length; i++) {
for (int j = 0; j < f[i].length; j++) {
if (f[i][j] == Field.EMPTY) {
list.add(new int[]{i,j});
}
}
}
return list;
}
}
}
```
[Answer]
# SpiralCat
Moves in a spiral way. It
* Tries to move to the top-left circle
* If not possible, tries to move to the top right circle
* If not possible, tries to move to the right circle
* If not possible, tries to move to the bottom right circle
* If not possible, tries to move to the bottom left circle
SpiralCat vs Agamemnon:

```
package players;
/**
* @author Cool Guy
*/
import main.Field;
public class SpiralCat implements Cat{
public String getName(){
return "SpiralCat";
}
public int[] takeTurn(Field f){
int[][] turns = {{-1,1},{0,1},{1,0},{1,-1},{0,-1},{-1,0}};//all valid moves
int[] move;
int i = -1;
do {
i++;
move = turns[i];
} while(f.isValidMove(move) == false);
return move;
}
}
```
[Answer]
## RabidCat
RabidCat has hydrophobia, so he is afraid of the water buckets. He finds the nearest one and runs in the opposite direction.
RabidCat vs ForwordCatcher:

```
package players;
import java.util.Random;
import main.Field;
/**
* Run away from water buckets
* @author cain
*
*/
public class RabidCat implements Cat {
public RabidCat() {
}
@Override
public String getName() {
return "RabidCat";
}
@Override
public int[] takeTurn(Field f) {
int[][] directions = {{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}};
//where am I?
int[] position = {0,0};
for(int i = 0; i < 12; i++){
for(int j = 0; j < 12; j++){
if(f.read(i,j) == -1){
position[0] = i;
position[1] = j;
}
}
}
//Find the closest water
int direction = 0;
for(int d = 0; d < 10; d++){
if(f.read(position[0] + d, position[1] - d) == 1 && f.isValidMove(directions[0])){
direction = 1;
break;
}
if(f.read(position[0], position[1] - d) == 1 && f.isValidMove(directions[1])){
direction = 2;
break;
}
if(f.read(position[0] + d, position[1]) == 1 && f.isValidMove(directions[2])){
direction = 3;
break;
}
if(f.read(position[0] - d, position[1]) == 1 && f.isValidMove(directions[3])){
direction = 4;
break;
}
if(f.read(position[0], position[1] + d) == 1 && f.isValidMove(directions[4])){
direction = 5;
break;
}
if(f.read(position[0] - d, position[1] + d) == 1 && f.isValidMove(directions[5])){
direction = 6;
break;
}
}
//If there is no water near, wander
while(direction == 0){
Random rand = new Random();
direction = rand.nextInt(6) + 1;
if(!f.isValidMove(directions[direction - 1])){
direction = 0;
}
}
return directions[direction - 1];
}
}
```
[Answer]
# ChoiceCat
For every possible new cat positions we check its goodness and choose the best one. Goodness is the function of the two best neighbour cells who are further away from the cat position than the position whose score we calculate. We use only two cells because one can be blocked and the cat only needs one more to get away. Our function prefers two fairly good cells than one great and one bad. Positions with buckets have a score of 0 and the furthest free cells have a score of 1.
ChoiceCat seems to score better than the current cats.
ChoiceCat vs ChoiceCatcher:

```
package players;
/**
* @author randomra
*/
import java.util.Arrays;
import main.Field;
public class ChoiceCat implements Cat {
private class Values {
public final int size;
private double[][] f;
Values(int size) {
this.size = size;
f = new double[size][size];
}
public double read(int[] p) {
int i = p[0];
int j = p[1];
i = (i % size + size) % size;
j = (j % size + size) % size;
return f[i][j];
}
private double write(int[] p, double v) {
int i = p[0];
int j = p[1];
i = (i % size + size) % size;
j = (j % size + size) % size;
return f[i][j] = v;
}
}
final int[][] turns = { { -1, 1 }, { 0, 1 }, { 1, 0 }, { 1, -1 },
{ 0, -1 }, { -1, 0 } };// all valid moves CW order
final int stepCheck = 5;
public String getName() {
return "ChoiceCat";
}
public int[] takeTurn(Field f) {
int[] pos = f.findCat();
int[] bestMove = { 0, 1 };
double bestMoveValue = -1;
for (int[] t : turns) {
int[] currPos = { pos[0] + t[0], pos[1] + t[1] };
double moveValue = movePosValue(currPos, f);
if (moveValue > bestMoveValue) {
bestMoveValue = moveValue;
bestMove = t;
}
}
return bestMove;
}
private double movePosValue(int[] pos, Field f) {
Values v = new Values(f.SIZE);
for (int ring = stepCheck; ring >= 0; ring--) {
for (int phase = 0; phase < 2; phase++) {
for (int sidepos = 0; sidepos < Math.max(1, ring); sidepos++) {
for (int side = 0; side < 6; side++) {
int[] evalPos = new int[2];
for (int coord = 0; coord < 2; coord++) {
evalPos[coord] = pos[coord] + turns[side][coord]
* sidepos + turns[(side + 1) % 6][coord]
* (ring - sidepos);
}
if (phase == 0) {
if (ring == stepCheck) {
// on outmost ring, init value
v.write(evalPos, -1);
} else {
v.write(evalPos, posValue(evalPos, v, f));
}
} else {
// finalize position value for next turn
v.write(evalPos, -v.read(evalPos));
}
}
}
}
}
return -v.read(pos);
}
private double posValue(int[] pos, Values v, Field f) {
if (f.read(pos[0], pos[1]) == Field.BUCKET) {
return 0;
}
int count = 0;
double[] product = new double[6];
for (int[] t : turns) {
int[] tPos = new int[] { pos[0] + t[0], pos[1] + t[1] };
if (v.read(tPos) > 0) {
product[count] = 1 - 1 / (v.read(tPos) + 1);
count++;
}
}
Arrays.sort(product);
double fp = 1;
for (int i = 0; i < Math.min(count,2); i++) {
fp *= product[5-i];
}
double retValue = Math.min(count,2) + fp;
return -retValue;
}
}
```
[Answer]
# StupidRightCat
This was made just for testing the controller. The cat move right whenever possible, otherwise moves in a random direction.
```
package players;
import main.Field;
public class StupidRightCat implements Cat{
public String getName(){
return "StupidRightCat";
}
public int[] takeTurn(Field f){
int[][] turns = {{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}};//all valid moves
int[] move;
if(f.isValidMove(turns[3])){
return turns[3];
} else {
do {
move = turns[(int) (turns.length * Math.random())];
} while(f.isValidMove(move)==false);
return move;//chose one at random
}
}
}
```
[Answer]
# RandCat
This was made just for testing the controller. The cat just moves randomly.
```
package players;
import main.Field;
public class RandCat implements Cat{
public String getName(){
return "RandCat";
}
public int[] takeTurn(Field f){
int[][] turns = {{-1,1},{0,1},{-1,0},{1,0},{0,-1},{1,-1}};//all valid moves
int[] move;
do {
move = turns[(int) (turns.length * Math.random())];
} while(f.isValidMove(move)==false);
return move;//chose one at random
}
}
```
[Answer]
# StraightCat
This cat moves straight.
At the start, it chooses a random direction and keeps moving in this direction until it cannot in which case, it shifts the direction in a clockwise manner to the next valid direction and repeats this process.
StraightCat vs Agamemnon:

```
package players;
/**
* @author Cool Guy
*/
import main.Field;
public class StraightCat implements Cat{
int lastDirection = -1; //Holds the last direction the cat moved
public String getName(){
return "StraightCat";
}
public int[] takeTurn(Field f){
int[][] turns = {{-1,1},{0,1},{1,0},{1,-1},{0,-1},{-1,0}};//all valid moves
if(lastDirection == -1)
lastDirection = (int) (turns.length * Math.random());
int[] move = turns[lastDirection];
int i = lastDirection;
while(true)
{
if(f.isValidMove(move))
break;
i = (i+1)%6;
lastDirection = i;
move = turns[i];
}
return move;
}
}
```
] |
[Question]
[
Given a setup of dominoes your task is to figure out which dominoes fall and which don't.
## Input
Take a rectangular ASCII representation of a domino setup. The following characters are used for the ASCII grid:
* (space): empty cell
* `|`, `-`, `/`, `\`: dominoes
Dominoes can fall in 8 directions, which are represented by the following letters (similar to WASD orientations):
```
Q W E
A D
Z X C
```
One or more of the dominoes will be replaced by one of these letters to indicate that the domino is pushed over at the start. Here is an example:
```
D||||/
- /
- -
- -
/|||||
```
I don't want this challenge to turn into an exercise in input parsing so any of the following input forms are allowed:
* A string with the grid (optionally preceded by its dimensions if that helps)
* An array/list/tuple with one string for each line (optionally along with width and height integers)
* A (nested) array/list/tuple with one string/character for each grid cell (optionally along with width and height variables)
You can read from STDIN or take a function argument or even expect the input to be stored in a variable.
## Output
Write to STDOUT or return (or save in a variable) the resulting grid in any of the valid input formats, indicating which dominoes have fallen and which haven't. That is, replace each fallen domino with `#` and leave each standing domino as it was in the input.
## Rules
Of course, dominoes propagate their fall through the setup. As there may be race conditions, we assume that there are fixed time steps and the falling propagates one grid cell per time step.
Dominoes generally fall the way you would intuitively expect them to, but a rigorous specification of common sense turns out to be quite lengthy. Sorry for that, I hope the examples help. [Here is a gist](https://gist.github.com/mbuettner/26348ec42f6efd2cd1e6) with all unique two-tile combinations (up to rotation and reflection). Read on for the rigorous rules.
Each domino can fall in only two directions:
```
W Q E
A | D - / \
X C Z
```
Whenever a domino falls it affects the cell in the direction of the fall. If that cell contains a domino which can fall in the same direction or in a direction which differs by 45 degrees, that domino does so in the next time step.
Examples:
```
D| -> DD (falls in same direction)
D/ -> DC (falls at 45 degrees)
C -> C (falls at 45 degrees)
- X
```
Whenever a diagonally oriented domino (`/` or `\`) falls, it also affects the two cells which touch both its cell and the cell in the direction of its fall. If these cells contain a domino which can fall in the same direction as the original domino, or in the axis-aligned direction away from it, that domino does so in the next time step.
Examples:
```
C/ -> CC (the cell in the direction of the fall is the one below
the /, so it falls in the same direction)
C| -> CD (falls in the axis-aligned direction away from the C)
C- -> C- (the direction away from the Q is W,
or but neither - nor \ can fall to W)
C\ -> C\
```
**Exception**: if a domino is pushed in both valid directions at once (i.e. if any of the above rules are in conflict), it doesn't fall.
Examples:
```
D|A -> D|A (central domino in pushed in both directions)
Z Z (although it's pushed in one direction by two dominoes
D\A -> D\A and in the other by only one, it doesn't fall)
X X (the domino is being pushed from two opposing sides
D-A -> DXA D and A, but neither is valid for that domino. Hence,
there is no conflict and the X can push the domino over)
Z Z (pushed in the same direction by two dominoes, so falls)
\A -> ZA
Z Z Z (once the conflict arises, the affected
\ -> Z -> Z domino is locked in its position and can't
D|A D|A D|A be pushed over by future dominoes)
```
## Examples
```
8 5
D||||/ ######
- / - #
- - --> - #
- - - #
/||||| /|||||
===============================================
17 9
E|/|||/ #######
- - # #
- - # #
- - # #
/|||/|||||||||/ --> ###############
/ - # #
/ - # -
/ - # #
/|||||\ #######
===============================================
19 8
\|/ ###
- - # #
D||||/|\ /|||/ ######## #####
/ - # #
- \- --> - \#
\- \ - #- \ #
D||||\ / \ / ###### / \ #
|\ ||||| |\ #####
==============================================
11 11
-\\\/|\|\-| -\##/|###-|
-|\\||\-|\- -|#####-|\-
|\//\//|-/- |#//\//|#/-
\|//|-|\-\| #####-|##\|
---||/-\//| #-######//|
///|||\---- --> #/#####----
-|/---|-|-\ #|##--|-|-\
--|--\/|/// ####-\/|///
/|//--|//-| ####--|//-|
|/\-|||-/-\ |/\####-/-\
E||\-|\---/ ####-|\---/
```
Let me know if you think I made a mistake (especially with the last one).
[Answer]
## C# ~~1048~~ ~~907~~ 850bytes
Now heavily golfed, pretty much just a jumble of bit operations on a two-dimensional array of integer enums. Could probably be made somewhat shorter by using a 1-dimensional array, but I'm not prepared to try and re-work this at this point. Reads the dimensions and string from stdin, for example:
```
11 11 -\\\/|\|\-|-|\\||\-|\-|\//\//|-/-\|//|-|\-\|---||/-\//|///|||\-----|/---|-|-\--|--\/|////|//--|//-||/\-|||-/-\E||\-|\---/
```
Golfed:
```
using L=System.Console;class R{static void Main(){int p=255,e,c,E=7,D,C,X,Z,A,m=-1,t=m,f=t,u,i=t;for(;t<0;)for(t=f,f=0;(C=L.Read())>47;)f=f*10+C-48;var T=new int[f,t];for(;++i<f;)for(c=0;c<t;T[i,c++]=(C>99?68:C>91?34:C>89?112:C>87?56:C>86?131:C>80?193:C>68?7:C>67?14:C>66?28:C>64?224:C>46?136:C>44?17:0)*(C>64&C<91?1:257))C=L.Read();for(;i+E>0;E=-E)for(i=c=m;++c<f;)for(C=m;++C<t;){if(E>0&(A=D=T[c,C])>0&D<p){T[c,C]=m; X=C+(i=(D&4)>0?1:(D&64)/-64);Z=c+(u=(D&16)>0?1:D%2*m);System.Action v=()=>{if(Z>m&Z<f&X>m&X<t&&(e=T[Z,X])>p&(e>>8&A)>0)T[Z,X]&=65280|A;};v();if((i&u)!=0){X=i==u?C:X;Z=i==u?Z:c;A=((D&128)/128+D*2)&D;v();X=C+i-X+C;Z=c+u-Z+c;A=(D%2*128+D/2)&D;v();}i=8;}if(E<0&D>p&((D=D&p)&(D-1))<1&D>0)T[c,C]=D<2?131:D>64?193:D/2*7;}for(D=m;++D<f;L.WriteLine())for(c=0;c<t;L.Write(C<0?'#':(C=C>>8)>99?'/':C>67?'|':C>33?'\\':C>9?'-':' '))C=T[D,c++];}}
```
Because I have too much time I've modified the ungolfed version to output an animated gif of the dominoes falling (with help from [this SO question](https://stackoverflow.com/questions/1196322/how-to-create-an-animated-gif-in-net) and these documents [1](http://www.fileformat.info/format/gif/egff.htm) [2](http://www.matthewflickinger.com/lab/whatsinagif/animation_and_transparency.asp)). This has only added code, and it's either in a `#if gifness` block or clearly marked.
To create the gifs you provide a pair of command line arguments describing the frame times, output file, etc,
```
dominoGolf.exe console_delay (out_file_name (gif_frame_time (final_frame_time)))
dominoGolf.exe 0 outfile.gif 1 100
```
The third argument is the frame time for each frame (1/100s of seconds). The fourth argument is the frame time for last frame (1/100s of seconds). The second argument is the output filename for the gif. You can omit the filename, delay, and final delay if you just want the console output. The first argument is a delay between frames rendered to the terminal in milliseconds. You can omit all arguments if you don't want an animation at all and just want to see the result. It reads the domino data from stdin just like the golfed version. This code is horrible in it's own way (butchers the gif so that it loops).
Ungolfed gif-generating code:
```
#define gifness
using L=System.Console;
class R
{
static void Main(string[] args) // don't need args
{
int p=255,P=0xFF00,m=15,M=240, // might be able to inline a couple of these
w=1,e=2,d=4,c=8,x=16,z=32,a=64,q=128, // most of these are reusable
W=131,E=7,D=14,C=28,X=56,Z=X*2,A=Z*2,Q=193, // most (all?) of these are reusable
Y=w+x,U=a+d,N=c+q,B=z+e, // one of these atleast is pre-evalable
// recognise this?
t=-1,f=t,k,u,i=t,j,J,K,o,O,b;
for(;t<0;)
for(t=f,f=0;(k=L.Read())>47;)
f=f*10+k-48;
var T=new int[f,t]; // main arr
// domino: dir, copy(for render)
// motion: pickup
// input
for(;++i<f;) // values of i and j don't matter, just counters
{
for(j=0;j<t;) // increment done 3down
{
k=L.Read();
T[i,j++]=(
// fallen
k=='W'?W:k=='E'?E:k=='D'?D:k=='C'?C:k=='X'?X:k=='Z'?Z:k=='A'?A:k=='Q'?Q:
// dominos
k==' '?0:k=='-'?Y:k=='/'?N:k=='|'?U:B // ASCII, order for >
)*(k>64&k<91?1:257);
}
}
#if gifness
System.Drawing.Font font1 = null;
System.Windows.Media.Imaging.GifBitmapEncoder genc = null;
System.Drawing.Bitmap bmp = null;
System.Drawing.Graphics g = null;
if (args.Length > 1)
{
font1 = new System.Drawing.Font(System.Drawing.FontFamily.GenericMonospace, 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
genc = new System.Windows.Media.Imaging.GifBitmapEncoder();
bmp = new System.Drawing.Bitmap(t * 8, f * 14); // I have no clue what these should be in relation to em size
g = System.Drawing.Graphics.FromImage(bmp);
}
#endif
if (args.Length > 0) // not important
{
L.Clear();
}
// main
for(;i>0;) // can do i=1-i and swap setting 1 for 0 to remove {}
{
if (args.Length > 0) // non-critical, renders the current state to the console/gif
{
var os="";
for (o=0;o<f;o++) // values of i and j don't matter, just counters
{
for (j=0;j<t;j++)
{
k=T[o,j];
os += k==0?' ':k<p?'#':(k=k>>8)==Y?'-':k==N?'/':k==U?'|':'\\'; // order for >
}
os+="\n";
}
L.SetCursorPosition(0, 0);
L.Write(os);
#if gifness
if (args.Length > 1)
{
g.Clear(System.Drawing.Color.White);
g.DrawString(os, font1, System.Drawing.Brushes.Black, 0, 0);
System.IO.MemoryStream bms = new System.IO.MemoryStream();
bmp.Save(bms, System.Drawing.Imaging.ImageFormat.Gif);
var bmpf = System.Windows.Media.Imaging.BitmapFrame.Create(bms);
genc.Frames.Add(bmpf);
// do I chose the frame duraton1??!?!?! (take from args[2] is present else args[0])
}
#endif
System.Threading.Thread.Sleep(int.Parse(args[0]));
}
// back to important stuff
i=0; // set me to 1 if we do anything (8 in golfed version due to E being 7)
// move motions
for (j=0;j<f;j++) // careful!!
{
for (k=0;k<t;k++) // careful!!
{
O=o=T[j,k];
if (o>0&o<p) // we are motion
{
T[j,k]=-1; // do this so we can't skip it
K=k+(i=((o&d)>1?1:(o&a)>0?-1:0));
J=j+(u=((o&x)>1?1:(o&w)>0?-1:0));
System.Action v=()=>{
if(J>=0&J<f&K>=0&K<t&&(b=T[J,K])>p&&((b>>8)&O)>0)
{
T[J,K]&=(P|O);
}
};
v();
if (i!=0&u!=0)
{
K=i==u?k:K; // k+i == K
J=i==u?J:j; // j+u == J
O=(((o&q)>0?w:0)+o*2)&o;
v();
K=K==k?k+i:k;
J=J==j?j+u:j;
O=(((o&w)>0?q:0)+o/2)&o;
v();
}
i=1;
}
}
}
// move dominos
for (j=0;j<f;j++) // careful!!
{
for (k=0;k<t;k++) // careful!!
{
o=T[j,k];
if (o>p) // we are domino
{
o=o&p;
if ((o&m)<1!=(o&M)<1)
{ // we have motion
T[j,k]=o==w?W:o==q?Q:o+o/2+o*2;
}
}
}
}
}
if (args.Length > 0)
{
L.SetCursorPosition(0, 0);
}
// output
for (o=0;o<f;o++)
{
for (j=0;j<t;j++)
{
k=T[o,j];
L.Write(k<0?'#':(k=k>>8)==0?' ':k==Y?'-':k==N?'/':k==U?'|':'\\'); // order for >
}
L.WriteLine();
}
#if gifness
if (args.Length > 1)
{
g.Dispose();
bmp.Dispose();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
genc.Save(ms);
byte[] data = ms.GetBuffer();
byte[] netscape = { 0x21, 0xFF, 0x0B, 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00 };
if (args.Length > 2)
{
int last = -1;
int duration = int.Parse(args[2]);
// promise yourself now you will never use this in production code
// I've not read enough of the GIF spec to know if this is a bad idea or not
for (i = 0; i < ms.Length - 5; i++)
{
if (data[i] == 0x21 && data[i+1] == 0xF9 && data[i+2] == 0x04 && data[i+3] == 01)
{
data[i+4] = (byte)(duration & p); // something endian (least significant first)
data[i+5] = (byte)((duration & P) >> 8);
last = i+4;
}
}
if (last != -1 && args.Length > 3)
{
duration = int.Parse(args[3]);
data[last] = (byte)(duration & p);
data[last+1] = (byte)((duration & P) >> 8);
}
}
using (System.IO.FileStream fs = new System.IO.FileStream(args[1], System.IO.FileMode.Create))
{
fs.Write(data, 0, 13);
// behold
fs.Write(netscape, 0, netscape.Length);
fs.Write(data, 13, (int)ms.Length - 13); // lets hope these arn't in excess of 2GBs
}
}
#endif
}
}
```
An example gif for the 3rd example input (and that shown above)

Example randomly generated 100x25 domino layout

"Domino" in dominoes

[Answer]
# Python 1188
Basically just loops through continuously matching some hefty regex until it stops changing. It actually matches all the pushes of each direction separately (through regex), and then composes the different results making sure there are no conflicts and such.
The regex can probably be done much more compactly, but for now here is what I have (it assumes the grid is stored in a string, `g`, and the dimensions are in `x` and `y`):
```
import re;L='QWEADZXC';a='';m=(x*y+y);o=[0]*m;X='(.{%s})';t=X%x;u=X%(x+1);v=X%(x-1);R=range
def S(s,l):
f=s
for p,r in l:
n=re.sub(p,r,s,flags=re.DOTALL)
for i in R(len(n)):
if n[i]!=s[i]:f=f[:i]+n[i]+f[i+1:]
return f
while g != a:
a=g;n='';d=[S(g,[(r'D\|','DD'),(r'D\\','DE'),('D/','DC')]),S(g,[(r'\|A','AA'),(r'\\A','ZA'),('/A','QA')]),S(g,[('-%sW'%t,r'W\1W'),(r'\\%sW'%t,r'E\1W'),('/%sW'%t,r'Q\1W')]),S(g,[('X%s-'%t,r'X\1X'),(r'X%s\\'%t,r'X\1Z'),(r'X%s/'%t,r'X\1C')]),S(g,[('C%s/'%u,r'C\1C'),('C%s-'%u,r'C\1X'),(r'C%s\|'%u,r'C\1D'),('C%s/'%t,r'C\1C'),('C%s-'%t,r'C\1X'),('C/','CC'),(r'C\|','CD')]),S(g,[(r'Z%s\\'%v,r'Z\1Z'),('Z%s-'%v,r'Z\1X'),(r'Z%s\|'%v,r'Z\1A'),(r'Z%s\\'%t,r'Z\1Z'),('Z%s-'%t,r'Z\1X'),(r'\\Z','ZZ'),(r'\|Z','AZ')]),S(g,[('/%sQ'%u,r'Q\1Q'),('-%sQ'%u,r'W\1Q'),(r'\|%sQ'%u,r'A\1Q'),('/%sQ'%t,r'Q\1Q'),('-%sQ'%t,r'W\1Q'),('/Q','QQ'),(r'\|Q','AQ')]),S(g,[(r'\\%sE'%v,r'E\1E'),('-%sE'%v,r'W\1E'),(r'\|%sE'%v,r'D\1E'),(r'\\%sE'%t,r'E\1E'),('-%sE'%t,r'W\1E'),(r'E\\','EE'),(r'E\|','ED')])]
for i in range(m):
c=0
for r in d:
if r[i]in L:
if c==0:c=r[i]
elif r[i]!=c:o[i]=1;break
n+=g[i]if c==0 or o[i]else c
g=n
print re.sub(r'\w','#',g)
```
More ungolfed:
```
import re
L = 'QWEADZXC'
def sub_all(string,lst):
final = string
for p,r in lst:
new = re.sub(p,r,string,flags=re.DOTALL)
for i in range(len(new)):
if new[i]!=string[i]:
final=final[:i]+new[i]+final[i+1:]
return final
def dominoes(grid,x,y):
print len(grid),x*y+y
print grid
last = ''
locked = [0]*(x*y+y)
while grid != last:
last = grid
Dgrid = sub_all(grid,[(r'D\|','DD'),(r'D\\','DE'),('D/','DC')])
Agrid = sub_all(grid,[(r'\|A','AA'),(r'\\A','ZA'),('/A','QA')])
Wgrid = sub_all(grid,[('-(.{%s})W'%x,r'W\1W'),(r'\\(.{%s})W'%x,r'E\1W'),('/(.{%s})W'%x,r'Q\1W')])
Xgrid = sub_all(grid,[('X(.{%s})-'%x,r'X\1X'),(r'X(.{%s})\\'%x,r'X\1Z'),(r'X(.{%s})/'%x,r'X\1C')])
Cgrid = sub_all(grid,[('C(.{%s})/'%(x+1),r'C\1C'),('C(.{%s})-'%(x+1),r'C\1X'),(r'C(.{%s})\|'%(x+1),r'C\1D'),
('C(.{%s})/'%x,r'C\1C'),('C(.{%s})-'%x,r'C\1X'),
('C/','CC'),(r'C\|','CD')])
Zgrid = sub_all(grid,[(r'Z(.{%s})\\'%(x-1),r'Z\1Z'),('Z(.{%s})-'%(x-1),r'Z\1X'),(r'Z(.{%s})\|'%(x-1),r'Z\1A'),
(r'Z(.{%s})\\'%x,r'Z\1Z'),('Z(.{%s})-'%x,r'Z\1X'),
(r'\\Z','ZZ'),(r'\|Z','AZ')])
Qgrid = sub_all(grid,[('/(.{%s})Q'%(x+1),r'Q\1Q'),('-(.{%s})Q'%(x+1),r'W\1Q'),(r'\|(.{%s})Q'%(x+1),r'A\1Q'),
('/(.{%s})Q'%x,r'Q\1Q'),('-(.{%s})Q'%x,r'W\1Q'),
('/Q','QQ'),(r'\|Q','AQ')])
Egrid = sub_all(grid,[(r'\\(.{%s})E'%(x-1),r'E\1E'),('-(.{%s})E'%(x-1),r'W\1E'),(r'\|(.{%s})E'%(x-1),r'D\1E'),
(r'\\(.{%s})E'%x,r'E\1E'),('-(.{%s})E'%x,r'W\1E'),
(r'E\\','EE'),(r'E\|','ED')])
grids = [Dgrid,Agrid,Wgrid,Xgrid,Cgrid,Zgrid,Qgrid,Egrid]
ngrid = ''
for i in range(x*y+y):
c = None
for g in grids:
if g[i] in L:
if c==None: c = g[i]
elif g[i] != c:
ngrid += grid[i]
locked[i]=1
break
else:
ngrid += grid[i] if c==None or locked[i] else c
grid = ngrid
print grid
return re.sub(r'\w','#',grid)
```
The listed inputs all produce their outputs except the third, in which I'm pretty sure there's a mistake (the `\-/` at the very top should be `\|/` if the given output is desired). I'm also assuming that the `.` in the bottom left corner of the last one was intended to be a `D`.
] |
[Question]
[
Windows Batch (CMD) is probably the least suitable language for code golfing.
**Avoid newline characters**. If you're looking for the shortest code in bytes, as opposed to characters, you will want to get rid of all unnecessary carriage returns (newline characters = 2 bytes). You can use the `&` operation to do this, trimming one byte for each command.
```
echo Hello&echo World.
```
**Setting variables**. When setting variables using switches, the `set` parser will ignore spaces.
```
set /a a+=1
set /p b="User Input: "
:: Will be handled the same as..
set/aa+=1
set/pb="User Input: "
```
Note that the same parser rules do not apply to all commands - as an example, for loops require spaces. Except between the `set, string, or command` (i.e. what is inside the brackets) and the word `do`.
```
for /f %%a in (file.txt)do ...
```
**Simple mathematical expressions**. Also, notice the expression that I used for incrementing in the `set /a` command. For simple mathematical expressions use `+= -= *= /=` instead of (for example) `set /a a=%a%+1`.
**Gathering command output**. To get the output of a command, it can sometimes be useful to output to and read from a file, where you otherwise might have used a for loop to gather the output:
```
for /f %%a in ('echo test') do set a=%%a
:: Can be shortened to
echo test>f&set/pa=<f
```
`echo test` send stdout to a file called f, `>f`, start a new command `&` and get the contents of the file in a variable `set/pa=<f`. Obviously this isn't always useful. But it can be when all you need is a single line of output.
**Command output**. When suppressing command output, use `@` before the commands, unless you need to suppress *more than 9* commands, in which case, use `@echo off` at the start of your script. `@echo off` is 9 bytes long, and therefore will generally save more bytes with longer scripts.
**Commands often do more than just what is obvious** - think about what your commands are doing. For example; if you need to set a variable and echo another variable, instead of:
```
set a=OUTPUT
echo %a%
echo test>f
set /p b=<f
```
You can use the set command with the `/p` switch to output `%a%` for you.
```
set a=OUTPUT
echo test>f
set /p b=%a%<f
```
Completely golfed...
```
set a=OUTPUT&echo test>f&set/pb=%a%<f
```
A couple of expamples - [Count sum of all digits](https://codegolf.stackexchange.com/questions/18556/count-sum-of-all-digits-help-to-determine-winner/18598#18598) - [Goldbach's conjecture](https://codegolf.stackexchange.com/questions/19463/goldbachs-conjecture/19632#19632).
Any other tips are more than appreciated - I'll keep updating this if I think of anything else.
[Answer]
# Counters
Whenever you have a variable that will act as a counter starting from `0` you might want to write
```
set count=0
set/acount+=1
```
; however, you can eliminate the first lines because whenever `set/a` is used with an unset variable its value is assumed to be `0`
```
set/acounter+=1
```
# Code Blocks
There a number of ways you can shave off a few bytes when you have to used blocks of code.
Whenever you open a code block, you do not need to insert a line break before the first line of code in that block. The closing parentheses does not have to be on a line of its own either.
```
If %a%==%b% (
echo true
) else (
echo false
)
```
can be golfed to
```
If %a%==%b% (echo true)else (echo false)
```
# Printing Without Trailing New Line
The common pattern for this is
```
echo|set/p=text
```
but, you can save 2 bytes changing `echo` to `cd`
```
cd|set/p=text
```
[Answer]
## Directly print the result of a numeric calculation
If the challenge requires you to output a number that needs to be calculated, you can use `cmd/c set/a` to output the result of the calculation directly instead of saving the calculation and then echoing it. Example:
```
@set/a a=%1+%2
@echo %a%
```
becomes
```
@cmd/cset/a%1+%2
```
Edit: Apparently no spaces are necessary at all, saving 2 more bytes.
[Answer]
# Ampersands
Although &'s make the code seem shorter, as it uses less lines, it uses just as many characters as a newline. This means that
```
echo a&echo b
```
is as long as
```
echo a
echo b
```
so your code can stay readable without wasting characters.
There may be exceptions because some text editors combine line feed and carridge return for each new line.
[Answer]
### Delayed Expansion
Instead of using the lengthy `setLocal enableDelayedExpansion` you can use `cmd /v on` (or `cmd/von`) which will start a new interpreter with delayed variable expansion enabled.
I have yet to implement this so I don't have any examples, but you could use this in conjunction with the `/c` switch. Example:
```
@cmd/von/cset test=test^&echo !test!
```
Notice the use of the carat before the ampersand. if you need to use multiple ampersands or any other special characters, you may be better off enclosing everything after the `/c` switch in quotation marks:
```
@cmd/von/c"set test=test&set test1=test1&echo !test! !test1!"
```
This method also has the advantage of only having to use one `@` character to mask *all* input, and can therefore be used, without `/von`, as a shorter alternative to `@echo off` (or multiple `@` symbols).
9 characters: `@echo off`
6 characters: `@cmd/c`
For more lengthy scripts, which you can't do on one line, you can do the following to save some bytes:
```
@!! 2>nul||cmd/q/v/c%0&&exit/b
```
Or, ungolfed:
```
@!! 2>nul || cmd /q /v on /c %0 && exit/b
```
Replace `@echo off&setLocal enableDelayedExpansion` with the above.
When you first run your script `!!` will not expand at all, so you recieve an error because `"!!"` is not a command. The error output is then piped to nul (`2>nul`). When this first 'command' fails (`||`), it calls a new instance of cmd, which calls the batch file itself (using `/v (on)` to enable delayed expansion, and `/q` to turn echo off). Then `!!` will expand to nothing, as there is no variable called `<NULL>`. The rest of your script then runs. After which it will return to the original instance of cmd, and (`&&`) exit with the `/b` condition to keep the window open (the exit is so it doesn't continue to run through your script in the context of the first cmd instance, with echo on and delayed expansion off).
[Answer]
## Start of a string
The notation `%var:~start,end%` extracts a substring of the variable `var`. However if `start` is `0` then you can omit it entirely. We already know that you can omit `,end` if you want the rest of the string, which makes `%var:~%` an almost useless synonym for `%var%`, except that it returns `~` when `%var%` is empty. (Perhaps you could use it in a test: `if %var:~%==~`?)
[Answer]
## Repetitive strings
Set repetitive code blocks in variables, where the number of bytes used to set the variable + the number of bytes to output the variable are less than the number of bytes to just call the code directly.
For an example, see: [Draw the combinations that add up to 100](https://codegolf.stackexchange.com/questions/53434/draw-the-combinations-that-add-up-to-100/53463#53463)
You save 1 byte per usage of the set command, if you create a variable (named with one character, like "s") which contains `set<space>`. This only generates value if you use the set command more than 12 times. (Note there is a character at the end of the string `set s=set`).
```
set s=set
%s%a=1
%s%b=2
%s%c=3
%s%d=4
%s%e=5
%s%f=6
%s%g=7
%s%h=8
%s%i=9
%s%j=10
%s%k=11
%s%l=12
%s%m=13
```
The above is 1 byte shorter than..
```
set a=1
set b=2
set c=3
set d=4
set e=5
set f=6
set g=7
set h=8
set i=9
set j=10
set k=11
set l=12
set m=13
```
This is probably a pretty poor example - but it gets the point across.
[Answer]
# Shortening `IF EQU` statements
```
if %a% equ %b% do_something
if %a%==%b% do_something
```
Using `==` instead of `equ` saves **3** bytes.
---
# Shortening quotes in `IF` statements
This is a traditional so-called "safer" `if` comparsion.
```
if "%a%"=="%b%" do_something
```
To shorten this statement, do the following when the input can only be **alphanumerical**/**empty**:
```
if %a%.==%b%. do_something
```
Saving a total of **2** bytes.
---
# Challenges that require output
If the question says something like:
>
> Outputs at least 1 visible character.
>
>
>
then you could just do this:
```
cd
```
The `cd` shows the current directory to `STDOUT`.
---
# `GOTO`ing a label
Here's some methods of `goto`ing a label, ordered in descending order of bytes.
```
goto :l
goto l
goto:l
```
The above method saves **1** byte.
[Answer]
## Omitting space between command and parameters with slashes
Sorry about the uninformative title. What I'm trying to get at is that for some (not all) Windows command, you can omit the space in between the command/program name and the parameter, as long as that parameter starts with a slash. For example:
```
for /f %%G in ...
```
becomes
```
for/f %%G in ...
```
-1 Byte!
# Piping output instead of using ERRORLEVEL
Using ERRORLEVEL to determine whether a command ran correctly is not the shortest or most elegant method. Instead, you can pipe output. This works as follows (remember that any command after the `&&` operator only executes if the command before the `&&` ran without errors. Any command after the `||` operator, on the other hand, will run only if the command before it did NOT run properly. My example is:
```
net session>nul
if %errorlevel%==0 (echo 1) else (echo 0)
```
This could be replaced with:
```
net session>nul&&echo 1||echo 0
```
-26 Bytes, wow! Note that this does not work with commands like `choice`, where the ERRORLEVEL has a special value according to some input.
Regards,
Gabe
[Answer]
# Using parentheses effectively
Hi again,
Sorry to post a second answer but I felt this one deserved it. I have noticed that people often use one of the following methods to display command output without displaying that pesky `C:\Windows\System32>echo foo` line before each command.
The first method (using `echo off`):
```
@echo off
echo foo
echo bar
echo foobar
echo barfoo
```
The second method:
```
@echo foo
@echo bar
@echo foobar
@echo barfoo
```
However, neither of these methods are as short as the following:
```
@(echo foo
echo bar
echo foobar
echo barfoo)
```
Pretty handy, right? On another note, this can be used to pipe multiple lines of output to a file or device easily. For example, this lengthy code:
```
echo foo>file.txt
echo bar>file.txt
echo foobar>file.txt
echo barfoo>file.txt
```
becomes significantly shorter:
```
(echo foo
echo bar
echo foobar
echo barfoo)>file.txt
```
Thanks for reading this rather lengthy answer, and I hope this helps you.
Regards,
Gabe
] |
[Question]
[
Anyone who is moderately into low level code optimization know about the perils of branching, be it implemented as if-statements, loops or select-statements the possibility of a branch misprediction is a terrible clock-wasting thing.
Simple problems can be solved much better with simple arithmetic, so let's do that.
For the following problems all variables are 32 bit unsigned integers and the only allowed code is plain set statements involving only the following operators:
```
+ addition
- subtraction
* multiplication
/ integer division, rounds down, division by 0 not allowed
% modulo
& binary and
| binary or
^ binary exclusive or
>> bitshift right
<< bitshift left
Logic operators, return 1 if the expression is true and 0 if it is false.
== equal
!= not equal
< less than
<= less than or equal
> greater than
>= greater than or equal
Set operator
=
```
Every line must consist of a variable identifier followed by a set operator, followed by an expression.
An expression may not contain additional set operators, but may contain variable identifiers, literal numbers and parentheses.
The golfing score shall only count the number of operators.
Example:
```
myvar = ( ( ( foo + 5 ) * bar ) % 7 ) == 3
```
Has a score of 5 operators.
A solution may include as many variables as the author see fit.
Variables that have not been set have value `0`.
Overflow and underflow is allowed, all negative numbers underflow, so `3 - 5` is `4294967294`, even as part of a larger statement.
### Task 1: Max
Two values, `A` and `B`, exist in the scope, make the `RESULT` variable contain the largest of those values when the program terminates.
### Task 2: Median
Three values, `A`, `B` and `C`, exist in the scope, make the `RESULT` variable contain the median of those values when the program terminates.
### Task 3: Square root
One value, `A`, exist in the scope, make the `RESULT` variable contain the square root of `A`, rounded down, when the program terminates.
It is ok to post an answer to only one or two of the questions, to some of you just finding valid solutions will be a challenge.
[Answer]
## Task 3, 23 ops
```
x = (A >> 16) + A / ((A >> 13) + 511) + 15
x = (x + A/x) >> 1
x = (x + A/x) >> 1
x = (x + A/x) >> 1
RESULT = x - (x > A/x)
```
Using Newton's method, as the other solutions do, with a more tactfully chosen seed. The first bit `A >> 16` keeps the top of the range happy, the second bit `A / ((A >> 13) + 511)` keeps the middle of the range happy, and the last bit `15` the bottom, and also prevents division by zero errors (15 is the largest value possible which allows `0` to converge correctly - halved three times minus correction equals zero). For the input values `225, 275625, 82137969, 2908768489` (and nearby values) the initial seed is exact. All edge cases (perfect squares, perfect squares + 1, and perfect squares - 1) on the range `0 .. 2**32-1` have been tested and are correct.
A few comments about the rules:
*Overflow and underflow is allowed, all negative numbers underflow, so 3 - 5 is 4294967294, **even as part of a larger statement**.*
That last bit turns out to be something of an innovation killer. I initially attempted a solution using a generalized form of [Halley's method](http://en.wikipedia.org/wiki/Halley%27s_method), but realized that it was invalid given the above restriction. The iteration (as applied to square roots) is this:
```
x = x * (3*A + x*x) / (A + 3*x*x)
```
This iteration has nice qualities that Newton's does not. It converges cubically (rather than quadratically), it converges from above or below (rather than only from above), and it is not as sensitive to a poorly chosen seed (if Newton's iteration is provided a seed which is far too low, it will greatly over-shoot the convergence point, and then need to work its way back down).
Newton's method also has the problem (at least when dealing with integers) that it will quite often reach an *x* such that *A / x - x = 2* - in this case, it will converge to a value one larger than the proper integer root, which needs to be corrected for; Halley's method needs no such correction. But unfortunately, the value of `3*A + x*x` will quite often be larger than the allowed 32-bit integer space.
There are a number of other generalized nth root algorithms, but they all share this same characteristic:
```
x = x + x*(v - x**n)/(v*n)
x = (x*(n+1) - x**(n+1)/v)/n
x = ((n-2)*x + (4*v*x)/(v + x**n))/n
x = x*((n+2)*v + (n-2)*x**n)/(v + x**n)/n
x = ((n-2)*x + (n*x*v)/(v + (n-1)*x**n))/(n-1)
x = ((n-2)*x + x*((n*2-1)*v + x**n)/(v + (n*2-1)*x**n))/(n-1)
x = x + 2*x*(v - x**n)/(v + x**n)/n
x = x + x*31*(v - x**n)/(10*v + 21*x**n)/n
x = x + x*561*(v - x**n)/(181*v + 380*x**n)/n
x = x + x*1153*(v - x**n)/(372*v + 781*x**n)/n
```
etc. Most of these display either cubic or quadratic convergence. The last four are part of a series of iterations which converges on quartic convergence. But in praxis, Newton's method will get you what you need with fewer operations, unless you need to calculate many hundreds of digits.
[Answer]
# 65(61) operations (5 + 13 + 47(43))
**Task 1** -- Max(A,B)
```
RESULT = A + (B - A) * (A <= B)
```
This is the obvious solution. You need the assignment, you need comparison, you need to multiply the comparison with something, the multiplicand cannot be one of the variables and the product cannot be the result.
**Task 2** -- Mid(A,B,C)
```
RESULT = A \
+ (B - A) * (A > B) ^ (B <= C) \
+ (C - A) * (A > C) ^ (C < B)
```
This is an improvement over my previous 15-op solution, which conditioned all three variables - this saved two subtractions, but it introduced another centrality test. The test itself is simple: an element is in the middle iff exactly one other of the two is above.
**Task 3** -- sqrt(A)
```
X1 = 1024 + A / 2048
X2 = (X1 + A / X1 ) / 2
...
X10 = (X9 + A / X9 ) / 2
RESULT = X16 - (X16 * X16 > A)
```
Eleven rounds of newton approximation. The magic constant of 1024 is already beaten by [WolframW](https://codegolf.stackexchange.com/a/12516/7209) (and 512 causes division by zero for a=0 before a=2\*\*32 converges), but if we can define 0/0 as zero, ten iterations will work with the starting value of 512. I do admit that my claim of ten iterations is not entirely clean, but I still claim them in parentheses. ~~I'll have to investigate if nine is possible, however.~~ WolframH's solution *is* nine iterations.
[Answer]
### 1: 5 operators
```
RESULT = B ^ (A ^ B)*(A > B)
```
### 2: 13 operators
```
RESULT = B ^ (A ^ B)*(A > B) ^ (A ^ C)*(A > C) ^ (B ^ C)*(B > C)
```
### 3: 27 operators
```
g = 47|((0x00ffffff & A)>>10)|(A>>14)
r = (g + A/g)/3
r = (r + A/r)>>1
r = (r + A/r)>>1
r = (r + A/r)>>1
RESULT = r - (r*r-1>=A)
```
[Answer]
## Task 3, 39 Operations
**EDIT:** Changed last line; see comments.
This is an implementation of the Newthon method.
Tested with all positive squares, and also with the positive squares minus one, and also one million random numbers in the range from 0 to 2^32-1.
The seemingly funny starting value is short for `(1022 + A/1022) / 2`, which needs the least number of iterations (I think), and also makes the `RESULT` for `A=0` right (which would not be the case for `1024` instead of `1022`).
```
r = (511 + A/2044)
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
r = (r + A/r) / 2
RESULT = r - (r > A/r)
```
] |
[Question]
[
Your task is to create one brainfuck program for each of the following binary operators. Each program should take one or two 8-bit numbers (A and B) from input and calculate the specified operation:
1. `A XOR B`
2. `A AND B`
3. `A OR B`
4. `A Shifted Left by 1 (circular shift)`
5. `NOT A`
You do not have to implement all 5. Score is calculated by:
```
#totalCharacters + {4000 * #problemsNotCompleted}
```
So valid scores are from zero (best) to 20,000(nothing completed).
I don't care where you store the result, or whether or not you preserve the input. Assume 8-bit cells, and as many empty cells as you need to the right only.
You may assume the numbers are already in whatever memory location works best for you, so you don't need to worry about IO operations.
[Answer]
## Score: 275
It works better to expand these with a binary counter. The less intuitive parts deal with the possibility that A or B is 0. I didn't find a profitable way to use nondestructive flow control in the actual bit manipulation of the first three. Incidentally these should all work fine with 16-bit cells and slowly with 32-bit.
**XOR, 86**
Assumes A and B are in cells 1 and 2, stores A XOR B in cell 2, pointer starts in cell 0 and ends in cell 5.
```
-[[>>>>>>[>>>]++[-<<<]<<<-]>]>>>[<]>[[>[>-<-]>[<<<<<<+>>>>>>[-]]>]+[<[<<<++>>>-]<<]>>]
```
**AND, 78**
Assumes A and B are in cells 1 and 2, stores A OR B in cell 4, pointer starts in cell 0 and ends in cell 5.
```
-[[>>>>>>[>>>]++[-<<<]<<<-]>]>>>[<]>[[>[>[<<<<+>>>>-]<-]>+>]<[<[<<<++>>>-]<<]]
```
**OR, 86**
Assumes A and B are in cells 1 and 2, stores A OR B in cell 2, pointer starts in cell 0 and ends in cell 5.
```
-[[>>>>>>[>>>]++[-<<<]<<<-]>]>>>[<]>[[>[>+<-]>[<<<<<<+>>>>>>[-]]>]+[<[<<<++>>>-]<<]>>]
```
**ROL, 18**
Assumes A is in cell 0, stores A ROL 1 in cell 1, pointer starts and ends in cell 0.
```
[>++[>>]<[>+>]<<-]
```
**NOT, 7**
Assumes A is in cell 0, stores NOT A in cell 1, pointer starts and ends in cell 0.
```
+[>-<-]
```
[Answer]
## Score: 686
All snippets assume that the numbers are already loaded in cell 0 and 1 and that the pointer points to cell 0.
I can add an atoi snippet later if that's required for the challenge. For now, you can try the code like this:
```
+++++++++> number 1
++++< number 2
```
**XOR, 221**
Result is written to cell 10, pointer ends at cell 5
```
>>>>>++++++++[-<<<<<[->>+<<[->>->+<]>>[->>>>+<<]<<<<]>>>[-<<<+>>>]<<[->+<[->->+>
>>>>]>[->>>>>+>>]<<<<<<<<]>>[-<<+>>]>>>[->>+<<]>[>[-<->]<[->+<]]>[[-]<<<[->+>-<<
]>[-<+>]+>+++++++[-<[->>++<<]>>[-<<+>>]<]<[->>>>+<<<<]>>]<<<]
```
**AND, 209**
Result is written to cell 10, pointer ends at cell 5
```
>>>>>++++++++[-<<<<<[->>+<<[->>->+<]>>[->>>>+<<]<<<<]>>>[-<<<+>>>]<<[->+<[->->+>
>>>>]>[->>>>>+>>]<<<<<<<<]>>[-<<+>>]>>>[->[->+<]<]>[-]>[-<<<[->+>-<<]>[-<+>]+>++
+++++[-<[->>++<<]>>[-<<+>>]<]<[->>>>+<<<<]>>]<<<]
```
**OR, 211**
Result is written to cell 10, pointer ends at cell 5
```
>>>>>++++++++[-<<<<<[->>+<<[->>->+<]>>[->>>>+<<]<<<<]>>>[-<<<+>>>]<<[->+<[->->+>
>>>>]>[->>>>>+>>]<<<<<<<<]>>[-<<+>>]>>>[->>+<<]>[->+<]>[[-]<<<[->+>-<<]>[-<+>]+>
+++++++[-<[->>++<<]>>[-<<+>>]<]<[->>>>+<<<<]>>]<<<]
```
**Rotate Left, 38**
Result is written to cell 1, pointer ends at cell 4
```
[->++>+<[>-]>[->>+<]<<<]>>>>[-<<<+>>>]
```
**NOT, 7**
Result is written to cell 1, pointer ends at cell 0
```
+[+>+<]
```
## Explanation:
XOR, AND and OR all work in a similiar fashion: Calculate n/2 for each number
and remember n mod 2. Calculate the logical XOR/AND/OR for the single bits. If
the resulting bit is set, add 2^n to the result. Repeat that 8 times.
This is the memory layout I used:
```
0 1 2 3 4 5 6 7
n1 | n2 | marker | n/2 | 0 | counter | bit1 | bit2 |
8 9 10
temp | temp | result
```
Here's the source for XOR (numbers indicate where the pointer is at that time):
```
>>>>>
++++ ++++ counter
[
-
<<<<<
divide n1 by two
[ 0
-
>>+ set marker 2
<< 0
[->>->+<] dec marker inc n/2
>> 2 or 4
[->>>>+<<]
<<<<
]
>>>
[-<<<+>>>]
<<
divide n2 by two
[ 1
-
>+ set marker 2
< 1
[->->+>>>>>] dec marker inc n/2
> 2 or 9
[->>>>>+>>]
<<<< <<<<
]
>>[-<<+>>] 3
>>> 6
[->>+<<]>[>[-<->]<[->+<]]> one bit xor 8
[
[-]<<< 5
[->+>-<<] copy counter negative
> 6
[-<+>]
+> 7
++++ +++ cell 6 contains a one and cell 7 how many bits to shift
[-<[->>++<<]>>[-<<+>>]<] 2^n
< 6
[->>>>+<<<<]
>> 8
]
<<<
]
```
For left rotate, once again there is a marker in cell 2 to determine if 2n
is zero, since you can only determine if a cell is non-zero directly. If
so, a carry bit is written to cell 4 and later added to 2n. This is the memory
layout:
```
0 1 2 3 4
n | 2n | marker | 0 | carry
```
[Answer]
## Score (current): 12038 837/-
The programs assume numbers are loaded in whatever cell is specified, by `,` or similar. It also assumes that all cells are 8-bit unsigned with wrapping as needed. At the start of each snippet, numbers are loaded at cell 0 (and 1 if needed).
### Bit operations - 799
The bit operations follow the same general structure.
```
Firstly, we define a divmod 2 (DM2) function.
CELLS: A B C D
INPUT: *A 0 0 0
OUTPUT: *0 A/2 A%2 0
dp@A; while{
dec A,2; inc B,1; dp@A; inc A,1
while{ #Check if A was 1 at the start
dec D,1; pour A,C; dp@A;
}
dec C,1; pour C,A; inc D,1; dp@D
#If A was 1 at the start, D will be 1 here
while{
dec D,1; inc C,1; dec B,1; dp@D
}
dp@A
}
Translated into BF, we have
[->+<[>>>-<<<[->>+<<]]>>-[<<+>>-]>+[-<+<->>]<<<]
I'm not that good at BF, so my algorithm may not be the smallest.
Next, we define the program.
In this, we assume that the numbers are loaded in $2 (cell 2) and $3.
inc $1,8; dp@1 {
dec $1
pour $3,$6
DM2 $2 # result in $3,$4
DM2 $6 # result in $7,$8
pour $7, $2
pour $8,$5
bop $4,$5 # result in $6
pour $1,$5
pour $5,$4,$1
down $4,$5 # decrease $4 till 0, decrease $5 by same amount
inc $5,#7
shl $6,$5
pour $6,$0 # $0 is result
dp@ 1
}
#Now, the result is in $0
Translated to BF (with linebreaks for readability):
>++++++++[
->>[->>>+<<<]<
[->+<[>>>-<<<[->>+<<]]>>-[<<+>>-]>+[-<+<->>]<<<]>>>> #DM2 $2
[->+<[>>>-<<<[->>+<<]]>>-[<<+>>-]>+[-<+<->>]<<<]> #DM2 $6
[-<<<<<+>>>>>]>
[-<<<+>>>]<<<<
(bop)<<<
[->>>>+<<<<]>>>>
[<+<<<+>>>>-]<
[->-<]>
+++++++
[->[-<<++>>]<<[->>+<<]>]
[-<<<<<<+>>>>>>]
<<<<<
]
Replace (bop) by the appropriate expression.
XOR works like this: (252-5+15=262)
[->-<]>[[-]>+<]
AND works like this: (252-5+11=258)
[>[>+<-]<-]
OR works like this: (252-5+32=279)
[->>>+<<<]>[->>+<<]>>[[-]<+>]<<<
So, combining these, we have a total of 262+258+279=799 D:
```
### Rotate Left A, 1 - 31/-
The number `A` is loaded in cell 0.
```
Pseudocode
$0 := A
$1 := $0 << 1 # this has the effect of discarding the top bit of A
$2 := $0
$3 := $0 << 1
$2 -= $1 >> 1 # $2 now contains the top bit of A
if $2 then $3++ # $3 now contains A rotated left 1
res:= $3 # the result is in cell 3 now
Real code
[->++>+>++<<<]>[-->-<]>[>+<[-]]
If you don't always need the pointer in the same position,
substitute [>+>] for the last loop (3 less chars).
However, the pointer will then sometimes end up in position 2, sometimes in position 4.
```
### NOT A - 7
The number `A` is loaded in cell 0.
```
Pseudocode
$0 := A
$0 += 1
$1 := 256-$0 #since ~A=255-A
res := $1
+[->-<]
```
] |
[Question]
[
An interesting puzzle came to me looking at the elevator buttons this morning.
You are required to generate a list of all [Braille](http://en.wikipedia.org/wiki/Braille) patterns that fit in a 2x3 grid. Use a hash `#` to denote a bump and a hyphen `-` to denote a flat area.
Expected output sample:
```
#-
--
--
##
--
--
#-
#-
--
(and so on...)
```
Rules:
* Your program must separate each pattern by at least one character or line.
* The patterns may be generated in any order.
* All patterns, regardless of what the Braille alphabet actually uses, should be produced. The completely blank pattern is optional.
* Only unique bump patterns should be generated. The following patterns are considered equivilent as the bumps are in an identical arangement. In these cases, use the pattern that is closest to the top-left corner (ie. the first option in this example.)
```
#- -# -- --
#- -# #- -#
-- -- #- -#
```
Bonus points if you can make it work for any *x* by *y* sized grid. (**EDIT:** Within reasonable bounds. Up to 4x4 is enough for proof of concept.)
Reading the wiki article, it appears there are 45 patterns (including the blank) that meet this puzzle's rules.
[Answer]
## GolfScript, ~~34~~ 32 chars
```
44,{84+2base(;{'-#'=}/@\n.}%2/n*
```
Turns out that there *are* shorter solutions than simply generating all 64 patterns and filtering out the bad ones. In fact, by suitably mapping bits to grid positions, it's possible to map all valid (non-empty) patterns to a consecutive range of numbers, as this program does.
Specifically, the mapping I use is:
```
5 4
3 1
2 0
```
where the numbers denote the bit position (starting from the least significant bit `0`) mapped to that position in the grid. With this mapping, the valid grids correspond to the numbers 20 to 63 inclusive.
This is almost the same as the obvious mapping obtained by writing out the 6-bit number in binary and adding line breaks between every second bit, *except* that the bits `1` and `2` are swapped — and indeed, that's exactly how my program computes it. (I also add 64 to the numbers before converting them to binary, and then strip the extra high bit off; that's just to zero-pad the numbers to 6 bits, since GolfScript's `base` would otherwise not return any leading zeros.)
Ps. [Online demo here.](http://golfscript.apphb.com/?c=NDQsezg0KzJiYXNlKDt7Jy0jJz19L0Bcbi59JTIvbio%3D) (Server seems overloaded lately; if you get a timeout, try again or [download the interpreter](http://www.golfscript.com/golfscript/) and test it locally.)
**Edit:** Managed to save two chars by avoiding unnecessary array building and dumping. [Phew!](https://codegolf.stackexchange.com/a/8489)
[Answer]
# Mathematica 97
```
Grid /@ Cases[(#~Partition~2 & /@ Tuples[{"#", "-"}, 6]), x_ /;
x[[All, 1]] != {"-", "-", "-"} && x[[1]] != {"-", "-"}]
```

---
Blank is not included:
```
Length[%]
```
>
> 44
>
>
>
N.B. != is a single character in Mathematica.
[Answer]
## C# – 205
```
class C{static void Main(){var s="---##-##";Action<int,int>W=(i,m)=>{Console.WriteLine(s.Substring((i>>m&3)*2,2));};for(int i=0;i<64;++i){if((i&3)>0&&(i&42)>0){W(i,0);W(i,2);W(i,4);Console.WriteLine();}}}}
```
Readable version:
```
class C
{
static void Main()
{
var s = "---##-##"; // all two-bit combinations
// a function to write one two-bit pattern (one line of a Braille character)
Action<int,int> W = (i,m) => { Console.WriteLine(s.Substring(((i >> m) & 3) * 2, 2)); };
// for all possible 6-bit combinations (all possible Braille characters)
for(int i = 0; i < 64; ++i)
{
// filter out forbidden (non-unique) characters
if ((i & 3) > 0 && (i & 42) > 0)
{
// write three rows of the Braille character and an empty line
W(i,0);
W(i,2);
W(i,4);
Console.WriteLine();
}
}
}
}
```
[Answer]
## Perl, 71 67 65 char
```
y/10/#-/,s/../$&
/g,/^#/m&&print
for map{sprintf"%06b
",$_}18..63
```
Convert int to binary, perform transliteration, and add a newline after every two chars.
The `/^#/m` test eliminates two patterns (20 and 21) that don't have a raised bump in the leftmost column.
## General solution, 150 106 103 100 char
Read `x` and `y` from command line args. Newlines are significant
```
y/01/-#/,s/.{$x}/$&
/g,/^#/m*/^.*#/&&print
for map{sprintf"%0*b
",$x*$y,$_-1}1..1<<($y=pop)*($x=pop)
```
Iterate over 0..2xy like before, converting each int to binary,
substituting `-` and `#` for `0` and `1`, and inserting a newline after
every `$x` characters.
`/^#/m` tests that there is a raised bump in the leftmost column, and
`/^.*#/` tests that there is a raised bump in the top row. Only the
patterns that pass both tests are printed.
[Answer]
# Python, ~~120~~ ~~118~~ ~~113~~ ~~95~~ 118
```
for j in range(256):
if j/4&48and j/4&42:print''.join('_#'[int(c)]for c in bin(j/4)[2:].rjust(6,'0'))[j%4*2:j%4*2+2]
```
Edit: used Winston Ewert suggestion and added x by y grid solution
Edit: I somehow missed the last constraint about uniqueness. This script generates all the possible sequences, not just the 45.
Edit: Back up to 118 but now correct
[Answer]
## J, ~~35~~ 33 chars
```
3 2$"1'-#'{~(2 A.i.6){"1#:20+i.44
```
Uses the approach Ilmari Karonen came up with in their Golfscript solution. However, since the J verb [`#:`](http://www.jsoftware.com/help/dictionary/d402.htm) (antibase) stores the bits (or, well, digits in the generic case) in a list, we need to index it from the left instead of right (i.e. index 0 is the leftmost, highest bit).
The solution is rather straightforward: `20+i.44` gives a list of the numbers `20..63`, inclusive. `#:` takes the antibase-2 of each element in this list, and thus produces a list of bitpatterns for each number in that range. [`{`](http://www.jsoftware.com/help/dictionary/d520.htm) selects (basically reorders) the bits into the right pattern, and then `{` is used again in order to use the digits as indices in the string '-#' in order to prepare the output. Finally, we arrange each entry into a 2-by-3 rectangle with [`$`](http://www.jsoftware.com/help/dictionary/d210.htm) (shape).
---
```
3 2$"1'-#'{~(2 A.i.6){"1#:20+i.44 N.B. use A. (anagram) to generate the right permutation
```
```
3 2$"1'-#'{~0 1 2 4 3 5{"1#:20+i.44
```
[Answer]
## Python - 121 112
blank is not included
```
from itertools import*
print'\n'.join('%s%s\n'*3%b for(b,n)in zip(product(*['_#']*6),range(64))if n&48and n&42)
```
] |
[Question]
[
## Challenge
>
> Write a function which takes an argument which is a verb, and returns the past tense of the verb. (Assume that the verb is regular)
>
>
>
## Past tense
Note: consider y as neither consonant nor vowel.
Normally, just adding `ed` after the end of verb makes the past tense of the verb.
Ex: `jump` → `jumped`, `ask` → `asked`
However, there are other rules.
* If the last character of the given verb is `e`, just add `d`.
Ex: `love` → `loved`, `move` → `moved`
* If the verb is ended with a consonant + `y`, then change `y` to `i`, and add `ed`.
Ex: `study` → `studied`, `cry` → `cried`
* However, if the verb is ended with a vowel + `y`, then just add `ed`.
Ex: `play` → `played`, `stay` → `stayed`
* If a verb is ended with a vowel and a consonant, then write the consonant one more time, and add `ed`.
Ex: `stop` → `stopped`, `plan` → `planned`
* However, if a verb is ended with multiple vowels + a consonant or single vowel + multiple consonants, then just add `ed`.
Ex: `look` → `looked`, `jump` → `jumped`
There are more rules but let's care above rules only. For example, according to above rule, `visit` → `visitted`.
## Winner
Since this is code golf, the shortest code that correctly returns past tenses wins.
## Example (JS, 127)
`function f(x){return x.replace(/([^aeiouy])y$/,'$1i').replace(/([^aeiouy][aeiou])([^aeiouy])$/,'$1$2$2').replace(/e$/,'')+'ed'}`
[Answer]
**sed, 76 characters**
Does a sed script count as a function for this problem?
```
s/\([^aeiou]\)y$/\1i/
s/\([^aeiou][aeiou]\)\([^aeiouy]\)$/\1\2\2/
s/e\?$/ed/
```
[Answer]
## Mathematica 43 chars
```
f=WordData[#,"InflectedForms","List"][[1]]&
```
Usage:
```
f /@ {"call", "try", "use", "wash", "play", "stop", "look"}
{"called", "tried", "used", "washed", "played", "stopped", "looked"}
```
Also:
```
f /@ {"buy", "run", "swim"}
{"bought", "ran", "swam"}
```
[Answer]
## Groovy - 111 characters
```
v={it==~'[aeiou]'};p={s->r=s[0..-2];a=s[-1];b=v s[-2];(a=='e'?r:a=='y'?!b?r+'i':s:v(s[-3])|!b|v(a)?s:s+a)+'ed'}
assert ['jump', 'ask', 'love', 'move', 'study', 'cry', 'play', 'stay', 'stop', 'plan', 'look'].collect { p(it) } == ['jumped', 'asked', 'loved', 'moved', 'studied', 'cried', 'played', 'stayed', 'stopped', 'planned', 'looked']
```
[Answer]
Perl 5 (82 characters):
```
sub f{$_=pop;$C='[^aeiouy]';s/($C)y$/$1i/;s/($C[aeiou])($C)$/$1$2$2/;s/e?$/ed/;$_}
```
I am sure it can be improved.
[Answer]
# C - 120 119 characters
In typical C style, the function f updates a string buffer in place, assuming that the caller has reserved enough space for up to three extra characters. The second argument should be given as 0. The declaration of the global state variable `l` is included in the total character count.
```
#include <stdio.h>
#include <string.h>
l;void f(b,i)char*b;{*b?f(b+1,i/2+4*!strchr("aeiouy",l=*b)):(i-5?*--b=l=='y'&i/2?'i':l:(*b=l),strcpy(b+=l!='e',"ed"));}
int main()
{
char b[10000];
while (gets(b)) {
f(b,0);
puts(b);
}
return 0;
}
```
Explanation: The function iterates over the characters recursively. The second argument `i` encodes which of the previous three characters were consonants in its bottom three bits. At the end of the string, if `i==5` then the last three characters were a consonant, a vowel and a consonant, and thus the last character must be duplicated. Similarly, if bit 1 of `i` indicates that the second-to-last character was a consonant and the last character is 'y', then the 'y' is replaced by 'i'.
[Answer]
### Scala 199 273 chars
```
def v(c:Char)="aeiouy" contains c
def p(o:String)={val s=o.reverse
if(s(0)=='e')o+"d"else
if(!v(s(1))&& s(0)=='y')o.replaceAll("y$","ied")else
if(!v(s(0))&& v(s(1))&& !v(s(2)))o+s(0)+"ed"else
o+"ed"}
```
Invocation:
```
val li = List ("move", "cry", "plan", "play", "look")
li map p
```
My first approach was much longer, by moving the if-else-cascade to a list=> to a function:
```
type S=String
def f(l:List[(Boolean,S)]):S=if(l(0)._1)l(0)._2 else f(l.tail)
def v(c:Char)="aeiouy" contains c
def c(o:S)={val s=o.reverse
f(List((s(0)=='e',o+"d"),(!v(s(1))&& s(0)=='y',o.replaceAll("y$","ied")),(!v(s(0))&& v(s(1))&& !v(s(2)),o+s(0)+"ed"),(true,o+"ed")))}
```
Maybe the approach is interesting. Degolfed and explained:
```
// just for shortening
type S=String
/* take a list of Booleans and Strings, and return early
if a Boolean is true. This approach would work,
if there where much more conditions, I guess.
*/
def doFirst (list: List[(Boolean, S)]): S =
if (list(0)._1) list(0)._2 else doFirst (list.tail)
// vocal - is it a vocal
def v(c:Char)="aeiouy" contains c
// here is the key function
def toPast(o:S)={
// reversing the String allows easy access to the last elements,
// without considering how long the string is.
val s=o.reverse
doFirst (List (
(s(0)=='e', o+"d"),
(!v(s(1)) && s(0)=='y', o.replaceAll("y$","ied")),
(!v(s(0)) && v(s(1)) && !v(s(2)), o+s(0)+"ed"),
(true, o+"ed")
))}
```
[Answer]
# Ruby, 101 characters
Probably can be smaller.
```
def f x;x.sub(/([^aeiouy])y$/,'\1i').sub(/([^aeiouy][aeiou])([^aeiouy])$/,'\1\2\2').sub(/e$/,'')+'ed';end
```
Usage:
```
f("try") #=> "tried"
f"call" #=> "called"
```
[Answer]
## Poop - 72 characters
```
f[s]s^6pow>4<<last&8*(/"ed""id""eid"/|out|flush)+rep'y'1-2-3"aeiou"ord#s
```
[Answer]
## Python - 147
```
def f(v):T,x,m='aeiou',"ed",v[-1];return[[[v+x,v+m+x][v[-2]in T and m and v[-3]not in T],[v+x,v[:-1]+"ied"][v[-2]not in T]][m=='y'],v+"d"][m=='e']
```
] |
[Question]
[
Given the amplitude and period for a wave, print the wave. See sample output for more details. The total number of wave forms equals the period, and the height of each wave equals the amplitude. Amplitude and Period are less than 10. You can ignore the trailing spaces but not the leading spaces.
```
Sample Input
3 2
Sample Output
3 3
232 232
12321 12321 12321 12321
232 232
3 3
```
[Answer]
# Dyalog APL, ~~43~~ 40 bytes
~~[`{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)(n,1-n←2×⍵)↑↑b⍴¨⍕¨b←a,1↓⌽a←⍳⍵}`](http://tryapl.org/?a=2%7B%u2349%u2283%u236A/%u237A%u2374%u2282%28%u233D%u236A%u22A2%29%28n%2C1-n%u21902%D7%u2375%29%u2191%u2191b%u2374%A8%u2355%A8b%u2190a%2C1%u2193%u233Da%u2190%u2373%u2375%7D3&run)~~
[`{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)n(1-n←2×⍵)↑↑⍴∘⍕¨⍨a,1↓⌽a←⍳⍵}`](http://tryapl.org/?a=2%7B%u2349%u2283%u236A/%u237A%u2374%u2282%28%u233D%u236A%u22A2%29n%281-n%u21902%D7%u2375%29%u2191%u2191%u2374%u2218%u2355%A8%u2368a%2C1%u2193%u233Da%u2190%u2373%u2375%7D3&run) ([Thanks, Moris Zucca](https://codegolf.stackexchange.com/questions/951/print-triangle-wave-of-numbers/45159#comment-106530))
This is a dyadic function with the amplitude as the right argument (`⍵`) and the period as the left argument (`⍺`). A program that reads user input would take the same number of characters.
Drawing some inspiration from [Martin Büttner's CJam answer](https://codegolf.stackexchange.com/questions/951/print-triangle-wave-of-numbers/45159#answer-45150):
```
{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)n(1-n←2×⍵)↑↑⍴∘⍕¨⍨a,1↓⌽a←⍳⍵}
a←⍳⍵ ⍝ numbers 1 2 3, call them "a"
⌽ ⍝ reverse them: 3 2 1
1↓ ⍝ drop one: 2 1
a, ⍝ prepend "a": 1 2 3 2 1
⍴∘⍕¨⍨ ⍝ format a[i] and repeat it a[i] times:
⍝ (,'1') '22' '333' '22' (,'1')
↑ ⍝ mix, i.e. obtain a character matrix:
⍝ ┌───┐
⍝ │1 │
⍝ │22 │
⍝ │333│
⍝ │22 │
⍝ │1 │
⍝ └───┘
n(1-n←2×⍵)↑ ⍝ take a 2×⍵ by 1-2×⍵ matrix
⍝ (negative length extends backwards):
⍝ ┌─────┐
⍝ │ 1 │
⍝ │ 22 │
⍝ │ 333│
⍝ │ 22 │
⍝ │ 1 │
⍝ │ │
⍝ └─────┘
(⌽⍪⊢) ⍝ the reverse of it, vertically joined with it
⍝ ┌─────┐
⍝ │ 1 │
⍝ │ 22 │
⍝ │333 │
⍝ │ 22 │
⍝ │ 1 │
⍝ │ │
⍝ │ 1 │
⍝ │ 22 │
⍝ │ 333│
⍝ │ 22 │
⍝ │ 1 │
⍝ │ │
⍝ └─────┘
⍺⍴⊂ ⍝ take ⍺ copies
⊃⍪/ ⍝ join them vertically
⍉ ⍝ transpose
```
[Answer]
## Python - 135 chars
```
A,F=map(int,raw_input().split());R=range
for y in R(-A+1,A):print"".join((" %s"%x)[-x<s*y<1]for s in(1,-1)for x in R(1,A)+R(A,-1,-1))*F
```
This version with a leading space is 132 chars
```
A,F=map(int,raw_input().split());R=range
for y in R(-A+1,A):print"".join((" %s"%x)[-x<s*y<1]for s in(1,-1)for x in R(A)+R(A,0,-1))*F
```
It also can be considerably shorter if not required to read from stdin or even if the input is comma separated
For comma separated input, the first line becomes
```
A,F=input();R=range
```
[Answer]
## APL (77)
```
,/{×⍎⍵:⍵⋄' '}¨¨⊃∘↑∘⍕¨¨K⍴⊂(⊖M),⍨M←(2⍴N+N-1)↑(0 1↓M),⍨⌽M←(⌽⊖/¨M)×≥/¨M←⍳2⍴⊃N K←⎕
```
[Answer]
## J, 87 characters
As a program:
```
b=:]\@(]#~' '~:])(":@:>:@i.@-)
,.~^:(<:Y)(,.|.)@(' ',.~((<:({."1|."1)b),.b),' '$~2<:])X
Y X
```
---
runs like this:
```
,.~^:(<:2)(,.|.)@(' ',.~((<:({."1|."1)b),.b),' '$~2#<:) 3
3 3
232 232
12321 12321 12321 12321
232 232
3 3
,.~^:(<:4)(,.|.)@(' ',.~((<:({."1|."1)b),.b),' '$~2#<:) 2
2 2 2 2 2 2 2 2
121 121 121 121 121 121 121 121 121 121 121 121 121 121 121 121
2 2 2 2 2 2 2 2
```
It's 5 more characters if we need it as a function F:
```
3 F 2
3 3
232 232
12321 12321 12321 12321
232 232
3 3
```
[Answer]
## Haskell (~~226~~ ~~225~~ ~~222~~ ~~220~~ 214)
My try in Haskell:
```
import List
n!k|n>k=p:n!(k+1)++[p]|0<1=[p]where p=(n-1)?" "++k?show k++(n-k)?" ">>=id
f[n,k]=k?(n!1++(2*n-1)?' ':map reverse(n!1)++[(2*n-1)?' '])>>=id
main=interact$unlines.transpose.f.map read.words
(?)=replicate
```
Sorry guys, `(€)` is optimized away, it takes three bytes for one € as opposed to ! which only takes one byte each.
Here is a "beta Version", that doesn't satisfies the spec:
```
import List
-- Creates a single wave of numbers. k should be equal to 1
-- and is used for internal stuff,
wave n k|n==k=[peek]
|otherwise = peek:wave n(k+1)++[peek] where
peek=replicate(n-1)" "++replicate k(show k)++replicate(n-k)" ">>=id
-- Creates a full wave
-- k: number of waves, n: size of waves
fullWave[n,k]=unlines.transpose.concat.replicate k$wave n 1++map reverse(wave n 1)
main=interact$fullWave.map read.words
```
[Answer]
# CJam, 45 bytes
CJam is a lot younger than this challenge, so this answer is not eligible for the green checkmark (which should btw be updated to marinus's APL answer). This was still a fun little exercise though.
```
r~:I2*,{)IS*I@I\-z-_a*+I~)>I(S*+}%_Wf%+r~*zN*
```
[Test it here.](http://cjam.aditsu.net/)
The idea is to generate half a period *vertically*, like so:
```
1
22
333
22
1
```
(Plus the next empty row which SE swallows). This then duplicated, each row is reversed, and the second half of the period is appended. Then the entire thing is repeated by the number of periods, and ultimately the grid is transposed to orientate the wave along the horizontal.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 24 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
H(¹)*!∔}─L╷ ×;+ ∔:↔∔⤢╶×↔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjI4JXVGRjA4JUI5JXVGRjA5JXVGRjBBJXVGRjAxJXUyMjE0JXVGRjVEJXUyNTAwJXVGRjJDJXUyNTc3JTIwJUQ3JXVGRjFCJXVGRjBCJTIwJXUyMjE0JXVGRjFBJXUyMTk0JXUyMjE0JXUyOTIyJXUyNTc2JUQ3JXUyMTk0,i=MyUwQTI_,v=8)
] |
[Question]
[
Part of [**Code Golf Advent Calendar 2022**](https://codegolf.meta.stackexchange.com/questions/25251/announcing-code-golf-advent-calendar-2022-event-challenge-sandbox) event. See the linked meta post for details.
---
There's a good news and a bad news.
Good news: you got a Christmas present from Santa. (Already?! Christmas is two weeks away!)
Bad news: the present is locked with a laser lock. And a note next to it says:
>
> Only the ones who can properly open the lock deserve the present inside. If you force it or fail to open in 24 hours, the present will turn into a piece of coal.
>
>
>
You carefully examine the laser lock. It has a laser, a sensor, and a grid of square cells. Some cells already have a piece of mirror, and some of the empty ones are colored red; the others are green.
```
+-+-+-+-+-+-+-+
laser --> |G|G|R|\|G|G|G|
+-+-+-+-+-+-+-+
|\|R|/|G|R|G|\| --> sensor
+-+-+-+-+-+-+-+
```
You immediately think, "Aha, so I'm supposed to place some mirrors on some of the green cells so the laser goes to the sensor."
So one possible solution to the above would be:
```
+-+-+-+-+-+-+-+
laser --> |.|.|R|\|.|/|\|
+-+-+-+-+-+-+-+
|\|R|/|\|R|/|\| --> sensor
+-+-+-+-+-+-+-+
```
## Task
In this task, the positions of the laser and the sensor are fixed, and the height of the grid is always 2. Given the state of the lock as a 2-by-N grid, output a possible solution.
The input grid is given as a 2D string like
```
GGR\GGG
\R/GRG\
```
but the following variations (and combinations thereof) are allowed:
* an array of rows / a matrix / a flattened string or array
* charcodes instead of characters
* transposed grid (in other words, columns instead of rows)
* lowercase instead of uppercase
The output must be in the same format as the input, with each `G` replaced with `.` (nothing) or one of `\/` (a mirror). Replacing all `R`s with `.` in addition to the above is allowed.
```
..R\./\ or ...\./\
\R/\R/\ \./\./\
```
You may assume that the solution always exists. If there are multiple solutions, you may output any one of them.
No other alternative I/O formats are allowed.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
G
G
->
\
\
GG
RG
->
.\
R\
G\/R/\/GG
GRGGGRGR\
->
\\/R/\/.\
\R...R/R\
G\
G\
->
.\ or .\ or .\
.\ /\ \\
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 128 bytes
```
f=a=>[...'./\\'].some(c=>(b=a.replace(/g/,c))<a?f(b):b.split`
`.map(v=>p=v==['\\\\','//'][p]?1-p:p/ /r|\./.test(v[p]),p=0)|p)&&b
```
[Try it online!](https://tio.run/##VZFNc4MgEIbv/IpcGtiJLkmPmaKHHrz0ZI/ijGgxQ8YIUcfkkP@eorZJy8Jhn33ZDziqUfVVZ9wQtvZL32vhtxJRhogUuZQ0x96eNKtExEqhsNOuUZVm/MCDCuBNxTUrYV9i7xozFKTAk3JsFJEToxAZlX7RgHJO88zl8S50e8dXvLtJ5DjofmCj5xA4sYWbg/W6vE@0Ur3uV2L1OXSmPWCnLgVJvIURkd5IkpB09lCSdPIlT7nkHidpkvjj4aRdsBfJ1E@Uco8LQirb9rbR2NgDe1RbJmBctizehxHEsuUwT3MV0RV9IycGPyIqWwqAtWkG3THWBgZEZF5ehZ9ivsIyF5xzWB7S5QsbZ9m4OWcmBzxa0y6JcLAf9qK7d98GA/h9wZqNT2f8X3mi/pvUI5xtHykpbCbV5k9w9yf4rDynun8D "JavaScript (Node.js) – Try It Online")
\$O\left(3^n\right)\$ solution. Input a multiple line string as transposed matrix with lowercase letters.
>
> Is this somehow *"if you force it"*?
>
>
>
```
f=(
a // the input grid
)=>
[...'./\\'].some(c=> // for each possible replacement of letter "g"
(b=a.replace(/g/,c)) // replace the first occurrence of "g"
<a? // if any "g" exists (replaced successfully)
// or the string is out of "g" otherwise
f(b): // recursively try next "g"s
b.split`\n`.map(v=> // for each column of a possible replacement
p=v==['\\\\','//'][p]?1-p: // If the pattern is '//' or '\\' it reflect laser to another row
p/ /r|\./.test(v[p]) // if the cell is 'r' or '.', it keeps laser on the same row (p/1==p); otherwise, set to invalid values (NaN or Infity)
,p=0) // the laser starts from first row
|p)&&b // if the laser finally output from second row, "b" is a solution we found
```
---
# [JavaScript (Node.js)](https://nodejs.org), 142 bytes
```
f=([x,y,...a],p=[],q,h=s=>q&&!/(.).(?!\1)[^RG]|[^.].R/.test(s+x+y)&&q+s,o=h(x+'.')||h`..`,O=h`//`)=>x?f(a,h('.'+y,q=p)||h`..`||O,o||h`\\\\`):q
```
[Try it online!](https://tio.run/##VVDBjoIwEL3zFXpYmYY61T2aFI8cTdgjxdCwKBgtxRIWE/7dHcTdaKdNZt57fTPtSXfa5dfKtktTfxf3g6QNSc9vHBF1yq1MUt7wUjoZNovFXAAyhO1crVmyj6N0SPaYYiywLVwLLuiDG1ssmsDxWpbQBz76bBjKDDHjO1lmQmRMhv32AJqXQGxw4420f5ph2PF6zBWtjG2a@@iba1e4mZx9tdfKHPGqfzIvoliGnqLwosiLHxUqLx5rJWKhBMFRHEV0CBy1E0wiFdPrYkFw5nl5bVx9LvBcH@G/Gzp7rloQysB2swzZVhnB8KIt9DQ@0iAXYE@Rr4zPJhISy5uUXphQA5tOWMcrQrqgSaqU4amuDPjjhUN1bosrgHnw1cenlKvJRsuQPujpaWVoKWnzEgSiOL7DFjryTlYvzsE4UPBCrt/aTpkyj6nvvw "JavaScript (Node.js) – Try It Online")
\$O(n)\$ solution. Input transposed flatten string with uppercase letters.
```
f=(
[x,y, // for each column of the grid, "x" and "y" are two cells on this column
...a], // the remaining grid
p=[], // A solution where laser on the first row, or falsy if impossible
q, // A solution where laser on the second row, or falsy if impossible
h=s=> // "s" is a possible replacement of current column
// if the laser can running on row "p" ("p" is reassigned later)
// and the replacement of current column is valid
// then we got a solution
p&&!/(.).(?!\1)[^RG]|[^.].R/.test(s+x+y)&&p+s,
o=h('\\\\')
)=>x? // if any more columns here
f(a,
h(D='..')||h('.'+y)||h('//',p=q), // all possible patterns where laser on first row
o||h(D,p=q)||h(x+'.') // all possible patterns where laser on second row
):q
```
---
Only valid patterns are:
```
Laser -> \
\ -> Laser
Laser -> . -> Laser
?
/ -> Laser
Laser -> /
?
Laser -> . -> Laser
```
So we only need to verify all these patterns and treat all other patterns as invalid.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~93~~ 74 bytes
```
⊞υ\FEθ⁺ι§ηκ≔ΣEυΦ⟦⁺⭆κ⎇νμ⁻\/μײ§κ⁰⁺κ⪫⪪ιG¦.⟧⎇ν№α§ι⁼§κ⁰/⬤ι№⁺G§κ⁰ξυ⪪Φ⊟Φυ⌕\ικ²‖↙
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVG9TsMwEBZrn8LyZEsuQZ0QnSJ-LBCVopSt6WBSp7HiOGlsQ1l4EZYOINh5G56GixtUlZNO8um-n7vz21deii5vhN7tPrwrxuc_J6-JtyXxDOEsw3Q6KpoOkZloyYahRHtLFEOxuzUruSUlQxWFQLG1am3I3NcBCuwbpZ3syCJQ5q5TZt13KoYeZGdE90IMQzVDM2UAAF4Rhhq0AKBqacnkYAOks9AJYlDdNQrMWq1cPw3mGHr4FFO6PJK_bLxxRByEAHy98UJbciQN5AgHg1jrHrQnBjcQ_z8IQ1sagiEPB0pgNzdMM2ydNO3fM5zCrPoNQUgFVgU5oUBNZaFl7sjFVfNs7mXh6PTdPuZ2-IzPBR4_abz85lmURlnE-YinnEOm2R7xCw "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation: Inspired by the alternate input format, this sticks to the original input format and pays the 8 byte penalty for transposing the input and output.
```
⊞υ\
```
Start with a single state of the beam in the top row. The first character of the state is `\` if the beam is in the top and `/` if the beam is in the bottom row, while the remaining characters are the columns processed so far in a flattened representation.
```
FEθ⁺ι§ηκ
```
Transpose the input and loop over each column. (Note: row/column here refer to the original input, not the transposed version.)
```
≔ΣEυΦ⟦⁺⭆κ⎇νμ⁻\/μײ§κ⁰⁺κ⪫⪪ιG¦.⟧⎇ν№α§ι⁼§κ⁰/⬤ι№⁺G§κ⁰ξυ
```
* `⭆κ⎇νμ⁻\/μ` - Flips the row of the state.
* `⪫⪪ιG¦.` - Replaces `G`s in the current column with `.`s
* `№α§ι⁼§κ⁰/` - Checks whether the current cell is empty.
* `⬤ι№⁺G§κ⁰ξ` - Checks whether both the rows can contain the correct mirror.
Loop over the current states, collecting states where the beam switches or doesn't switch appropriately depending on whether the column can have the correct mirrors or there is an empty space in the current cell.
```
⪪Φ⊟Φυ⌕\ικ²
```
Output any state which has the beam in the bottom row.
```
‖↙
```
Transpose the output.
66 bytes using the new transposed input format:
```
⊞υ\WS≔ΣEυΦ⟦⁺⭆κ⎇νμ⁻\/μײ§κ⁰⁺κ⪫⪪ιG¦.⟧⎇ν№α§ι⁼§κ⁰/⬤ι№⁺G§κ⁰ξυ⪪Φ⊟Φυ⌕\ικ²
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XZBPSsQwFMZxm1OErBLIWJmVMKsiGkYYKB137Sxip07DpGltEh3P4mYWit7Bm3gaX9KKjIGEF973_d6f18-qkUPVSX08vnv3MLv8PisybxvqOSZlSdgCPTdK15guTe_d2g3K7ChjOLVW7Qxd-5auZB_kN0q7eqBFpr2lozBk9hzf1YORwws1HLccr5QBAcATAn_GGAhUW1s65zh1S7OtD8F0ETMRBr_bTkGxXitHFXQmCOTIOWFsc4K_6rxxVP6BQHz96KW29AQN5oTEAqnWQTQaYzWA_2-E4wOLh2MPG8lgNjd1M02ddf1vGFdhtmFCAKno2sOdM7Z4s_eVnTb9UZDZkyabLyFQmaNEoFyEd4xFjkSJRuUP "Charcoal – Attempt This Online") Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation: As above but simply uses `WS` to iterate over the input and doesn't need to transpose at the end either of course.
[Answer]
# JavaScript (ES6), 147 bytes
I/O format: matrix of ASCII codes.
I would probably have golfed this differently if I had noticed the rule about removing all G's earlier.
```
m=>(g=(x,y=0,d=1,_,r=m[y],c=r[x])=>c?c%9&2?c%2^y^d&&g(x+!d,y^d,!d):d&&g(x+1,y)||c==71&&g(x,y,d,r[x]=y^d?92:47):y&&m.map(r=>r.map(c=>c-71?c:46)))(0)
```
[Try it online!](https://tio.run/##RZBda8IwFIbv@yuisDbBmK4iEyupDNlyXy@NjpJ@WGkTl3bDMvfb3WkVRuB8Puc9h5yS76RRtjy3U23S7JbzW80jXHB8oR1/pikP6Ae1vN51e6q43V32hEdqrZ6W7gzs7NAdUtct8GUySinEdJSS8FEJaEeuV8X5IhgKtKMp7SU4gOvlLJwvSNi5bs3q5Iwtj@wQKFgwXQRrFc5fCCH4mdxs9vlV2gx7eeMRZrMkfS@rbNtpBV3Wmm1rS11gwppzVbZ4LLXUY8JyY98SdcQN4hH6cRCqshbViKPmHwSsXzogO8ZYs78f0eeKqWNiN/Axry2GU1YgoYxuTJWxyhQ4x/V92vb0/QiWW1NvHmMYBC0h7GRKjT2pPYImaPAr55fchIilEMKRsS9iIR1HwHOgEPdO@rEvfcigBySwfw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python](https://www.python.org), ~~309~~ ~~281~~ 243 bytes
```
lambda a:max(map(lambda t,b=0:all(i%2^1and(s:=j)or s==j=="\\/"[b]and~(b:=b^1)or(s,j)[b]in".R"for i,j in E(t))and t*b or"",["".join(sum(zip(a.split("G"),[*g,""]),()))for g in product(*["\\/."]*a.count("G"))]))
from itertools import*
E=enumerate
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XVLBbtQwEBXH9VdYI6G1sybt9oQi-VjlxCXXJEVO4ywOiR3ZTgtU5Ue4rITg3s-B3-AHsJNtKT1kxjPz5s0bx99-Tp_9B6OP3zte_Zh99-btrz-DGJtWYJGN4hMZxUROCc8afp6JYSDq9cXVXuiWuIz31FjsOO85h6o6g7KpQ-UraTLeXO1DkTjW05BVGtICuoBWrMdK40viKQ1Y7JMGGwvASoC0N0oTN4_ki5qISN00KE8gB8rK5MAAasoIpTTyHCLLZE07X3uSlHF8CnUi0msz67WJ1pSizpoRKy-tN2ZwWI2TsT5Bl1zqeZRWeLmu_vvVg5fOO14iAMhRHixbjjkq_gVhTHEWTMjmRZ6Hr6iqZ1WUn8IaIW-FdpNxsn1_oq5RlB6DqH5JZmgTPY_mceFKA43pceIAaLP0mIk1xvu4jMbxemJDeV6zxe9rGoiWlh0P2N2KDSQvNOx4GUE1amWHZ30rxY0kzlulD5Fhu92-Ex-lw3GmFE7JOBrfKDeLQTmJA9uttC7gAveTJr4ylFl2UbPTeR8DtLHSz1bjDu4C_L7Sd2vHPaD_7-KFzqBlCjSePGrsloUpZVK34bHpeEfrnzseV_8X)
-a massive 38 bytes thanks to @tsh.
Saved 20 bytes by switching to a flattened transposed string for input and output. Brute force solution. Explanation:
```
["".join(sum(zip(a.split("G"),[*g,""]),()))for g in product(*["\\/."]*a.count("G"))]
```
Generates all possible substitutions for `"G"` using
```
product(*["\\/."]*a.count("G"))
```
The cartesian product of `\/.` repeated for every occurence of `"G"`, where each combination is
```
"".join(sum(zip(a.split("G"),[*g,""]),()))
```
Manually mapped to the input string to replace the respective `"G"`'s.
```
lambda t,b=0:all([i%2^1and(s:=j)or s==j=="\\/"[b]and~(b:=b^1)or(s,j)[b]in".R"for i,j in E(t)])and t*b or""
```
The testing function is then mapped over the generated combinations, which checks for every column that either:
* `s==j=="\\/"[b]` the correct mirror for the given laser row `b` is in that column. `~(b:=b^1)` is used to switch the laser row
* `(s,j)[b]in".R"` the laser row in the column is `R` or `.`
* `or ""` outputs an empty list if above two tests fail
* `t*b` outputs the combination tested if the laser is on the bottom row for the last column, otherwise an empty list
`i%2^1and(s:=j)or` is used to generate the column pairs from the transposed flattened list by storing a value on every even iteration and testing on every odd iteration
Then `max()` is used to return a correct solution from the test results of all combinations
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~92~~ ~~75~~ 71 bytes
```
@FI{WG N({UQaQ"\/"@i&Ui|a@iN".R"}M<>a)&aX%i}M J(a^'GWV_)MCP:"\/."Ma@*'G
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJARkl7V0cgTih7VVFhUVwiXFwvXCJAaSZVaXxhQGlOXCIuUlwifU08PmEpJmFYJWl9TSBKKGFeJ0dXVl8pTUNQOlwiXFwvLlwiTWFAKidHIiwiIiwiXCJHXFwvL1xcR1wiIFwiR0dcIiBcIkdSR0dcIiBcIkdHXFxSL0dSRy9HXFxSL0dHUkdcXFwiIFwiR0dcXFxcXCIiLCIiXQ==)
-~~17~~ 21 bytes thanks to @DLosc
Port of [my Python answer](https://codegolf.stackexchange.com/a/255436/110555). I'm sure there are some further golfs that can be done. I could save a byte by outputting the list of all possible solutions as in [@KevinCruijssen's answer](https://codegolf.stackexchange.com/a/255422/110555). Explanation:
```
J(a^'GWV_)MCP:"\/."Ma@*'G
```
Generates all possible combinations using the cartesian product of `"\/."` by the number of `"G"` in the input
```
WG N({UQaQ"\/"@i&Ui|a@iN".R"}M<>a)&aX%i
```
Is the testing function that is mapped over all combinations. `WG` is required to reset the global variable `i`, which is used to store the laser row.
```
@FI
```
Finally filters out all falsy values from the output list, giving only the list of solutions. `@` outputs the first in the list.
[Answer]
# Python3, 350 bytes:
```
def f(b):
q=[(0,0,[*map(list,b.replace('R','.').replace('G','.').split('\n'))])]
while q:
x,y,B=q.pop(0)
if(x,y)==(1,len(B[0])):return B
try:
B=eval(str(B))
if(V:=B[x][y])in'\\/':B[(X:=x+[-1,1][V=='\\'])][y]=V;q+=[(X,y+1,B)]
else:j=eval(str(B));j[x][y]=(K:='\\/'[x]);j[(X:=x+[-1,1][K=='\\'])][y]=K;q+=[(x,y+1,B),(X,y+1,j)]
except:1
```
[Try it online!](https://tio.run/##bY89b4MwEEB3foWVxefiJqAulSMvXjxkY4giGYZ8GIXIJca4Lfx6eiSR2kgdfJLf3b2782M8X9u3dx@m6WRrUsOBiYR00kDGM25ePvYeXNNHflgG693@aIEWlNMlZb9AP0DvXROBli1lrGJVQr7PjbOkQyMZ@MiV7Jb@6iFjCJoakDEpIefOtqBMVjEmgo2foSUKK2IY506ipP3aO@hjAMXm1rl3K6QyQ2XGijUtLcsVFcrATsghNa85zyuzlRI5xUWwSG7XXYpX7fiY5lzNyxFiXW/F5cm@vtylEjZC3rT4n@mTevOk3tzVw0PNH0MutyF2OFofRT750LQRalgsFjrRGPGUv0wnxT8UNyhWGDCtC63xFWV5K5t@AA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~61~~ 50 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
…\/.I'G¢ãε'GsS.;}ʒ0U¶¡ε„\\º2äXèQiX_Uë„R.yXèå}Ā}PX*
```
Takes the input as a transposed multiline string. Outputs a list of all possible results (`R` remains `R`).
[Try it online](https://tio.run/##yy9OTMpM/f//UcOyGH09T3X3Q4sOLz63Vd29OFjPuvbUJIPQQ9sOLTy39VHDvJiYQ7uMDi@JOLwiMDMiPvTwaqBYkF4lkH94ae2RhtqACK3//5WUlNxjuNyDuIL0uWLcQQx3IBkDFAYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@mFFCUWlJSqVtQlJlXkpqikJlXUFpipaCkU6nDpeSYXFKamKOgUVKUmFdckF@cmqKJpCD40LZDCw/v8Dq02yVM5/@jhmUx@nqR6u6HFh1efG5rZLG6e3GwnnXtqUkGoSCF57a6PGqYFxNzaJfR4SURh1cEZkbEhx5eDRQL0qsE8g8vrT3SUBsQofW/Fqu9@aUlQIt1czKLwbbbcqG7HKKgGCRZhuQ2nUPb7GvVdUMOTwex/kcrubsHxcS4u7vH5MXEBOm7B7nHxCjpKCgB@e5gGsgIgrBiYvSD9IEESAioDqgRpFUp9r@ubl6@bk5iVSUA).
**Explanation:**
Partially inspired by [*@tsh*'s JavaScript's answer](https://codegolf.stackexchange.com/a/255410/52210), so also checks pairs as:
```
0 → \
\ → 1
/ → 0
1 → /
0 → . → 0
*
0 → R → 0
*
*
1 → . → 1
*
1 → R → 1
anything else: invalid
```
```
…\/. # Push string "\/."
I'G¢ '# Count how many "G" are in the input-string
ã # Get the cartesian product of "\/." with this count
ε # Map over each string:
.; # Replace in the (implicit) input-string every first occurrence of
'G '# character "G", one by one with
sS # the characters in the current string
} # Close the map
ʒ # Filter this list of potential results with:
0U # (Re)set `X` to 0
¶¡ # Split the multiline string on newlines
ε # Map over each pair:
„\\ # Push string "\\"
º # Mirror it to "\\//"
2ä # Split it into two parts: ["\\","//"]
Xè # Get the 0-based `X`'th string in this pair
Qi # If it's equal to the current pair we're mapping over:
X_U # Invert `X` (0 becomes 1 and vice versa)
# (and implicitly map to the implicit input-string)
ë # Else:
yXè # Get the 0-based `X`'th character from the current pair
„R. å # Check if this character is in string "R."
}Ā # After the if-else: Python-style trutify the value
# (0 remains 0; everything else becomes 1)
}P # After the map: check if all are truthy by taking the product
X* # Multiply it by `X` to check whether we've ended at the bottom row
# (after which the filtered results are output implicitly)
```
] |
[Question]
[
Uilta is a minority tungusic language spoken in the far east of Russia.
A neat thing about Uilta is that it has pitch accent which can be predicted by a computer program. In this challenge we are going to take Uilta a word and determine where the accent peak is.
Let me explain how this can be done.
## Phonemes
The first thing needed is to split the input into phonemes. Phonemes are the smallest unit of language and they consist of vowels and consonants.
We will be using XSAMPA for this challenge so a vowel in Uilta is any of the following characters:
```
iu@oEOa
```
A consonant is any of the following characters:
```
mnJNptkbdgsx4ljw
```
Additionally the digraphs `tS` and `dZ` count as single consonants. Every input will have a unique decomposition into phonemes. So you don't have to worry about handling bad input.
Here are some example words split into phonemes:
```
na4i -> n a 4 i
mOO -> m O O
tuN@ndZi -> t u N @ n dZ i
ilaa -> i l a a
patala -> p a t a l a
xamdatta -> x a m d a t t a
@@kt@ -> @ @ k t @
isaaptu -> i s a a p t u
dZakpu -> dZ a k p u
bitSix@ -> b i tS i x @
xaiwaddaa -> x a i w a d d a a
```
## Syllables
Each word in Uilta can be broken into syllables. Syllables give the rhythm of the word. Syllables in Uilta match the regex `C?VV?C?`, where `C` matches any consonant and `V` matches any vowel.
There is one further restriction: Only the first syllable may begin with a vowel.
Every input will have a unique decomposition into valid syllables.
Here are some example words split into syllables:
```
na4i -> na.4i
mOO -> mOO
tuN@ndZi -> [[email protected]](/cdn-cgi/l/email-protection)
ilaa -> i.laa
patala -> pa.ta.la
xamdatta -> xam.dat.ta
@@kt@ -> @@k.t@
isaaptu -> i.saap.tu
dZakpu -> dZak.pu
bitSix@ -> bi.tSi.x@
xaiwaddaa -> xai.wad.daa
```
## Morae
Each syllable is made up of 1-3 smaller units called "morae". The first mora is all of the syllable up to and including the first vowel, this forms the primary mora. Every other letter in the syllable is its own mora, these are secondary morae.
Every input will have a unique decomposition into **at least two** valid morae.
Here are some example words split into syllables with `.` and morae with :
```
na4i -> na.4i
mOO -> mO O
tuN@ndZi -> tu.N@ n.dZi
ilaa -> i.la a
patala -> pa.ta.la
xamdatta -> xa m.da t.ta
@@kt@ -> @ @ k.t@
isaaptu -> i.sa a p.tu
dZakpu -> dZa k.pu
bitSix@ -> bi.tSi.x@
xaiwaddaa -> xa i.wa d.da a
```
## Pitch accent
Once you've split the word up into morae you can determine where the accent peak is.
The process is as follows:
* Check the second to last mora. If it's a primary mora then it's the accent peak. If it's not ...
* Check the mora preceding it. If it's a primary mora then it's the accent peak. If it's not ...
* The mora preceding it is the accent peak. (It must be a primary mora)
```
na4i -> na
mOO -> mO
tuN@ndZi -> N@
ilaa -> la
patala -> ta
xamdatta -> da
@@kt@ -> @
isaaptu -> sa
dZakpu -> dZa
bitSix@ -> tSi
xaiwaddaa -> da
```
## Task
Given a valid Uilta word output its accent peak mora. Input will always be valid as described above.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so your goal is to minimize the size of your source code as measured in bytes.
---
If you want to read more about the Uilta language the following is an excellent resource and was invaluable for creating this challenge:
[*Grammatical Outline of Uilta* (Revised)](https://eprints.lib.hokudai.ac.jp/dspace/bitstream/2115/37062/1/TSUMAGARI.pdf)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~102~~ ~~77~~ ~~39~~ 38 bytes
```
.*((^|[^iu@oEOaSZ]S?Z?)[iu@oEOa]).+
$1
```
[Try it online!](https://tio.run/##LcmxCoMwEAbg/Z7DQrQgFLp7i7iZIVtE8QcdDjWKXqBD3z1S6PjxnbNKQHqYZkxlYczw7QaJvNcWzveu8lXe/d3n5ZOyV0oBb6HNWtLYcpi8kKwAHVCsoA@2Caog5kWZ5AIOjb91CDc "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Now heavily inspired by @WheatWizard's Haskell answer, simply matches the last nonterminal vowel with its immediately preceding consonant or at the beginning of the string. Edit: Saved 1 byte thanks to @OlivierGrégoire.
[Answer]
# [Haskell](https://www.haskell.org/), ~~154~~ ~~108~~ 103 bytes
*5 bytes saved thangks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string)*
```
v=(`elem`"iu@oEOa")
g"S"="tS"
g"Z"="dZ"
g x=x
m(x:y:z)|v x>v y=g[y]++[x]|1>0=m$y:z
m x=x
```
```
m.tail.reverse
```
[Try it online!](https://tio.run/##TYtBi8IwEEbv/RVD8NDiKruwJyEllz26PXhrLTqQqMFMLO20pOJ/7wYFu7f35s13we5qnJumQaZH4wwdhe3V7adAkSVnsRNS8E5EKiPpMhIEGRJKw2bc3LPHACEfYJTnaqyXyyrUj6/8U9IixoSerydJa0br1q0ZTNuZidB6kKBvCQBhsz1AuocAqxya1nqGBZwgZDECVCA8flvxlA8QVBRv5v5XeV3O0TrEtzTI6GYNSBqZ54NSV1bztENsuP@31iX6l9bTHw "Haskell – Try It Online")
# Explanation
This is overall pretty simple. The first thing we do is `reverse` the input. We do this because the pitch accent is easier to describe relative to the end of a word than the beginning. From there we use `tail` to remove the final character. If this is a primary mora we've broken it up and the solution is now the final primary mora. If it wasn't well now we removed the final mora, and the solution is the new final primary mora.
So we are looking for the final primary mora. That's a vowel followed by a non-vowel. So `m` does just that, it trims until it finds a vowel followed by a consonatn and returns them reversed. We use a small bit of extra logic to handle `tS` and `dZ`: If the non-vowel was `S` or `Z`, we replace it with `tS` or `dZ` respectively otherwise we leave it alone.
And that's it, it gives us the accent peak.
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 78 bytes
```
v=kB$fe"iu@oEOa"
```
```
rv<gj<gP(h_*>l2p(p<v)(nA v*>hds++pM""en++(ʃ>/wR"St Zd")))<rv
```
# Explanation
This works a lot like my [haskell answer](https://codegolf.stackexchange.com/a/247963/).
First we setup `v` which is a parser which accepts any vowel. With that the first step in our function is to reverse the input with `rv`. We do this since we want to do things relative to the end of the list rather than the front of the list.
From here we have the actual parser.
```
h_*>l2p(p<v)(nA v*>hds++pM""en++(ʃ>/wR"St Zd"))
```
The actual parser just finds all primary morae except ones that end the list First it does `h_` which parses one or more characters then we parse a primary mora.
Since `h_` never parses 0 characters this breaks up any primary mora that would be at the end of the list.
The part that parses a primary mora is a little bit more complex
```
l2p(p<v)(nA v*>hds++pM""en++(ʃ>/wR"St Zd"))
```
But it can be broken down into further parts, first it parses a vowel `p<v` which parses a single vowel as a string. Then it parses a non-vowel, it does this with a negative look-ahead to check it's not a vowel `nA v`. Then it parses either, any one character `hds`, the end of the string `pM""en` or one of the digraphs `ʃ>/wR"St Zd"`. It can do both the first and last option at the same time, but since the digraphs are placed last they will have higher priority in the final result.
Once we have that parser we can run it. We run it with `gP` to get all results as a list. We use `gj` to get the last result, which do to the way we've done things will be the mora closest to the end of the string. This is also where the digraphs get higher priority than single characters, they will always appear later in the list.
Finally we reverse the given mora back to the correct order.
## Relfection
There were some pretty painful things here. When I first started I immediately realized there were some very important functions missing. I added them to the repo, although they are not present above.
I won't go into much detail but they would have saved 3 bytes overall:
```
v=xay"iu@oEOa"
```
```
rv<gj<gP(h_*>l2p(p<v)(nA v*>hds++pM""en++asy["St","Zd"]))<rv
```
However there are still some things that could be improved:
* `pM""en` is so painful. It's just an extremely expensive way to say the end of the list. `en` should in theory do that, but it returns a `()` instead and we need it to be an empty list. A version of `en` that returns an empty list would be useful.
* We really shouldn't have to do `gj<<gP`, there should be a built in way to get the highest / lowest priority parse, and only that.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 193 bytes
```
s=>System.Text.RegularExpressions.Regex.Match(s,$"^((?<P>{C}?{V}){V}?{C}?)((?<P>{C}{V}){V}?{C}?)*?({C}{V})?$").Groups["P"].Captures[^1].Value;string T="iu@oEOa",C=$"([^{T}][SZ]?)",V=$"([{T}])";
```
[Try it online!](https://tio.run/##VY9Na8JAEIbv@yuWxcNujQuF3jQfILaXtkoVC4YIQ1zt0mQTMhOIhPz2NNFS6GGG4YF35pkUZyna/rl26QKpsu7ina4OcpsGZ79HP9hekUyud6Yh/WEudQbVqikrg2gLhyMyjX4DSr8kehNxlDJcbIJ22YXtvlNDheOs/vA/@hDKXxROhNIvVVGXGIuNSPQSSqqHM/HxMdF7yGozv/vxnS9sHRWrNQhv6U@EjI/trkvi7SEJlfD2NzQSJeY9u4fihAwS93kkHDxZlq/XjOr3yJ0OltkMgJVAkAFrID8BEbAo@qaIWYTRQ@htmVmSas7ORWVgfPYug9w6Pu5WLfusLJlX64xEPuWCz4KhTflZohqCXf8D "C# (Visual C# Interactive Compiler) – Try It Online")
```
^((?<P>{C}?{V}){V}?{C}?)((?<P>{C}{V}){V}?{C}?)*?({C}{V})?$
```
This regex does all of the work. C and V stand for consonants and vowels respectively.
```
((?<P>{C}?{V}){V}?{C}?)
```
The first part matches the first syllable, and captures its primary mora in capturing group `P`.
```
((?<P>{C}{V}){V}?{C}?)*?
```
This part matches the next syllables, again capturing their primary mora in capturing group `P`. Note the lazy quantifier at the end.
```
({C}{V})?
```
This matches a single-mora syllable at the very end, if any.
We can then take the final mora captured within `P`, since it is guranteed to be primary, and also guranteed to not be the final mora (since that would either be captured within the last part, or it would be non-primary).
[Answer]
# Python 2, 113 Bytes
```
lambda s,v='iu@oEOa':(['dt'[i<'T'][:i in'SZ']+i+j for i,j in zip(s[:-1],s[1:-1])if(i in v)<(j in v)][-1:]or s)[0]
```
[Try it online!](https://tio.run/##fY47b4MwGEV3foUVBhsBUkk6WUnkDl3DkE64Hr4IodoFg2ITtf3zlFeC00j14sfxd89tvu1HrdddsXvvSqhOOSATXXZYtqx@TQFTwnFuMZdb/IYFpxJJjY8ZFqEMFSrqM5KR6t/Qj2yI4TRORGR4MuyBLMjwHV2CLVHTQfA4oaKfMgF/Ep2PXkpToyTZnDwf/edXs1/d/CqUj/54TecK8Yb@KbG/lbj6Pa85S21JQVYanuUqCFC/fBTvkYaFVWk6o4lV6cJse2A6z4bZkR3YwmQJ4GaWTmYDFsqJjsw67AuqHKyFa2buMMY@LZtCR@bqDEBj2wGOyNzp8gz0outvd12OLuxv3S8)
Heavily inspired by Wheat Wizard's [Haskell answer](https://codegolf.stackexchange.com/a/247963/65425).
### Approach
* Split the word into two-letter chunks, excluding the last letter
* Find all chunks of the form CV (consonant then vowel)
+ If no such chunk exists, return the first letter of the word
+ Return the last such chunk
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
¨.γ"tSdZ"så_N*}ü2¬нšʒžM'@«slåJ}θJÔ
```
Inspired by [*@WheatWizard♦*'s Haskell answer](https://codegolf.stackexchange.com/a/247963/52210).
[Try it online](https://tio.run/##AUAAv/9vc2FiaWX//8KoLs6zImR0U1oic8OlX04qfcO8MsKs0L3FocqSxb5NJ0DCq3Nsw6VKfc64SsOU//9iaXRTaXhA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Qyv0zm1WSikJjlIqPrw03k@r9vAeo0NrLuw9uvDUpKP7fNUdDq0uzjm81Kv23A6vw1P@6/yPVspLNMlU0lFQyvX3B1ElpX4OeSlRYKHMnMREEF2QWJKYA2ZVJOamJJaUgNkODtklDmBlxYmJBSWlIGZKVGJ2AZiVlFkSnFnhANGUWZ6YkgI0KxYA).
**Explanation:**
```
¨ # Remove the final character of the (implicit) input-string
.γ # Adjacent group by:
s # Check if the current character
å_ # is NOT in
"dtSZ" # string "dtSZ"
N* # Multiply it by the index, so everything else is in its own group
}ü2 # After the group-by: get all overlapping pairs of this list
¬нš # For the edge case of a leading vowel:
¬ # Get the first pair (without popping the list)
н # Pop and get its first character
š # Prepend it to the list
ʒ # Filter this list of pairs (plus the single leading item) by:
žM # Push the vowels "aeiou"
'@« '# Append a "@"
s # Swap so the current pair is at the top of the stack
l # Convert all letters to lowercase
å # Check if its in the vowels string
J # Join these checks together
# (truthy: "1"/"01"; falsey: "0"/"00"/"10"/"11")
}θ # After the filter: pop and keep the last valid item
J # Join this pair back together to a string
Ô # For the edge case of "tt" or "dd":
Ô # Connected uniquify
# (after which the result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 45 bytes
```
Ṫλ&›`dtSZ`$c¬¥*;Ḋ2l:hhp'ɽkv\@J$vcṅ⌊1=;tfṅĠvhṅ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCLGmyIsIuG5qs67JuKAumBkdFNaYCRjwqzCpSo74biKMmw6aGhwJ8m9a3ZcXEBKJHZj4bmF4oyKMT07dGbhuYXEoHZo4bmFIiwiO1rGm2AgPT4gYGo74oGLIiwiW1wibmE0aVwiLCBcIm1PT1wiLCBcInR1TkBuZFppXCIsIFwiaWxhYVwiLCBcInBhdGFsYVwiLCBcInhhbWRhdHRhXCIsIFwiQEBrdEBcIiwgXCJpc2FhcHR1XCIsIFwiZFpha3B1XCIsIFwiYml0U2l4QFwiLCBcInhhaXdhZGRhYVwiXSJd)
Port of 05AB1E.
[Answer]
# Python3, 650 bytes:
```
lambda x:[*s(T(x),1)][0]
T=lambda x,c=[]:c if''==x else T(x[len((t:=[(a,b)for a,b in[('C','tS'),('C','dZ')]+[('C',i)for i in'mnJNptkbdgsx4ljw']+[('V',i)for i in'iu@oEOa']if x[:len(b)]==b][0])[1]):],c+[t])
P=lambda x:''.join(i[1]for i in x)
def M(w):
w=[i for j in w for i in j]
for i in[-2,-3,-4]:
if w[i][0]:return w[i][1]
def s(t,l,c=[]):
if[]==t:yield M([[(1,P(i[:I[0]+1])),*[(0,P([j]))for j in i[I[0]+1:]]]if(I:=[x for x,(a,_)in enumerate(i)if'V'==a])else i for i in c]);return
for i in'CVVC CVV CVC CV VVC VV VC V'.split():
if len(t)>=len(i)and(i[0]!='V'or l)and all(a==k for(a,b),k in zip(t,i)):yield from s(t[len(i):],0,c+[t[:len(i)]])
```
[Try it online!](https://tio.run/##VVLBbtswDD3PX6HlIrFRimTNYfCgIkCwQwesKbAih6rCQMf2pkRWDFtB3P58RtlJih0s8ZFP5CPp@i383fu7r3VzKtXryWGV5ci6VN@04ll0IGdg9NQkz@oSkhulTbphtuRcqY4Vri0YUbUrvBAhVVqgzKDcN4xuZr0WfMklD784yMHMXziY8eC3PdMSj1f@x2Mddln@p@3mbnvkPWf9H8ceFvvvK@TGlqzTaayZgVEqiypBzwykRm7GOhhInq6aU85vt3vrhSXGJRfrIMmLkv0UR0gTdlTashjbxtiRXWlbk1yBnnyRkzs5mRt6QSNgR21j5bQpwqHxA5yZPm8rgnT9tGJ6W2qSGdI3W7icamotZvKJBKUP9H5MwkHeaDEln94SuCqxeiCkxlDT4oEG3PV6OkmD/g1EKfyhKhoMhbBAa1nTXtBAvxj70cfGwLdB5kc/fLleLxkd9MWbRUgonvy2rZ0NAs6txlkHuFfxtoA@J/FT81lRPcrmooehcwKV2sUC/W8gd7H0u61pGBbg3H7Z7Ks4Hz3kopVN@6UNC7VgDJyuukejkce5ZZN75jGpVqtoVaskHB4XPn/pA4@LxDrEaDpMagzoehAw6bDKMYQe5pgsFruwiDa9aBHrcIigRapy7pe/ek49f0LJMqaYvbgjjwP527ZoAisFAlOKZad/)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 39 bytes
```
≔…θ⌈⌕A⁺00⭆…θ⊖Lθ№iu@oEOaι01η✂η±⁺²№SZ§η±²
```
[Try it online!](https://tio.run/##VY09C8IwGIR3f0XI9AYi1K4ulqogWC1kcwvpSxNIk34kUn99LBVEbzqOu@eUlqPy0qZUTJNpHZQvZbHUvoeBk0rOposdnI1rCmuhtnECmmWUExFG49pK9v@LI6oRO3QBG7iia4OGgTHGSemjC0BNPPjTXS4As8Y029HVaLbf1AsygLBGIWhObtjKgJ/T/EsQj2VchItrcP5p5WzVPqVeBiFd2j7tGw "Charcoal – Try It Online") Link is to verbose version of code. Alternative formulation, also 39 bytes:
```
≔✂θ⁰±⌕⪫00⭆Φ⮌θκ№iu@oEOaι10¹η✂η±⁺²№SZ§⮌η¹
```
[Try it online!](https://tio.run/##PY1BCsIwEEX3niJkNYEIqdtuLKKgoBazcxfa0ARDUpO0ePs4FunAZ2CG935nVOyCcqU0KdnBg3S20/DmRHBy04PKGk7W93AJ1gMVgnIic7R@uKoRPy7rCA8965iQYpy8MIcw@QzUTvtwvCskLGN4ppWgv11hDKs3LWryv9Csba2bEuxWiXwi3@Sz7/VnLTKLZZm6lFFlqXzZzu4L "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Ports of @WheatWizard's Haskell answer.
```
≔…θ⌈⌕A⁺00⭆…θ⊖Lθ№iu@oEOaι01η
```
Except for the last letter, map each letter to whether it is a vowel or not, prefix `00` to the result, find the last index of `01`, and truncate the input string at that point, which thanks to the `00` prefix will be just after the desired primary mora, although the second `0` does double duty by allowing an initial vowel to be detected as a primary mora.
```
≔✂θ⁰±⌕⪫00⭆Φ⮌θκ№iu@oEOaι10¹η
```
Reverse the string except for the last letter, map each letter to whether it is a vowel or not, wrap the result in `00`, find the index of `10`, and remove that many characters from the end of the input string. The leading `0` adjusts the find index to be the number of characters to remove while the trailing `0` allows an initial vowel to match as a primary mora.
```
✂η±⁺²№SZ§η±²
✂η±⁺²№SZ§⮌η¹
```
Output the last two characters of the remaining string, unless the second last character is `S` or `Z`, in which case output the last three.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 59 bytes
```
s->s.replaceAll(".*((^|[^iu@oEOaSZ]S?Z?)[iu@oEOa]).+","$1")
```
[Try it online!](https://tio.run/##hZDBctowEIbveoodT5mRKShh2lNpiHtoTy3M1DcYMrOxRSKQhWqtCEzDU/TQS5@uL0KRMWCSQy9e/d5/v3@lOa6wO88XO1XYZUkw32vhSWnR7rNX/2beZKSWJjQzjc7BN1QGfjIA6@@1ysAR0r6sliqHYt/jKZXKPEymgOWDiysrwJea8/HQ7RzKAGZws3PdgROltBoz@UlrHok253fPkzvlk@XnEabjaXo7vo0ntZ7G4m3Uid70onjXr@hUbvgKS3AZGiNLuAEjnyA9KJ5uHMlCKBMftwF4elRaAq8HxCO6oVzTV2Ukb7gAApWkoz3y6DUno3BWK@IRdAcQxf2LIWWsD1NheHI9vWzKtZUZyfy7dF6fXL0XrvLYnQm0Vm94xWzkqBnwS5SQPzxqxw@jFzcBqN9h6UnY/evTjEd///yCVu/ahRu03rmWiTqHzTt1eiNtC1I7@X/i7ybxvOAHaLn4dUDnxWM0A1mzhu@WbdlVmxl8r1gxGjHyw8TkY8WURmQWCTWyNRY5EiFLkgUlTDlES57lY1xYz@4VpWqdsPbVLmDCmgYDLJyKMzLIYVKBw1Ef8UHQOSTIvI4K51NeEA7r1Mo1xmN4xUjVPw "Java (JDK) – Try It Online")
## Credits
* -96 bytes by porting the [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s [Retina answer](https://codegolf.stackexchange.com/a/247949/16236), thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 49 bytes
Port of [Olivier Grégoire’s Java answer](https://codegolf.stackexchange.com/a/247997/14109).
```
{S:g/.*((^|<-[iu@oEOaSZ]>S?Z?)<[iu@oEOa]>).+/$0/}
```
[Try it online!](https://tio.run/##PY3NTsMwEITP3aewIgslrZoUCXHoT@oLBy7JIbfQIi04Aat2GmJHtCrh1YNttVxW883OzrZVJx9HdSZ3NdmMl2L5kcTTMHz9Wc9fRM@OTzkW5T4ttuU2Wt@cfRrFs4QukmFcQX3sCJ0@Z7EUTaXJBSaiJkm4K2YRCcg8tcND4lYT@4kKsiG/dLG6YuXx/oadxTqkInKGxjMJlNAKzfvn0p3aOO0C0jey0tpR9WWN/6xN2Jc2AZMBhrHBB280CCrPnVI5mD5jDS/9ImMgJKKTEqFFg9KDQTih4miMR47A2MEwp@2FRmxN70Aj8BIPrQer4E2YQpx80ApbIr6Rc7y2/AE "Perl 6 – Try It Online")
] |
[Question]
[
A *Steiner quadruple system* \$SQS(n)\$ is a collection of subsets (*blocks*) of size 4 of a set \$S\$ of size \$n\$ such that every subset of \$S\$ of size 3 is in exactly one block. It is easy to show that the number of blocks is \$\frac14\binom n3\$ and that a necessary condition for an \$SQS(n)\$ to exist is \$n\equiv2,4\bmod6\$. It is much harder to show that that condition is also sufficient, which is what Haim Hanani did [in 1960](https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.371.9477).
Hanani's proof is almost completely inductive: the only explicitly listed \$SQS(n)\$ is an \$SQS(14)\$ with 91 blocks. It can't be memorised, however, so I want a program to generate such a system for me.
## Task
Output all blocks of some \$SQS(14)\$ – how it is constructed is irrelevant.
Output should consist of 91 blocks of four values each. You may use any 14 distinct values. Formatting is flexible, but there must be a clear separation between blocks, and it must be clear which four values are in each block.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. You must run your code to completion and include its output in your answer.
## Example
[I have found](https://math.stackexchange.com/q/4371518/357390) an \$SQS(14)\$ whose blocks arise from the orbits of the base blocks \$1235, 126C, 12AB, 12DE, 12FG\$ under the permutations \$(1234567)(ABCDEFG)\$ and \$(1A)(2F5G3D)(4B6E7C)\$. The following are two possible output formats for this system:
```
1235 2346 3457 4561 5672 6713 7124
AGFD GFEC FEDB EDCA DCBG CBAF BAGE
126C 237D 341E 452F 563G 674A 715B
AGC6 GFB5 FEA4 EDG3 DCF2 CBE1 BAD7
12AB 23BC 34CD 45DE 56EF 67FG 71GA
15AE 52EB 26BF 63FC 37CG 74GD 41DA
13AC 35CE 57EG 72GB 24BD 46DF 61FA
12DE 23EF 34FG 45GA 56AB 67BC 71CD
15FC 52CG 26GD 63DA 37AE 74EB 41BF
13GB 35BD 57DF 72FA 24AC 46CE 61EG
12FG 23GA 34AB 45BC 56CD 67DE 71EF
15GD 52DA 26AE 63EB 37BF 74FC 41CG
13DF 35FA 57AC 72CE 24EG 46GB 61BD
```
```
[[0, 1, 2, 4], [1, 2, 3, 5], [2, 3, 4, 6], [3, 4, 5, 0], [4, 5, 6, 1], [5, 6, 0, 2], [6, 0, 1, 3], [7, 13, 12, 10], [13, 12, 11, 9], [12, 11, 10, 8], [11, 10, 9, 7], [10, 9, 8, 13], [9, 8, 7, 12], [8, 7, 13, 11], [0, 1, 5, 9], [1, 2, 6, 10], [2, 3, 0, 11], [3, 4, 1, 12], [4, 5, 2, 13], [5, 6, 3, 7], [6, 0, 4, 8], [7, 13, 9, 5], [13, 12, 8, 4], [12, 11, 7, 3], [11, 10, 13, 2], [10, 9, 12, 1], [9, 8, 11, 0], [8, 7, 10, 6], [0, 1, 7, 8], [1, 2, 8, 9], [2, 3, 9, 10], [3, 4, 10, 11], [4, 5, 11, 12], [5, 6, 12, 13], [6, 0, 13, 7], [0, 4, 7, 11], [4, 1, 11, 8], [1, 5, 8, 12], [5, 2, 12, 9], [2, 6, 9, 13], [6, 3, 13, 10], [3, 0, 10, 7], [0, 2, 7, 9], [2, 4, 9, 11], [4, 6, 11, 13], [6, 1, 13, 8], [1, 3, 8, 10], [3, 5, 10, 12], [5, 0, 12, 7], [0, 1, 10, 11], [1, 2, 11, 12], [2, 3, 12, 13], [3, 4, 13, 7], [4, 5, 7, 8], [5, 6, 8, 9], [6, 0, 9, 10], [0, 4, 12, 9], [4, 1, 9, 13], [1, 5, 13, 10], [5, 2, 10, 7], [2, 6, 7, 11], [6, 3, 11, 8], [3, 0, 8, 12], [0, 2, 13, 8], [2, 4, 8, 10], [4, 6, 10, 12], [6, 1, 12, 7], [1, 3, 7, 9], [3, 5, 9, 11], [5, 0, 11, 13], [0, 1, 12, 13], [1, 2, 13, 7], [2, 3, 7, 8], [3, 4, 8, 9], [4, 5, 9, 10], [5, 6, 10, 11], [6, 0, 11, 12], [0, 4, 13, 10], [4, 1, 10, 7], [1, 5, 7, 11], [5, 2, 11, 8], [2, 6, 8, 12], [6, 3, 12, 9], [3, 0, 9, 13], [0, 2, 10, 12], [2, 4, 12, 7], [4, 6, 7, 9], [6, 1, 9, 11], [1, 3, 11, 13], [3, 5, 13, 8], [5, 0, 8, 10]]
```
If you have your system in list-of-lists format like the second example you may verify it is a Steiner quadruple system [here](https://tio.run/##VZQ/j9swDMX3fAoikwV4sCz/PSAFbilQoEOBG4MbnKtzNerYgeOlnz6V9EhJl4lURPK9Hw3d/@1/1sV09@35vG7rjaZ93PZ1nR803e7rttPHertMy7BP6/I4jPb8RPP02LNtWD7HTFdKHS7z@vHX/XE@FznpnMqcqveczghNTrXLEFY5NS5DWOdUuAxhY6tdhtD2Kl2G0PYyLmttaGu17aZ9acjsjd4fcKJtVecPOOlzan2OuHOdXI7YNfbzOHZtvRoMr6W799TIdJgq5C5caWkFW6UMgi/DMuCrYpE8smdY4qoTlGyqZQziyd0rE1P@XjTlrhWJqYLpw1MrgLzGjh3CUi8O2VKwCE86eOS9BZO8LnEJi21SrVEtk2sIlV4leomSBkqks@HFiLICymRS6SdJbYVamduwauml0Ut0GOiQzjV7Fl0FdLWRXkQCfhEJCEYkjFCQgKDABz@BD3oBPugFIKAXgIBeBML4BAjwBfSMT9CDXkBf8HfK/wJfAML4AhDGJ0CAT9CDXkDP8AL6ItQGF2VCp5ReXUTXRf91QqeOqnTy6enEU5XyqcLe2oivTXSWCZ9S9hIcm2QTJuzJJPSK5AuoEj6VbKKP8Prk6zEpHxO22kV82MT7YbrSMM/ZPC6Zf4av02xf7GwebpffA11e6DHu2UXRNx/s26RywvuslDqdNF3XjewxTcuXpz2zT7vVodTLgezvvk3Lnh1/vb69HZV79scv599ff/w8qufzPw).
---
Thanks to @DLosc for help with the phrasing.
[Answer]
# Python, 85 bytes
```
print({(*sorted((i*3**j+j)%14for i in[1,5,j%5^22,9910>>j%5*4]),)for j in range(210)})
```
[Try it online!](https://tio.run/##FcpLCoAgEADQq7gJZiYXaQW18SJREPTThcrkJqKzWy0fvHilI/i6i5xzZOsT3EBn4LQuAJZqIlc6LFSzBRZWWD8o2UpXtJPWsu9VZcwHakaU@Bf3FcGz31fQqsIHc34B "Python 3.8 (pre-release) – Try It Online")
Outputs {(0, 1, 4, 5), (6, 8, 11, 12), (1, 7, 9, 11), (2, 3, 12, 13), (2, 4, 9, 11), (0, 6, 7, 13), (4, 5, 11, 12), (4, 8, 10, 12), (8, 9, 10, 11), (2, 6, 9, 13), (1, 2, 5, 7), (3, 5, 7, 11), (1, 3, 7, 13), (0, 1, 2, 3), (1, 4, 8, 11), (0, 2, 11, 13), (2, 7, 10, 13), (1, 6, 8, 13), (2, 7, 11, 12), (8, 9, 12, 13), (0, 1, 12, 13), (0, 2, 4, 10), (4, 6, 11, 13), (0, 4, 6, 8), (1, 4, 9, 12), (2, 4, 6, 12), (4, 5, 10, 13), (3, 4, 10, 11), (4, 7, 12, 13), (0, 8, 10, 13), (1, 2, 10, 12), (0, 1, 10, 11), (0, 2, 8, 12), (5, 7, 8, 10), (10, 11, 12, 13), (0, 4, 7, 11), (6, 7, 10, 11), (3, 4, 8, 13), (0, 1, 7, 8), (3, 9, 11, 13), (3, 7, 8, 12), (0, 3, 4, 12), (0, 2, 5, 6), (0, 4, 9, 13), (0, 1, 6, 9), (0, 3, 8, 9), (2, 4, 7, 8), (0, 5, 8, 11), (5, 6, 9, 11), (1, 3, 8, 10), (1, 5, 8, 12), (1, 3, 11, 12), (1, 3, 4, 6), (1, 2, 8, 9), (0, 3, 7, 10), (0, 3, 5, 13), (2, 5, 10, 11), (6, 7, 8, 9), (2, 3, 4, 5), (1, 9, 10, 13), (2, 3, 6, 7), (1, 5, 6, 10), (4, 6, 9, 10), (3, 5, 6, 8), (3, 6, 9, 12), (0, 5, 9, 10), (0, 6, 10, 12), (5, 7, 9, 13), (0, 5, 7, 12), (5, 6, 12, 13), (0, 9, 11, 12), (7, 9, 10, 12), (3, 6, 10, 13), (4, 5, 8, 9), (0, 3, 6, 11), (3, 4, 7, 9), (7, 8, 11, 13), (1, 4, 7, 10), (2, 3, 8, 11), (1, 6, 7, 12), (2, 3, 9, 10), (1, 5, 11, 13), (2, 5, 8, 13), (2, 5, 9, 12), (2, 6, 8, 10), (1, 2, 6, 11), (1, 3, 5, 9), (3, 5, 10, 12), (1, 2, 4, 13), (4, 5, 6, 7), (0, 2, 7, 9)}.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 182 bytes
```
»∨vw\\ẇẆ|ετfẆτ›≥Πo∩Ṗ…›Ẏ⟑ȮĠḃ…°Ṗ5=₴ƛ¯⇩7¡∇∞}⁺εḭ>∑‛u²%¤ßǔ]‡∨ε⁼Ġ†ȧ£€Ż₁T±↑⁋N∵ɽE"@∩⁺ ≤Ǐ0¬ė⅛6⌈0ż⇧⌊≈ŀ¬∑ȮW√꘍↓ṗX→≥bOÞẇṀÞ≈¢e5Ṙẏð₀ꜝ→£∴∑↑›∇₇⋏o½↓t¼¨8¾‹O¾ṪO\ȧ₁↑żẆðŀErc⊍≤λ?↓ṙ…k;,ε÷5M<ṅǒR‡,∩ŻIλ»14τṘ4ẇ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu+KIqHZ3XFxcXOG6h+G6hnzOtc+EZuG6hs+E4oC64omlzqBv4oip4bmW4oCm4oC64bqO4p+RyK7EoOG4g+KApsKw4bmWNT3igrTGm8Kv4oepN8Kh4oiH4oiefeKBus614bitPuKIkeKAm3XCsiXCpMOfx5Rd4oCh4oiozrXigbzEoOKAoMinwqPigqzFu+KCgVTCseKGkeKBi07iiLXJvUVcIkDiiKnigbog4omkx48wwqzEl+KFmzbijIgwxbzih6fijIriiYjFgMKs4oiRyK5X4oia6piN4oaT4bmXWOKGkuKJpWJPw57huofhuYDDnuKJiMKiZTXhuZjhuo/DsOKCgOqcneKGksKj4oi04oiR4oaR4oC64oiH4oKH4ouPb8K94oaTdMK8wqg4wr7igLlPwr7huapPXFzIp+KCgeKGkcW84bqGw7DFgEVyY+KKjeKJpM67P+KGk+G5meKApms7LM61w7c1TTzhuYXHklLigKEs4oipxbtJzrvCuzE0z4ThuZg04bqHIiwiIiwiIl0=)
This just hardcodes the result.
```
»...» # Base-255 compressed integer
14τ # Convert to base 14
Ṙ # Reverse (because leading zero)
4ẇ # Chunks of length 4
```
Or, if we're allowed to take a few universe lifetimes:
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
14ɾ364↔'4ẇ3vḋÞf:U⁼;h
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIxNMm+MzY04oaUJzThuoczduG4i8OeZjpV4oG8O2giLCIiLCIiXQ==)
This is a horrendously inefficient bruteforcer. It computes all \$14^{364}\$\* sets of 14 symbols of length 364, for each gets combinations of three elements and checks if they all appear once.
The last two bytes can be removed if we're allowed to output all such sets.
```
14ɾ # 1...14
364↔ # Combinations of length 364
' ;h # Find one such that...
4ẇ # When grouped into lengths of 4
3vḋÞf # And all subsets of length 3 within those lists
:U⁼ # Does it include all subsets exactly once?
```
\* Roughly 10^400, so give it a few universe lifetimes
[Answer]
# JavaScript (ES6), 229 bytes
Returns a rearranged version of the example \$SQS(14)\$ with symbols \$1\$ to \$9\$ and \$a\$ to \$e\$.
```
x=>`2zmGWS01bV02fOWIS3j01dGF4uHUF4yC01b4kQVbm1hk01dHA01b3b015F01b3jXFG5cFU4yFCj61hk01aV01b3bSCF5dFF5dFFpt1ikAV4gZCF5dFF6m27gVV4h01bFcw27gVV4z2l82sgU5r742en6m2sf`.match(/[A-Z]|[012]?../g).map(s=>(x=parseInt(s,36)-~x).toString(15))
```
[Try it online!](https://tio.run/##JYpda4MwGEb/ToRpTYx2N3aIENurMcR0tBTqZ/xMxGSbLWN/3Wb24oXnPee06Xcq86kZlclFUS6Vv8z@7oruQ3SMbZhRG1Xvx0PstDYsIoK/9gnBt1Ab3H3QbIB1p8U@0MDJbOiS/9F@ksjNSYJvJGy9NUnpWsQhcQuy3qhg0wUUs9OTeQPaMkpxrUOS/zyfO@pfkWSJO20xKrluZHW1hlTlNdicA/N0@T3bEF3eLGvDDC1GIP0dmP0xnWR54ArIF8czzL/ZsJSI1dRwBqBrGEsuuBR9afWCgQpo8AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 180 bytes
```
⪪”$↶⧴F»ZÀ{XBS↧⁺MDu➙{ν%↘D12W?xV_*o}ηφ|Xη&S↗[-W⦄[×±α_M«Sl5 rυ№|↷ηx?«Xü¡×=IvM±&3i◧5¿C№⟦sB⁴σχ?‽∨K↷¤⌊﹪➙νηT\⎚ι‴;Z8←$�✳L\`κⅈ5·⊖;,⊙ς7qo⊞▶ïsG⁻Yωr§ς1C-Cτ&≔⊞7AηγpβD9a›ω ≔1“Þω⬤m@‖PEI↙⊕≕¦·G*Fρ”⁴
```
[Try it online!](https://tio.run/##Dc85SkMBFEDRrUgqBe3srN48PwRXEGwUgkoQt/9NfeHAff84X9@/z5fjeL1@fv3ev/1cPn/vT4AkSKzEYiwKooZqQAbIvlM7ndMVXemVsRk@4duAmkhWxNAsOKK0auwGcsupOyHTzl1LlYMZDeF1Yz2QIomzWKpFe9RmDdZBvAU7UGOUJslyjbcYyoE8SbLFeg03kKNYaxTGAauReohnWdZFPdQiDbJAJgVzUbeUysm8jTsYYoA2SKLEagzHb8fJmq3QCziLtE7swRIpmqVWbdADsiVYjuqt1EEWYzzJkAtUQzIu5mmYjdzLuqEQdXq8e354eDmO4@nv8g8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs values `A`-`N`. Explanation: Splits a compressed string into chunks of 4.
] |
[Question]
[
Inspired by [this OEIS entry](https://oeis.org/A193764).
## Background
A **saturated domino covering** is a placement of dominoes over an area such that
1. the dominoes are completely inside the area,
2. the dominoes entirely cover the given area,
3. the dominoes may overlap, and
4. removal of any domino reveals an uncovered cell (thus failing to satisfy condition 2).
The following is an example of a maximal such covering of `3 × 3` rectangle (since dominoes may overlap, each domino is drawn separately):
```
AA. B.. ..C ... ... ...
... B.. ..C .D. ... ...
... ... ... .D. EE. .FF
```
## Challenge
Given the dimensions (width and height) of a rectangle, compute the maximum number of dominoes in its saturated domino covering.
You can assume the input is valid: the width and height are positive integers, and `1 × 1` will not be given as input.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
[A193764](https://oeis.org/A193764) gives the answers for square boards. The following test cases were verified with [this Python + Z3 code](https://tio.run/##lVPLbtswELzrK7aHQmTMGH4VRRI4QHrzpf2AwjBoiaqIWKQg0qlsw9/u7pK04yA9JDpoSO7MLHe1ane@tmZ6OummtZ2H/TTLSlWBtyttPOv5fQb4dMpvO4PR4aJivYCxgBGPTCf9qrSNNnZV2BfVsc7@dQIKu3FJHKPKwRx@H1DcwwDGR6hsh0ttoJPmjwoyuIk60BWGvoYNfJlHvIXx8q3f4MqQKO88oykK@dk5OqwtGaIaC/qBa1bl5eqArljwEReyp0XOX/3OOZdZMLCtRzmqf7VeN3qvGA/nxF@LxCbdXrcsZBMXi9QVemolS7rGLgh3Iub6n4Y6QveLB5xoPUhT4hv7E0@XF18v9eYTvljux3zJrSYOXfy1jHPIU4hyvw2dGzYIHftpPUN4MiXDTtUCPOexqS62dIFzl7ucZ1c6DOFr27BGtizOpohfkV94Q6wjfgsXz6RzCkeaQkWtimfGqSbMsDU4tIHSdjTlQWxLtWF8qF7khpFrVkgXZ5bhtE@4AMJpwruE4xEtJokwSQTEb4TTtEecJfxOOEv7Ge2XGfWuoN6FlPdXNysE5PNHyAUoU87znD@8/99uCn46/QM) (not supported on TIO).
Only the test cases for `n <= m` are shown for brevity, but your code should not assume so; it should give the same answer for `n` and `m` swapped.
```
n m => answer
1 2 => 1
1 3 => 2
1 9 => 6
1 10 => 6
2 2 => 2
2 3 => 4
2 5 => 7
3 3 => 6
3 4 => 8
3 7 => 15
4 4 => 12
4 7 => 21
```
[Answer]
# Sagemath, 60 bytes
```
lambda m,n:m*n-len(graphs.GridGraph([m,n]).dominating_set())
```
[Try it online!](https://sagecell.sagemath.org/?z=eJwtztEKgyAUBuB7wXc4N5GGRVljLNhue4gmw81qQlpY7888wwPy_T_nXDjfn5Ss2r2NBid87wpfrpNnS9D796iGYM2AkY1xq3hlNme9Pq1fXsd0Ms4poWTeAnz0MYH1MLJGgOQC0DZ5SzY1BpkOZDqIXtA29WiXvKJd6h121VMCcfZg_cnyTBrAVz6QHDJg-JOxVuJvo8TMCoyc8x_yGjn0&lang=sage&interacts=eJyLjgUAARUAuQ==)
---
From [Saturated Domino Coverings](https://arxiv.org/pdf/1112.2115.pdf) by Buchanan et al:
>
> **Corollary 6.3:** *If \$B\$ is a rectangular \$m \times n\$ board, then \$d(B) = |B| - \gamma(G\_{m,n})\$.*
>
>
>
Where \$\gamma(\ldots)\$ is the [domination number](https://mathworld.wolfram.com/DominationNumber.html) and \$G\_{m,n}\$ is a grid graph. We also clearly have that if \$B\$ represents an \$m\times n\$ board then \$|B| = mn\$.
[Answer]
# JavaScript (ES6), 120 bytes
A shorter (and slower) version, using the same algorithm with `eval()` and two `for` loops.
Expects `(m)(n)`.
```
m=>n=>eval("for(M=0,b=1<<m*n;b--;)for(k=j=m*n;j--?b>>j&1&&k--||(b<<m|b>>m|(j%m&&b*2)|(~j%m&&b/2))>>j&1:k>M&&!(M=k););M")
```
[Try it online!](https://tio.run/##bc/tDoIgFAbg/12FtcXARQppXwpdgRchpi38oFXzF@vWTcPNzfjH3uc9nB2Ztukre94fb9yoa94VrKsZbxjP27SCq0I9YcL8jWAkjmu3iQTGERrSkkk2BBLji@BcAgJAibHWUPRN3Ue1hnJdAyBcijT8mLdHEfq1zyVPAFj2v5coQlGyQl2mmpeq8m2lbrCABEGnLzue55DFP@0MUQudDO3/ifh2otMuaqFxV2Ch0NBhRrtpam@hwNDRQofx5HBmwTRGaPcF "JavaScript (Node.js) – Try It Online")
Or [try an implementation in C (gcc)](https://tio.run/##fdDRasMgFAbg@z7FSaGiQUm1abvNmj1B2AvspmZYqosb3WAXTffoc6YkkIvam4Pn5@PnYMMOTROCpo5aWkuDW@rJ2XyccK2WVCu@27W5l5oxSfrUKav6wDL2rKvKIo6QY6zrsI6yi1EcucizDNtFSzpdXN@//UKu/slVNUJZ7HdEEqlVLS/h6L@h3R89JnCeAXyeYmDwfPH26ucUDOYUQBAioSiAp8BqACIFHgewSQC@vAfE5AaRAuMNZQqsB7C9BVaThk0KlAN4SIHt@FHrW6KcVHCREmOH4LNL@GvM@/7wFdhPYC/8Hw) (127 bytes) which can process the last test case on TIO.
---
# JavaScript (ES6), 128 bytes
Expects `(m)(n)`.
```
m=>n=>[...Array(1<<m*n)].map(M=(_,b)=>(g=j=>j--?b>>j&1&&k--||(b<<m|b>>m|(j%m&&b*2)|(~j%m&&b/2))>>j&1?g(j):0:k<M?0:M=k)(k=m*n))|M
```
[Try it online!](https://tio.run/##bc/haoMwEAfw73sKvyzclSWa1LareJE9gE8wxtCulcVGiy2DQdirO7cUhDbfjvvdnz9nqq/qvBs@Txfe9R/78UCjJd2RfhVCvAxD9Q0yz@2iwzdhqxOUBO9PNZKGhgxpw3lRa22YZKzl3Dmop2s3rawD82gZqxcKHfz4OVaI/9dFAwazJGvzskiyklqElv5a0JXjru/O/XEvjn0DB5AI0RSL4jiSD/e09KQCtPW0vieZhEnNXSpA1640QCtPmxtazql1gFJPzwHaXF9e3Vg6x6QafwE "JavaScript (Node.js) – Try It Online")
### How?
This is based on [the formula used by Sisyphus](https://codegolf.stackexchange.com/a/211261/58563), except that we have to actually compute \$\gamma(G\_{m,n})\$ since there's obviously no JS built-in for that.
For each \$b\$, \$0\le b<2^{m\times n}\$, we test whether at least one of the following conditions is true for all \$j\$, \$0\le j<m\times n\$:
* the \$j\$-th bit of \$b\$ is set
* or the \$j\$-th bit of \$b\$ is adjacent to a set bit in \$b\$ when re-arranging the bits in a grid of size \$m\times n\$
If this is successful, the set bits in \$b\$ represent the vertices of a valid dominating set of the \$m\times n\$ grid graph.
While doing that, we also compute the number \$k\$, which is equal to \$m\times n\$ minus the total number of bits that are set in \$b\$. We update the final result \$M\$ to \$k\$ whenever \$b\$ is a valid bit mask and \$k\ge M\$.
### Commented
```
m => n => // (m, n) = size of the grid
[...Array(1 << m * n)] // build an array of 2 ** (m * n) values
.map(M = // initialize M to a non-numeric value
(_, b) => ( // for each b, 0 <= b < 2 ** (m * n):
g = j => // g is a recursive function taking a counter j
j-- ? // decrement j; if it was not equal to 0:
b >> j & 1 // if the j-th bit of b is set:
&& k-- // decrement k
|| // otherwise, we compute a bit mask where all bits of
( // b adjacent to the j-th bit in the grid are shifted
// to the rightmost position and OR'd together:
b << m | // this is the bit 'below'
b >> m | // this is the bit 'above'
(j % m && b * 2) // this is the bit 'on the right', which is valid
| // only if j mod m = 0
(~j % m && b / 2) // this is the bit 'on the left', which is valid
// only if (j + 1) mod m = 0
) >> j & 1 // test the least significant bit of the result
? // if one of the above tests is successful:
g(j) // do a recursive call
: // else:
0 // abort
: // else:
k < M ? 0 : M = k // if k is better than M, update M to k
)(k = m * n) // initial call to g with j = k = m * n
) | M // end of map(); return M
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands)
```
*LIô2FD€ü2€`sø}\«æʒ˜D¢2ô2@PO_}éθg
```
Input as two loose integers.
[Try it online](https://tio.run/##yy9OTMpM/f9fy8fz8BYjN5dHTWsO7zECkgnFh3fUxhxafXjZqUmn57gcWmQElHcI8I@vPbzy3I70//@NuEwB) or [verify the small test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWWCS@h/LZ@Iw1uM3FweNa05vMcISCYUH95RG3No9eFlpyadnuNyaJERUN4hwD@@9vDKczvS/@v8j4421DGK1Yk21jEEkoY6liDSAMwxAksY6RgDSVOoIuPYWAA).
**Explanation:**
Step 1: Get a list of all possible dominos based on the input-dimensions:
```
* # Multiply the two (implicit) inputs together
L # Pop and push a list in the range [1, n*m]
Iô # Split it into parts equal to the second input
2F # Loop 2 times:
D # Duplicate the matrix at the top of the stack
€ # For each row:
ü2 # Create overlapping pairs
€` # Flatten it one level down to a list of pairs
s # Swap so the copy is at the top of the stack
ø # Zip/Transpose; swapping rows/columns
}\ # After the loop: discard to leftover copy
« # And merge the two list of pairs together
```
Step 2: Create all possible combination of dominos:
```
æ # Get the powerset of this list of pairs
```
Step 3: Filter every possible combination so only valid ones are left that comply to all four rules:
```
ʒ # Filter the list of list of pairs by:
˜ # Flatten the list of pairs to a list of integers
D # Duplicate it
¢ # Count each integer in the flattened list
2ô # Convert it back to a list of pairs
# (unfortunately `¢` doesn't vectorize apparently, otherwise `D˜¢` would
# have sufficed..)
2@ # Check for each count if it's >= 2
P # Check if this is truthy for both values within a pair
O # Sum the checks of all pairs together
_ # And check that this is 0 (thus falsey for all of them)
} # Close the filter
```
Step 4: Get the length of the longest valid board of dominos, and print it as our result:
```
é # Sort the list of list of pairs by length
θ # Pop and push the last/longest list of pairs
g # And pop and push its length
# (after which it is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes
```
ṙJḊÑ$€¬Ȧ
ẎQL=³×⁴¤
pp`_/ṢF⁼ʋƇØ.ŒPÇƇÑƇL€Ṁ
```
[Try it online!](https://tio.run/##AVQAq/9qZWxsef//4bmZSuG4isORJOKCrMKsyKYK4bqOUUw9wrPDl@KBtMKkCnBwYF8v4bmiRuKBvMqLxofDmC7FklDDh8aHw5HGh0zigqzhuYD///8y/zU "Jelly – Try It Online")
This is kinda (very) clunky lol. Haven't used Jelly in a while.
Will golf for a bit before I give a full explanation, but basically how it works is it generates all of the cells, and then gets all adjacent pairs to get all dominoes, then takes the powerset and filters for valid states by two conditions: firstly, using the second line to ensure all squares are covered, and secondly, using the first line to ensure condition 4 by checking all modifications of removing one domino and making sure all fail condition 2 using the second line.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 60 bytes
```
NθNη⊞υ×1×θηFθFηFυ«⎚⪪ληJκι¿∧ΣKK№KV1«UMΦKVΣμ0¹⊞υ⪫KAω»»⎚I⌈Eυ№ι0
```
[Try it online!](https://tio.run/##ZU9Li8IwED63vyL0NIEKKuzJkxQEBaWg7D2rkQzmUdPEXRB/e3bSdpeFzWXmm8z3mLMS/uyETmlruxgO0XxID3e@Kv9iRbiNvYJYsxMa2UO1qH7ae80U57RxdZ4RlQ1VTTVy9iyLRkvhgXaK1qMNcOw0BtADk4a7aLqTg1vNMEO8MljbCxyjgVbKG3Bes8ZFImb47uxBRiOsBZpTEnLPJsVedI0z9HGBDepAwf@vZ02T9ap5lb2mQIuxn27cObQDd611Jn0OKV/lq/w9ZKQ1og@wF19oSJbsM3kMiqNDfquUluwtzR76Gw "Charcoal – Try It Online") Link is to verbose version of code. Brute force, so `4 × 7` times out on TIO. Explanation:
```
NθNη
```
Input the dimensions of the rectangle.
```
⊞υ×1×θη
```
Start a breadth-first search with a string of `1`s representing an empty rectangle.
```
FθFη
```
Loop over each row and column.
```
Fυ«
```
Loop over each rectangle discovered so far.
```
⎚⪪λη
```
Wrap the string to the size of the rectangle and output it on a clear canvas.
```
Jκι
```
Jump to the cell under consideration.
```
¿∧ΣKK№KV1«
```
If both the cell and at least one neighbour are empty, then:
```
UMΦKVΣμ0
```
Change all of the neighbours to `0`s (somewhat arbitrary choice; any non-digit except `-` would also work).
```
¹
```
Change the cell itself to `-` (chosen for golfiness of course).
```
⊞υ⪫KAω
```
Save the resulting rectangle.
```
»»⎚I⌈Eυ№ι0
```
Print the maximum number of dominoes that were placed. (I can't believe that it's possible for the code to place more dominoes and yet fail to cover the rectangle than its best result that does cover the rectangle.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
pŒcạ/SỊƊƇŒPẎċⱮⱮ$Ṃ€ṀỊƲƇṪL
```
A dyadic Link accepting the dimensions which yields the maximal number of dominos which may be placed.
**[Try it online!](https://tio.run/##y0rNyan8/7/g6KTkh7sW6gc/3N11rOtY@9FJAQ939R3pfrRxHRCpPNzZ9KhpzcOdDSDpTcfaH@5c5fP/v15FRYUeFxBXVHBxOTpWuLlxVTg7gzhOFS4V7lASqAAIgKSrK1Dmv9F/UwA "Jelly – Try It Online")** (Too slow for the last three test-cases, but [here](https://tio.run/##y0rNyan8/7/g6KTkh7sW6gc/3N11rOtY@9FJAQ939R3pfrRxHRCpPNzZ9KhpzcOdDSDpTcfaH@5c5fP/8HJ9oOD//9HRhjoKRrE6CiDaGEpbQmlDAxDDCKrACKoASJuCaGMoH0ibxMYCAA) are all the others.)
### How?
Make all grid-contained dominos as pairs of coordinates, then filter the power-set of these to those sets which don't contain any domino whose coordinates are both contained by others, then return the length of the longest such set.
```
pŒcạ/SỊƊƇŒPẎċⱮⱮ$Ṃ€ṀỊƲƇṪL - Link: n; m
p - Cartesian product (all coordinates)
Œc - all pairs (of coordinates)
Ƈ - filter keep those for which:
Ɗ - last three links as a monad:
/ - reduce (the pair) by:
ạ - absolute difference
S - sum
Ị - insignificant? (effectively: equals 1?)
(-> all grid-contained dominos)
ŒP - power-set (ordered by length)
Ƈ - filter keep those (sets of dominos) for which:
Ʋ - last four links as a monad:
$ - last two links as a monad:
Ẏ - tighten (-> list of all coordinates used)
Ɱ - map (across the dominos in the set) with:
Ɱ - map (across the coordinates in the domino) with:
ċ - count (of the coordinate in all coordinates used)
Ṃ€ - minimum of each
Ṁ - maximum
Ị - insignificant? (effectively: equals 1?)
Ṫ - tail
L - length
```
] |
[Question]
[
[Question inspired by [Can you calculate the average Levenshtein distance exactly?](https://codegolf.stackexchange.com/questions/197565/can-you-calculate-the-average-levenshtein-distance-exactly) . Thank you Anush. ]
The [longest common substring](https://en.wikipedia.org/wiki/Longest_common_substring_problem) between two strings is the longest substring which is common to both. Please note this is *not* the same as the longest common **subsequence** whose fastest algorithm takes quadratic time.
The challenge is to compute the average length of the longest common substring between two independent and uniformly random chosen binary strings of length `n` each. Your output must be exact but can be given in any easy to understand human readable form.
# Examples for `n = 1..12`
* 1/2
* 9/8
* 7/4
* 295/128
* 361/128
* 6741/2048
* 15217/4096
* 8389/2048
* 291431/65536
* 2500643/524288
* 2657159/524288
* 22420789/4194304
# Score
Your score is the highest value of ùëõ you can reach. I will run your code on my Linux machine for 1 minute and then kill the job to get the score.
I will maintain a leaderboard that shows the best score for each language used in an answer.
# Worked example
Following a request, here is the full set of distances for `n = 3`. I have not include strings B and A if A and B are already listed. This is because the distance function is symmetric.
```
000 000 3
000 001 2
000 010 1
000 011 1
000 100 2
000 101 1
000 110 1
000 111 0
001 001 3
001 010 2
001 011 2
001 100 2
001 101 2
001 110 1
001 111 1
010 010 3
010 011 2
010 100 2
010 101 2
010 110 2
010 111 1
011 011 3
011 100 1
011 101 2
011 110 2
011 111 2
100 100 3
100 101 2
100 110 2
100 111 1
101 101 3
101 110 2
101 111 1
110 110 3
110 111 2
111 111 3
```
# Leaderboard
* `n = 22` in **C++** by my pronoun is monicareinstate.
* `n = 18` in **Rust** by Plasma\_000.
* `n = 14` in **C** by Mitchel Spector.
* `n = 11` in **Python** with pypy 3 by Alex.
[Answer]
# C++, n = 21 (40s on an AMD Ryzen 5 2500U)
This used to be a fast brute force answer that got up to n=17. That is currently preserved in the revision history.
```
#include <cstring>
#include <omp.h>
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <bitset>
#include <random>
typedef unsigned uint;
typedef unsigned char byte;
const int threadnum = 8;
const int maxn = 22; //for 24 bytes total size of Row
struct Row; struct hasher { size_t operator ()(const Row& row) const; };
struct Row
{
char max = 0;
std::array<char, maxn+1> row {0};
Row() { }
Row(int nmax)
{
max = nmax;
}
bool operator ==(const Row& rhs) const
{
const uint64_t* x = reinterpret_cast<const uint64_t*>(this);
const uint64_t* y = reinterpret_cast<const uint64_t*>(&rhs);
return x[0] == y[0] && x[1] == y[1] && x[2] == y[2];
}
};
uint64_t rotl(uint64_t x, char a)
{
return (x << a) | (x >> (64 - a));
}
size_t hasher::operator() (const Row& row) const
{
const uint64_t* mem = reinterpret_cast<const uint64_t*>(&row);
//I tried really many different hashes...
uint64_t h = mem[0]; h += rotl(h, 4);
h ^= mem[1]; h += rotl(h, 4);
h ^= mem[2]; h += rotl(h, 4);
return h;
}
const short hashTableSize = 1009;
struct Map
{
std::array<std::pair<Row, int>, hashTableSize> table {};
Map()
{
}
void add_or_add(const Row row, const int delta)
{
size_t hash = hasher()(row) % hashTableSize;
while(table[hash].second != 0 && !(table[hash].first == row))
{
hash++;
if(hash == hashTableSize) hash = 0; //just loop :)
}
if(table[hash].second == 0)
table[hash].first = row;
table[hash].second += delta;
}
void clear()
{
std::memset(table.data(), 0, sizeof(table));
}
};
constexpr uint bitRev(uint n)
{
n = ((n >> 1) & 0x55555555) | ((n << 1) & 0xaaaaaaaa);
n = ((n >> 2) & 0x33333333) | ((n << 2) & 0xcccccccc);
n = ((n >> 4) & 0x0f0f0f0f) | ((n << 4) & 0xf0f0f0f0);
n = ((n >> 8) & 0x00ff00ff) | ((n << 8) & 0xff00ff00);
n = ((n >>16) & 0x0000ffff) | ((n <<16) & 0xffff0000);
return n;
}
constexpr bool is_substring(int target, char n, short subs, char m)
{
//n=2, m=1 -> i from 0 to 1
int max = n-m+1;
bool flag = false;
for(int i = 0; i < max; i++)
flag |= (((target >> i) ^ subs) & ((1<<m) - 1)) == 0;
return flag;
}
int supermax = 0;
int main()
{
uint n; std::cin >> n;
std::vector<uint64_t> sums(threadnum);
uint64_t sum = 0;
#pragma omp parallel for num_threads(threadnum) schedule(dynamic)
for(uint sa = 0; sa < 1<<~-n; sa++) //the second half is the bitwise complement of the first one
{
uint sb = bitRev(sa);
sb ^= -(sb >> 31);
sb >>= 32 - n;
if(sb < sa) continue;
//find a lower bound = len(the shortest non-substring of sa) - 1
//if Row.max is immediately set to it, that reduces the number of states slightly
char lb = 0; bool found = false;
for(char len = 0; len < 10; len++)
{
for(short j = 0; j < (1<<len); j++)
if(!is_substring(sa, n, j, len))
{
lb = len - 1;
goto out;
}
}
out:;
Map dpcur;
Map dpnext;
dpcur.add_or_add(Row(lb), 1);
int ans = 0;
for(char j = 0; j < n; j++)
{
for(auto[row, cnt] : dpcur.table)
{
if(!cnt) continue;
Row nr0 {}, nr1 {};
nr0.max = nr1.max = row.max;
for(char i = 0; i < n; i++)
{
Row& r = (sa >> i)&1 ? nr0 : nr1;
r.row[i+1] = row.row[i] + 1;
}
char n0max = 0, n1max = 0;
for(char i = 0; i < 23; i++)
n0max = std::max(n0max, nr0.row[i]);
for(char i = 0; i < 23; i++)
n1max = std::max(n1max, nr1.row[i]);
//possibly, cut an entire would-be branch that would never improve!
if(n0max + n - j - 1 <= nr0.max)
ans += (cnt * nr0.max) << (n - j - 1);
else
nr0.max = std::max(nr0.max, n0max), dpnext.add_or_add(nr0, cnt);
if(n1max + n - j - 1 <= nr1.max)
ans += (cnt * nr1.max) << (n - j - 1);
else
nr1.max = std::max(nr1.max, n1max), dpnext.add_or_add(nr1, cnt);
}
std::memcpy(dpcur.table.data(), dpnext.table.data(), sizeof(Map));
dpnext.clear();
}
for(auto[row, cnt] : dpcur.table)
ans += cnt * row.max;
sums[omp_get_thread_num()] += ans;
if(sb != sa)
sums[omp_get_thread_num()] += ans;
}
for(uint64_t e : sums) sum += e;
sum *= 2;
printf("%ld\n", sum);
uint64_t num = sum, denom = 1ll<<(2*n);
while(num % 2 == 0) num /= 2, denom /= 2;
printf("%ld/%ld\n", num, denom);
}
```
This uses OpenMP for multi-threading. To be compiled with `clang++ -std=c++17 -Ofast -march=native -flto -fopenmp file.cpp`.
## Explanation I tried (please don't use it as a Rust translation guide)
The longest common substring can be found in \$O(n^2)\$ time via dynamic programming. That dynamic programming can be calculated (if the strings are \$s\$ and \$t\$) via the formula $$dp\_{i,j} = \begin{cases}dp\_{i-1,j-1} + 1& s\_i = t\_j\\0& \text{otherwise}\end{cases}$$
(and then the answer is just the highest value in \$dp\$). A naive solution would be to iterate over pairs of strings of length \$n\$ (resulting in \$O(4^n n^2)\$ time complexity). However, instead of simply doing that, my program only iterates over all possible values of the first string. Then, it simply does that, but instead of storing a proper dynamic programming array (that wouldn't be possible because there is no second string), it stores an array of all *possible* rows in it with counters of how many ways exist to reach this row. To calculate the next array of possible rows from the current array of possible rows, my program simply tries all of them with both possible values of the next bit in the second string. This leads to a speedup, because if two prefixes of the second string lead to the same state, they can be "merged" into one execution path.
I suspect this is similar to the optimization from the top answer in a similar challenge but for Levenshtein distance, but the explanation there is so bad I couldn't understand it at all.
The optimization that got this to 21: if at a certain point a possible row is encountered such that all its numbers are too small to ever improve the length of the longest substring in it, it can be directly calculated how much it will add to the answer.
Takes input as a single number from `stdin`. Outputs `734551/131072` for 13, `392340511/67108864` for 14, `1630366263/268435456` for 15, `6751032665/1073741824` for 16, `6967595579/1073741824` for 17, `114759115773/17179869184` for 18, `235733542633/34359738368` for 19, `1933121200141/27877906944` for 20 and `7912473298597/1099511627776` for 21.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), n=12 (~53s TIO)
```
t=0;
For[i=0,i<2^a,i++,
For[j=0,j<2^(a-1),j++,
t=t+Length@LongestCommonSubsequence[IntegerDigits[i,2,a],IntegerDigits[j,2,a]]]]
```
[Try it online!](https://tio.run/##Vc6xCoMwFIXh3ae4o2JKNasNFCyFgkOhY1BI5RJvIAnV6/OnsVvP@P3L8YYX9IZpNsmAglZ2iVXTFfe4alKNoIucjKC6FgUAHOqyuqylObWVcLnAkYAV1wMGy8t1iMHixn30PobX/t7ws2OYUT8Co8X1RpZ40ySkMKP4R/fDvPRcKbCWwOcyf6gmOab0BQ "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/) ~~308~~ 293 bytes, n=10 (30sec TIO)
```
a=lambda S,T:max((*(i+1 for i in range(len(S)) for j in range(len(S)-i)if S[j:j+i+1]in T),0));b=lambda i,n:'0'*(n-len(bin(i)[2:]))+bin(i)[2:]
for n in range(1,11):m=2**n;t=sum([a(b(i,n),b(j,n))for i in range(m)for j in range(m)]);y=bin(t);v=2**(len(y)-len(y.rstrip('0')));print(t/v,'/',4**n/v)
```
[Try it online!](https://tio.run/##XY5BboMwEEX3PYV3zAenhDQrI05BdoiFrSbtoHiCHBeV01ODVEViNZo/@m/eOMfvh3wsi23u1rtPq1p9Md7@EuXERaVuj6BYsahg5etK96tQC2zxsI8PDL6pthvMUKRun84X6CNQu386azHZMctJDmvHsRCjO5keKF7L24qXF77SVQXjm1OeSx2b54@nzpKjRIN2NKSBnajHTtGjRz0365OIelpZm/aMzWR@D88YeKRkh2Q8BpZIsZx0Vmb6nB6XE5blDw)
Not elegant or super fast but it's the first time I've been able to get something like this on so few lines. Potential speed up possible with numpy functions.
I feel like this problem is similar to [Project Euler Question 701](https://projecteuler.net/problem=701). Maybe with an algorithm for that this problem could be done in sub-exponential time.
[Answer]
# Rust, (n=15 ~6 sec, n=16 ~25 sec on 2.5GHz intel i7)
More heavily parallelised rewrite of @monicareinstate's answer in rust
>
> src/main.rs
>
>
>
```
use rayon::prelude::*;
const MAX_N: usize = 22;
const ARRAY_SIZE: usize = 1 << MAX_N;
static mut LOOKUP: [u8; ARRAY_SIZE] = [0; ARRAY_SIZE];
#[inline]
fn longest_sub(left: u32, right: u32, bits: u8) -> (u8, u8) {
// Uses of unsafe are sound here since we are only reading immutably
let mask = (1u32 << bits) - 1;
let unshifted = mask & !(left ^ right);
let max_unshifted = unsafe { *LOOKUP.get_unchecked(unshifted as usize) };
let max_shifted = (1..bits)
.map(|shift| {
let mask = (1u32 << (bits - shift)) - 1;
let shift_l = mask & !((left >> shift) ^ right);
let shift_r = mask & !(left ^ (right >> shift));
unsafe {
std::cmp::max(
*LOOKUP.get_unchecked(shift_l as usize),
*LOOKUP.get_unchecked(shift_r as usize),
)
}
})
.max()
.unwrap();
let max = std::cmp::max(max_unshifted, max_shifted);
if left == right {
(max, 1)
}
else {
(2 * max, 2)
}
}
#[inline]
fn calculate(bits: u8) -> (u64, u64) {
for number in 1..1usize << bits {
// Safe since we have no other references to LOOKUP in the current program
unsafe {
*LOOKUP.get_unchecked_mut(number) = 1 + LOOKUP.get_unchecked(number & (number >> 1))
}
}
(0..1u32 << bits)
.into_par_iter()
.flat_map(move |left| {
(left..1u32 << bits)
.into_par_iter()
.map(move |right| longest_sub(left, right, bits))
})
.map(|(max, weight)| (max as u64, weight as u64))
.reduce(|| (0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
}
fn main() {
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let line = line.trim();
let number = line.parse().unwrap();
let (num, denom) = calculate(number);
let (num, denom) = {
let (mut a, mut b) = (num, denom);
while a % 2 == 0 && b % 2 == 0 {
a /= 2;
b /= 2;
}
(a, b)
};
println!("{}/{}", num, denom);
}
```
>
> Cargo.toml
>
>
>
```
[package]
name = "golf"
version = "0.1.0"
authors = ["Plasma_000"]
edition = "2018"
[profile.release]
opt-level = 3
lto = true
[dependencies]
rayon = "1.3"
```
>
> Build with
>
>
>
```
RUSTFLAGS="-Ctarget-cpu=native" cargo +nightly build --release
```
Using nightly compiler 1.43.0
This performs a very slightly faster than the @monicareinstate's current answer on my machine:
```
‚ùØ time "echo 15 | ./target/release/golf"
Benchmark #1: echo 15 | ./target/release/golf
Time (mean ± σ): 5.872 s ± 0.114 s [User: 21.332 s, System: 0.127 s]
Range (min … max): 5.665 s … 6.017 s 10 runs
```
VS @monicareinstate's
```
‚ùØ time "echo 15 | ./a.out"
Benchmark #1: echo 15 | ./a.out
Time (mean ± σ): 5.983 s ± 0.092 s [User: 22.038 s, System: 0.120 s]
Range (min … max): 5.868 s … 6.157 s 10 runs
```
EDIT: well done @monicareinstate on your latest edit, you have me beat :)
[Answer]
# Java, n=11 (~30-35 sec on TIO)
```
import java.util.ArrayList;
import java.util.List;
class Main{
public static void main(String[] args){
for(int n=1; ; n++){
String binaryFormat="%"+n+"s";
int sum=0, c=0;
double powerOf2=Math.pow(2,n);
for(int a=0; a<powerOf2; a++){
String binaryA=toBinary(n,a);
for(int b=0; b<powerOf2/2; b++){
String binaryB=toBinary(n,b);
sum += solve(binaryA, binaryB);
c++;
}
}
System.out.println(n+": "+sum+"/"+c);
}
}
private static String toBinary(int n, int a){
return String.format("%"+n+"s", Integer.toBinaryString(a)).replace(' ','0');
}
private static int solve(String a,String b){
String s=a+2+b+3;
List<Integer> M = new ArrayList<>();
for(int c : s.getBytes())
M.add(c);
List<Integer> S = suffixList(M, 51);
List<Integer> I = new ArrayList(S);
for(int i=0; i<S.size(); i++)
I.set(S.get(i), i);
int L=0,R=0,m=0,h=0;
for(int i=0; i<S.size(); i++){
if(I.get(i)!=0){
int j=S.get(I.get(i)-1);
while(s.charAt(i+h)==s.charAt(j+h))
h++;
if(h>m){
int len = a.length();
int sortedMid = (i-j)*(j-len)>0 ? j
: (i-j)*(i-len)>0 ? len
: i;
if(len == sortedMid){
m=h;
L=i<j?i:j;
R=L+h;
}
}
if(h>0)
h--;
}
}
return R-L;
}
private static List<Integer> suffixList(List<Integer> s, int K){
int n=s.size();
s.add(0);s.add(0);s.add(0);
int n0=(n+2)/3, n1=(n+1)/3, n2=n/3;
int n02=n0+n2;
int adj=n0-n1;
int length=(n+adj)/3;
List<Integer> A=new ArrayList<>();
for(int x=0; x<n+adj; x++)
if(x%3!=0)
A.add(x);
A.add(0);A.add(0);A.add(0);
radixPass(K,s,A,2,n02);
radixPass(K,s,A,1,n02);
radixPass(K,s,A,0,n02);
List<Integer> B=new ArrayList<>();
for(int i=0; i<n02; i++)
B.add(0);
int[] t=new int[3];
int m=0;
for(int i=0; i<n02; i++){
int x=A.get(i);
int[] u=new int[3];
for(int j=x; j<x+3; j++)
u[j-x]=s.get(j);
if(t[0]!=u[0]||t[1]!=u[1]||t[2]!=u[2])
m++;
t=u;
B.set(x/3+x%3/2*n0, m);
}
if(n02==1)
for(int i=0; i<n02; i++)
A.set(i, 0);
else{
List<Integer> X = suffixList(B,m);
for(int i=0; i<n02; i++)
A.set(i, X.get(i));
}
List<Integer> I = new ArrayList<>(A);
for(int i=0; i<n02; i++)
I.set(A.get(i), i+1);
B = new ArrayList<>();
for(int x:A)
if(x<n0)
B.add(3*x);
radixPass(K,s,B,0,n0);
List<Integer> R = new ArrayList<>();
int p=0;
for(int T=adj; T<n02; ){
int x = A.get(T);
boolean bool = x>=n0;
int b = bool?1:0;
int i=(x-b*n0)*3-~b;
int j=B.get(p);
if(p==n0
|| (bool ? s.get(i)<s.get(j) || (s.get(i)==s.get(j)&&s.get(i+1)<s.get(j+1)) || (s.get(i)==s.get(j)&&s.get(i+1)==s.get(j+1)&&I.get(A.get(T)-n0+1)<I.get(j/3+n0))
: s.get(i)<s.get(j) || (s.get(i)==s.get(j)&&I.get(A.get(T)+n0)<I.get(j/3)))){
R.add(i);
T++;
}else{
R.add(j);
p++;
}
}
for(int i=p; i<n0; i++)
R.add(B.get(i));
return R;
}
private static void radixPass(int K, List<Integer> s, List<Integer> a, int o, int n){
int[] c=new int[K+3];
for(int i=0; i<n; i++)
c[s.get(a.get(i)+o)+1]++;
for(int i=0; i<K+3; i++)
c[i]+=c[i<1?c.length-1:i-1];
List<Integer> A = new ArrayList<>(a);
for(int i=0; i<n; i++){
int x=A.get(i);
int j=s.get(x+o);
a.set(c[j], x);
c[j]++;
}
}
}
```
NOTE: The fractions aren't normalized like in the challenge description. The decimal values the fractions represent are correct, though.
[Try it online with indefinite printing - times out after 60 sec](https://tio.run/##lVdLb@JIEL7nV/QgTdKOH9igvQCdCA4rRQnaVZLDSIhDY0xoL9jINhlnJuxfz1a/bDePkI2UuF1d/dWjv6pyYvpK3Xj@z8cHW2/SrEAxCLxtwVbeMMvo2wPLi/7FwZ4Uhyua52hMWfL7AqHNdrZiIcoLWsDjNWVztIYt/FRkLHmZTBHNXnKLayK0SDPMkgIlJOijPkpsW20gJNXRjCU0e/szzda0IK3vLTuxW3mrr5T42Xy7Jr6DQuJr6TwFFyK0SX9G2V@LDhnTYunBG@44iaWVtGkK5xAdaGVYN5zYc2NIinQkVjhxaAVVg8042KwCawPczIDbAxw1AWcNQMTDQjZBebp6jbAy7@hjhmZo2/Xr7sJ8Pr3lRbT20m3hbcBwsUowZLCHWjYYsFvtlh0qMH5id8EvMGOvtIj0DSqHK0fFfTki9VRFlkXFNkuUprcQl4Wry3LQXVJEL1HmaQypiKlleVm0WdEwwlfoyrnyr4Qvx7wQNy1yofyhjs6kckK95oTaHXtmd2VUnKEDZf8GjRFBSfQTVZwe3GAVvr7CEPVQ7r1ExeitiHJsWSqRY4/O51gny4R9Ath8u1iwksvx2EF/BEcV7/bt46c984wziA2evJz9isA3xIA/yoU7L4/gBHcOMwuuQJ3l5x6gBh7hl9fCUpfCp6CalGyB7xTkN@I3uMpPxkSa0xpu0KDezyVbRTj3wiXNhrBrLy1CqtcYXq0GTZdNmoLR5c3aKAxubhUlkCHqwfOlWGKD5pIBWRHNx9BSCMLMja1rHLugbN346BbFDe1zPz19ntXnYfE/EI5hMsPhBRbxkNptI2CE1mTZNwQPhA3iW9aLTfEjebANzd3F4Uqk1Dcy7rp9ox3smtX66D6cKjaTtA1m723ILnCvopKNPNckE7JcVI1v9Q8X9RmfQE/qWO2ug5KArwO57pCk3W3qgcC3k04tovMYRG4S1CJJHY4Cm1b7aBsYkjNNoOQFUw4EBizqEoQkl9@7vE6qPA9FQKVCGOrwDhcy@XTOyr9hXuJ7J3eGDowkv3NiL/hkz2/smcGNzgWnugGcN7rLaP9iYFQXAouvu9M6xesT/aVC/N0YzyUZqt7RGNoAvT2ArvFiUvZRPCihiaO49hCh7SR2yykR/RnHNeICFxN/@o1s4e/7ezEJxDoQ645Yd6Y1yrruRAXZ9qv4eXct210bbrjduU7go2LdmI3CDOcgCaw9f09klLOBYzIH6bRGqzzS2TGv7Yc5Q0bO@uBT5byZHyrVhttnRhAQZPg1hsj5M6znj62nwej8XC17w2YRAXjtv6Re97o8SvaRIPtRrj@etsttbvaJ@kxEQT/L0EyeApQM7blK/CxNVxFNxBO2yxtoNs1PzxkI@d5t0DPkjODSnQGDrOuu@@@suRWTkTCyaZJ3QwC4btzv7wgLk7fySwSSPdCUF5taSqpKuLxUMrgSrQvLr6hXUlhfXspBrxPhQr8FQCmMoTQgJOvi2OT7uqOmBY5Y41vwU4/IR0EL1vgKeK4rd9csJa0bN3Q3Dd1GNdQc30iOGxSXMCOzjPTAPDUuxf84NWfFTHTQwaw0BVQOz1Q@knqGQm8Mq954b@vuuF@bhtvhROaXKsft1LKDqU7A3tF73laNw2xqE/g7CG5D9enlBj3mBtOjw/NIzVHrMyfPjgOoCul/CY5rORXdJpzEUweVlZS/67jkfyy7j4//AA) or [try it online with given argument \$n\$](https://tio.run/##lVdbb@o4EH7nV/ggndZpLiSgfQHcCh5Wqlq0q7YPR0I8mBCKs5CgJLTpbrt/vTu@xQmX0kVq4ozH34zH38y4MX2hbrz46/OTbbZpVqAYBN6uYGtvlGX07Z7lxaB1MCfF4ZrmOZpQlvzTQmi7m69ZiPKCFvB6SdkCbWAKPxYZS56nM0Sz59zimgixpEAJSaJXdJsU0XOUYT459WfWQMzLNWjOEpq9/Z5mG1qQ9s@2ndjtvD2oIPLdhvgOCokvZYsUfIjQNn2Nsj@WXTKhxcqDL9x1EoW8TDPMl1JYg@hQq8LYtpVze@ZHpEjHYoQThyoYAzTnQPMKqANQ8xrUHti4DjavwBDfCrIJytP1S4SVYUcvqumFtq0/Plrm@fiWF9HGS3eFtwVzxTrBEKs@atsAbLc7bTsUIB8tflIZe6FFpI9KOVg5Jg7HEQGmah9ZVOyyRGl6S3EguDoQR5@ipzGkIqaW5WXRdk3DCF@iS@fSvzzphThPsXvlD3V05JQT6jMn1O7ac7sn48CpOFT2r9EEEcRpVZF3eI33Tj5EfZR7z1ExfiuiHFuWCufEo4sFDq1jsI8Am@@WS1ZyOZ446LfgqOLtvn38uGeecb6w4aOXs78j8A0xYIty4dbLI1jBncPMgiOwDNfvgekP8McZv9KE/xJUU5At8a2C/EH8GjP5yphIc1rDDWpke12xdYRzL1zRbASz9soipPqM4dOqdBFaGWoKo6vrTc2YNLeOEogQ9eD9XKxwzZbKaKgz0WICtYMgzNzYusKxC8rWtY9uUFzTPvfr6/XMrIfB/0A4hskaDi@x2A8xbjc2jNCGrAYNwT1hw/iG9eOm@IHc2w3Nj9bhSITUb0TcdY8VA5WtD@79qWRrkrbG7L0JWQXuGlU71yQTslxkjW8NDgdmjU@gGnWtTs9BScDHgRx3SdLp1fVA4NtJ14joIgaRmwRGJKnDUWDS6hwtAyNypgiUPGHKocCAgUlBCHL5s8fzpIrzSGyoVAgjvb3DgQw@XbDyT2iM@M7JnZEDrcfvnpgLvpjza3PNzY3PbU5VA1jfqC7j/YOBnlwILD7uzUyINyfqS4VYlRYRypGqHQMjBejdAbTBi0k5QPGwhCKOYuMhQrtp7JYzIuozjg3iEhdwO/hBdvB8fy@mgRgHYtwV4@7MoGxMJSrIblDtn1fXstOz4YQ73asErg4bZUImDpjhHCSBtefviYhyNnBM5iAd1midRzo6zWP71ewhY2dzcJc4b@aXCnXD7TMtCAgy@h5DZP8Zmf5j624wPt9Xy/6onkQAbvyX1OtdlUfJPhZkP8r1h9N2uc3tPlGfiEjoJ7m1Jk8BSm7tqQr8PE3XEU3EG6bLayg2NRajOQj53E3Qb8gZwaU7BwZZVz3333l9KiZjYWRbJ@@WALAp3O/vCAuTN/ImAsEeasqLSS0lVSZcXCgZHInWheF31CspjC8uZKPXgXCh3gKgFMaQGrAlq3Ws833f0aYFjmjwLfiZFvkgaMFqt4Cn2vW2nkpaN67pbo9fhQ3Ht5LjDYpLmHEzjXTDPNUuxT8zhrOiJzrooFc2BVQ2z1S@EtNDoTaGVW28s3V13M/NhtvhVMaXKsft1LKDmQ7A3tI7XlYbi9nMJvAcBjehunq5QZ@5wexo8zySc9T6ysmz7QCyQvpfguNaTkW1CafxzEFlJeXfel8f4jw@Pj8/g@A/).
Only just got it working, so will try to improve its performance later on.
**Short explanation of my solution:**
I first modified [*@MitchSchwartz*' Python 2 answer](https://codegolf.stackexchange.com/a/108016/52210) for the [*Longest common substring in linear time* challenge](https://codegolf.stackexchange.com/questions/47249/longest-common-substring-in-linear-time) so it will loop over the binary-string pairs we want to check. This challenge asks for the starting and ending index of the longest common substring between two strings, in lineair time (\$O(n)\$ complexity).
His answer implements ['The Skew Algorithm' described in Juha K√§rkk√§inen's & Peter Sanders' *Simple Linear Work Suffix Array Construction* article](http://www.cs.cmu.edu/%7Eguyb/realworld/papersS04/KaSa03.pdf), with the implementation of the Longest Common Prefix part using the algorithm described in [Toru Kasai's, Gunho Lee's, Hiroki Arimura's, Setsuo Arikawa's, and Kunsoo Park's *Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its Applications* article](http://web.cs.iastate.edu/%7Ecs548/references/linear_lcp.pdf).
Since we basically want to check all binary-string pairs \$A\$ and \$B\$, where \$A\$ are binary strings for integers \$a\$ in the range \$a=[0, 2^n)\$ and \$B\$ are binary strings for integers \$b\$ in the range \$b=[0,\frac{2^n}{2})\$ (similar as the existing Mathematica answer does), I've modified *@MitchSchwartz*' ungolfed answer to take the difference between the found indices, and sum those together for our numerator (the denominator will be \$n^{2n-1}\$ for any given \$n\$).
Here is that modified Python code:
[Try it online printing indefinitely](https://tio.run/##bVRNj6MwDL3zK3JZAU1Q@dBemHElehtNT@0xilZhShdQCQjoDnPZv961A1Wns3NpjONn@z077T7GsjXx9XosTmy4nE7V9Ev3vf7wBvHqpw4zcC6MN/gOGzjIUK0S9IXgGR77a7IjsqPZjsHYM0Qj5CZ2mD7WaAYmchhV6PURC3R6GDwtWmHwLqYq7M3m9l55gpXYqe3ZxCrDtEyNonv2Jgc58VbxSHGIlpiKYnptfhcWuQRWGIG/QaS@T1XDnIpsLd9krRRMM7Sek2cgpztyLmA4cvFZdWLTj0TxRYpPhDIR@18c0VdHiI6tpYrEHTZCA6Fzr5Rhj2Fsu7xQk@nEE2qz4TA@X9AYgX63clonHNtYx5hHQePckBCt8VhhAUz5MM6taLD2C2SryPmq3W0ILzJD8RRUPLJtJqtPKmSW@jPWe@C0FaEwRGsPEm864jMCSuWw97I6F2xESEzZJ8jkSGxymDY4eLQq8KYgRw7@Kgn@5g7NZis7CsJiHWAUw/qeN8gqrXisBLU4qgC3K1L@M/rrtJ79NUqCzdkJ5aw4DwUj2A1i7yxgCVa@n@45VOJpnBeKIOSpxVNnPX0xXnrD9hxbSom3Yx9Je/5T4PbmJNkAmruxy3PuJq7DDvCgeaM7r@2PYvDFz8iqf/hGfXpfB38ZwGEegMN2sMflKG/r8X08Un1BwLLVB0kf89ov4qMAvFSAu1TjaeNYOdMlcLlpmDZHRim1j2FtPxZHT1aiFrNP@TJacNiNPXfQVMbDEN9@7mHH7UUZQLkJ77IFO8cxWMp24kXUcF4Z3X/8QkKNHhkwN3T5MPae8bmbo37Dxb6Hrn2PIV6tzMxd37nTjWWewZyEBvE56e3fI3/ErGcULvUCy/@HUXUO83gzsUVX11dmZEa4wcYVeCvctSuwLw@fXUADNSjl9foP) or [try it online with given input \$n\$](https://tio.run/##bVNNb9swDL3rV2iHwVYkI/7ADkvLAM6taE7JURAKuXFmGbFi2M7mXvbXO0p2kKbrxaIpPpLvkWrfhups0/f3Q3mk/eV4NOOL7jr9Fvbima0ItXAqbdgzQnsOMlaLDH0xhJanbOnsxNnJZKdg/RmjEXObEqoPNZqRTQh1FTp9wAKt7vtQi7OweJe6KvTV5w6feYaV6PHc0ZEaS7VcWeXu6avs5cjPiieKQzLHGBfTafur9Mg50GAEfqNEfZ2qhimVs7V8lbVSME7QekqegxxvyKmA5ciFUXOk4/dM8VmKD4RykbJPjuSzI0bHxlNF4oQO0EBMbpVy7DFOfZcX1@Rq5Jlrs@EwfIMLWoP/buS4zDj2sUwxkYKGXKGQLPFYYAXMeTfPjWiw@BPki4R8Fu86hSeZo3oKDE98n9nigwy55/6I9e5IbUQsrOO1A4k3rSM0AGpF6J/KnEo6ICR12UfI5eDoFDCucfJoGQjHqEAObJFFfwvihrORrQvCYi1gFMX6YdhLszI8VcK1OKgI1ytR7BH99aqe/DVKgs35ERW0PPUldbArxN95wBysGFvtOBjxMEwb5SDOU4uH1nu6crh0lu44trRyvIl/JefT7xLXt3CS9aB5kAa84EEWELqHO80b3Ybn7iB6Jn4kXv39F@q7B7Zn8wD20wAI3cIOt6O67sfX8Uj1CQHzWu@l@5n2fhYfBeCVAlymGk8fR6uJrgNX64Zqe6AupWYYdu6G8hBKI2ox@RSTyYzDbvy5hcbYEEOY/93BlvuLKoJqHd9ki7aEWDB2CI1tL0PIGCmM1d3bCxJq9ECBBnHA@6ELLeNBEZD@4t6Do6tvdNPFwjqyOUwwJ/3HNGwSqLhHLKeN3lxBxX8gfB74rqZp5mLDSNthr9SKIFoHAi9FsAwE5sJ8NkrY@/vPfw) (which produces \$n=9\$ in about 25-30 sec on TIO).
Since I'm not too skilled with Python, I decided to port everything to Java which I use on a daily basis. This allows me to make performance enhancing modifications (which I will try to do later on) easier. And I also knew that the larger \$n\$ would become, the better the performance of the Java program in comparison to the Python program would be (which can also be seen by checking some \$n\$ in both programs on TIO - i.e. the inputs \$n=1,5,7,9\$ will take approximately 1.5, 2.25, 1.75, 4.0 seconds in Java, but 0.02, 0.1, 1.5, 30.0 seconds in Python 2 respectively.
**Long explanation:**
*TODO: I will describe the actual implementation and perhaps add some comments to the code later on. This already took long enough to modify and port to Java for now.*
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 1769 bytes, n=14 in 31 sec. on TIO
**n=15 in 2 min 7sec on my MacBook Pro (3.1 GHz Intel Core i7)**
**NOTE: If you test this program to see how far it can get in one minute,
change `#define END` to be some larger number, say `(17)`. The value
of `(14)` was picked so as not to time out in 1 minute on TIO.**
**Output will be computed from `n = START` to `n = END`.**
**Do not change the `#define CUTOFF` value -- this is the point at which long longs are needed, instead of just longs.**
```
#include <stdlib.h>
#include <stdio.h>
#define START (1)
#define END (14)
#define CUTOFF (15)
// Find length of longest common substring of binary numbers a and b, of length l.
int f(int a, int b, int l)
{
int i, j;
for (int lengthOfMatch=1, mask=1; lengthOfMatch<=l; lengthOfMatch++, mask = 2*mask+1)
{
for (i=0; i <= l-lengthOfMatch; i++)
{
for (j=0; j <= l-lengthOfMatch; j++)
{
if ( ((a>>i)& mask) == ((b>>j) & mask) )
{
if (lengthOfMatch == l)
return lengthOfMatch;
goto NextMatchLength;
}
} // for j
} // for i
return lengthOfMatch - 1;
NextMatchLength:
;
} // for lengthOfMatch
return 0;
} // f
int main(void)
{
for (int numberOfBits=START; numberOfBits <= END; numberOfBits++)
{
if (numberOfBits >= CUTOFF)
{
long long t=0;
for (int a=0;a<(1<<numberOfBits);a++)
{
for (int b=0; b<a; b++)
t += f(a, b, numberOfBits);
} // for a
// Make up for the entries f(a, a, numberOfBits) that weren't counted above.
t += numberOfBits*(1<<(numberOfBits-1));
printf("%d => %lld/%lld\n", numberOfBits, t, 1ll<<(2*numberOfBits-1));
}
else
{
long t=0;
for (int a=0;a<(1<<numberOfBits);a++)
{
for (int b=0; b<a; b++)
t += f(a, b, numberOfBits);
} // for a
// Make up for the entries f(a, a, numberOfBits) that weren't counted yet.
t += numberOfBits*(1<<(numberOfBits-1));
printf("%d => %ld/%ld\n", numberOfBits, t, 1l<<(2*numberOfBits-1));
}
}
exit(0);
} // main
```
[Try it online!](https://tio.run/##5VTJbtswEL3zKwYJ0oqWvChtL9UCdPMpiYHWvfVCSZRMhaYCiUoTBP71uqS2mraMXnorAZPS07zHMd8M42kWx/v9JRMxrxMKfiUTzqLZJkQGxgoNocuEpkxQ@Lb@8HUNlosH5MvdZ/X@Fv@J@fR9vVouFfhOgfM5LJlIgFORyQ0UKfBCZLSSEBfbbSGgqqNKlkxk@lvEBCmfQdTbiJYVECCKGjkNrRXgM8SEhNTSM3FAL1G7cIwAXtSveWMO5B7Sb2lRQhPeSqzSWyLjTeA6sCXVfeB65gc/4EeIbbehEMD1RD/Yrt5Kj5du7TYJFh4w8APgU0NBobbdcwzewM01Nx/l5iZ3RKEfLAULLIuEIcOvmpwxBIFCojDMMfQQHuOekexUjZS0Jj8jokZJZV0K8wxbK0ZGVsgC7uiTbMJuGo43Hrs7gXeg6ksfX45GQDbsOZYRTMFVWR1t/b6n9DkMagZZKXeaCw@1IQg1lbklTFiPBUswUuc51F5b0qv0I5NV0HSRZ2DaeNVKJtj63pa08sCID4Ou0TofevN0e7WTVBXVn8CQB1Eg8S3X9w/VsEeMGjushIEa6QqNfKKm04KUYAeqK1VHqm40pdGpM6S5GG7JPYX6oUHkhgIV6iKgVStDjmRUBJHwk5ZUvNaXRy0kTYBExSOdoYMcDkkT/T@NY5u6GA@H8qCuHZlaF1cJBCFccZ7M9fRDXJh7OyAdcDlXWteTU7WD2qS8oiN2/A9OPFP5r3zQNpx14a8m7BCiT0xaC9x1pu5ItN//ilNOsmo/Xb35DQ "C (gcc) – Try It Online")
---
**Sample output for \$n=15\$ from my MacBook Pro (3.1 GHz Intel Core i7) -- 2 min 7 sec.**
```
$ time ./l5
1 => 1/2
2 => 9/8
3 => 56/32
4 => 295/128
5 => 1444/512
6 => 6741/2048
7 => 30434/8192
8 => 134224/32768
9 => 582862/131072
10 => 2500643/524288
11 => 10628636/2097152
12 => 44841578/8388608
13 => 188045056/33554432
14 => 784681022/134217728
15 => 3260732526/536870912
real 2m6.814s
user 2m5.842s
sys 0m0.402s
```
] |
[Question]
[
[Sandbox Post](https://codegolf.meta.stackexchange.com/a/16815/78039)
**Intro**
The information panels are everywhere. When the technology became cheaper, the paper posters were transformed into luminous signs that show words that appear on one side and come out on the other, like the one on the figure:
[](https://i.stack.imgur.com/ANz2e.gif)
When one of these signs starts up, it usually starts empty and the text leaves from the right side to the left, moving until it disappears.
Its functionality is to go on and off the small light bulbs (LEDs) to give the sensation of movement.
If instead of text we only need to show numbers, the poster can be much less sophisticated using the so-called seven-segment markers like the following:
[](https://i.stack.imgur.com/KDiBZ.jpg)
In this case each number is represented by the combination on / off of only 7 light segments that allow to represent all the numbers:
[](https://i.stack.imgur.com/RaSXZ.png)
The question we ask ourselves is how many changes of lights (how many on and off) should be made to pass through one of these posters a certain number?
For example, to show the 123 in a 3-digit sign that starts with all the LEDs off we will have:
[](https://i.stack.imgur.com/bP58B.png)
This makes a total of 42 changes of lights.
---
**Challenge**
Given a non-negative number and a positive sign length calculate the number of lights changes.
**Rules**
* Assume input consist in a non-negative number (N >= 0) and a positive sign length (M > 0)
* Assume Sign length >= Number length (M >= digits(N))
**Test cases**
```
123, 3 => 42
45, 5 => 60
111, 3 => 12
98765, 10 => 220
0, 3 => 36
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~129~~ ~~126~~ ~~119~~ 104 bytes
```
def f(n,k,p=0):z=p<1or n>0;q=-~ord('}/lx2Z^o~z'[n%10])*z;return(z and f(n/10,k,q))+k*bin(p^q).count('1')
```
[Try it online!](https://tio.run/##HY7LDoIwFETX@hXdmLZ4lRbEBwgfYgOJCkSCuS0NJEoiv47AajKzOHPMt31p9MYxL0pSMoQaTCx42MfmKrUlmIioiXeDtjmjP/f98W6ZHnqqcCNFyp0@skXbWWQ9uWM@E1wpJkjD@bZ2HhUykzV8/9QdtoxKysdypkJNKiRKSc8HPwV1CCCYQkq51Mv5dAxgOgAlpiEN1ytjK2zJLMiBxgmFRZaPfw "Python 2 – Try It Online")
Thx for a big 15 bytes from [ovs](https://codegolf.stackexchange.com/users/64121/ovs).
As specified, takes a non-negative number and a positive sign length, and returns total changes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Dị“¤]þ+>~Œ¶?w‘Ø0j^ƝBFS×
```
A dyadic link accepting the integer to display on the left and the sign length on the right which yields the number of changes (also works if the number of digits in the integer to display is greater than the sign length).
**[Try it online!](https://tio.run/##ATYAyf9qZWxsef//ROG7i@KAnMKkXcO@Kz5@xZLCtj934oCYw5gwal7GnUJGU8OX////OTg3NjX/MTA "Jelly – Try It Online")**
### How?
During the entire show each 7-segment display (at some point) transitions from empty to the first digit, then to the second and so on, and finally from the last to empty again. The transitions each cost the bitwise XOR of the on-segments of the from-digit and to-digit (where empty is a "digit" with 0 on-segments). I stole the on-segments as integers from a previous revision of [ETHproductions' answer](https://codegolf.stackexchange.com/a/171069/53748), but any permutation of the 7 segments would do just as well.
```
Dị“¤]þ+>~Œ¶?w‘Ø0j^ƝBFS× - Link: integer to display, V; integer sign length, L e.g. 123, 3
D - cast V to decimal digits [1,2,3]
“¤]þ+>~Œ¶?w‘ - code-page indices list = [3,93,31,43,62,126,19,127,63,119]
ị - index into (1-based & modular) (vectorises) [3,93,31]
Ø0 - literal = [0,0] [0,0]
j - join [0,3,93,31,0]
Ɲ - pairwise application of:
^ - bitwise XOR [3,94,66,31]
B - convert to binary digits (vectorises) [[1,1],[1,0,1,1,1,1,0],[1,0,0,0,0,1,0],[1,1,1,1,1]]
F - flatten [1,1,1,0,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,1]
S - sum 14
× - multiply by L 42
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~104~~ ~~94~~ ~~93~~ 93 bytes
*Saved 1 byte thanks to @Shaggy*
```
B=n=>n&&n%2+B(n>>1)
F=(d,w,q)=>w*B(q^(q=d&&"w`>|i]_p}".charCodeAt(d%10)))+(d&&F(d/10|0,w,q))
```
[Try it online!](https://tio.run/##bc7JDoIwFIXhPU/RkEBupWJbBnXRJmLCWzgQShRDyhjZYHx0bHSnrv/7ndxbds/6vCubYalrVcxzIrSQ2nW1w70EtJQMW6kARUbSYiHHRQLtEVqhXNcez3IqD6fm@bD9/Jp1e7OwG0A5jGKMPTA3KagVoxN9czznte7rqvCr@gIoBcYDggJMUMgRtr5iGBEUmRbT38YY@0D2B24369hY8wRBnBs9vwA "JavaScript (Node.js) – Try It Online")
[Answer]
# Japt, ~~31~~ 30 bytes
Adapted from Jonathan's Jelly solution. Takes input in reverse order with the number to be displayed as a digit array.
```
*Vm!c"w]+>~?" pT ä^T x_¤¬x
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=KlZtIWMidwNdHys+fhN/PyIgcFQg5F5UIHhfpKx4&input=MwpbMSwxLDFdCi1R)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 280 bytes
```
import StdEnv,Data.List
~ =toInt
?s=sum[(~s>>p)rem 2\\p<-[0..6]]
$n l#j=repeatn l 0
#n=j++[~c-47\\c<-:toString n]++j
#k=[getItems(map((!!)[0,119,3,62,31,75,93,125,19,127,95])n)[i-l..i-1]\\i<-[0..length n]]
=sum(zipWith@(tl k)k)
@[u][]= ?u
@[u:x][v:y]= ?((bitxor)u v)+ @x y
@[][]=0
```
[Try it online!](https://tio.run/##RY7BjoIwEIbvfYoaPJRQCOCq0Vj14B5MPGziYQ@lh4oVq7QQGIzuwUdfFqLJ3v5v8s3Mn@ZK2tYUxyZX2EhtW23KogK8h@OnvdGNBBnsdA3oiRkUWwtoVbO6MZw86@WydCtlcJwk5cLnYRBMhEBDi3PnwipVKgldxiFyLLt4Hn@m/sc0SdKFP4diD5W2GbbC8y7IuTKeKdiCMjUxsiRkMHB5SKNoRkd0EtNRRKdjOhvRKB7TbhjFUzobC9e6XPt5EGg/EkmiXy1yZTM4d6cF6quSH11@azivCeT46l5dtOaN4ILhVdPH@V3w2/zRMyEHDfeicht8cz28vuNHZ/Ru2O5BVoAcbBtzUBVmOIpHHb6fMdzDqbEp6MJ2OETsH987L7f9TU@5zOrW3@7azcNKo9MXfOUSTkVl/gA "Clean – Try It Online")
There has to be a shorter way..
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
≔⁺×⁷0⭆S§⪪”)∧??%←⁶%*An”⁷IιθI×NΣEθ¬⁼ι§θ⁺⁷κ
```
[Try it online!](https://tio.run/##RY9NDsIgEIX3noKwGhJMYKHVuGqMiy5smtQLYG0qkdIfwHh7pLTVFyDz5hH4pnqKseqE8j41RjYaCuUM3GRbG0gowgwTiko7St1cRQ@Z7p2dLYQgtZl@1B8oeyUtYM45mzYLi8UymqX7q2OwHozN9xYFgylKwttnYSxIEkTRQE6bInxqIXZnvMiSu/ZejxNL6VqYEAeK8s7CZXBCGZB/yBDE4cJYL7Lq5P3xkOx3iDO/fasv "Charcoal – Try It Online") Link is to verbose version of code. Works by converting the input into the binary segment values, then counting the number of changes between each character. Explanation:
```
S Convert first input to string
⭆ Map over digits and join
”)∧??%←⁶%*An” Compressed segment value string
⪪ ⁷ Split into groups of seven characters
ι Current digit
I Convert to integer
§ Index into groups
0 Literal `0`
×⁷ Repeat seven times
⁺ Concatentate
≔ θ Assign to variable `q`
θ Variable `q`
E Map over characters
κ Current index
⁺⁷ Add seven
θ Variable `q`
§ Cyclically index
ι Current character
⁼ Compare
¬ Logical not
Σ Sum results
N Second input
× Multiply
I Cast to string
Implicitly print
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 88 bytes
Takes input as `(integer)(width)`.
```
n=>w=>[...n+'',g=n=>n&&1+g(n&n-1)].map(c=>s+=g(x^(x=Buffer('w$]m.k{%o')[c])),x=s=0)|s*w
```
[Try it online!](https://tio.run/##XYxLDoJAEAX3noKFQrfowPBTF83CaxBMCALxN0MYFRJNPDqOmhill12vap9dM5U3u/o8F3Jb9CX1guKW4oQxJmzLmlWkH8I0uV2BMMWcY8pOWQ05xcqmCroNdLS@lGXRgNWO0xM73CYPaWGSp4izjhS5eFfTts@lUPJYsKOsoATu@Qg@oqHPcYzAG/3zIEQIP/jFI3fAOee/Ph/6q@Ui0gnu6onmnjcMuF/9HfCj/gk "JavaScript (Node.js) – Try It Online")
### How?
Given a list \$\{d\_1,d\_2,\dots,d\_n\}\$ of \$n\$ digits and a display width \$w\$, the total number \$N\$ of light changes is given by:
$$N=({T'}\_{d\_1}+\sum\_{i=2}^n{T\_{d\_{i-1},d\_i}}+{T'}\_n)\times w$$
Where \$T\_{x,y}\$ is the number of light changes for a transition from digit \$x\$ to digit \$y\$ and \${T'}\_{x}\$ is the number of light changes for a transition from the blank digit to digit \$x\$ (or the other way around).
### Commented
```
n => w => // n = integer; w = width of display
[ ...n + '', // coerce n to a string and split it
g = n => // g = helper function counting the number of 1's
n && 1 + g(n & n - 1) // by defining it here, we also force an extra iteration
] // with an undefined digit (interpreted as the blank digit)
.map(c => // for each entry c in this array:
s += g( // add to s the result of a call to g():
x ^ (x = // XOR the previous value of x
Buffer('w$]m.k{%?o')[c] // with the new one, picked from a 10-entry lookup
) // gives undefined (coerced to 0) for the last entry
), // end of call to g()
x = s = 0 // start with x = 0 and s = 0
) | s * w // end of map(); return s * w
```
] |
[Question]
[
# Description :
Given `x` and `y` positions of two circles along with their `radii`, output the area of intersection of the two circle.
---
# Input :
You will be given following input :
```
array 1 = x and y positions of circle a
array 2 = x and y positions of circle b
radius = radii of the two congruent circles
```
## Input method :
```
([12 , 20] , [20 , 18] , 12) ---> two array and number
([12 , 20 , 20 , 18] , 12) ---> array and a number
(12 , 20 , 20 , 18 , 12) ---> all five numbers
('12 20' , '20 18' , 12) ---> 2 strings and a number
('12 20 20 18' , 12) ---> string and a number
('12 20 20 18 12') ---> one string
```
---
# Output :
* A non-negative integer (no decimal) equal to area of intersection of two circles.
* A string equal to the above mentioned integer.
### Note :
* Output must be >= 0, since area can't be negative.
* In case of decimal round down to nearest integer
---
# Examples :
```
([0, 0], [7, 0], 5) ---> 14
([0, 0], [0, 10], 10) ---> 122
([5, 6], [5, 6], 3) ---> 28
([-5, 0], [5, 0], 3) ---> 0
([10, 20], [-5, -15], 20) ---> 15
([-7, 13], [-25, -5], 17) ---> 132
([-12, 20], [43, -49], 23) ---> 0
```
---
# Winning criteria :
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each language wins.
---
# Suggestions :
* Provide a TIO link so it can be tested.
* Provide an explanation so others can understand your code
These are only suggestions and are not mandatory.
[Answer]
# JavaScript (ES6), 72 bytes
*Alternate formula suggested by @ceilingcat*
Takes input as 5 distinct parameters **(x0, y0, x1, y1, r)**.
```
with(Math)f=(x,y,X,Y,r)=>-(sin(d=2*acos(hypot(x-X,y-Y)/r/2))-d)*r*r*2>>1
```
[Try it online!](https://tio.run/##bZDBboMwDIbvewqOSZUM4iSUHuANdm@PCNpBVZEK0FaentkJ1bR0iW0pypfff3ytv@qpGfv7LAfXntf1u5879lHPHb@U7CEWcRQnMfKykmzqB9aWsKsbN7FuubuZPeRRLPLE0zEFzmXLdyNuqCq1Nm6Y3O38fnOf7MIykWDsfbWcJ9tK00SZt/9QDOXzCRMKELFWJDkK@qr/yEIRodKG5r7@sohmEUl9AZNeSGXpQDgZsLEo/khpxMAGXu2fqI69Sq9pKKnBAcexsbEBXVBjLCYn6cM2BiRz8yKKt5ocFMGJspvoi1UF4VuGaIPPQAfRbP0B "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), ~~81~~ ~~80~~ 77 bytes
*Saved 3 bytes thanks to @Neil*
Takes input as 5 distinct parameters **(x0, y0, x1, y1, r)**.
```
(x,y,X,Y,r,d=Math.hypot(x-X,y-Y))=>(r*=2)*r*Math.acos(d/r)-d*(r*r-d*d)**.5>>1
```
[Try it online!](https://tio.run/##bZBNbsMgEIX3PYWXgMA2f46zsG/QfbK0TNK0ikKErSo@vTsDjqqSImYQmm/ePPgavodpDJ/3Wdy8O63nbiUPvvADP/LAXfc@zJfystz9TB7iwBdxpLTrSWCdoiywWB5GPxFXBSocg0qAw1HGStv3ch39bfLXU3n1H@RMal7A3sVsKS22VVWFNG//obBljCeMqFIZa3nRgGDM@o@sajNU2DQ85l8W0Dojca6CwA4hLV4QRwM2F4UXSQ2YsomXuyeqc68iahoMHLCH79jY3IBucTAk06D0fvsGIBvzIgpVjQ7a5ETaTfTFqlTpWQZpA21KJ9F6/QE "JavaScript (Node.js) – Try It Online")
### How?
This is based on [a generic formula from MathWorld](http://mathworld.wolfram.com/Circle-CircleIntersection.html) for non-congruent circles:
```
A = r².arccos((d² + r² - R²) / 2dr) +
R².arccos((d² + R² - r²) / 2dR) -
sqrt((-d + r + R)(d + r - R)(d -r + R)(d + r + R)) / 2
```
where **d** is the distance between the two centers and **r** and **R** are the radii.
With **R = r**, this is simplified to:
```
A = 2r².arccos(d / 2r) + d.sqrt((2r - d) * (2r + d)) / 2
```
And with **r' = 2r**:
```
A = (r'².arccos(d / r') + d.sqrt(r'² - d²)) / 2
```
*Note*: If **d** is greater than **2r**, `Math.acos()` will return `NaN`, which is coerced to **0** when the right-shift is applied. This is the expected result, because **d > 2r** means that there's no intersection at all.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27 25 24~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
×,²I½
÷ÆAײ}_çHḞ
ạ/çḤ}
```
A full program accepting a list of the two centres as complex co-ordinates and the radius which prints the result (as a dyadic link it returns a list of length 1).
**[Try it online!](https://tio.run/##AUIAvf9qZWxsef//w5cswrJJwr0Kw7fDhkHDl8KyfV/Dp0jhuJ4K4bqhL8On4bikff///1stNysxM2osIC0yNS01al3/MTc "Jelly – Try It Online")**
To take the two co-ordinates as pairs add `Uḅı` to the main link, [like this](https://tio.run/##AUoAtf9qZWxsef//w5cswrJJwr0Kw7fDhkHDl8KyfV/Dp0jhuJ4KVeG4hcSx4bqhL8On4bikff///1tbLTcsMTNdLFstMjUsLTVdXf8xNw "Jelly – Try It Online").
### How?
```
×,²I½ - Link 1, get [√(s²d² - s⁴)]: separation of centres, s; diameter, d
, - pair = [s, d]
× - multiply (vectorises) = [s², sd]
² - square (vectorises) = [s⁴, s²d²]
I - incremental differences = [s²d² - s⁴]
½ - square root (vectorises) = [√(s²d² - s⁴)]
÷ÆAײ}_çHḞ - Link 2, get intersection area: separation of centres, s; diameter, d
÷ - divide = s/d
ÆA - arccos = acos(s/d)
²} - square right = d²
× - multiply = acos(s/d)d²
ç - call last Link (1) as a dyad (f(s,d)) = [√(s²d² - s⁴)]
_ - subtract (vectorises) = [acos(s/d)d² - √(s²d² - s⁴)]
H - halve (vectorises) = [(acos(s/d)d² - √(s²d² - s⁴))/2]
Ḟ - floor = [⌊(acos(s/d)d² - √(s²d² - s⁴))/2⌋]
- ...Note: Jelly's Ḟ takes the real part of a complex input so when
- the circles are non-overlapping the result is 0 as required
ạ/çḤ} - Main link: centres, a pair of complex numbers, c; radius, r
/ - reduce c by:
ạ - absolute difference = separation of centres, s
- ...Note: Jelly's ạ finds the Euclidean distance when inputs are complex
- i.e. the norm of the difference
Ḥ} - double right = 2r = diameter, d
ç - call last Link (2) as a dyad (f(s,d))
- implicit print
```
[Answer]
# Mathematica ~~66 57~~ 51 bytes
```
Floor@Area@RegionIntersection[#~Disk~#3,#2~Disk~#3]&
```
A `Disk[{x,y},r]`refers to the region circumscribed by the circle centered at `{x,y}` with a radius of `r`.
`RegionIntersection[a,b]` returns the intersection of regions `a`, `b`.
`Area` takes the area.
`IntegerPart` rounds down to the nearest integer.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 50 bytes
```
Floor@Area@RegionIntersection[#~Disk~#3,Disk@##2]&
```
[Try it online!](https://tio.run/##PY8xC8IwEIX/ymHAKQGTtFoHJYIIbuJaOhSJWtQW2myh/ev1Lokuee/uy71LPrV72k/tmls932EH8@nddb059LY2V/touvbcOtsP9ubQl2w6NsNrYpqTGsZUtZwvfdO60jM2cliA2MOCw71krKqWYIwB7/2Kwwqp30TNyf@bqJJMOLzPOazJJNWhKfJ0OWnsShxVoU1cSMqNtRe4SoZbQhEjJDcRKRwTWWAZJWzRRqQLiinIZ2u0AaV3YYF7Y2SRwmX8iZDqtzjTlE1jSo/j/AU "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~83 79 71~~ 66 bytes
```
f(a,b,c,d,e){float g=cacos(hypot(a-c,b-d)/e/2)*2;e*=(g-sin(g))*e;}
```
[Try it online!](https://tio.run/##dZDbaoQwFEXf/YowpZBIUs3NcbDTL@lLJl7By1DtQxnm12tPdJQWbcg5kMPaOzuxrLB2fKpaW3@m2Ws/pFX3Ur5566QxQwmDMceGXqilKc3ILa87M6DibI3telx@XbsBG2bphaUkyAJBfJFk/hkXrK9aXBDiZ8l9rNoBNQYG5OZdP@CU48Nz@t4eKMpxSBHs49Q1IQl6rCBAXP2Hw@ZTrQKHC7HlNUURGE9d/rUX8RZneg4y9V884OGWdhkElFMxrt1hkrgwesccXskloELPGn5ccbmTnU3eypW76ATftPA7YWTsQkBTkbvitHwP0JHaMwdCujTxnIrrxXwvOhfzU5VTKJAK@TAPvfv4bfPaFP3I6uYH "C (gcc) – Try It Online")
[Answer]
# Python 3, 106 chars with centers given as lists
```
from numpy import*
def f(a,b,r):d=min(1,hypot(*subtract(b,a))/2/r);return(arccos(d)-d*(1-d*d)**.5)*r*r//.5
```
# 100 chars with center coords separately
```
from math import*
def f(a,b,A,B,r):d=min(1,hypot(A-a,B-b)/2/r);return(acos(d)-d*(1-d*d)**.5)*r*r//.5
```
[Answer]
# [Haskell](https://www.haskell.org/), 83 bytes
```
(k!l)m n r|d<-sqrt$(k-m)^2+(l-n)^2=floor$2*r^2*acos(d/2/r)-d/2*sqrt(4*r*r-d*d)::Int
```
Just the formula, really. Type has to be declared as `Int` for NaN to map to 0 with `floor`.
[Try it online!](https://tio.run/##HctNCsIwEEDhq0whi5mRUIg/i2IP4CUKwSiWTJI6ydK7x@ri8a3ey9f4EOkd4yCUIIN@wtXWtzaD0SZa3AHF5t35KaWocayLY38vFcPoRiW7w78BT6ysNnCgabrl1pNfM8yw6ZobGMCB4AyXf8f@BQ "Haskell – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 69 bytes
```
with(Math)f=(a,b,c,d,r)=>(-sin(x=2*acos(hypot(a-c,b-d)/2/r))+x)*r*r|0
```
[Try it online!](https://tio.run/##FcJRCsIwDADQ6yQ1dWMgftUbeIgs3WxlNCMtOsG7V@S9J7@4iuW9@aJx6f2dW4I7t4RrAKaZhCIZhhv4mgscYXIsWiF9dm3AXmj2EYdpMMTTgc6cfccuWqpuy3nTB6ww0t@VLoj9Bw "JavaScript (Node.js) – Try It Online")
Short not sure if it can be golfed any further. Any suggestions are welcome
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 56 bytes
```
{{1>$_&&{$_-.sin}(2*.acos)}(abs($^p-$^q)/2/$^r)*$r²+|0}
```
[Try it online!](https://tio.run/##NYpBDsIgFET3noLFTwOltNAGuzB6FAgaSZqorbBqKJfyCF4MBePmTebNLFd326f7iiqLjikEcQJdVQE0a/30iLivW3OZPYnYnD0GtTBQT9L1HShHanDvF914TN6syOINNEF2djvMKZ8aNBZK0vwFpyKH4Fkx@ZsLh2JGKoZvYb1kMv9Gckgf "Perl 6 – Try It Online")
Takes circle coordinates as complex numbers.
[Answer]
# Excel, 119 bytes
```
=INT(IFERROR(2*E1^2*ACOS(((C1-A1)^2+(D1-B1)^2)^.5/2/E1)-((4*E1^2-((C1-A1)^2+(D1-B1)^2))*((C1-A1)^2+(D1-B1)^2))^.5/2,0))
```
Input taken as 5 separate variables:
```
x-coordinate y-coordinate x-coordinate y-coordinate radius
A1 B1 C1 D1 E1
```
[Answer]
# [Python 2](https://docs.python.org/2/), 109 bytes
```
from math import*
a,b,x,y,r=input()
d,R=hypot(x-a,y-b),2*r
print int(d<R and R*r*acos(d/R)-d*sqrt(R*R-d*d)/2)
```
[Try it online!](https://tio.run/##LU5bjsMgDPznFChfgEAtkPQhbS7BDWjIKvlIoJSVktNnbVKJGdnjsYe0lymu5hhiGPumaY7fHBe6@DLReUkxF0G8fMlN7jL385r@CuMkSNdPe4qFbcrLXb24NCKTlOe1UAALP476NVAnsvBD/LBwcVwF8XnnwpxwUAZ@MfyARDJu40AxX@jrwa6SwrtX7jj59vB0BSidpDeYVbbQq@40V0YBnQaAA6U7bNAGN7UFxXTnSN9RrcYWgVtPiAbVPnATqL3hwvObXCuLNx7nLY0/VNqceS1OWrAYy/8B "Python 2 – Try It Online")
Pretty straightforward. Get the distance between circles, and use `R=2r` as a substituite in the equation. `d<R and` to short-circuit if circles don't overlap.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 63 bytes
```
J@+^-hhQh@Q1 2^-ehQe@Q1 2 2K*2eQs&<JK-**KeQ.tcJK4c*J@-*KK*JJ2 2
```
[**Test suite**](https://pyth.herokuapp.com/?code=J%40%2B%5E-hhQh%40Q1+2%5E-ehQe%40Q1+2+2K%2a2eQs%26%3CJK-%2a%2aKeQ.tcJK4c%2aJ%40-%2aKK%2aJJ2+2&test_suite=1&test_suite_input=%5B0%2C0%5D%2C%5B7%2C0%5D%2C5%0A%5B0%2C0%5D%2C%5B0%2C10%5D%2C10%0A%5B5%2C6%5D%2C%5B5%2C6%5D%2C3%0A%5B-5%2C0%5D%2C%5B5%2C0%5D%2C3%0A%5B10%2C20%5D%2C%5B-5%2C-15%5D%2C20%0A%5B-7%2C13%5D%2C%5B-25%2C-5%5D%2C17%0A%5B-20%2C-4%5D%2C%5B-40%2C29%5D%2C7%0A%5B38%2C-18%5D%2C%5B46%2C-29%5D%2C10%0A%5B-29%2C33%5D%2C%5B-8%2C13%5D%2C15%0A%5B-12%2C20%5D%2C%5B43%2C-49%5D%2C23&debug=0)
Takes input as a triple consisting of two doubles and a number.
[Answer]
# T-SQL, 122 bytes
```
SELECT FLOOR(Geometry::Parse('POINT'+a).STBuffer(r).STIntersection(
Geometry::Parse('POINT'+b).STBuffer(r)).STArea())FROM t
```
(line break for readability only).
Uses MS SQL's support of [spatial geometry](https://docs.microsoft.com/en-us/sql/t-sql/spatial-geometry/spatial-types-geometry-transact-sql?view=sql-server-2017).
[Per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), SQL can take input from a pre-existing table **t** with `int` field **r** and `varchar` fields
**a** and **b** containing coordinates in the format `(x y)`.
My statement parses the coordinates as `POINT` geometry objects expanded by the radius using the function `STBuffer()`, then taking the `STIntersection()` followed by the `STArea()`.
If I am allowed to input the *actual* geometry objects in the table instead, then my code becomes almost trivial (48 bytes):
```
SELECT FLOOR(a.STIntersection(b).STArea())FROM t
```
] |
[Question]
[
*(with apologies to [Jim West](http://thinkexist.com/quotation/bridges-are-metaphors-for-everything-in-life-the/568318.html) for the title, and randomly inspired by Cisco's textual representation of their logo:* `.:|:.:|:.` *for the concept)*
Given an input integer `1 <= n <= 255`, output an ASCII art representation of a suspension bridge of distance `n` following the below construction rules:
* The start and end of the bridge (not counted in the `n` distance) are always `-|` and `|-`, so the bridge can appropriately connect to the highways next to it.
* The bridge doesn't extend downward (the roadway level, composed of the `-` row, is the bottom row).
* There can be at most two roadway pieces `--` in a row, any longer span requires suspension cables for support.
* The suspension cables `\` extend from the roadway up to the towers `|` in straight lines.
* The towers `|` must be tall enough to support the adjacent suspension cables, but no taller.
* The bridge must be balanced left-to-right about the middle point, favoring the center sections whenever possible.
* All of the above should result in a minimization of the cables, but just to be clear, the number of suspension cables must be minimized while still following the above rules.
To provide a visual representation, here are the expected outputs for `n = 1, 2, 3, ... 15` --
```
1
-|-|-
2
-|--|-
3
-|\-/|-
4
-|\--/|-
5
|\ /|
-|-\-/-|-
6
|\ /|
-|-\--/-|-
7
|\ /|
| \ / |
-|--\-/--|-
8
|\ /|
| \ / |
-|--\--/--|-
9
|\ /|
| \ / |
| \ / |
-|\--\-/--/|-
10
|\ /|
| \ / |
| \ / |
-|\--\--/--/|-
11
|\ /|
| \ / |
| \ / |
|\ \ / /|
-|-\--\-/--/-|-
12
|\ /|
| \ / |
| \ / |
|\ \ / /|
-|-\--\--/--/-|-
13
|\ /|
| \ / |
| \ / |
|\ \ / /|
| \ \ / / |
-|--\--\-/--/--|-
14
|\ /|
| \ / |
| \ / |
|\ \ / /|
| \ \ / / |
-|--\--\--/--/--|-
15
|\ /|
| \ / |
| \ / |
|\ \ / /|
| \ \ / / |
| \ \ / / |
-|\--\--\-/--/--/|-
```
### Input
A single positive integer [in any convenient format](https://codegolf.meta.stackexchange.com/q/2447/42963), `n > 9`.
### Output
The ASCII-art bridge following the above construction technique.
### Rules
* Leading or trailing newlines or whitespace are all optional, so long as the bridge characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so people can try out your code!
* [Standard loopholes](https://codegolf.meta.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]
## Python 2 , 173 bytes
```
i=input()
f=lambda b:'-|'+b[::-1].replace('/','\\')+-~(~i%2)*'-'+b+'|-'
b=(i*'/--')[:~-i/2]
for x in range(1,~-i/2):print f((len(b)-x)*'-'+b[:x]).replace('-',' ')
print f(b)
```
Mirror the value of b and add the central "-"
`f=lambda b:'-|'+b[::-1].replace('/','\\')+-~(~i%2)*'-'+b+'|-'`
Base pattern (right half of the bottom line)
`b=(i*'/--')[:~-i/2]`
Loop for non-bottom layers
`for x in range(1,~-i/2):`
Get the first x characters of the base pattern and complete with "-"
`(len(b)-x)*'-'+b[:x]`
Replace all - with spaces to print all the layers (except bottom)
`print f().replace('-',' ')`
Print bottom layer
`print f(b)`
[Answer]
# Befunge, 150 bytes
```
45&3+:00p4+2/:10p`-v
*\00g1-\`*2*+\1-!+v>1+:20p55+00g>::::00g1--!\:20g+00g-:0`\3%!
`1\*!%3\`0:-\g02:\<^_@#-g01<:,$_^#`\0:-1,g3+**4!-g01g02!:+*3*
|\/-
```
[Try it online!](http://befunge.tryitonline.net/#code=NDUmMys6MDBwNCsyLzoxMHBgLXYKKlwwMGcxLVxgKjIqK1wxLSErdj4xKzoyMHA1NSswMGc+Ojo6OjAwZzEtLSFcOjIwZyswMGctOjBgXDMlIQpgMVwqISUzXGAwOi1cZzAyOlw8Xl9AIy1nMDE8OiwkX14jYFwwOi0xLGczKyoqNCEtZzAxZzAyITorKjMqCiB8XC8t&input=MTU)
I've also provided an ungolfed version of the code which better demonstrates the architecture used in the construction of the bridge.
```
>4 5v
v+3 <&<
>:00 p4+v
v-`p0 1:/2<
*+\1-!+v>1+:20p55+00g>::::00g1--!\:20g+00g-:0`\3%!*\00g1-\`*2
-\g02:\<^_@#-g01<:,$_^#`\0:-1,g6+7+**4!-g01g02!:>#+<v*!%3\`0:
|\/->3#* *#`^#1\<
```
[Try it online!](http://befunge.tryitonline.net/#code=ICAgICAgICA+NCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgNXYKICAgICAgICB2KzMgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA8JjwKICAgICAgICA+OjAwICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHA0K3YKICAgICAgICB2LWBwMCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgMTovMjwKKitcMS0hK3Y+MSs6MjBwNTUrMDBnPjo6OjowMGcxLS0hXDoyMGcrMDBnLTowYFwzJSEqXDAwZzEtXGAqMgotXGcwMjpcPF5fQCMtZzAxPDosJF9eI2BcMDotMSxnNis3KyoqNCEtZzAxZzAyITo+Iys8diohJTNcYDA6CiAgICAgICAgfFwvLT4zIyogICAgICAgICAgICAgICAgICAgICAgICAgICAgICojYF4jMVw8&input=MTU)
The towers handle the input and parameter initialisation. The deck is made up two loops calculating the parts of the bridge that need to be output for each x,y coordinate. And the foundation holds the character table for the those bridge parts, as well as some other completely unrelated code.
**Detailed Explanation**
We start by calculating the width and height of the output area that will need to be iterated in order to render the bridge.
```
w = n + 3 (stored at 0,0)
h = (w + 4)/2 (stored at 1,0)
```
Note that the *y* range is not zero-based. The initial value is `5 - (h<5)` and is iterated up to *h* (the current value is stored at 2,0). The *x* value is iterated from *w* down to 0 and is stored on the stack.
The inner loop is just a series of boolean conditions determining whether a particular *x*,*y* coordinate matches any of the locations that require a non-space character. These calculations are based on two sliding offsets that follow the path of the suspension cables.
```
loff = y + x - w
roff = y - x
```
The various conditions are then determined as follows:
```
left_tower = (x == w-1)
left_suspension = (loff > 0) and (loff%3 == 0) and (x < w-1)
right_tower = (x == 1)
right_suspension = (roff > 0) and (roff%3 == 0) and (x > 1)
bridge_deck = (y == h)
```
To translate these conditions into the correct character offset, we just need to multiply each of them by an appropriate offset and sum the result. This calculation is performed as the conditions are evaluated. So it looks something like this:
```
char_offset = left_tower
char_offset += left_suspension * 2
char_offset += right_tower
char_offset += right_suspension * 3
char_offset += !char_offset * bridge_deck * 4
```
Note that the *bridge\_deck* value is merged in based on whether any of the other conditions have been met, since a suspension or tower character will take precedence over the deck.
The end result is an offset into the character table on the last line of the playfield. We simply output that character and repeat the loop.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~79~~ ~~59~~ 58 bytes
```
"\ "×¹<;£R.sð«¹3‹ið}.BvyD¹Éi¨}R„\/„/\‡«'|.øð.ø}ð'-‡¹2›i»}
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IlwgICJzw5fCuTw7wqNSLnPDsMKrwrkz4oC5acOwfS5CdnlEwrnDiWnCqH1S4oCeXC_igJ4vXOKAocKrJ3wuw7jDsC7DuH3DsCct4oChwrky4oC6acK7fQ&input=NQ).
Explanation:
```
"\ "× # Push n copies of "\ ".
¹<;£ # Push a[0:(n-1)/2]
R.s # Reverse, get substrings.
ð« # Append a space.
¹3‹ið} # If n < 3, push a space.
.B # Boxify.
vy } # For each...
D¹Éi¨}R # Dupe, if n is odd, a[0:-1].
„\/„/\‡ # Reverse the slashes.
«'|.øð.ø # Surround with | and a space.
ð'-‡ # Replace spaces with "-".
¹2›i } # If it's more than 2...
» # Join stack by newlines.
```
Found the better solution, the key was to return the following arrays for each number as follows:
```
1=[" "]
2=[" "]
3=["\"]
4=["\ "]
5=["\"," \"]
6=["\"," \ "]
7=["\"," \"," \"]
8=["\"," \"," \ "]
Etc...
```
[Answer]
## Batch, 241 bytes
```
@echo off
set t=set s=
%t%
for /l %%i in (1,1,%1)do call %t% %%s%%
%t% !%s%!
for /l %%i in (5,2,%1)do call:l 0
:l
%t%%s:\ = \%
%t%%s: /=/ %
%t%%s:! =!\ %
%t%%s: != /!%
%t%%s:\ !=\ /!%
if %1 gtr 0 %t%%s: =-%
echo %s:!=^|%
```
Note: Trailing space on line 5. Starts by building up a row of spaces, then adding cables as necessary, repeating to build towers to the desired height, ending by replacing any remaining spaces with road.
[Answer]
# WinDbg, 312 bytes
```
r$t4=@$t0+4;.block{j3>@$t0'r$t5=1';r$t5=(@$t0-1)/2};f8<<16 L@$t4*@$t5 2d;f8<<16 L@$t4*(@$t5-1) 20;.for(r$t1=0;@$t1<@$t5;r$t1=@$t1+1){eb2000001+@$t4*@$t1 7c;e1fffffe+@$t4*(1+@$t1) 7c;j2<@$t0'.for(r$t2=@$t1;@$t2>=0;r$t2=@$t2-3){e2000002+@$t4*@$t1+@$t2 5c;e1fffffd+@$t4*(1+@$t1)-@$t2 2f}'};da/c@$t4 8<<16 L@$t4*@$t5
```
Input is done by setting the pseudo-register `$t0`.
I feel like there should be a way to combine the two `for` loops into one... maybe some other golfing opportunities too...
This one works by filling the entire area with road, then replacing all but the last row with space, and finally building the columns and cables.
```
r$t4 = @$t0+4; * Set width to input+4
.block * Code block, needed for some reason...
{ * and .block+j is shorter than .if/.else
j 3>@$t0 * If input is less than 3...
'
r$t5 = 1 * ...set height to 1
'; * Implicit else...
r$t5 = (@$t0-1)/2 * ...set height to (input-1)/2
};
f 8<<16 L@$t4*@$t5 2d; * Fill area with -
f 8<<16 L@$t4*(@$t5-1) 20; * Fill all but last row with space
.for(r$t1=0; @$t1<@$t5; r$t1=@$t1+1) * For each row
{
eb 2000001+@$t4*@$t1 7c; * Build the left column with |
e 1fffffe+@$t4*(1+@$t1) 7c; * Build the right column (e is the same as last e* call, ie- eb)
j 2<@$t0 * If input is more than 2...
'
.for(r$t2=@$t1; @$t2>=0; r$t2=@$t2-3) * ...Enumerate from counter back to 0
{
e 2000002+@$t4*@$t1+@$t2 5c; * Build left cables with \
e 1fffffd+@$t4*(1+@$t1)-@$t2 2f * Build right cables with /
}
'
};
da /c@$t4 8<<16 L@$t4*@$t5 * Print the string in lines of length width
```
Sample output of 1-15:
```
0:000> .for(r$t0=1;@$t0<10;r$t0=@$t0+1){.printf"%d\n",@$t0;r$t4=@$t0+4;.block{j3>@$t0'r$t5=1';r$t5=(@$t0-1)/2};f8<<16 L@$t4*@$t5 2d;f8<<16 L@$t4*(@$t5-1) 20;.for(r$t1=0;@$t1<@$t5;r$t1=@$t1+1){eb2000001+@$t4*@$t1 7c;e1fffffe+@$t4*(1+@$t1) 7c;j2<@$t0'.for(r$t2=@$t1;@$t2>=0;r$t2=@$t2-3){e2000002+@$t4*@$t1+@$t2 5c;e1fffffd+@$t4*(1+@$t1)-@$t2 2f}'};da/c@$t4 8<<16 L@$t4*@$t5}
1
Filled 0x5 bytes
Filled 0x0 bytes
02000000 "-|-|-"
2
Filled 0x6 bytes
Filled 0x0 bytes
02000000 "-|--|-"
3
Filled 0x7 bytes
Filled 0x0 bytes
02000000 "-|\-/|-"
4
Filled 0x8 bytes
Filled 0x0 bytes
02000000 "-|\--/|-"
5
Filled 0x12 bytes
Filled 0x9 bytes
02000000 " |\ /| "
02000009 "-|-\-/-|-"
6
Filled 0x14 bytes
Filled 0xa bytes
02000000 " |\ /| "
0200000a "-|-\--/-|-"
7
Filled 0x21 bytes
Filled 0x16 bytes
02000000 " |\ /| "
0200000b " | \ / | "
02000016 "-|--\-/--|-"
8
Filled 0x24 bytes
Filled 0x18 bytes
02000000 " |\ /| "
0200000c " | \ / | "
02000018 "-|--\--/--|-"
9
Filled 0x34 bytes
Filled 0x27 bytes
02000000 " |\ /| "
0200000d " | \ / | "
0200001a " | \ / | "
02000027 "-|\--\-/--/|-"
10
Filled 0x38 bytes
Filled 0x2a bytes
02000000 " |\ /| "
0200000e " | \ / | "
0200001c " | \ / | "
0200002a "-|\--\--/--/|-"
11
Filled 0x4b bytes
Filled 0x3c bytes
02000000 " |\ /| "
0200000f " | \ / | "
0200001e " | \ / | "
0200002d " |\ \ / /| "
0200003c "-|-\--\-/--/-|-"
12
Filled 0x50 bytes
Filled 0x40 bytes
02000000 " |\ /| "
02000010 " | \ / | "
02000020 " | \ / | "
02000030 " |\ \ / /| "
02000040 "-|-\--\--/--/-|-"
13
Filled 0x66 bytes
Filled 0x55 bytes
02000000 " |\ /| "
02000011 " | \ / | "
02000022 " | \ / | "
02000033 " |\ \ / /| "
02000044 " | \ \ / / | "
02000055 "-|--\--\-/--/--|-"
14
Filled 0x6c bytes
Filled 0x5a bytes
02000000 " |\ /| "
02000012 " | \ / | "
02000024 " | \ / | "
02000036 " |\ \ / /| "
02000048 " | \ \ / / | "
0200005a "-|--\--\--/--/--|-"
15
Filled 0x85 bytes
Filled 0x72 bytes
02000000 " |\ /| "
02000013 " | \ / | "
02000026 " | \ / | "
02000039 " |\ \ / /| "
0200004c " | \ \ / / | "
0200005f " | \ \ / / | "
02000072 "-|\--\--\-/--/--/|-"
```
[Answer]
# Java 8, 423, 412 bytes
11 bytes saved thanks to Kritixi Lithos
golfed:
```
void f(int n){int i,j,k,t=n/2+n%2,u=t-2,q;char v=45;char[][]a=new char[t-1][n+4];for(char[]c:a)Arrays.fill(c,' ');a[u][0]=v;a[u][n+3]=v;for(q=0;q<t-1;q++){a[q][1]='|';a[q][n+2]='|';}for(i=t+1;i>1;i--){if((t-i)%3==0){k=u;for(j=i;j>1;j--)a[k--][j]='\\';}else a[u][i]=v;}for(i=n/2+2;i<n+2;i++){if((i-n/2-3)%3==0){k=u;for(j=i;j<n+2;j++)a[k--][j]='/';}else a[u][i]=v;}for(char[]w:a)System.out.println(new String(w));}
```
ungolfed:
```
void f(int n){
int i,j,k,t=n/2+n%2,u=t-2;
char v=45;
char[][] a=new char[t-1][n+4];
for (char[]c : a) Arrays.fill(c,' ');
a[u][0]=v;
a[u][n+3]=v;
// left and right columns
for (int q=0;q<t-1;q++){
a[q][1]='|';
a[q][n+2]='|';
}
// left part of base
for (i=t+1;i>1;i--){
if ((t-i)%3==0){
k=u;
for (j=i;j>1;j--)
a[k--][j]='\\';
}
else a[u][i]=v;
}
// right part of base
for (i=n/2+2;i<n+2;i++){
if ((i-n/2-3)%3==0){
k=u;
for (j=i;j<n+2;j++)
a[k--][j]='/';
}
else a[u][i]=v;
}
for (char[]w : a) System.out.println(new String(w));
}
```
] |
[Question]
[
Your task is to, as the title discreetly suggests, make a bad fade animation of one word turning into a second word for yours truly.
**What exactly *is* this "fade animation" you may ask?**
To make a spectacular(ly bad) fade animation, you take two strings which will contain only printable ASCII characters. You start by printing your starting string (the first of the two). Then, you **randomly pick** a character in the original word and change it to the corresponding character in the word you want to animate to. When the words are of unequal length, *you* must pad them with spaces.
You keep on doing this until all of the characters have been changed, but **you will not change the character at a certain index more than once**. Here is an example i/o:
```
Hey -> Peeps
Hey # original string
Hey s # replace char at index 4
Hey s # replace char at index 1
Pey s # replace char at index 0
Pee s # replace char at index 2
Peeps # replace char at index 3
```
You must write a function or full program that changes a letter and then prints the new string at increments of one second. The input format is loose, but the output format is strict.
**This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins.**
Some test cases (Form: `init -> final`):
```
Stringy -> Blingy
Banana -> Republic
United -> States
Make America -> Tissue box
I like walls -> I have small hands
Hello, -> world!
```
**Reference implementation in Python 2:**
```
import random
import time
def F(c,f):
print c # before we do stuff
if len(c)>len(f):f+=" "*(len(c)-len(f)) # add padding part 1
if len(f)>len(c):c+=" "*(len(f)-len(c)) # add padding part 2
c, f = list(c), list(f)
ai = [i for i in range(len(c))] # a list for keeping track
while len(ai) > 0: # of available indices
time.sleep(1) # 1 second pause...
i = ai.pop(random.randint(0,len(ai)-1)) # get a random index and remove
c[i] = f[i] # it from the list
print ''.join(c) # print the new string
```
[Answer]
# Pyth - ~~25~~ 24 bytes
Will refactor.
```
AC.tQdV.SU
G
[[email protected]](/cdn-cgi/l/email-protection)_1
```
[Try it online here](http://pyth.herokuapp.com/?code=AC.tQdV.SU%0AG%0A%3DXGN%40HN&input=%22Hey%22%2C+%22Peeps%22&debug=0).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 33 bytes
```
cn2/XKZ@!Oyhg*XR"GcK:@mK:Eq+)D1Y.
```
Try it at [MATL Online](https://matl.io/?code=cn2%2FXKZ%40%21Oyhg%2aXR%22GcK%3A%40mK%3AEq%2B%29D1Y.&inputs=%7B%27Banana%27%2C+%27Republic%27%7D&version=19.1.0). You may need to refresh the page and press "Run" again if it doesn't work.
Alternatively, [this version](https://matl.io/?code=cn2%2FXKZ%40%21Oyhg%2aXR%221Y.XxGcK%3A%40mK%3AEq%2B%29D&inputs=%7B%27Banana%27%2C+%27Republic%27%7D&version=19.1.0) (**35 bytes**) deletes the screen before each new string is displayed, which results in the output being "modified in place":
[Answer]
## Perl, 131 + 4 (`-F -l`) = 135 bytes
```
@T=@F if!$i++}$T[$_]||=$",$F[$_]||=$"for 0..$#F,0..$#T;say@T;{$==rand@T;redo if$h{$=}++;$T[$=]=$F[$=];sleep 1;say@T;redo if++$v!=@T
```
Needs `-F` and `-l` flags to run, as well as `-M5.010` (or `-E`). Note that if your version of perl is a bit old, you'll need to add `-an` on your command line (which I'll add too bellow to show it, but it's not needed).
For instance :
```
$ cat fade.pl
@T=@F if!$i++}$T[$_]||=$",$F[$_]||=$"for 0..$#F,0..$#T;say@T;{$==rand@T;redo if$h{$=}++;$T[$=]=$F[$=];sleep 1;say@T;redo if++$v!=@T
$ perl -F -anl -M5.010 fade.pl <<< "Hey
Peeps"
Hey
Pey
Pee
Pee s
Pee s
Peeps
```
I'm pretty sure this could be shorter, but I couldn't find out how... yet! Still, I don't think this is a bad answer, and hopefully someone will be inspired to make it shorter (or have a totally different idea!).
[Answer]
# Python 2, ~~171 169 168~~ 163 bytes
```
import time,random as r
def f(a,b):
d=len(a)-len(b);a+=' '*-d;b+=' '*d;o=range(len(a));r.shuffle(o);print a
for i in o:time.sleep(1);a=a[:i]+b[i]+a[i+1:];print a
```
Test cases are on **[ideone](http://ideone.com/Us4AuU)**
[Answer]
# C# 299 Bytes
```
void f(string a,string b){var m=Math.Max(a.Length,b.Length);var t=new Collections.Generic.HashSet<int>();while(t.Count<m)t.Add(new Random().Next()%m);var s=a.PadRight(m).ToCharArray();Console.WriteLine(s);foreach(var x in t){Threading.Thread.Sleep(1000);s[x]=b.PadRight(m)[x];Console.WriteLine(s);}}
```
**Ungolfed**
```
void f(string a, string b)
{
var m = Math.Max(a.Length, b.Length);
var t = new Collections.Generic.HashSet<int>();
while(t.Count < m) t.Add(new Random().Next()%m);
var s=a.PadRight(m).ToCharArray();
Console.WriteLine(s);
foreach (var x in t)
{
Threading.Thread.Sleep(1000);
s[x] = b.PadRight(m)[x];
Console.WriteLine(s);
}
}
```
[Answer]
# Perl, ~~109~~ ~~108~~ 99 bytes
Includes +3 for `-n`
Give strings on STDIN ***without final newline***
```
echo -n "Make -> Tissue box" | perl -M5.010 fade.pl
```
`fade.pl`:
```
#!/usr/bin/perl -n
/ -> /;$_=$`^$`^$'^$';{$==rand(y/\x00//)+sleep say+($`&~$_|$'&$_)=~y/\x00/ /r;s%(.*?\K\x00){$=}%\xff%&&redo}
```
Works as shown, but replace `\xhh` by the literal characters to get the claimed score.
This way of using `\K` is new I think...
[Answer]
# Python 3, 214 bytes
```
import time,random
o,f=list(input()),list(input())
F=len(f);O=len(o);o+=[" "]*(F-O);f+=[" "]*(O-F);p=-1;l=[p]
while o!=f:
while p in l:p=random.randrange(max(F,O))
l+=[p];o[p]=f[p];print(''.join(o));time.sleep(1)
```
[**Ideone it!**](https://ideone.com/2AvT0y)
[Answer]
**Java, ~~456~~ ~~454~~ ~~437~~ 428 bytes**
```
import java.util.*;public class c{public static void main(String[]s)throws Exception{char[]a=s[0].toCharArray(),b=s[1].toCharArray();int l,j=0;if(a.length<b.length){l=b.length;a=Arrays.copyOf(a,l);}else{l=a.length;b=Arrays.copyOf(b,l);}Vector i=new Vector();for(;j<l;i.add(j++));System.out.println(s[0]);while(l>0){Thread.sleep(1000);j=(int)i.remove(new Random().nextInt(l--));a[j]=b[j];System.out.println(String.valueOf(a));}}}
```
Ungolfed:
```
import java.util.*;
public class c
{
public static void main(String[] s) throws Exception
{
char[] a = s[0].toCharArray(), b = s[1].toCharArray();
int l, j = 0;
if (a.length < b.length)
{
l = b.length;
a = Arrays.copyOf(a, l);
}
else
{
l = a.length;
b = Arrays.copyOf(b, l);
}
Vector i = new Vector();
for (; j < l; i.add(j++));
System.out.println(s[0]);
while (l > 0)
{
Thread.sleep(1000);
j = (int) i.remove(new Random().nextInt(l--));
a[j] = b[j];
System.out.println(String.valueOf(a));
}
}
}
```
**Edit:** minus 2 byte by CAD97
**Edit:** minus 17 byte by Kevin Cruijssen (I slightly altered the suggestion by reusing `j` instead of creating a new variable `x` to hold the size)
**Edit:** minus 9 byte
[Answer]
# PHP, ~~123~~ 121 bytes
```
<?=$a=$argv[1];for($b=str_split(str_pad($argv[2],strlen($a)));$b;print"
$a"){$a[$i=array_rand($b)]=$b[$i];unset($b[$i]);}
```
save as file, execute with `php <filename> <string1> <string2>` (or `php-cgi`)
**breakdown**
```
<?=$a=$argv[1]; // 0. print original
for(
$b=str_split( // 2. split to array of single characers
str_pad($argv[2],strlen($a)) // 1. pad 2nd argument to length of 1st argument
);
$b; // 3. while $b has characters left
print"\n$a" // 6. print altered string
){
$a[$i=array_rand($b)]=$b[$i]; // 4. pick random index from $b, copy character to $a
unset($b[$i]); // 5. remove character from $b
}
```
[Answer]
# CJam, 44 bytes
```
q~{_,@\Se]s}2*1$peemr{es{_es-zA3#<}g;~t_p}/;
```
Explanation:
```
q~ get input
{_,@\Se]s}2* pad each string to the length of the other
1$p print starting string
eemr{ }/ for each randomly shuffled enum of target string
es{_es-zA3#<}g; 1 second waiting loop
~t_p replace one character and print new string
; clear stack
```
The delay only works using the Java interpreter, not in the online interpreter.
```
java -jar cjam.jar badfade.cjam <<< '"banana" "republic"'
```
[Try it online](http://cjam.tryitonline.net/#code=cX57XyxAXFNlXXN9MioxJHBlZW1ye2Vze19lcy16QTAjPH1nO350X3B9Lzs&input=ImJhbmFuYSIgInJlcHVibGljIg) (delay set to 1 ms)
[Answer]
# JavaScript (ES6) + HTML, 210 bytes
```
s=>e=>{s=[...s],e=[...e],d=e[k="length"]-s[k],(d>0?s:e).push(..." ".repeat(d>0?d:-d)),a=[...e.keys()],u=_=>{O.value=s.join``,s[i=a.splice(Math.random()*a[k]|0,1)[0]]=e[i],i+1&&setTimeout(u,1e3)},u()}
```
```
<input id=O
```
Called using curry syntax: `f("from this")("to this")`.
## Cleaned up JS
```
s => e => {
s = [...s],
e = [...e],
d = e[ k="length" ] - s[k],
(d>0 ? s : e).push(..." ".repeat(d>0 ? d : -d)),
a = [...e.keys()],
u = _ => {
O.value = s.join``,
s[ i = a.splice(Math.random()*a[k]|0, 1)[0] ] = e[i],
i+1 && setTimeout(u, 1e3)
},
u()
}
```
## Test Snippet
Requires closing brace on the `input` to work here.
```
f=
s=>e=>{s=[...s],e=[...e],d=e[k="length"]-s[k],(d>0?s:e).push(..." ".repeat(d>0?d:-d)),a=[...e.keys()],u=_=>{O.value=s.join``,s[i=a.splice(Math.random()*a[k]|0,1)[0]]=e[i],i+1&&setTimeout(u,1e3)},u()}
```
```
<style>*{font-family:Consolas;}</style>
Starting String: <input id="A" type="text"><br>
Ending String: <input id="B" type="text">
<button onclick="f(A.value)(B.value)">Run</button>
<br><br>
<input id=O>
```
[Answer]
# Ruby, 106 bytes
```
->a,b{puts a=a.ljust(l=[a.size,b.size].max);b=b.ljust l
[*0...l].shuffle.map{|i|sleep 1;a[i]=b[i];puts a}}
```
[Try it online!](https://repl.it/IMgi/2)
Oh, all right. No more rick rolling in the Try It Online link, if that's what's causing the downvotes. If not, please let me know what I'm doing wrong
] |
[Question]
[
## Disclaimer
While I know there is [this particular related question](https://codegolf.stackexchange.com/questions/79668/is-the-electric-garage-door-open), my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)
## The Background
Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.
Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.
So, the code-golf challenge is divided on two parts:
## Part One
Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:
* 0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.
* 1: The button for the left garage door has been pressed by Lucas
* 2: The button for the right garage door has been pressed by Lucas
## Part Two
Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.
My garage doors are pretty quick (see Disclaimer above as to why). Once you press the button it takes four seconds to be fully open or closed.
So, if closed:
* 0 sec: 0% open (closed); when button is pressed, door starts opening
* 1 sec: 25% open
* 2 sec: 50% open
* 3 sec: 75% open
* 4 sec: 100% open, door stops
And therefore, if open:
* 0 sec: 100% open; when button is pressed, door starts closing
* 1 sec: 75% open
* 2 sec: 50% open
* 3 sec: 25% open
* 4 sec: 0% open (closed), door stops
If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.
With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:
```
2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
```
## Output
The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
`212022112021202211202120221120212022112021202211202120221120`
Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.
Each of these processed lines will be in the form of:
`N: (L:X% XXXXXXX, R:Y% YYYYYYY)` where:
* N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.
* X% is the percentage of openness of the left door (there is no zero padding)
* XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".
* Y% is the percentage of openness of the right door (there is no zero padding)
* YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".
Example shown below using 10 "signals" and 10 processed lines
```
2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
```
This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.
Best of luck!
[Answer]
## Javascript (ES6), ~~277~~ ~~275~~ ~~263~~ ~~253~~ ~~250~~ ~~247~~ 234 bytes
```
_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)
```
### Ungolfed and commented
```
_ => (
// Initialize array:
// - d = door states as integers
// - bits 0 to 2: door opening state (from 0b000 = 0% to 0b100 = 100%)
// - bit #3: door in motion (0: no, 1: yes)
// - bit #4: door direction (0: closing, 1: opening)
d = [0, 0],
// Initialize strings:
// - l = list of commands
// - s = door states in plain text
l = s = '',
// Iterate on an array of 60 entries.
[...Array(60)].map(_ => (
// c = new random command (0, 1 or 2)
// Append new line and new command to s.
s += `\n${c = Math.random() * 3 | 0}:(`,
// Append new command to l.
l += c,
// For each door ...
d = d.map((v, i) => (
// If the door is in motion, update its opening state.
// Clear the 'in motion' bit if a bound is reached (either closed or fully open).
v = v & 8 ? v & 16 ? v - 27 ? v + 1 : 20 : v - 9 ? v - 1 : 0 : v,
// If the current command is intended for this door, update its direction and
// 'in motion' bit. Direction is changed on the 'stopped => moving' transition.
v ^= c + ~i ? 0 : v & 8 || 24,
// Translate the door state in plain text and append it to s
s +=
'LR'[i] +
`:${(v & 7) * 25}% ` +
(v & 8 ? v & 16 ? 'opening' : 'closing' : 'stopped') +
',)'[i],
// Value to be taken into account by map()
v
))
)),
// Final result to be returned
l + s
)
```
### Demo
```
let f =
_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)
console.log(f())
```
[Answer]
# Python 2, ~~377~~ ~~370~~ ~~361~~ ~~357~~ ~~345~~ ~~335~~ ~~326~~ ~~316~~ ~~312~~ ~~306~~ 304 bytes
The second indent level is a raw tab (`\t`), which plays *really* badly with Markdown, so it's been replaced by two spaces.
```
from random import*
p=[randint(0,2)for d in[[0]*3]*60]
print`p`[1::3]
v=[-1]*3
c=[0]*3
f=lambda y:str(c[y]*25)+'% '+'csoltpooespnipinengdg'[d[y]+1::3]
for x in p:
for i in 1,2:
q=d[i];c[i]+=q
if(2*-~q==c[i])*q:v[i]=q;d[i]=0
z=d[x]
if z:v[x]=z
d[x]=-v[x]*(z==0);print'%d: (L:%s, R:%s)'%(x,f(1),f(2))
```
I'm almost certain this can be golfed further.
Ungolfed, with comments:
```
import random
# Generate the random string - represented as a list of ints
presses = [random.randint(0, 2) for _ in range(60)]
print ''.join(map(str, presses))
# Constants for door states used for easier reading
CLOSING = -1
STOPPED = 0
OPENING = 1
# Variables representing the state of the garage doors
# There's a third element in these so that x[0] resolves to a dummy slot
# (this way, we can avoid a conditional down the road)
prev_states = [CLOSING, CLOSING, 0]
door_states = [STOPPED, STOPPED, 0]
door_pcts = [0, 0, 0] # delta 1 = 25%
for press in presses:
# Close/open the door 1 more
for i in 1, 2:
if door_states[i] != STOPPED:
delta_pct, stop_pct = (-1, 0) if door_states[i] == CLOSING else (1, 4)
door_pcts[i] += delta_pct
if door_pcts[i] == stop_pct:
prev_states[i] = door_states[i]
door_states[i] = STOPPED
# Handle pressing a button
# If the press is 0 (no press), the 0th element resolves to a dummy
# door, thus saving us an expensive conditional
if door_states[press] == STOPPED:
door_states[press] = -prev_states[press]
else:
prev_states[press] = door_states[press]
door_states[press] = STOPPED
# Print the status update
print '%d: (L:%d%% %s, R:%d%% %s)' % (
press,
door_pcts[0]*25,
['closing', 'stopped', 'opening'][door_states[0]+1],
door_pcts[1]*25,
['closing', 'stopped', 'opening'][door_states[1]+1],
)
```
*Saved ~~4~~ ~~14~~ **15** bytes thanks to @TheBikingViking!*
*Saved 6 bytes thanks to @ValueInk!*
[Answer]
# Pyth, ~~156~~ ~~149~~ 145 bytes
```
jkJmO3U60K=G*]Z3=b*3]_1VJFHS2I&=T@KHq*2hT@XHGTH XbHT XKH0)) XKN*_@XbN|@KN@bNN!@KN%+N": (L:%s, R:%s)"m++*@Gd25"% "%3>"csoltpooespnipinengdg"h@KdS2
```
A direct translation of [my Python answer](https://codegolf.stackexchange.com/a/91562/56755).
[Try it online!](http://pyth.herokuapp.com/?code=jkJmO3U60K%3DG%2a%5DZ3%3Db%2a3%5D_1VJFHS2I%26%3DT%40KHq%2a2hT%40XHGTH+XbHT+XKH0%29%29+XKN%2a_%40XbN%7C%40KN%40bNN%21%40KN%25%2BN%22%3A+%28L%3A%25s%2C+R%3A%25s%29%22m%2B%2B%2a%40Gd25%22%25+%22%253%3E%22csoltpooespnipinengdg%22h%40KdS2&debug=0)
Explanation:
```
jk " print ''.join(map(str, "
JmO3U60 " J = [randint(0,2) for _ in range(60)])) "
K=G*]Z3 " K = copy(G = [0] * 3) "
=b*3]_1 " b = [-1] * 3 "
VJ " for N in J: "
FHS2 " for H in range(1, 3): "
I&=T@KH " if ((T = K[H]) and "
q*2hT@XHGTH " (2 * (T + 1) == (G[H] += T)[H]): "
XbHT " b[H] = T "
XKH0)) " K[H] = 0 "
XKN*_@XbN|@KN@bNN " K[N] = (-(b[N] = K[N] or B[N])[N] * "
!@KN " (not K[N])) "
%+N": (L:%s, R:%s)" " print(str(N) + ': (L:%s, R:%s)' % "
m++ " map(lambda d: "
*@Gd25 " G[d] * 25 + "
"% " " '% ' + "
%3>"csoltpooespnipinengdg"h@Kd " 'csoltpooespnipinengdg'[K[d]+1::3]] "
S2 " ), range(1, 3)) "
```
[Answer]
# Ruby, ~~263~~ ~~261~~ ~~260~~ 254 bytes
How did JavaScript's answer get so short??? It overtook mine while I was away and still is winning currently...
```
s=(1..60).map{rand 3}
puts s*''
D=1,2
d=[25]*3;a=[0]*3;m=[p]*3
s.map{|i|D.map{|j|m[j]&&a[j]+=d[j];(0..100)===a[j]+d[j]||i!=j&&(d[j]*=-1;m[j]=p)}
(m[i]^=1)||d[i]*=-1
puts"#{i}: (L%s, R%s)"%D.map{|j|":#{a[j]}% #{%w"stopped opening closing"[m[j]?d[j]:0]}"}}
```
[Answer]
## C, ~~420~~ ~~433~~ ~~424~~ 374 bytes
```
#define F(X,x) X=x==1?X+1:x==2?X-1:X;X=X<0?0:X>4?4:X;x=X==0?0:X==4?3:x
#define G(x) x=x==1?3:x==2?0:x==3?2:x+1
#define H(X,x) X*25,x==0||x==3?"stopped":x==1?"opening":"closing"
c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)G(l);else if(x[c]==2)G(r);printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],H(L,l),H(R,r));F(L,l);F(R,r);}}
```
Doesn't seed the random generator but does use random for a better distribution.
There must be a better way to golf this logic though...
```
110121100121212100112200222111200020111100022122202112202211002
1: (L:0% opening, R:0% stopped)
1: (L:25% stopped, R:0% stopped)
0: (L:25% stopped, R:0% stopped)
1: (L:25% closing, R:0% stopped)
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
1: (L:25% stopped, R:50% opening)
0: (L:25% stopped, R:75% opening)
0: (L:25% stopped, R:100% stopped)
1: (L:25% closing, R:100% stopped)
2: (L:0% stopped, R:100% closing)
1: (L:0% opening, R:75% closing)
2: (L:25% opening, R:50% stopped)
1: (L:50% stopped, R:50% stopped)
2: (L:50% stopped, R:50% opening)
1: (L:50% closing, R:75% opening)
0: (L:25% closing, R:100% stopped)
0: (L:0% stopped, R:100% stopped)
1: (L:0% opening, R:100% stopped)
1: (L:25% stopped, R:100% stopped)
2: (L:25% stopped, R:100% closing)
2: (L:25% stopped, R:75% stopped)
0: (L:25% stopped, R:75% stopped)
0: (L:25% stopped, R:75% stopped)
2: (L:25% stopped, R:75% opening)
2: (L:25% stopped, R:100% closing)
2: (L:25% stopped, R:75% stopped)
1: (L:25% closing, R:75% stopped)
1: (L:0% opening, R:75% stopped)
1: (L:25% stopped, R:75% stopped)
2: (L:25% stopped, R:75% opening)
0: (L:25% stopped, R:100% stopped)
0: (L:25% stopped, R:100% stopped)
0: (L:25% stopped, R:100% stopped)
2: (L:25% stopped, R:100% closing)
0: (L:25% stopped, R:75% closing)
1: (L:25% closing, R:50% closing)
1: (L:0% opening, R:25% closing)
1: (L:25% stopped, R:0% stopped)
1: (L:25% closing, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
0: (L:0% stopped, R:0% stopped)
2: (L:0% stopped, R:0% opening)
2: (L:0% stopped, R:25% stopped)
1: (L:0% opening, R:25% stopped)
2: (L:25% opening, R:25% closing)
2: (L:50% opening, R:0% opening)
2: (L:75% opening, R:25% stopped)
0: (L:100% stopped, R:25% stopped)
2: (L:100% stopped, R:25% closing)
1: (L:100% closing, R:0% stopped)
1: (L:75% stopped, R:0% stopped)
2: (L:75% stopped, R:0% opening)
2: (L:75% stopped, R:25% stopped)
0: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% closing)
2: (L:75% stopped, R:0% opening)
1: (L:75% opening, R:25% opening)
1: (L:100% closing, R:50% opening)
```
### Older version 1:
```
c,i,l,r,L,R,x[60];main(){while(i<60)printf("%d",x[i++]=random()%3);while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("\n%d: (L:%d%% %s, R:%d%% %s)",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}
```
### Older version 2:
```
c,i,l,r,L,R,x[60];g(){while(i<60)printf("%d",x[i++]=random()%3);}main(){g();while(c<60){if(x[c]==1)l=l==1?3:l==2?0:l==3?2:l+1;else if(x[c]==2)r=r==1?3:r==2?0:r==3?2:r+1;printf("%d: (L:%d%% %s, R:%d%% %s)\n",x[c++],L*25,l==0||l==3?"stopped":l==1?"opening":"closing",R*25,r==0||r==3?"stopped":r==1?"opening":"closing");L=l==1?L+1:l==2?L-1:L;R=r==1?R+1:r==2?R-1:R;L=L<0?0:L>4?4:L;R=R<0?0:R>4?4:R;l=L==0?0:L==4?3:l;r=R==0?0:R==4?3:r;}}
```
[Answer]
# PHP, ~~254~~ ~~247~~ ~~246~~ ~~245~~ ~~235~~ ~~230~~ 226 bytes
beating ES again!
```
for($t=60;$t--;)$s.=rand()%3;echo$s;for(;++$t<60;print"
$c: ($o[1], $o[2])")for($i=3;--$i;$o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '.[opening,stopped,closing][abs($z-1)])if(((1&$z=&$r[$i])&&!(3&$d[$i]+=2-$z))|$i&$c=$s[$t])$z=++$z%4;
```
golfed down from these 311 (the first complete version, already had some golfing):
```
<?for($i=60;$i--;)$s.=rand(0,2);echo$s;$d=$r=[0,0];$n=[L,R];$p=[stopped,opening,stopped,closing];for($t=-1;++$t<60;print"
$c: (".join(', ',$x).")")for($m=$c=$s[$t],$i=-1;$i++<1;){if($r[$i]&1)if(!($d[$i]+=2-$r[$i])||4==$d[$i])$m|=$i+1;if($m&$i+1)$r[$i]=(1+$r[$i])%4;$x[$i]="$n[$i]:".($d[$i]*25)."% ".$p[$r[$i]];}
```
**breakdown**
```
for($t=60;$t--;)$s.=rand()%3; // part 1 also initializes $t to -1
echo$s;
for(
;
++$t<60;
print"\n$c: ($o[1], $o[2])" // print output
)
for($i=3;--$i; // loop $i from 2 to 1 (door number)
// generate output
$o[$i]='.LR'[$i].':'.$d[$i]*25 .'% '
.[opening,stopped,closing][abs($z-1)] // map 0123 to 1012
)
if(((1&$z=&$r[$i]) // if door in motion ... and reference the array item
&&!(3& // 2. if end position "&&" needed for short circuit
$d[$i]+=2-$z // 1. move door 2-$z maps 1,3 to 1,-1 = delta
)
)|$i&$c=$s[$t]) // 3. or if button $i pressed "|" needed for no short circuit
$z=++$z%4; // rotate direction ++$z%4 maps 0,1,2,3 to 1,2,3,0
// generate output (loop post condition)
// print output (loop post condition)
```
[Answer]
## Java 8 lambda, 500 characters
I did my best, here is what I came up with:
```
()->{String r="";int i=0,l=0,m=0,n=1,o=1,p=0,q=0;for(;i++<60;)r+=(int)(Math.random()*3);for(char s:r.toCharArray()){l+=p;m+=q;if(l>99&p>0){l=100;p=25*(((n=++n%4)-1)%2);}if(l<1&p<0){l=0;p=25*(((n=++n%4)-1)%2);}if(m>99&q>0){m=100;q=25*(((o=++o%4)-1)%2);}if(m<1&q<0){m=0;q=25*(((o=++o%4)-1)%2);}if(s<49);else if(s>49)q=25*(((o=++o%4)-1)%2);else p=25*(((n=++n%4)-1)%2);r+="\n"+s+": (L:"+l+"% "+(p<0?"closing":p>0?"opening":"stopped")+", R:"+m+"% "+(q<0?"closing":q>0?"opening":"stopped")+")";}return r;}
```
Ungolfed into a complete class:
```
public class Q91479 {
public static String movedDoorsCombined() {
String result = "";
int i = 0, leftDoor = 0, rightDoor = 0, stepLeft = 1, stepRight = 1, changeLeft = 0, changeRight = 0;
for (; i++ < 60;) {
result += (int) (Math.random() * 3);
}
for (char step : result.toCharArray()) {
// update stats
leftDoor += changeLeft;
rightDoor += changeRight;
if (leftDoor > 99 & changeLeft > 0) {
leftDoor = 100;
changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
}
if (leftDoor < 1 & changeLeft < 0) {
leftDoor = 0;
changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
}
if (rightDoor > 99 & changeRight > 0) {
rightDoor = 100;
changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
}
if (rightDoor < 1 & changeRight < 0) {
rightDoor = 0;
changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
}
if (step < 49) {
// 0
}
else if (step > 49) {
// right
changeRight = 25 * (((stepRight = ++stepRight % 4) - 1) % 2);
}
else {
// left
changeLeft = 25 * (((stepLeft = ++stepLeft % 4) - 1) % 2);
}
result += "\n" + step + ": (L:" + leftDoor + "% "
+ (changeLeft < 0 ? "closing" : changeLeft > 0 ? "opening" : "stopped")
+ ", R:" + rightDoor + "% "
+ (changeRight < 0 ? "closing" : changeRight > 0 ? "opening" : "stopped")
+ ")";
}
return result;
}
}
```
Pretty straight forward. The stepLeft/stepRight variables circle from 0-3. Doing some simple maths changeLeft/changeRight hold the respective relative changes per step, which will be added to leftDoor/rightDoor. Many if statements for catching when the door has to stop on it's own.
Feel free to help me shorten this, I think there's a lot to do.
[Answer]
# Haskell (lambdabot) - 409 bytes
```
p=(cycle[0,1,0,-1],0)
t(d:q,s)=(if d/=0&&(s+d<1||3<s+d)then q else d:q,s+d)
k i(a,b)=[o i,": (L:",j a,", ","R:",j b,")"]>>=id
j(d:_,s)=o(round$(fromIntegral s/4)*100)++"% "++words"closing stopped opening"!!(d+1)
s=scanl$ \(a,b)i->i(t a,t b)
main=do b<-(fmap(round.(*(2::Float))).take 60<$>randoms)<$>getStdGen;putStrLn.unlines$(o=<<b):(zipWith k b.w.s(p,p)$([id,f$f w,second$f w]!!)<$>b)
o=show;f=first;w=tail
```
] |
[Question]
[
Many important topics in abstract algebra involve a binary function acting on a set. A number of properties of such functions have been defined in the investigation of such topics.
Your challenge will be to determine whether a given binary function on a given domain possesses five of these properties.
## Properties
**[Closure](https://en.wikipedia.org/wiki/Closure_(mathematics))**
A binary function is closed if every possible output is in the domain.
**[Associativity](https://en.wikipedia.org/wiki/Associative_property)**
A binary function is associative if the order in which the function is applied to a series of inputs doesn't affect the result. That is, `$` is associative if `(a $ b) $ c` always equals `a $ (b $ c)`. Note that since the value `(a $ b)` is used as an input, associative functions must be closed.
**[Commutativity](https://en.wikipedia.org/wiki/Commutative_property)**
A binary function is commutative if swapping the order of the inputs doesn't change the result. In other words, if `a $ b` always equals `b $ a`.
**[Identity](https://en.wikipedia.org/wiki/Identity_element)**
A binary function has an identity element if there exists some element `e` in the domain such that `a $ e = a = e $ a` for all `a` in the domain.
**[Idempotence](https://en.wikipedia.org/wiki/Idempotence)**
A binary function is idempotent if applying it to two identical inputs gives that number as the output. In other words, if `a $ a = a` for all `a` in the domain.
## Input
You will be given a function in the form of a matrix, and the domain of the function will be the numbers `0 ... n-1`, where `n` is the side length of the matrix.
The value `(a $ b)` is encoded in the matrix as the `a`th row's `b`th element. If the input matrix is `Q`, then `a $ b` = `Q[a][b]`
For example, the exponentiation function (`**` in Python) on the domain `[0, 1, 2]` is encoded as:
```
[[1, 0, 0]
[1, 1, 1]
[1, 2, 4]]
```
The left and right domains are the same, so the matrix will always be square.
You may use any convenient matrix format as input, such as a list of lists, a single list in row- or column- major order, your language's native matrix object, etc. However, you may not take a function directly as input.
For simplicity, the matrix entries will all be integers. You may assume that they fit in your language's native integer type.
## Output
You may indicate which of the above properties hold in any format you choose, including a list of booleans, a string with a different character for each property, etc. However, there must be a distinct, unique output for each of the 24 possible subsets of the properties. This output must be easily human-readable.
## Examples
The maximum function on domain n=4:
```
[[0, 1, 2, 3]
[1, 1, 2, 3]
[2, 2, 2, 3]
[3, 3, 3, 3]]
```
This function has the properties of closure, associativity, commutativity, identity and idempotence.
The exponentiation function on domain n=3:
```
[[1, 0, 0]
[1, 1, 1]
[1, 2, 4]]
```
This function has none of the above properties.
The addition function on domain n=3:
```
[[0, 1, 2]
[1, 2, 3]
[2, 3, 4]]
```
This function has the properties of commutativity and identity.
The K combinator on domain n=3:
```
[[0, 0, 0]
[1, 1, 1]
[2, 2, 2]]
```
This function has the properties of closure, associativity and idempotence.
The absolute difference function on domain n=3:
```
[[0, 1, 2]
[1, 0, 1]
[2, 1, 0]]
```
This function has the properties of closure, commutativity and identity.
The average function, rounding towards even, on domain n=3:
```
[[0, 0, 1]
[0, 1, 2]
[1, 2, 2]]
```
This function has the properties of closure, commutativity, identity and idempotence.
The equality function on domain n=3:
```
[[1, 0, 0]
[0, 1, 0]
[0, 0, 1]]
```
This function has the properties of closure and commutativity.
## Challenge
This is code golf. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. Least bytes wins.
[Answer]
## Haskell, ~~178~~ 171 bytes
```
import Data.List
f x=[c,c&&and[(m%n)%o==m%(n%o)|m<-b,n<-b,o<-b],x==t,all(elem b)[x,t],b==[i%i|i<-b]]where c=all(l>)(id=<<x);b=[0..l-1];a%b=x!!a!!b;l=length x;t=transpose x
```
Returns a list with five booleans, which are in order closure, associativity, commutativity, identity and idempotence.
Usage example: `f [[1, 0, 0],[0, 1, 0],[0, 0, 1]]` -> `[True,False,True,False,False]`.
How it works:
```
f x=[
c, -- closure (see below)
c&&and[(m%n)%o==m%(n%o)| -- assoc: make sure it's closed, then check the
m<-b,n<-b,o<-b], -- assoc rule for all possible combinations
x==t, -- comm: x must equal it's transposition
all(elem b)[x,t], -- identity: b must be a row and a column
b==[i%i|i<-b] -- idemp: element at (i,i) must equal i
]
where -- some helper functions
c=all(l>)(id=<<x); -- closure: all elements of the input must be < l
b=[0..l-1]; -- a list with the numbers from 0 to l-1
a%b=x!!a!!b; -- % is an access function for index (a,b)
l=length x; -- l is the number of rows of the input matrix
t=transpose x
```
Edit @xnor found some bytes to save. Thanks!
[Answer]
# Pyth, 51 bytes
```
[qKUQ@VQKCIQ}]Km{@RdCBQKJ!-sQK&JqF.bsm@[[email protected]](/cdn-cgi/l/email-protection),sQK
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=[qKUQ%40VQKCIQ%7D]Km%7B%40RdCBQKJ!-sQK%26JqF.bsm%40L%40QdYN.p%2CsQK&input=[[0%2C+1%2C+2%2C+3]%2C+[1%2C+1%2C+2%2C+3]%2C+[2%2C+2%2C+2%2C+3]%2C+[3%2C+3%2C+3%2C+3]]&test_suite_input=[[0%2C+1%2C+2%2C+3]%2C+[1%2C+1%2C+2%2C+3]%2C+[2%2C+2%2C+2%2C+3]%2C+[3%2C+3%2C+3%2C+3]]%0A[[1%2C+0%2C+0]%2C+[1%2C+1%2C+1]%2C+[1%2C+2%2C+4]]%0A[[0%2C+1%2C+2]%2C+[1%2C+2%2C+3]%2C+[2%2C+3%2C+4]]%0A[[0%2C+0%2C+0]%2C+[1%2C+1%2C+1]%2C+[2%2C+2%2C+2]]%0A[[0%2C+1%2C+2]%2C+[1%2C+0%2C+1]%2C+[2%2C+1%2C+0]]%0A[[0%2C+0%2C+1]%2C+[0%2C+1%2C+2]%2C+[1%2C+2%2C+2]]%0A[[1%2C+0%2C+0]%2C+[0%2C+1%2C+0]%2C+[0%2C+0%2C+1]]&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=[qKUQ%40VQKCIQ%7D]Km%7B%40RdCBQKJ!-sQK%26JqF.bsm%40L%40QdYN.p%2CsQK&input=[[0%2C+1%2C+2%2C+3]%2C+[1%2C+1%2C+2%2C+3]%2C+[2%2C+2%2C+2%2C+3]%2C+[3%2C+3%2C+3%2C+3]]&test_suite=1&test_suite_input=[[0%2C+1%2C+2%2C+3]%2C+[1%2C+1%2C+2%2C+3]%2C+[2%2C+2%2C+2%2C+3]%2C+[3%2C+3%2C+3%2C+3]]%0A[[1%2C+0%2C+0]%2C+[1%2C+1%2C+1]%2C+[1%2C+2%2C+4]]%0A[[0%2C+1%2C+2]%2C+[1%2C+2%2C+3]%2C+[2%2C+3%2C+4]]%0A[[0%2C+0%2C+0]%2C+[1%2C+1%2C+1]%2C+[2%2C+2%2C+2]]%0A[[0%2C+1%2C+2]%2C+[1%2C+0%2C+1]%2C+[2%2C+1%2C+0]]%0A[[0%2C+0%2C+1]%2C+[0%2C+1%2C+2]%2C+[1%2C+2%2C+2]]%0A[[1%2C+0%2C+0]%2C+[0%2C+1%2C+0]%2C+[0%2C+0%2C+1]]&debug=0)
This prints a list of 5 boolean values. They indicate the properties in the order:
```
[Idempotence, Commutativity, Identity, Closure, Associativity]
```
Here is a better output format: [Demonstration](http://pyth.herokuapp.com/?test_suite=0&input=%5B%5B0%2C%201%2C%202%2C%203%5D%2C%20%5B1%2C%201%2C%202%2C%203%5D%2C%20%5B2%2C%202%2C%202%2C%203%5D%2C%20%5B3%2C%203%2C%203%2C%203%5D%5D&code=%2B%22Idempotence%3A%20%20%20%22qKUQ.e%40bkQ%0A%2B%22Commutativity%3A%20%22CIQ%0A%2B%22Identity%3A%20%20%20%20%20%20%22%7D%5DKm%7B%40RdCBQK%0A%2B%22Closure%3A%20%20%20%20%20%20%20%22J%21-sQK%0A%2B%22Associativity%3A%20%22%26JqF.bsm%40LdY%40LQN.p%2CsQK&test_suite_input=%5B%5B0%2C%201%2C%202%2C%203%5D%2C%20%5B1%2C%201%2C%202%2C%203%5D%2C%20%5B2%2C%202%2C%202%2C%203%5D%2C%20%5B3%2C%203%2C%203%2C%203%5D%5D%0A%5B%5B1%2C%200%2C%200%5D%2C%20%5B1%2C%201%2C%201%5D%2C%20%5B1%2C%202%2C%204%5D%5D%0A%5B%5B0%2C%201%2C%202%5D%2C%20%5B1%2C%202%2C%203%5D%2C%20%5B2%2C%203%2C%204%5D%5D%0A%5B%5B0%2C%200%2C%200%5D%2C%20%5B1%2C%201%2C%201%5D%2C%20%5B2%2C%202%2C%202%5D%5D%0A%5B%5B0%2C%201%2C%202%5D%2C%20%5B1%2C%200%2C%201%5D%2C%20%5B2%2C%201%2C%200%5D%5D%0A%5B%5B0%2C%200%2C%201%5D%2C%20%5B0%2C%201%2C%202%5D%2C%20%5B1%2C%202%2C%202%5D%5D%0A%5B%5B1%2C%200%2C%200%5D%2C%20%5B0%2C%201%2C%200%5D%2C%20%5B0%2C%200%2C%201%5D%5D) or [Test Suite](http://pyth.herokuapp.com/?test_suite=1&input=%5B%5B0%2C%201%2C%202%2C%203%5D%2C%20%5B1%2C%201%2C%202%2C%203%5D%2C%20%5B2%2C%202%2C%202%2C%203%5D%2C%20%5B3%2C%203%2C%203%2C%203%5D%5D&code=%2B%22Idempotence%3A%20%20%20%22qKUQ.e%40bkQ%0A%2B%22Commutativity%3A%20%22CIQ%0A%2B%22Identity%3A%20%20%20%20%20%20%22%7D%5DKm%7B%40RdCBQK%0A%2B%22Closure%3A%20%20%20%20%20%20%20%22J%21-sQK%0A%2B%22Associativity%3A%20%22%26JqF.bsm%40LdY%40LQN.p%2CsQK&test_suite_input=%5B%5B0%2C%201%2C%202%2C%203%5D%2C%20%5B1%2C%201%2C%202%2C%203%5D%2C%20%5B2%2C%202%2C%202%2C%203%5D%2C%20%5B3%2C%203%2C%203%2C%203%5D%5D%0A%5B%5B1%2C%200%2C%200%5D%2C%20%5B1%2C%201%2C%201%5D%2C%20%5B1%2C%202%2C%204%5D%5D%0A%5B%5B0%2C%201%2C%202%5D%2C%20%5B1%2C%202%2C%203%5D%2C%20%5B2%2C%203%2C%204%5D%5D%0A%5B%5B0%2C%200%2C%200%5D%2C%20%5B1%2C%201%2C%201%5D%2C%20%5B2%2C%202%2C%202%5D%5D%0A%5B%5B0%2C%201%2C%202%5D%2C%20%5B1%2C%200%2C%201%5D%2C%20%5B2%2C%201%2C%200%5D%5D%0A%5B%5B0%2C%200%2C%201%5D%2C%20%5B0%2C%201%2C%202%5D%2C%20%5B1%2C%202%2C%202%5D%5D%0A%5B%5B1%2C%200%2C%200%5D%2C%20%5B0%2C%201%2C%200%5D%2C%20%5B0%2C%200%2C%201%5D%5D)
### Explanation:
**Idempotence:**
```
qKUQ@VQK
Q Q = input matrix
UQ [0, 1, ..., len(matrix)-1]
K assign to K
@VQK vectorized lookup of Q and K //gets the diagonal elements
qK check, if this is equal to K
```
**Commutativity:**
```
CIQ check if transpose(Q) is equal to Q
```
**Identity:**
```
}]Km{@RdCBQK
m K map each d in K to:
CBQ the list [Q, transpose(Q)]
@Rd take the d-th element of each ^
{ remove duplicates
}]K check if [K] is in ^
```
**Closure:**
```
J!-sQK
sQ sum(Q) //all elements of Q
- K remove the elements, that also appear in K
! ckeck, if the results in an empty list
J store the result in J
```
**Associativity:**
```
&JqF.bsm@[[email protected]](/cdn-cgi/l/email-protection),sQK
.p,sQK all permutations of [sum(Q), K] //all 2 ;-)
.b map each pair (N,Y) of ^ to:
m N map each d of N to:
@Qd the row Q[d]
@L Y map each element of Y to the corr. element in ^
s unfold this 2-d list
qF check if they result in identically lists
&J and J
```
[Answer]
# CJam, 95 bytes
```
q~:Ae_A,:Bf<:*'**B3m*{_{A==}*\W%{Az==}*=}%:*'A*A_z='C*B{aB*ee_Wf%+{A==}f*B,2*='1*}%Ae_B)%B,='I*
```
Prints a subsequence of `*AC1I`. `*` is the symbol for **closure**, `A` is for **associative**, `C` is for **commutative**, `1` is for **identity** and `I` is for **idempotent**.
---
The input array is read `q~` and stored in A (`:A`).
### Closure
```
Ae_A,:Bf<:*'**
```
If all (`:*`) elements in the matrix (`Ae_`) are smaller `f<` than B=size(A) (`A,:B`), print a `*` (`'**`).
### Associativity
```
B3m*{_{A==}*\W%{Az==}*=}%:*'A*
```
Generate all triples in the domain (`B3m*`). We print `A` if they all satisfy a condition (`{...}%:*'A*`).
The condition is that, for some triple `[i j k]`, left-folding that list with **A** (`_{A==}*`) and left-folding its reverse `[k j i]` (`\W%`) with **Aop** (`{Az==}*`), the flipped version of `A`, are equal (`=`).
### Commutativity
**A** must equal its transpose: `A_z=`. If so, we print `C` (`'C=`).
### Identity
```
B{ }% For each element X in the domain (0..N-1):
aB* Make N copies.
ee [[0 X] [1 X] ...]
_Wf%+ [[0 X] [1 X] ... [X 0] [X 1] ...]
{A==}f* [A(0, X) A(1, X) ... A(X, 0) A(X, 1)]
B,2*= This list should equal the domain list repeated twice.
'1* If so, X is an identity: print a 1.
```
The identity is necessarily unique, so we can only print one `1`.
### Idempotent
```
Ae_B)%B,='I*
```
Check if the diagonal equals `B,`. If so, print an `I`.
[Answer]
# Matlab, 226
```
a=input('');n=size(a,1);v=1:n;c=all(0<=a(:)&a(:)<n);A=c;for i=v;for j=v(1:n*c);for k=v(1:n*c);A=A&a(a(i,j)+1,k)==a(i,a(j,k)+1);end;end;b(i)=all(a(i,:)==v-1 & a(:,i)'==v-1);end;disp([c,A,~norm(a-a'),any(b),all(diag(a)'==v-1)])
```
An important thing to notice is that non-closed implies non-associative. Many of those properties can easily be checked using some properties of the matrix:
* **Closure**: All all matrix entries in the given range?
* **Associativity**: As always the most difficult one to check
* **Commutativity**: Is the matrix symmetric?
* **Identity**: Is there an index k such that the k-th row and k-th column are exactly the list of the indices?
* **Idempotence**: Does the diagonal correspond to the list of indices?
Input via standar Matlab notation: `[a,b;c,d]` or `[[a,b];[c,d]]` or `[a b;c d]` e.t.c.
Output is a vector of ones a zeros, 1 = true, 0 = false, for each of the properties in the given order.
Full code:
```
a=input('');
n=size(a,1);
v=1:n;
c=all(0<=a(:)&a(:)<n); %check for closedness
A=c;
for i=v;
for j=v(1:n*c);
for k=v(1:n*c);
A=A&a(a(i,j)+1,k)==a(i,a(j,k)+1); %check for associativity (only if closed)
end;
end;
b(i)=all(a(i,:)==v-1 & a(:,i)'==v-1); %check for commutativity
end
%closure, assoc, commut, identity, idempotence
disp([c,A,~norm(a-a'),any(b),all(diag(a)'==v-1)]);
```
[Answer]
# JavaScript (ES6) 165
An anonymous function returning an array with five 0/1 values, which are in order Closure, Associativity, Commutativity, Identity and Idempotence.
```
q=>q.map((p,i)=>(p.map((v,j)=>(w=q[j][i],v-w?h=C=0:v-j?h=0:0,q[v]?A&=!q[v].some((v,k)=>v-q[i][q[j][k]]):A=K=0),h=1,p[i]-i?P=0:0),h?I=1:0),A=P=K=C=1,I=0)&&[K,A,C,I,P]
```
**Less golfed**
```
f=q=>(
// A associativity, P idempotence, K closure, C commuativity
// assumed true until proved false
A=P=K=C=1,
I=0, // Identity assumed false until an identity element is found
q.map((p,i)=> (
h=1, // assume current i is identity until proved false
p[i]-i? P=0 :0, // not idempotent if q[i][i]!=i for any i
p.map((v,j)=> (
w=q[j][i], // and v is q[i][j]
v-w // check if q[j][i] != q[i][j]
? h=C=0 // if so, not commutative and i is not identity element too
: v-j // else, check again for identity
? h=0 // i is not identity element if v!=j or w!=j
: 0,
q[v] // check if q[i][j] in domain
? A&=!q[v].some((v,k)=>v-q[i][q[j][k]]) // loop for associativity check
: A=K=0 // q[i][j] out of domain, not close and not associative
)
),
h ? I=1 : 0 // if i is the identity element the identity = true
)
),
[K,A,C,I,P] // return all as an array
)
```
**Test**
```
f=q=>
q.map((p,i)=>(
p.map((v,j)=>(
w=q[j][i],
v-w?h=C=0:v-j?h=0:0,
q[v]?A&=!q[v].some((v,k)=>v-q[i][q[j][k]]):A=K=0
),h=1,p[i]-i?P=0:0),
h?I=1:0
),A=P=K=C=1,I=0)
&&[K,A,C,I,P]
// test
console.log=x=>O.textContent+=x+'\n';
T=[
[
[[0, 1, 2, 3],
[1, 1, 2, 3],
[2, 2, 2, 3],
[3, 3, 3, 3]]
,[1,1,1,1,1]] // has the properties of closure, associativity, commutativity, identity and idempotence.
,[ // exponentiation function on domain n=3:
[[1, 0, 0],
[1, 1, 1],
[1, 2, 4]]
,[0,0,0,0,0]] // has none of the above properties.
,[ // addition function on domain n=3:
[[0, 1, 2],
[1, 2, 3],
[2, 3, 4]]
,[0,0,1,1,0]] // has the properties of commutativity and identity.
,[ // K combinator on domain n=3:
[[0, 0, 0],
[1, 1, 1],
[2, 2, 2]]
,[1,1,0,0,1]] // has the properties of closure, associativity and idempotence.
,[ // absolute difference function on domain n=3:
[[0, 1, 2],
[1, 0, 1],
[2, 1, 0]]
,[1,0,1,1,0]] // has the properties of closure, commutativity and identity.
,[ // average function, rounding towards even, on domain n=3:
[[0, 0, 1],
[0, 1, 2],
[1, 2, 2]]
,[1,0,1,1,1]] // has the properties of closure, commutativity, identity and idempotence.
,[ // equality function on domain n=3:
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
,[1,0,1,0,0]] // has the properties of closure, commutativity,
]
T.forEach(t=>{
F=t[0],X=t[1]+'',R=f(F)+'',console.log(F.join`\n`+'\n'+R+' (expected '+X+') '+(X==R?'OK\n':'Fail\n'))
})
```
```
<pre id=O></pre>
```
] |
[Question]
[
In a round of the [prisoner's dilemma](https://en.wikipedia.org/wiki/Prisoner%27s_dilemma) exercise, two players each decide whether to *cooperate* or *defect* for that round. The scoring for a round is:
* Player A and Player B both cooperate: **1 point for both**
* Player A and Player B both defect: **2 points for both**
* Player A cooperates and Player B defects: **3 points** for cooperating Player A and **0 points** for defecting Player B
You don't need to worry about strategy, though: your program will merely be tabulating the score for a game. (In case you are already familiar with prisoner's dilemma, my "points" here correspond to "years in prison.")
Your challenge is to take input that represents the players' choices over several rounds and compute their respective total scores. One player submits choices in lowercase, `c` and `d` (for *cooperate* and *defect*), and the other submits choices in uppercase, `C` and `D`. These choices are supplied to your program as a string.
Normally, players in prisoner's dilemma submit their moves simultaneously and iteratively. In this challenge, however, the players may have submitted their choices for several rounds at once. If a player's move is out of sequence, the scoring program remembers it and matches it with the next available move from the opposing player.
Here's a sample input string:
```
cDCddDDCcCc
```
To show the matches that exist in this input, I'll call out the lowercase and uppercase separately, and pair them up:
```
cDCddDDCcCc
c dd c c => cddcc
DC DDC C => DCDDCC
```
These will be paired into the rounds:
```
c vs D (3 pts for lowercase-player, 0 pts for uppercase-player)
d vs C (0 pts for lowercase-player, 3 pts for uppercase-player)
d vs D (2 pts for both)
c vs D (3 pts for lowercase-player, 0 pts for uppercase-player)
c vs C (1 pt for both)
```
Which produces the score `9` (lowercase) to `6` (uppercase), so the output should be `9,6` (or any unambiguous delimiter).
To express it in yet another way, here's each pairing pulled out on its own row:
```
cDCddDDCcCc
cD
Cd
dD
D c
C c
```
There is one unmatched `C`, because the uppercase player submitted more moves than the lowercase player. That is acceptable, and it is totally ignored for scoring purposes.
Here are the requirements:
* You must write a program or function that accepts a string of the regular-expression form `/[cdCD]+/`, through some input mechanism (STDIN, function argument, read from file, etc.). (Your program may optionally accept input with a trailing newline.)
* Your program or function must output or return the players' scores as a string. The output format must start with the lowercase player's score, followed by the uppercase player's score, separated by any non-empty, non-numeric delimiter of your choice. (A trailing newline is optional.)
* If one player has more moves than the other, the excess moves are ignored.
* If all moves in the input are from exclusively one player (that is, no rounds have been played at all), then each player's score is `0`.
* The smallest submission in bytes wins.
## Test cases
```
Input: cDCddDDCcCc
Output: 9,6 -- or any delimiter; I chose commas here
Input: cccDDD
Output: 9,0
Input: DDDDDDccc
Output: 9,0
Input: cDcDcD
Output: 9,0
Input: dcDDC
Output: 5,2
Input: CcdCDDcd
Output: 6,6
Input: Ddd
Output: 2,2
Input: ccccccccccc
Output: 0,0
```
[Answer]
## Haskell, ~~139~~ 134 bytes
```
g=filter
(n!m)(a,b)=(a+n,b+m)
f s=init$tail$show$foldr id(0,0)$zipWith(#)(g(>'a')s)$g(<'E')s
'c'# 'C'=1!1
'c'#_=3!0
_# 'D'=2!2
_#_=0!3
```
Usage example: `f "cDCddDDCcCc"` -> `"9,6"`
15 bytes just to get the output format right, i.e. turning a pair of numbers `(x,y)` into a string `"x,y"`.
How it works:
```
g(>'a')s -- extract all lowercase letters
g(<'E')s -- extract all uppercase letters
zipWith(#) -- combine both lists element wise with function #
-- # calls ! depending on the combination of c/d/C/D
-- ! takes 2 numbers a and b and returns a function
-- that takes a pair (x,y) and returns (x+a,y+b)
-- now we have a list of such functions
foldr id(0,0) -- apply those functions starting with (0,0)
init$tail$show -- format output
```
Edit: @Zgarb helped me saving 5 bytes. Thanks!
[Answer]
# LabVIEW, 77 Bytes
[](https://i.stack.imgur.com/IOfWE.png)
The code scans from tokens and uses those indicies to decide where the points go.
Counting goes like [this](http://meta.codegolf.stackexchange.com/a/7589/39490)
[Answer]
# Pyth, 23 bytes
```
jsMc2/L`C,@Gz-zG"cDDCdd
```
[Test suite](https://pyth.herokuapp.com/?code=jsMc2%2FL%60C%2C%40Gz-zG%22cDDCdd&test_suite=1&test_suite_input=cDCddDDCcCc%0AcccDDD%0ADDDDDDccc%0AcDcDcD%0AdcDDC%0ACcdCDDcd%0ADdd%0Accccccccccc&debug=0)
---
## Explanation:
`@Gz`: Lowercase letters
`-zG`: Uppercase letters
`C,`: Pair, truncate the remainder.
```: Take the string representation of the list of pairs
`/L ... "cDDCdd`: For each letter in `"cDDCdd"`, count how many time it appears in the above string repr.
`c2`: Chop the resulting list in half.
`sM`: Add up each half.
`j`: Join on newlines and print.
---
` must be used instead of s to make the case where one party never plays work.
[Answer]
# Python 3, 110
Saved 5 Bytes thanks to FryAmTheEggman.
Saved 7 Bytes thanks to apsillers.
Saved 26 Bytes thanks to DSM.
```
x=[[],[]]
a=b=0
for m in input():x[m<'E']+=m
for w,p in zip(*x):d=p>'C';c=w<'d';b+=d*2+c;a+=3-d-2*c
print(b,a)
```
I think it's finally all golfed out.
It scans through each character in the input and sorts it based on being uppercase or not. It then does some fancy math that abuses Python's implicit conversion of bools to ints.
[Answer]
# JavaScript (ES6), ~~124~~ 118 bytes
```
s=>(A=B=i=0,U=(r=x=>s.replace(/c|d/g,x))``,r(l=>U[i]&&(U[i++]<'D'?l<'d'?++A&++B:B+=3:l<'d'?A+=3:(A+=2,B+=2))),A+','+B)
```
### Live demo
(Expanded slightly for readability.)
```
var f=function (s) {
A=B=i=0;
U=(r=function(x){return s.replace(/c|d/g,x)})("");
r(l=>U[i]&&(U[i++]<'D'?l<'d'?++A&++B:B+=3:l<'d'?A+=3:(A+=2,B+=2)));
return A+','+B;
}
var input = ["cDCddDDCcCc","cccDDD","DDDDDDccc","cDcDcD","dcDDC","CcdCDDcd","Ddd","ccccccccccc"];
var output = ["9,6","9,0","9,0","9,0","5,2","6,6","2,2","0,0"];
var passed = true;
for (var index=0;index<input.length;index++) {
if (f(input[index]) !== output[index]) passed = false;
}
document.getElementById("result").textContent =
passed ? "All tests passed." : "Some tests failed.";
```
```
<div id="result"></div>
```
Saved 6 bytes thanks to [user81655](https://codegolf.stackexchange.com/users/46855/user81655).
[Answer]
# [Par](http://ypnypn.github.io/Par/), 49 bytes
```
(lW▼·L)w▼·U))t˅y])[h7%Z2*↓″4>5*-]z2↔-″0<4*+╞)t.Σ¡
```
One byte is used per character. [See here](https://github.com/Ypnypn/Par/blob/gh-pages/README.md#the-encoding).
## Explanation
```
( ## Construct array
l ## Read line
W ## Assign to w
▼·L) ## Filter by immutable under lower-case
w ## Get w
▼·U) ## Filter by immutable under upper-case
) ##
t ## Transpose and truncate
˅y]) ## If empty, empty 2-D matrix
[ ## Map
h ## Decimal to hex
7% ## Modulo 7
Z ## Assign to z
2*↓″4>5*- ## Score of lower case
] ## Put in array
z2↔-″0<4*+ ## Score of upper case
╞ ## Add to array
) ##
t ## Transpose and truncate
.Σ ## Map - sum
¡ ## Empty array onto stack
```
Outputs in the form `9 6`.
[Answer]
# CJam, ~~92~~ ~~83~~ 81 bytes
This ended up longer than I thought it would...
```
0]K*X3tC30tG22tZ11t:L;0'a]q+{'D>}:B$_{B}%1#/z{,1>},{2<[:i:#K%L=]sY0e[{si}%}%:.+S*
```
[Try it here.](http://cjam.aditsu.net/#code=0%5DK*X3tC30tG22tZ11t%3AL%3B0'a%5Dq%2B%7B'D%3E%7D%3AB%24_%7BB%7D%251%23%2Fz%7B%2C1%3E%7D%2C%7B2%3C%5B%3Ai%3A%23K%25L%3D%5DsY0e%5B%7Bsi%7D%25%7D%25%3A.%2BS*&input=cDCddDDCcCc)
Explanation (Dare I explain this? :O):
```
0]K*C3tX30tG22tZ11t:L; e# Creates this array [0,30,0,11,0,0,0,0,0,0,0,0,3,0,0,0,22,0,0,0]
0'a]q+ e# Creates an array that looks like [0, 'a', input string]
{'D>}:B$ e# Sorts the array by if the int representation of each element is greater than the int value of the character 'D' (e.g. [0,C,D,a,c,d])
_{B}%1#/ e# Finds the index of the first value in the array that is > 'D' and splits the array at that index.
z{,1>},{ e# Zip the two sub arrays and filter for only sub arrays with more than one element. (e.g [[0,a],[C,c],[D,d]])
{2<[:i:#K%L=]s e# For each sub array, take the first two elements, convert each to an it, calculate n=(x[0]^x[1]) mod 20, and get the nth element in the very first array, and convert it to a string
Y0e[ e# Pad the string with 0 so it is length 2. (e.g. [["00"],["22"],["11"]])
{si}%}%:.+ e# get the numerical representation of each digit and dot sum all of them (e.g [[0,0],[2,2],[1,1] => [3,3])
S* e# Join with a space (e.g "3 3")
```
] |
[Question]
[
## Background
A [polyomino](https://en.wikipedia.org/wiki/Polyomino) is called *L-convex*, if it's possible to travel from any tile to any other tile by an L-shaped path, that is, a path that goes in the cardinal directions and changes direction at most once.
For example, the polyomino of `1`s in the figure
```
0 0 1 1 1 0
1 1 1 1 0 0
1 1 0 0 0 0
```
is not L-convex, since both L-shaped paths from the bottom left `1` to the top right `1` contain a `0`:
```
0>0>1>1>1 0
^ ^
1 1 1 1 0 0
^ ^
1>1>0>0>0 0
```
However, the polyomino of `1`s in this figure is L-convex:
```
0 1 1 1 0 0
1 1 1 1 1 1
0 1 1 0 0 0
```
## Input
Your input is a 2D array of bits in the native format of your language, or as a newline-delimited string if our language lacks arrays.
It is guaranteed to contain at least one `1`.
## Output
Your output shall be a truthy value if the set of `1`s is an L-convex polyomino, and a falsy value if not.
These outputs must be consistent: you must output the same truthy value for all L-convex inputs, and the same falsy value for others.
Note that a disconnected set of `1`s (which is not a polyomino) results in a falsy output.
## Rules and Scoring
You can write either a full program or a function.
The lowest byte count wins, and [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
## Test Cases
These test cases should work also if you rotate or reflect the arrays, or add rows of `0`s to any borders.
```
False instances
01
10
111
101
111
1101
1111
1110
1100
1000
0011
01100
11110
01110
00110
011000
011110
001111
True instances
1
01
11
010
111
010
001
011
111
11100
11110
01100
01000
011000
011000
111100
111111
001000
```
[Answer]
# [Snails](https://codegolf.stackexchange.com/a/47495/30688), ~~45~~ 24
```
&
!{\1t\1!{o\1,nf\1,!.!~
```
Right after posting my initial solution, I realized there was a much better way. The original program traveled around the square formed by the paths between two `1`s, testing for the presence of a 0 in each pair of sides. It also had to have a special case for straight line paths. The new version starts by teleporting from one `1` to the other, and testing for the absence of a straight or L-shaped path of `1`s back to the start.
[Answer]
# Matlab, 182 bytes
Idea: Repeat for every `1` in the polyomino matrix:
* Create new matrix with only the given `1` but the rest zero.
* for every `1` in this new matrix (repeat until nothing changes anymore)
+ add `1` as neighbours in x direction if there are `1` as neighbours in the polynomio
* for every `1` in this new matrix (repeat until nothing changes anymore)
+ add `1` as neighbours in x direction if there are `1` as neighbours in the polynomio
Now `1` in the new matrix should cover all `1` in the polynomio-matrix that are reachable from the given starting point by first going in x-direction and then in y-direction. Now we can repeat the same process but with first going into y-direction and then in x-direction. Now every `1` of the polyomino matrix should be reached at once or both times. If not, then we have found a position in the polynomio matrix that cannot be reached from every other position by an `L`-path.
Golfed:
```
function r=f(a);[i,j,b]=find(a);N=nnz(i);r=1;for k=1:N;K=1:3;for l=1:2;c=b;b=a*0;b(i(k),j(k))=1;for z=1:2*N; b=conv2(b+0,K,'s')&a;if z==N;K=K';end;end;end;r=r*all(b(:)|c(:)>=a(:));end
```
With comments:
```
function r=codegolf_L_convex(a);
%a=[0,1;1,1];
[i,j,b]=find(a);%b just needs to be initialized, does not really mattter
N=nnz(i);%number of ones in the matrix
r=1;%return value
for k=1:N;%go throu all '1' in the matrix
%expand that pixel in x dir:
K=1:3;%convolution kernel (just three positive values needed)
for l=1:2;%first horizontal->vertical then vertical->horizontal
c=b;%backup for considering both runs
b=a*0;
b(i(k),j(k))=1; %set the seed
for z=1:2*N;
b=conv2(b+0,K,'s')&a; %expand the seed horizontally (or vertically for the second half) but only within the polyomino
if z==N;
K=K'; %change horizontal/vertical
end;
end;
end;
r=r*all(b(:)|c(:)>=a(:));%check whether we can really reach every point
end
```
Test cases script:
```
disp('all false -------------');
a=[0,1;1,0];
f(a)
a=[1,1,1;1,0,1;1,1,1];
f(a)
a=[1,1,0,1;1,1,1,1;1,1,1,0];
f(a)
a=[1,1,0,0;1,0,0,0;0,0,1,1];
f(a)
a=[0,1,1,0,0;1,1,1,1,0;0,1,1,1,0;0,0,1,1,0];
f(a)
a=[0,1,1,0,0,0;0,1,1,1,1,0;0,0,1,1,1,1];
f(a)
disp('all true +++++++++++++');
a=[1];
f(a)
a=[0,1;1,1];
f(a)
a=[0,1,0;1,1,1;0,1,0];
f(a)
a=[0,0,1;0,1,1;1,1,1];
f(a)
a=[1,1,1,0,0;1,1,1,1,0;0,1,1,0,0;0,1,0,0,0];
f(a)
a=[0,1,1,0,0,0;0,1,1,0,0,0;1,1,1,1,0,0;1,1,1,1,1,1;0,0,1,0,0,0];
f(a)
```
[Answer]
# Mathematica, ~~129~~ 127 bytes
```
3>GraphDiameter@Graph[#,#<->#2&@@@Select[#~Tuples~2,!FreeQ[#-#2&@@#,0]&]]&@Position[#,1]&&{#,Thread@#}~FreeQ~{___,1,0..,1,___}&
```
### Explanation:
First, if there is a `0` between two `1`s on the same row or column, the array is not L-convex, because we can't connect the two `1`s.
After excluding this case, every two `1`s on the same row or column can be connected by a straight path. We can generate a graph, whose vertices are the positions of `1`s in the array, and edges are pairs of `1`s on the same row or column. Then the array is L-convex if and only if the [diameter](http://reference.wolfram.com/language/ref/GraphDiameter.html) of the graph is less than 3.
[Answer]
# Javascript ES6, 290 bytes
Ok, maybe it won't win any awards for brevity, but it does use a novel approach. See the ungolfed version for how it works.
Proof for this method can be found in: [Cellular Automata and Discrete Complex Systems](https://books.google.co.uk/books?id=nynMCQAAQBAJ&pg=PA132&lpg=PA132&dq=l-convex+NW+NE&source=bl&ots=eubAlTlqsQ&sig=DiXpUjfTzo1Il-iVFXU8rZ7C__0&hl=en&sa=X&ved=0CCAQ6AEwAGoVChMI7YOYiYm0yAIViroaCh0MbwEN#v=onepage&q=l-convex%20NW%20NE&f=false).
```
L=a=>[1,0,1].every($=>(a=a[0].map((_,col)=>a.map(row=>row[col]))).map(r=>($?r.reverse():r).join``).every((r,i,b)=>r.replace(/^(0*)(1*)(0*)$|(.+)/,(_,s,m,o,e)=>(c=e)?'':!m||b[i-1]&&+b[i-1][s.length]?1:b.every((r,j)=>j<i||(c=c||!+r[l=s.length])?r.search(`0{${l}}.*0{${o.length}}`)+1:1)||'')))
```
Ungolfed:
```
function L(a) {
/* Runs three times and ensure all pass validation
* 1: horizontally reversed
* 2: 90 degrees rotated
* 3: original
*
* | 1: | 2: | 3:
* =====================
* 001 | 100 | 111 | 001
* 011 | 110 | 011 | 011
* 111 | 111 | 001 | 111
*
* By finding maximal rectangles with corners on all NW and NE corners
* (separately) of a HV-convex polyomino and ensuring it doesn't enter the
* boundaries labelled ABCD for the rectangle X below:
*
* A | | B
* -----===========-----
* | X |
* -----===========-----
* C | | D
*
* The first iteration tests the NE corners and horizontal convexity.
* The second iteration test vertical convexity.
* The third iteration tests the NW corners.
*
* If all pass then the polyomino is L-convex.
*/
return [1,0,1].every(function($){
return (a=a[0].map((_,col)=>{
// Transpose rows with columns
return a.map(row=>row[col])
})).map(row=>{
// Join rows as strings and on odd iterations reverse them
return ($ ? row.reverse() : row).join``
}).every(function(row, i, b) {
if (i == 0) console.log(b.join('\n'));
return row.replace(/^(0*)(1*)(0*)$|(.+)/, function(_, start, middle, end, invalid) {
// Non H-convex polyomino (0 between 1s)
if (invalid) return '';
// Is not a NW corner (character above is 1)
if (!middle || b[i-1] && +b[i-1][start.length]) return 1;
c=1;
return b.every(function(row, j) {
// Above or below maximal rectangle from corner
if (j < i || !(c=c&&+row[l=start.length])) {
// Area before and after maximal rectangle doesn't contain 1
return row.search(`0{${l}}.*0{${end.length}}`)+1
}
return 1;
}) || '';
});
});
});
}
```
[Answer]
# JavaScript (ES6) 174
Looking at the grid of empty or filled cells, for any pair of filled cells I check the horizontal paths to the other cell column (there can be 1 if the cells are on the same row, else or 2) and the vertical paths to the other cell row (there can be 1 or 2 too). If I find an empty cell in both vertical paths or both horizontal paths, then there can not be an L shaped path between the cells.
(I had a hard time trying to put up this explanation - I hope to have been clear)
Test running the snippet below in any EcmaScript 6 compliant browser
```
F=p=>!p.some((n,y)=>n.some((q,x)=>q&&p.some((o,u)=>o.some((q,t)=>{for(f=0,i=y;q&i<=u;i++)f|=!p[i][x]|2*!p[i][t];if(f<3)for(f=0,j=x;q&j<=t;j++)f|=!n[j]|2*!o[j];return f>2}))))
// TEST
console.log=(...x)=>O.innerHTML+=x+'\n'
tko = [
[[0,1],[1,0]]
,[[1,1,1],[1,0,1],[1,1,1]]
,[[1,1,0,1],[1,1,1,1],[1,1,1,0]]
,[[1,1,0,0],[1,0,0,0],[0,0,1,1]]
,[[0,1,1,0,0],[1,1,1,1,0],[0,1,1,1,0],[0,0,1,1,0]]
,[[0,1,1,0,0,0],[0,1,1,1,1,0],[0,0,1,1,1,1]]
]
tko.forEach(t=>(console.log(t.join`\n`+`\nFalse? ${F(t)}\n`)));
tok = [
[[1]]
,[[0,1],[1,1]]
,[[0,1,0],[1,1,1],[0,1,0]]
,[[0,0,1],[0,1,1],[1,1,1]]
,[[1,1,1,0,0],[1,1,1,1,0],[0,1,1,0,0],[0,1,0,0,0]]
,[[0,1,1,0,0,0],[0,1,1,0,0,0],[1,1,1,1,0,0],[1,1,1,1,1,1],[0,0,1,0,0,0]]
]
tok.forEach(t=>(console.log(t.join`\n`+`\nTrue? ${F(t)}\n`)));
// LESS GOLFED
U=p=>
!p.some((n,y)=>
n.some((q,x)=>
q && p.some((o,u)=>
o.some((q,t)=>{
for(f=0,i=y; q&i<=u; i++)f|=!p[i][x]|2*!p[i][t]
if (f<3)
for(f=0,j=x; q&j<=t; j++)f|=!n[j]|2*!o[j]
return f>2
})
)
)
)
```
```
<pre id=O></pre>
```
] |
[Question]
[
You should write a program or function which receives a string describing the floor as input and outputs or returns the area of the simplest meta-tiling which could create the given pattern of the floor.
The floor is a part of a square grid. Every square tile is colored either azure or black (represented by `a` and `b` in the input).
An example floor:
```
aaaa
ababab
aaaaa
```
A meta-tiling
* is built from an `N` by `M` rectangular meta-tile of azure and black squares
* the used meta-tiles are identical up to translation (you cannot rotate or mirror them)
* if the sides of two meta-tiles are connected they should connect along their whole length (i.e. meta-tiles tile the space in a grid-like fashion)
An example meta-tile:
```
ba
aa
```
and the meta-tiling created by it:
```
.
.
.
babababa
aaaaaaaa
... babababa ...
aaaaaaaa
babababa
aaaaaaaa
.
.
.
```
This meta-tiling creates the upper shown floor as the left letters show:
```
.
.
.
********
***aaaa*
... *ababab* ...
*aaaaa**
********
********
.
.
.
```
A meta-tiling is simpler than another if the area of its meta-tile is smaller. Our example has an area of `2*2 = 4` which is the smallest possible for the example floor. So the output should be `4` for the example.
## Input
* A string consisting of the characters `a b space` and `newline` containing at least one `a` or `b`.
* The letters (`ab`) form one 4-connected (side-by-side connected) shape.
* There will be no unnecessary spaces at the front of the rows i.e. there will be at least one row starting with `a` or `b`.
* You can choose of two input format:
+ No unnecessary whitespace at the end of rows (as seen in the examples).
+ Spaces on the right side of the rows to make all rows the same length as the longest row.
* Trailing newline is optional.
## Output
* A single integer, the area of the smallest possible meta-tile whose tiling contains the input floor.
## Examples
Examples are delimited by dashes. The three parts of an example are input, output and one of the possible smallest meta-tiles.
```
a
1
a
-----------------
aaaa
aaa
a
1
a
-----------------
aabaab
abaa
aaba
6
aab
aba
-----------------
aabaab
a a a
aabab
18
aabaab
aaaaaa
aababa
-----------------
ba
aaab
8
baaa
aaab
-----------------
aaaa
ababb
aaaa
10
aaaaa
ababb
-----------------
a aa
ab ba
aba
6
aa
ab
ba
-----------------
aaaa
abab
aaaa
4
aa
ab
-----------------
ba
ba
b
4
ba
ab
-----------------
baa
aba
aab
9
baa
aba
aab
-----------------
aaaa
aabaa
aaaa
6
aaa
aab
```
This is code golf so the shortest entry wins.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~53~~ ~~37~~ 36 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{⌊/×/¨⍸(~6∊' a'∧/⍤⍳⍵⊢⌸⍥,⍨|)⍤0 2⍨⍳⍴⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U06V/eLr@oRWPendo1Jk96uhSV0hUf9SxXP9R75JHvZsf9W591LXoUc@OR71LdR71rqjRBIobKBgBmWDZLUAFtQA&f=y00sUXjUNuFRV5OhguGj3i3qiepcuYklOhCxR20T1RUSgUBdQR1KoksnJiYBEUgmCaosCY8aBYVEBZiqJHRlSVBrknA6AagpCaImEYs7FaCKFMAGKWBxCLJBUHOwOgJqggIWJ0K1Q/yAO6xggQG1gCvt0IpcUFD3zlUABrSCmYKhhYKFgqEBkGUChJYKZgA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Instead of partitioning, this one groups the characters in the matrix by their 2D indices modulo current size. I came up with it independently, but apparently it's the same as [Zgarb](https://codegolf.stackexchange.com/a/209609/78410)'s idea. But there's a funky part in this solution: in order to test if a group contains both `a` and `b`, it maps space/a/b into 1, 2, 3 respectively via find-index function, and calculates their LCM to see if it is 6.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 53 [bytes](https://github.com/abrudz/SBCS)
```
{⌊/×/¨⍸{∧/,⍲/¨'ab'∘∊¨⊃{⍉,⌿↑⍺⊂⍵}/(⊂,⍨⍴⍴¨⍺↑¨≡)⍵}∘⍵¨⍳⍴⍵}
```
[Try it online!](https://tio.run/##tZHPSsNAEMbv@xRzawMpMTaE9uxFr9YX2EXqpaAnoYRcFEIausUeRC8KnsxNUAviRYhvMi8Sv93YPxTEBHE32Qyb75vfzqw8G3WOx3J0elJGPM28zxuvyM891nnE6aPnsn7GRkuqFqe3nGZFztllxHri8vSDkznrd84uWC9ir91m/YrIwQcy/EjmRe477rfAJNALZOfkCnlfKnUs1lzWb/9GXQPLPwIRQJ/bbBtInjw4PwCHqJj1DCmLp67JNrseHO5hPdo/GJRDwhZY97E1@USs78gXUnS2h9jSdpdakhjCvrVdIfQKjzCrjesDeysvkaTKrX6371b2nlD2sKo@cGdZIjhK2LB@neaIxkrAUpM6gw1qM2hgSrQ8ql9lX6gKJpr0JlzdfnWPWITtGWaIq6Ie2ocowOxT@AU "APL (Dyalog Unicode) – Try It Online")
A function that takes a character matrix as the argument. Basically, tries all possible tile sizes, testing if partitioning by that size would give at most one of `ab` on every cell.
### Illustration
```
Example input:
a aa
ab ba
aba
Example tile size: 2 rows, 2 columns
Partition:
+--+--+-+
| a| a|a|
|ab| b|a|
+--+--+-+
| a|ba| |
+--+--+-+
Cells collected into a tile:
+------+------+
| a b |aa aa |
+------+------+
|a a |bb |
+------+------+
Since top left cell has both a and b, this tile size is invalid.
```
### How the code works
```
{⌊/×/¨⍸{∧/,⍲/¨'ab'∘∊¨⊃{⍉,⌿↑⍺⊂⍵}/(⊂,⍨⍴⍴¨⍺↑¨≡)⍵}∘⍵¨⍳⍴⍵}
⍝ ⍵ ← Char matrix
⍳⍴⍵ ⍝ Generate possible tile sizes as a matrix of length-2 vectors
{...}∘⍵¨ ⍝ Test if each tile size is valid...
⍝ ⍵ ← Input char matrix, ⍺ ← tile size
(⊂,⍨⍴⍴¨⍺↑¨≡)⍵ ⍝ Create partition vectors and join with ⍵ for RTL reduction
( ≡)⍵ ⍝ Depth of ⍵, which always gives 1 for valid input
⍺↑¨ ⍝ Overtake 1 to the length of each of ⍺, e.g. (1 0)(1 0 0)
⍴⍴¨ ⍝ Cycle each to the length of the dimensions of ⍵,
⍝ e.g. (1 0 1 0 1)(1 0 0 1 0)
⊂,⍨ ⍝ Append the enclosed ⍵
⊃{⍉,⌿↑⍺⊂⍵}/ ⍝ Partition and collect all cells at the same position in the tile
{ }/ ⍝ Reduce by...
⍺⊂⍵ ⍝ Partition ⍵ into consecutive columns at 1s of ⍺
↑ ⍝ Mix so that short partition is padded with spaces
,⌿ ⍝ Collect the cells at the same position
⍉ ⍝ Transpose to do the same for rows
⊃ ⍝ Disclose one level of nesting (which is a side effect of /)
∧/,⍲/¨'ab'∘∊¨ ⍝ Test if no tile position contains both a and b
'ab'∘∊¨ ⍝ For each tile position, evaluate (has a)(has b)
⍲/¨ ⍝ Reduce each by NAND; 1 if the tile position has at most one of ab
∧/, ⍝ Test if it is true for all positions
⌊/×/¨⍸ ⍝ Extract the answer (the smallest area)
⍸ ⍝ 1-based coordinates of ones; the tile sizes which passed the test
⌊/×/¨ ⍝ Minimum of the areas
```
[Answer]
## C - 208 bytes
```
w,q,n,m,r,g,u;t(char*f){for(w=0;f[w++]-10;);for(q=1;;q++)for(n=1;m=q/n,n<=q;++n)if(n*m==q){char t[q];bzero(t,q);r=q;for(g=0;f[g];++g){u=g/w%m*n+g%w%n;r=t[u]+f[g]-195?r:0;if(f[g]&64)t[u]=f[g];}if(r)return r;}}
```
Equivalent code before golfing:
```
#include <stdio.h>
#include <strings.h>
int t(char* f) {
int w = 0;
for ( ; f[w++] - 10; );
for (int q = 1; ; q++) {
char t[q];
for (int n = 1; n <= q; ++n) {
int m = q / n;
if (n * m == q) {
bzero(t, q);
int r = q;
for (int g = 0; f[g]; ++g) {
int u = g / w % m * n + g % w % n;
if (t[u] + f[g] == 195) {
r = 0;
}
if (f[g] & 64) {
t[u] = f[g];
}
}
if (r) {
return r;
}
}
}
}
}
```
The algorithm is fairly brute force, so it should be reasonably obvious how it works based on the code. Here are a few comments anyway:
* Input is expected to have the form with trailing spaces so that all lines have the same length.
* First loop finds the width by looking for first newline character.
* Outer loop is over candidate meta-tile sizes `q`. Exits with a `return` when a meta-tile can cover the floor. Note that the loop does not need another exit condition since there is always a solution (worst case is size of input).
* First nested loop and following `if` enumerates valid meta-tile width/height combinations for size `q`.
* A character array matching the candidate meta-tile size is zero-initialized.
* Inner loop iterates over all tiles in the floor.
* `u` is the index in the meta-tile that corresponds to the floor tile.
* If both floor tile and meta-tile tile are `a` or `b` and different (sum of `a = 97` and `b = 98` is `195`), there is a mismatch, and the meta-tile size with the attempted dimensions will not work.
* Otherwise, if the floor tile is `a` or `b`, the tile color is copied to the candidate meta-tile.
* Returns size of meta-tile when successful match was made, i.e. if the attempted match was not marked as failed.
Test code used:
```
#include <stdio.h>
extern int t(char* s);
int main()
{
printf("%d\n", t(
"a\n"
));
printf("%d\n", t(
" aaaa\n"
"aaa \n"
"a \n"
));
printf("%d\n", t(
"aabaab\n"
"abaa \n"
"aaba \n"
));
printf("%d\n", t(
"aabaab\n"
"a a a\n"
"aabab \n"
));
printf("%d\n", t(
"ba \n"
"aaab\n"
));
printf("%d\n", t(
" aaaa\n"
"ababb\n"
"aaaa \n"
));
printf("%d\n", t(
" a aa\n"
"ab ba\n"
" aba \n"
));
printf("%d\n", t(
" aaaa\n"
"abab \n"
"aaaa \n"
));
printf("%d\n", t(
"ba \n"
" ba\n"
" b\n"
));
printf("%d\n", t(
"baa\n"
"aba\n"
"aab\n"
));
printf("%d\n", t(
" aaaa\n"
"aabaa\n"
"aaaa \n"
));
return 0;
}
```
Output:
```
1
1
6
18
8
10
6
4
4
9
6
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 30 bytes
```
ḟ(SδV(ΛË←k→f←δṁz,¶⁰¤Ṫeo¢ḣ)↔Ḋ)1
```
[Try it online!](https://tio.run/##AVIArf9odXNr///huJ8oU860VijOm8OL4oaQa@KGkmbihpDOtOG5gXoswrbigbDCpOG5qmVvwqLhuKMp4oaU4biKKTH///8gIGFiYgphYiBhYgpiYmFi "Husk – Try It Online")
## Explanation
I loop through all nonnegative integers until I find one that, when split into two factors in some way, gives a horizontal and vertical period for the input patch.
The period is checked by grouping the 2D indices of non-space characters by their values modulo the two numbers, and checking that each group contains equal characters.
```
ḟ(…)1 Starting from 1, find a number that satisfies (…).
SδV(…)↔Ḋ We're looking at a number, say n=6.
Ḋ Divisors: d = [1,2,3,6]
S ↔ Reverse and apply to both:
δV(…) does any pair from d and its reverse satisfy (…)?
For n=6, the pairs are (1,6), (2,3), (3,2), and (6,1).
ΛË←k→f←δṁz,¶⁰¤Ṫeo¢ḣ Check if (a,b) is a valid metatile.
¤ For both a and b:
ḣ take range from 1 to it
o¢ and cycle it infinitely.
Ṫ Combine these by taking outer product by
e pairing.
For (a,b)=(2,3), this gives the infinite 2D array
A=[[[1,1],[1,2],[1,3],[1,1],..],
[[2,1],[2,2],[2,3],[2,1],..],
[[1,1],[1,2],[1,3],[1,1],..],
..]
¶⁰ The input, split at newlines.
δṁ For each row of it and A:
z, zip them (discarding overflowing rows and pairs of A)
δṁ and concatenate the results.
Now we have a list of pairs like ('a',[2,3]) that contain
a character from the input and its coordinates mod (a,b).
f← Keep those whose left part is truthy, i.e. not a space.
k→ Classify (into separate lists) by right part.
Λ Does every class
Ë← have all equal left parts?
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-r`, 52 bytes
```
MN:$*_M{$&{$*$Q*$.aDCs}M_UWa@1MMyUW@a}FI\,#gCP\,#@Yg
```
Takes input from lines of stdin, with trailing spaces as needed. [Try it online!](https://tio.run/##K8gs@P/f189KRSvet1pFrVpFSyVQS0Uv0cW5uNY3PjQ80cHQ17cyNNwhsdbNM0ZHOd05AEg6RKb//6@QqJCYyJWYpJCUyKWQmJSo8F@3CAA "Pip – Try It Online")
Approach taken from [Bubbler's APL answer](https://codegolf.stackexchange.com/a/207370/16766): We try all possible meta-tile dimensions, filtering for the ones that have a unique non-space character at each position. `UW` (unweave) is very useful for grouping the input grid by tile positions. We then multiply each successful pair of dimensions to get the area of the tile, and take the minimum.
Leave a comment if you'd like a more detailed explanation.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 44 bytes
```
∧ℕf⟨≡z↔⟩∋[X,Y]×.&ṇġ↙Xz₁ġᵐ²↙Yz₁ᵐ²zᵐ{c;Ṣx=}ᵐ²∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HH8kctU9MezV/xqHNh1aO2KY/mr3zU0R0doRMZe3i6ntrDne1HFj5qmxlR9aip8cjCh1snHNoE5EaCuGBOFZCsTrZ@uHNRhW0tRLpj@f//SgqJComJXIlJCkmJXAqJSYlK/x0B "Brachylog – Try It Online")
A port of [Zgarb's Husk answer](https://codegolf.stackexchange.com/a/209609/16766). Brachylog doesn't have infinite lists or cyclic indexing, so instead I'm using the "groups" predicate `ġ` (`[1,2,3,4,5]ġ₂ -> [[1,2],[3,4],[5]]`) and then zip `z` (`[[1,2],[3,4],[5]]z₁ -> [[1,3,5],[2,4]]`) to get lists of the characters at tile-equivalent positions.
] |
[Question]
[
## Challenge
Your challenge is to design an interpreter for a lisp-like language, which will from hence forth be coined: *GLisp*. The program code for *GLisp* will consist of an arbitrary amount of nested expressions denoted by brackets, in the following form:
```
(func arg1 arg2 ...)
```
Note that the interpreter must allow for extraneous whitespace characters before and after brackets, functions, and arguments.
## Types
You will implement four types, Integer, List, Boolean, and Function. Integers and Boolean values can be explicitly inserted into source code with their own syntax. Your interpreter must assume that a run of numeric characters denotes an Integer (you do not have to implement a syntax to explicitly insert negative integers). Your interpreter must also assume that `true` and `false` are designated Boolean values. Functions can not be explicitly defined by the user, and will always return a single value (a List of any length counts as a single value).
## Functions
The following functions are required to be implemented, and are in the format ***Function***, Arity. If an Arity `n` is proceeded by a plus sign, then that denotes `n` or more arguments. You may assume that all arguments given to a function are of the same type, unless specificed otherwise. You may also assume that if no behaviour is specified for a certian type, then you may assume that no argument of that function will ever be of that type. Arguments will be referred to as in the following diagram:
`(func argument1 argument2 ... argumentn)`
* **+**, 2+
+ If all arguments are of the type *Integer*, you must return the sum of the arguments
+ If all arguments are of the type *List*, you must return the concatenation of the arguments in ascending order (`arg1+arg2+ ...`)
+ If all arguments are of the type *Boolean*, you must return the logical All of the sequence of arguments
+ `(+ 1 2 3 4 5) -> 15`
+ `(+ (list 1 2) (list 3 4)) -> (list 1 2 3 4)`
+ `(+ true true true) -> true`
* **-**, 2+
+ If all arguments are of the type *Integer*, you must return the difference of the arguments (`arg1-arg2- ...`)
+ If all arguments are of the type *Boolean*, you must return the logical Any of the sequence of arguments
+ `(- 8 4 3) -> 1`
+ `(- 0 123) -> -123`
+ `(- true false false true false) -> true`
* **\***, 2+
+ If all arguments are of type *Integer*, you must return the product of the arguments
+ If one argument is of type *List* and the other is of type *Integer* (you may assume that these will only be the only arguments given), you must return a new **List** with the items in `arg1` repeated `arg2` times.
+ `(* 1 2 3 4 5) -> 120`
+ `(* (list 1 2 3) 2) -> (list 1 2 3 1 2 3)`
* **/**, 2+
+ If all arguments are of the type *Integer*, you must return the quotient of the arguments (`arg/arg2/ ...`) (you may assume that division is done sequentially, and that the decimal portion at every step is truncated)
+ If one argument is of type *List* and the other is of type *Function*, then you must return the resulting *List* after `arg2` has been mapped over every value
+ `(/ 100 10 3) -> 3`
+ `(/ (list 1 2 3) inc) -> (list 2 3 4)`
* **%**, 2
+ If all arguments are of the type *Integer*, you must return the modulus of the arguments
+ `(% 4 2) -> 0`
* **=**, 2+
+ If **both** the type and value of all arguments is the same, you must return true. Otherwise, return false.
+ `(= 0 0 0) -> true`
+ `(= 0 false (list)) -> false`
* **list**, 0+
+ You must return a list of all arguments, regardless of type. If no arguments are given, then you must return an empty list
+ `(list 3 4 (list 5)) -> (list 3 4 (list 5))`
* **inc**, 1
+ If argument is of type *Integer*, you must return the *Integer* incremented by one
+ If argument is of type *List*, you must return the *List* rotated clockwise a single rotation
+ `(inc 1) -> 2`
+ `(inc (list 1 2 3)) -> (list 3 1 2)`
* **dec**, 1
+ If argument is of type *Integer*, you must return the *Integer* decremented by one
+ If argument is of type *List*, you must return the *List* rotated counter-clockwise a single rotation
+ `(dec 1) -> 0`
+ `(dec (list 1 2 3)) -> (list 2 3 1)`
* **if**, 3
+ If given **three** arguments of any type: If the truth value of `arg1` is true, return `arg2`, else return `arg3`
+ `(if (not (list 1)) 8 false) -> false`
* **not**, 1
+ If given an argument of any type, if the truth value of `arg1` is False, return `true`, else return `false`.
+ `(not (list)) -> true`
* **len**, 1
+ If given an argument of type *List*, return the length of `arg1`
+ `(len (list 4 2 true (list 3) (list))) -> 5`
Truth table:
`0, (list), false -> false`, where `(list)` denotes an empty list. Everything else is `true`.
Your interpreter can either be a full program that reads the source input from stdin or a file, or a function which takes the source as a string and returns the output value.
If choosing the former, the output for *Integers* is simply numbers, for *Booleans* is `true` or `false`, and for lists is a space separated sequence of values enclosed in brackets (eg. `(1 2 3 4 (5 6 7))` denotes `(list 1 2 3 4 (list 5 6 7))`).
If choosing the latter, the value must be returned in the implementation language's corresponding type, or, if no similar type exists, a custom type. *Lists* can be returned as Arrays or Vectors if the language doesn't have a *List* type, *Booleans* should be returned as a Boolean type in the language, or a custom type if the language does not support them.
## Test cases
```
(list 1 2 3 (list 4 5 true)) -> (1 2 3 (4 5 true))
(/ 4000 (+ 1 2 3 4 (* 5 8))) -> 80
(+ (not (- (len (list 5 6 7)) (/ 10 3))) true) -> true
(if ( len (list ) ) 4 (if (+ (= 8 8 8) (not (list 4))) 8 5)) -> 5
```
## Clarifications
* Your interpreter may deal with invalid input in any way you choose, but it **must not** throw an exception (though, it may print an error message and exit smoothly)
* Functions will always evaluate arguments left to right
* Invalid input is any input which is syntactically incorrect. This includes, but is not limited to, mismatched brackets, division by zero, and partially applied functions (unless going for the bonus)
* For `=`, if any of the values are different **or** any of the types are different, return `false`
## Bonuses
* **Score \* 0.8** if you support partially applied functions. For example, `((+ 2) 3)` would be the same as `(+ 2 3)`, but allows for things such as `(/ (list 1 2 3) (+ 2))`. You may assume that a function is partially applied if it receives less than its minimum number of arguments
* **Score \* 0.85** if you do not evaluate the arguments applied to `if` unless they are going to be returned
This is code-golf, so the interpreter with the lowest byte count wins!
[Answer]
## Haskell, 1370 1263 1179 1128 1163 1107 1084 bytes \* 0.8 \* 0.85 = 737.12
```
import Text.Parsec
data V=I Int|L[V]|T|F|P[V]|X|A|S|M|D|U|E|Q|J|K|C|N|W deriving Eq
m Q=0;m C=3;m f|f`elem`[J,K,N,W]=1;m _=2
l=length
x v=[n|I n<-v]
y v=[l|L l<-v]
z v=[0<1|T<-v]++[1<0|F<-v]
(&)f=l.f>>=(.l).(==)
b a|a=T|0<1=F
s(I n)=show n
s(L v)='(':tail(v>>=(' ':).s)++")"
s T=d!!0;s F=d!!1;s _="error"
i(L v)=e$i%v
i v=v
e(P v:a)=e$v++a
e(f:a)|m f>l a=P(f:a)
e(A:a)|x&a=I$sum$x a|y&a=L$concat$y a|z&a=b$and$z a
e(S:a)|x&a=I$f$x a|z&a=b$or$z a
e(M:a)|x&a=I$product$x a
e[M,v,I n]=e$A:replicate n v
e(D:a)|x&a=I$v$x a
e[D,L v,f]=L$map(\a->e[f,a])v
e[U,I a,I b]=I$a`mod`b
e(E:a:v)=b$all(==a)v
e(Q:a)=L a
e[J,I a]=I$a+1
e[J,L[]]=L[]
e[J,L v]=L$last v:init v
e[K,I a]=I$a-1
e[K,L v]=L$drop 1 v++take 1 v
e[C,a,b,c]|a`elem`[I 0,L[],F]=c|0<1=b
e[N,a]=e[C,a,F,T]
e[W,L v]=I$l v
e _=X
f(a:b)=a-sum b
v(a:b)=foldl div a b
(%)f=fmap f
p=k$choice$try%([(I .read)%many1 digit,L%between(w"(")(k$w")")(many$try p)]++zipWith((.return).(>>).w)d[T,F,A,S,M,D,U,E,Q,J,K,C,N,W])
k=(spaces>>)
w=string
d=words"true false + - * / % = list inc dec if not len"
g=either show(s.i).parse p""
main=interact g
```
Full program, reading `stdin` and writing to `stdout`. `g` is the function version, as well.
Implements both partial functions, and lazy evaluation of `if`.
Sample runs (of the function version):
```
λ: g "(list 1 2 3 (list 4 5 true))"
(1 2 3 (4 5 true))
λ: g "(/ 4000 (+ 1 2 3 4 (* 5 8)))"
80
λ: g "(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)"
true
λ: g "(if ( len (list ) ) 4 (if (+ (= 8 8 8) (not (list 4))) 8 5))"
5
λ: g "(if false (/ 1 0) 5)"
5
λ: g "((+ 2) 3)"
5
λ: g "(/ (list 1 2 3) (+ 2))"
(3 4 5)
```
Now has all unit tests from the description:
```
λ: runTests
passed: g "(+ 1 2 3 4 5)" ==> 15
passed: g "(+ (list 1 2) (list 3 4))" ==> (1 2 3 4)
passed: g "(+ true true true)" ==> true
passed: g "(- 8 4 3)" ==> 1
passed: g "(- 0 123)" ==> -123
passed: g "(- true false false true false)" ==> true
passed: g "(* 1 2 3 4 5)" ==> 120
passed: g "(* (list 1 2 3) 2)" ==> (1 2 3 1 2 3)
passed: g "(/ 100 10 3)" ==> 3
passed: g "(/ (list 1 2 3) inc)" ==> (2 3 4)
passed: g "(% 4 2)" ==> 0
passed: g "(= 0 0 0)" ==> true
passed: g "(= 0 false (list))" ==> false
passed: g "(list 3 4 (list 5))" ==> (3 4 (5))
passed: g "(inc 1)" ==> 2
passed: g "(inc (list 1 2 3))" ==> (3 1 2)
passed: g "(dec 1)" ==> 0
passed: g "(dec (list 1 2 3))" ==> (2 3 1)
passed: g "(if (not (list 1)) 8 9)" ==> 9
passed: g "(not (list))" ==> true
passed: g "(len (list 4 2 true (list 3) (list)))" ==> 5
passed: g "(list 1 2 3 (list 4 5 true))" ==> (1 2 3 (4 5 true))
passed: g "(/ 4000 (+ 1 2 3 4 (* 5 8)))" ==> 80
passed: g "(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)" ==> true
passed: g "(if ( len (list ) ) 4 (if (+ (= 8 8 8) (not (list 4))) 8 5))" ==> 5
passed: g "(if false (/ 1 0) 5)" ==> 5
passed: g "((+ 2) 3)" ==> 5
passed: g "(/ (list 1 2 3) (+ 2))" ==> (3 4 5)
```
[Answer]
# Common Lisp, 868 bytes \* 0.85 = 737.8
Is it cheating to implement Lisp with Lisp? Lots to optimize here, still.
```
(SETF (READTABLE-CASE *READTABLE*) :PRESERVE)(PRINC(LABELS((B(X)(FIND X'(true false)))(R(X)(IF X'true'false))(V(X)(MEMBER X'(0()false)))(A(&REST X)(R(NOTANY #'V X)))(O(&REST X)(R(NOTEVERY #'V X)))(E(X &KEY N)(IF(LISTP X)(ECASE(FIRST X)(+(APPLY(IF(EVERY'NUMBERP #1=(MAPCAR(IF N #'IDENTITY #'E)(CDR X)))'+(IF(EVERY'LISTP #1#)'APPEND #'A))#1#))(-(APPLY(IF(EVERY'NUMBERP #1#)'- #'O)#1#))(*(IF(LISTP #2=(CAR #1#))(LOOP FOR I TO(1-(CADR #1#))APPEND #2#)(APPLY'* #1#)))(/(IF(LISTP #2#)(LOOP FOR I IN #2#COLLECT(E `(,(CADR #1#),I):N T))(REDUCE'FLOOR #1#)))(%(APPLY'MOD #1#))(=(R(LOOP FOR I IN(CDR #1#)ALWAYS(EQUAL I #2#))))(list #1#)(inc(IF(LISTP #2#)(APPEND(LAST #2#)(BUTLAST #2#))(1+ #2#)))(dec(IF(LISTP #2#)(APPEND(CDR #2#)`(,(FIRST #2#)))(1- #2#)))(if(IF(V(E(CADR X)))(E(CADDDR X))(E(CADDR X))))(not(R(V #2#)))(len(LENGTH #2#)))X)))(OR(IGNORE-ERRORS(OR(E(READ))"()")):E))
```
Prints out an E in case of an error in input. Sample runs:
```
$ sbcl --script glisp.lisp
(list 1 2 3 (list 4 5 true))
(1 2 3 (4 5 true))
$ sbcl --script glisp.lisp
(/ 4000 (+ 1 2 3 4 (* 5 8)))
80
$ sbcl --script glisp.lisp
(+ (not (- (len (list 5 6 7)) (/ 10 3))) true)
true
$ sbcl --script glisp.lisp
(if ( len (list ) ) 4 (if (+ (= 8 8 8) (not (list 4))) 8 5))
5
$ sbcl --script glisp.lisp
(this is an error)
E
$ sbcl --script glisp.lisp
(if (% 4 2) (this is an error) 42)
42
```
[Answer]
# Python 2, 1417 \* 0.8 \* 0.85 = 963.56
```
from operator import*
A=type;K="list"
def E():print"E";exit()
def R(G):
len(G)or E();T=G.pop(0);L=[]
if"("==T:
G or E()
while")"!=G[0]:L+=[R(G)];G or E()
G.pop(0);return L
if")"==T:E()
try:
x=eval(T.title())
if Q(x)<2:return x
E()
except:return T
H="+ - * / = % if inc dec not len"
Z=lambda y:lambda x:reduce(y,x)
D=dict(zip(H.split(),[[sum,any,0,lambda x:sum((y[1:]for y in x),[K])],[Z(sub)],[Z(mul),all,0,lambda x:x[0][:1]+x[0][1:]*x[1]],[Z(div),lambda x:[K]+map(lambda z:S([x[1],z]if Q(x[1])==2else x[1]+[z]),x[0][1:])],[lambda x:len(set(map(str,x)))<2]*6,[lambda x:x[0]%x[1]],[lambda x:S(x[2])if S(x[0])in[0,[K]]else S(x[1])]*6,[lambda x:x[0]+1,0,0,lambda x:x[0][:1]+x[0][-1:]+x[0][1:-1]],[lambda x:x[0]-1,0,0,lambda x:x[0][:1]+x[0][2:]+[x[0][1]]],[lambda x:x[0]in[0,[K]]]*6,[0]*3+[lambda x:len(x)-1]]))
H=H[:15]+H+" if"
def Q(x):
t=A(x);w=int,bool,str
if t in w:return w.index(t)
if t==list and x:return 5-(2*(x[0]==K)+(str==A(x[0])and len(x)<H.count(x[0])+1))
E()
def S(G):
if Q(G)<2:return G
G or E();c=G[0];r=G[1:];c==K or r or E()
if c!="if":r=[x if Q(x)in{2,4}else S(x)for x in r]
if c==K:return[c]+r
k=map(Q,r);m=min(k);M=max(k);v=[m,[-1,3][{m,M}=={4,5}]][m!=M]
try:return D[c][v](r)
except:E()
def C(x):return"(%s)"%" ".join(map(C,x))if A(x)==list else str(x).lower()
def I(G):
for c in"+-*/%=()":G=G.replace(c," %s "%c)
return C(S(R(G.strip().split())))
print I(raw_input())
```
Complete overhaul. If you want to see the previous versions, check out the [edit history](https://codegolf.stackexchange.com/revisions/43253/3).
There's a lot more to be golfed. I'm slowly working on it.
With zlib/base64 we get **1093 \* 0.8 \* 0.85 = 743.24**:
```
import base64,zlib
exec zlib.decompress(base64.b64decode("eJx9VE1P4zAQvedXGEuV7MbttgX2kOADAtSugANbTljWKqSuNku+5Lg0BfHfd8ZJCwjt9tLpdN6bmTczXtuqIFVtbOIqS7KirqwbBufS7WoTX0uaZ42jwcqsyRXjUW2z0tErGps2c4x7/08251FAclOCARwQF9/L+biuajbh8Y1UOiDZmjIq5T0EkjnposDc/s5yQzk9knM10dFNKBXS6fhDzIHJGrexJbnxbNyz+Qhnd0jbSvOc5Ox+7DKXG8YRm63JHWv52SzqwS04Pci0qand3n0fLCQNyYgMyTciyQCBWZmSlUlJWTlsjgYPMk+Kx1VCdlFvtIBfbVLDdqLlwaVcZaljL1nNFuOmzlEhoVSzKURS7sREHFDgYmynppFeQ5s7SEVaCL3WXAv1wJrNY2cUm5yLJM8/YlsQSkVTHXoDKIatmmofvsqe+Xsg0IVFUrPe8RItmcJQ8aI7WcDmUs5M3hiCP0L1ornY02IFBy4cbmMcQ77GWeiWg6h6+P1DDAIHfS0H5xLSzDSHhGhNwCrVBDvVPu2yq+IrUTiFnv/Z9Qjq2/c/+pwQvaP/gmeAVR1Yf4EeyvMlTfTwOPysQssxISzXQi6A81SHi5DiQvpbwGWDXXTyHIx4K+FaxGNV5QJEw7UlDme93a/ddpyVK9Myx7s/pcRzI0m58qvlY05HbDb02kl5zUOUXyI9iomBXVFni3FabUrX+cMpbv9Vf6DL7kD90OcfbmEeHE4xTv0Bxha+QFv4Ka/xL3s4Q0CnR5JCo5GVqt1fVla+zsTJ236YHPe5xR6t7jBA1OdTqQ5BhCeJS3QnLI8LWWQle+LxLfhaNJ6lKgSMVxxr9VqI2zcpX0/E6ZvWqjiSt7o79r7+S2BUz5rZ93Pet3yBc+jCKBs0nA4ooeM/FaTD7Be4wFAdTqnX3HcA2oJnnFdbY3umH5142FcKfdFwNPw2kIzTaA5vnDV1nsD9p4KSQUPoIIVa+vIu2JLBYzYGUngR+P5FgE/gn1Ggtsn2V1bWG3T/BUW+qRU="))
```
*Note: If you see my score going up, it's probably because I found a few bugs*
[Answer]
# Haskell, 972
```
r=fst.f
f('(':s)|(f:a,b)<-g s=(f%filter(/="")a,b)
f s=span(`notElem`" ()")s
j=dropWhile(==' ')
g""=([],"")
g s|')':l<-r=([x],l)|(y,t)<-g$j r=(x:y,t)where(x,r)=f$j s
"%"%c=show$foldr(mod.read)(maxBound::Int)c
"+"%c|t(c!!0)<1="(list "++tail(c>>=(' ':).drop 6.init)++")"|t(c!!0)<2=show$sum$map read c|0<1=i$all((=='t').head)c
"-"%c|t(c!!0)<2=show$foldl1(-)$map read c|0<1=i$any((=='t').head)c
"*"%c=fst$f$"(+ "++unwords([1..read$last c]>>init c)++")"
"="%c=i$all(==c!!0)c
"/"%c|t(c!!0)<1,[a,b]<-c="list"%map(\x->b%[x])(fst$g$drop 6 a)|0<1=show$foldl1 div$map read c
"if"%[p,a,b]|elem p["0","()","false"]=b|0<1=a
"list"%c="(list "++unwords c++")"
"len"%[c]=show$length(words c)-1
"inc"%[c]|t c>0=show$read c+1|([],_)<-g$drop 6 c="(list)"|(x,_)<-g$drop 6 c="list"%(last x:init x)
"dec"%[c]|t c<1,(x,_)<-g$drop 6 c="list"%(drop 1 x++take 1 x)|0<1=show$read c-1
"not"%[c]="if"%[c,"false","true"]
s%c="?"
i p|p="true"|0<1="false"
t('(':_)=0
t(c:s)|c<':',c>'/'=1|elem c"th"=2
t _=3
```
quite a hacky solution. this stores everything as strings in output-ready form - their types can be distinguished by their first letter - `0..9` for numbers, `(` for lists, `t` or `f` for booleans, and everything else for functions.
to run use the `r` function.
] |
[Question]
[
Entries for this challenge will display an animated rotating [Lissajous figure](http://en.wikipedia.org/wiki/Lissajous_curve). The appearance of 3d rotation occurs as the x parameter is successively phase-shifted in each frame.
### Input:
The `a` and `b` parameters (as per the [wikipedia article](http://en.wikipedia.org/wiki/Lissajous_curve)) will be specified at the command line, or read from stdin.
### Output:
This is [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'"), so output will be displayed in a terminal emulator window or equivalent. Output size may be hardcoded, but the Lissajous figure must be at least big enough to fill a 80x24 window.
The animation frame rate will be approximately 50fps. Sleeping for 20ms between each frame is fine, as long as the time to calculate each frame is small compared with the fixed sleep time. If your choice of language cannot calculate quick enough on your chosen platform, then you'll have to calculate the time to sleep dynamically.
Each frame will not be displayed until all calculation for that frame is complete. There is no need to clear the screen between each frame.
The figure will make a full `2*Pi` rotation approximately every 4 seconds.
For each frame, a full closed curve must be generated. At least 1000 points must be calculated along the curve. Line-drawing in between points is not necessary.
Points of the curve will be plotted as `#` characters. The rest of the display area will be blank/whitespace.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes (deemed acceptable by me) will be the accepted winner one week after this posting.
---
Ungolfed [reference answer](https://codegolf.stackexchange.com/a/26428/11259).
[Answer]
# Perl - 177

```
while($d+=.1){print"\e[H\e[2J";$a=0;while(($a+=.01)<4*atan2 1,0){$x=$==40+40*cos$d+$a*$ARGV[0];$y=$==13+13*sin$d+$a*$ARGV[1];print"\e[$y;$x"."H#";}print$/;select($v,$v,$v,.03);}
```
The coefficients are passed via arguments. The above gif is produced from `perl % 2 3`
[Answer]
# C (reference answer - not golfed)
Output with `./lissajous 2 3`:

```
/*
* lissajous.c
*
* Compile with:
* cc lissajous.c -lm -o lissajous
*
* Usage:
* ./lissajous a b
*
* a and b are the parameters as described in:
* http://en.wikipedia.org/wiki/Lissajous_curve
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
int main (int argc, char **argv) {
char buffer[25][80];
double t, p;
int x, y;
int a, b;
if (argc != 3) return 1;
a = atoi(argv[1]);
b = atoi(argv[2]);
for (;;) {
for (p = 0; p < 2 * M_PI; p += M_PI / 100) {
memset(buffer, ' ', sizeof(buffer));
/* Set 1st char of final line to nul. Then we can printf
* the whole 2d array as if it were one long 1d buffer.
* Line wraps at 80 chars are assumed */
buffer[24][0] = 0;
for (t = 0; t < 2 * M_PI; t += M_PI / 500) {
x = 39.5 * (1 + sin(a * t + p));
y = 11.5 * (1 + sin(b * t));
buffer[y][x] = '#';
}
printf("%s\n", &buffer[0][0]);
usleep(20000);
}
}
return (0);
}
```
---
# C, 257 bytes
Ok, well I couldn't resist golfing it a bit myself. I think there's a lot more golfing to be done on this though:
```
#include<math.h>
main(int a,char**v){char x,y,b,d[25][80];double t,p,q=2*M_PI;a=atoi(v[1]);b=atoi(v[2]);for(p=0;memset(d,32,2000);p+=q/100){p=p<q?p:0;d[24][0]=0;for(t=0;t<q;y=11.5*sin(b*t)+12,d[y][x]=35,t+=q/1e3)x=39.5*sin(a*t+p)+40;puts(d);usleep(20000);}}
```
[Answer]
# Python 3 - 280
Don't have one of those fancy animated gifs for ya, sorry. Windows console is slow at printing :P
Not sure this meets the 50fps requirement though I'm not sure it's really possible with Python. You can adjust the 1000 on the second line for the amount of points to calculate (the list is output width, output height, points to find, progression per frame (pi\*2/n) and starting point). Or you can remove them and specify in the input as well.
```
import math as m
a,b,w,h,p,r,t=list(map(int,input().split()))+[79,24,1000,100,0]
while 1:v,z=w/2,h/2;d=[[int(m.sin(a*k+t)*v+v),int(m.sin(b*k)*z+z)]for k in[m.pi*2/p*l for l in range(p)]];print('\n'.join(''.join([' ','#'][[i,j]in d]for i in range(w))for j in range(h)));t+=m.pi*2/r
```
MORE IMPORTANT EDIT: Input via stdin, space-separated, newline terminated. Will wait for your input.
EDIT: Screenshot. Changed height to 40 for this one.

[Answer]
# C# - 360 352 (cross platform - 332 for Windows only)
**Edited after micro-golfing and rounding bug fix + suggestion by Ypnypn**
Not exactly a contender at that length - and it's pretty much a verbatim copy of the reference - but oh well. :)
```
namespace System{class P{static int Main(string[]m){double p=Math.PI*2,a=int.Parse(m[0]),b=int.Parse(m[1]),q,t;for(;;)for(q=0;q<p;q+=p/200){var s=new string(' ',1920).ToCharArray();for(t=0;t<p;t+=p/1000)s[(int)(39.5*Math.Sin(a*t+q)+40)+(int)(11.5*Math.Sin(b*t)+12)*80]='#';Console.SetCursorPosition(0,0);Console.Write(s);Threading.Thread.Sleep(20);}}}}
```
Memory hog, creating a new array for every refresh - originally (re)used a StringBuilder, but sacrificed it for shortness. But at least the refresh takes less than 1 ms on my old Core2.
After removing some - now length-hurtful - old golfing, thereby reducing it by 8 characters, I tried to get it back to the "poetic" 360 by reverting to double rather than int parsing, and returning to 80\*24 instead of 1920. That's still only 359, though - and no other single character addition that I can think of really adds any value to the code. So we'll just stick with 352. :-)
Unrolled (lost the pre-golf code):
```
namespace System
{
class P
{
static int Main(string[] m)
{
double p = Math.PI * 2,
a = int.Parse(m[0]),
b = int.Parse(m[1]),
q, t;
for (;;)
{
for (q = 0; q < p; q += p/200)
{
var s = new string(' ', 1920).ToCharArray();
// Alternative - Windows console only:
// var s = new char[1920];
for (t = 0; t < p; t += p/1000)
{
s[
(int) (39.5*Math.Sin(a * t + q) + 40)
+ (int) (11.5*Math.Sin(b * t) + 12) * 80
] = '#';
}
Console.SetCursorPosition(0, 0);
Console.Write(s);
Threading.Thread.Sleep(20);
}
}
}
}
}
```
The Windows console actually accepts outputting a lot of null chars resulting in output that's (graphically) identical to using an actual space character - which allows a few characters less to initialize the character array.

[Answer]
## Python 2.7 - 214
I think I'm going to have another look at this. I have a feeling this can be brought down even further, but it will be hard to hit the Perl byte count. The math seems to be my biggest limitation here.
Warning: may crash whatever terminal you are using. I tested this on the Windows command prompt with `lissajous.py 2 3`. Because of the quick writing to the command prompt, expect the frames to jump a little bit. This can be mostly resolved (at the cost of speed) by using a greater `s` in the `range(s)` and `t=2*pi*i`.
I don't use `\r` or `\b` here purposely because I'm running it on Windows and it would cost extra characters.
```
from math import*;import sys;a,b=sys.argv[1:];p=s=1920
while p:
c = [" "]*s
for i in range(s):
t=2*pi*i/s;c[int(round((39.5*(1+sin(eval(a)*t+p))))+round(11.5*(1+sin(eval(b)*t)))*80)]="#"
print ''.join(c)
p+=.1
```
] |
[Question]
[
There already have been multiple [challenges](https://codegolf.stackexchange.com/questions/160069/finite-field-multiplication?noredirect=1&lq=1) [about](https://codegolf.stackexchange.com/questions/252189/carryless-factors?noredirect=1&lq=1) [carryless](https://codegolf.stackexchange.com/questions/50240/xor-multiplication)
[multiplication](https://codegolf.stackexchange.com/questions/66911/find-the-xor-primes?noredirect=1&lq=1), this challenge will work with the same calculation rules.
You task is given a quadratic polynomial `ax²+bx+c`, to find an integer `r` such that `a*r*r+b*r+c` is zero, with `+` meaning exclusive or and `*` being carryless multiplication (use xor to add up the numbers in binary long multiplication).
Input: Polynomial `ax²+bx+c` for instance given as an coefficient vector
Goal: find a number `r` such that `a*r*r+b*r+c=0` with `*` being multiplication without carry and `+` being exclusive or.
Rules:
* You may assume there is an integral solution
* You only need to return a **single solution** of the equation
* The returned solution may be different if the program is called multiple times
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest solution (per language) wins
Examples:
```
x²+x -> x=0 or x=1
x²+3x+2 -> x=1 or x=2
x²+5 -> x=3
x²+7x+12 -> x=3 or x=4
5x²+116x+209 -> x=25
x²+12x+45 -> x=5 or x=9
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~30~~ 28 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
àÝʒUεXN.DNFV0sbv·yY*^}}}.«^_
```
Takes a reversed polynomial triplet as input (if this is not allowed, a single `R` can be added between the `Uε`).
[Try it online](https://tio.run/##ATQAy/9vc2FiaWX//8Ogw53KklXOtVhOLkRORlYwc2J2wrd5WSpefX19LsKrXl///1sxMiw3LDFd) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8PLzg899Sk0EPrzm2N8NNz8XMLMyhOKju0vTJSK662tlbv0Oq4@P@1Ov@jow10DHUMY3WijXSMwbSpjgGYNjTSMQcyYgE).
**Explanation:**
`0sbv·yY*^}` is taken from [my answer for one of the resulted challenges](https://codegolf.stackexchange.com/a/252208/52210).
```
à # Push the maximum of the (implicit) input-list
Ý # Pop and push a list in the range [1,max]
ʒ # Filter this list by:
U # Pop and store the current value in variable `X`
ε # Map over the (implicit) input-list of the reversed polynomial
# (implicitly push the current polynomial integer of the map)
XN.D # Push the 0-based map-index amount of copies of value `X`
NF # Loop the 0-based map-index amount of times:
V # Pop and store the current top value in variable `Y`
0 # Push a 0
s # Swap so the next value is at the top of the stack
b # Convert it to a binary-string
v # Pop and loop over each of its bits `y`:
· # Double the current value
y # Push the current bit `y`
Y* # Multiply it to value `Y`
^ # Bitwise-XOR the two together
} # Close the foreach-loop
} # Close the ranged loop
} # Close the map
.« # Reduce the list by:
^ # Bitwise-XOR
_ # Check if the final result is 0
# (after which the filtered list is output implicitly as result)
```
[Answer]
# Haskell, ~~108~~ ~~102~~ 101 bytes
```
import Data.Bits
a%b=xor a b
0!_=0
a!b=(2*div a 2!b)%(mod a 2*b)
f a b c=head[x|x<-[0..],1>a!x%b!x%c]
```
[Try it online!](https://tio.run/##XYxBCsIwEEX3OcUvWGiLliRaRTEuxI0rDyAiE1s12DZSg3Th3WsUXNgZBmbe@8yVHreiLLvOVHfbOGzIUbo27sEo1Kq1DQia8eCoOKNAq0gmuXl6KAMdh1Fl88@e6JidP0mc1LWgfN@@2uVoz9P0MBQrCtpQ@zkduopMDYXcMvgqC4fSXrBYYFs7jFbY7hDFX/f13incG1M79rsHOEP45j0yhuwRjqxHZhD/oQxCTCH5vP9eYpJ1bw "Haskell – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 90 bytes
```
a->[subst(lift(t-x),y,2)|t<-factor(Pol([Pol(Mod(binary(i),2),y)|i<-a]))[,1],deriv(t,x)==1]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY3BCoJAGIRfZfH0__AvuEbUQb12Cjq3LLFmGwuiy7qGgm_SRYjomXqbFLvMfAPDzPPjtLeXu5tehmXvLhi-_541z2XbFW2AypoAgfdIAyU4hpQbfQ2Nh1NTgVzk2JRQ2Fr7ASzOHRpwtCnXClGSUFTevH1AoB6zTKj_w0E7Vw2gGc-Z87YOM0ZLiJgBjUhMSkGCYjWToA0lK8S0XWFHIlEK17lpWv0H)
Coverts the input to a polynomial in \$\mathbb{F}\_2[y][x]\$, and then factors it to find the roots.
[Answer]
# Python3, 338 bytes:
```
E=enumerate
def C(a,b):
d={}
for x,A in E(a[::-1]):
for y,B in E(b[::-1]):
if'11'==A+B:d[x+y]=int(d.get(x+y,0)==0)
return''.join(str(d.get(i,0))for i in range(0,max(d or[0])+1))[::-1]
def f(p):
r=0;A,B=bin(p[0])[2:],bin(p[1])[2:]
while 1:
if p[2]==int(''.join(C(C(A,J:=bin(r)[2:]),J)),2)^int(''.join(C(B,J)),2):return r
r+=1
```
[Try it online!](https://tio.run/##XY/BboMwEETvfMXesMU2sonStK58gCiX/AKiEhEmcdUYtCUqUdVvpzakUhL5tDPPs7PdpT@2bvnS0ThutXHnk6GqN1FtGtiwCvdcRVDrn98ImpZgwAysgy2rCqWeZBncybhgPhv7GwNsE0sZa50luaqLIbmU2rqe1YuD6ZkfUXCtBY@ATH8mF8eLj9Y69tXTlbGe4CHfhnSq3MEwgadqYDW0VIiSJ5LzeeXUuWFdWE1avGWY671P6wJWpKrEeZLzFMH30X4akKGpbaAr0lJP9f5rbPzLcKemFJo@cdxxjil/v@fyq6zmO4B8JCVajh0FsGGFRIm@Bo9ulCWmD4rA1YOyRnkPrVDKZ0zFq1fHPw)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 57 bytes
```
F³⊞υ⌕A⮌⍘N²1W⊙E⟦⌕A⮌⍘ⅈ²1⟧⁺§υ²∧κΣEκ⁺μ⁺§υ¹ΣEκ⁺ξ§υ⁰⊙κ﹪№κμ²M→Iⅈ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZDBasJAEIbpNU-x5DQDEUx6sNRTKhQ8WIJeCuJhTVYT3OzK7k6qz9KLh9r2mfo03VVBitA5DMzMNz__zPt3WXNTai4PhyO5Ve_h566_0obBPbKCbA2UsOdGVbmUMBWdMFbAE7di5kyj1jBWW3Iv1C6FAUxYhj7FaYw4jN7qRgoGudrDhG9h_o_K65_dRcIKSRZyN1aV2AUHmR_lqoJNwmbUnvQ2F6q9pVO8xXZe4Er08RpBeR-4ia5IahhpUi7U7dkUop90Ah6nzbp2_rDCe3Yw4tYF4_7UD7ss7eV9X_O418l48ZlGgyjNzs1f) Link is to verbose version of code. Explanation:
```
F³⊞υ⌕A⮌⍘N²1
```
Read in the three coefficients, then decompose them as a sum of powers of `2`.
```
⌕A⮌⍘ⅈ²1
```
Decomposing the trial result as a sum of powers of `2`, ...
```
E⟦...⟧⁺§υ²∧κΣEκ⁺μ⁺§υ¹ΣEκ⁺ξ§υ⁰
```
... compose the decomposed values together by matrix sum, then flatten and join the matrices together, ...
```
W⊙...⊙κ﹪№κμ²
```
... and while any power of two appears an odd number of times, ...
```
M→
```
... increment the trial result.
```
Iⅈ
```
Output the final result.
By representing an integer as a list of powers of `2`, the sum of integers is equivalent to the concatenation of the lists with duplicates removed, while the product of integers is equivalent to the Cartesian product of the lists, where each entry is reduced by sum, and then duplicates removed (note that in both cases triplicates become single entries). However it's not actually necessary to remove the duplicates, merely to check that there would be no left over entries.
I don't know whether there's a mathematical or computing term for creating an `N`-dimensional matrix where each entry is the sum of the relevant entries of `N` vectors, but `numpy.add.outer` performs the equivalent operation when `N=2`.
[Answer]
# JavaScript (ES6), 63 bytes
*-3 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil)*
```
(a,b,c)=>(g=r=>(m=n=>n&&n%2*r^2*m(n>>1))(m(a)^b)^c?g(r+1):r)(0)
```
[Try it online!](https://tio.run/##bc5RCsIwDAbgd0@RF0fiqraddSi03mQwpw7FtVJFei6P4MVmZYhTloc/EPj4cyrv5bXyx8ttat1u3x50iyXbsoq0wVr7mI222tgksWM58YWcNGiNEUTYYEnFlopqU6NPBa09Iae2cvbqzvvZ2dV4QMEA4B2cCOZzCM9HGuAzUwNBc3A@LjEakFkM@ZVZSGVPik7KIcljqK9Uv53ZEMkZiF5ZHlIhe6QrW/xJFZFYMslXnVRvGi/xU77qpFTtCw "JavaScript (Node.js) – Try It Online")
### Commented
```
(a, b, c) => // input triplet (a, b, c)
( g = r => ( // g is a recursive function taking r
m = n => // m is a recursive function taking n and
// computing the carryless multiplication n * r
n && // stop if n = 0
n % 2 * r ^ // otherwise XOR the LSB of n multiplied by r
2 * // with twice the result of
m(n >> 1) // a recursive call with floor(n / 2)
)(m(a) ^ b) // compute ((a * r) XOR b) * r
^ c // XOR it with c
? // if the result is not 0:
g(r + 1) // try again with r + 1
: // else:
r // stop and return r
)(0) // initial call to g with r = 0
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~68~~ 65 bytes
Utilizes the multiplication function from [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/263471/52194). -3 bytes from @Neil.
```
->a,b,c{(0..).find{|x|m=->a{a>0?a%2*x^2*m[a/2]:0}
m[m[a]^b]^c<1}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxbCoJAGEbfZxU_UVGi08yEXSSN1mEq460ENcmRDHUlvQjVotxNor0cPj4O5_W5F-6zfYf6-VuIUNl1J8Xgsit71YJgvMRhlPpVXdaJ3v8VN8iRz5hU2kxKTL5ilkYalJj9tmzXsr0DbZp_SHtcoziASyByBEMSdJg6OM_iSOCEZzDXxM2JEGSFyCE0B8dCQeqPhbabUKBAEIU1sJ4E1J5boAypQOkGGNmP6g8)
] |
[Question]
[
Scientists have made contact with a parallel universe. Just one problem: They write math differently. Help the scientists make a program that can convert normal math expressions to their equivalent in alternate universe math. The connection through the portal is bad so your code needs to be as short as possible
Given a expression, containing only the operators `*`, `+`, parenthesis, and variables represented by single lower case ASCII letters, convert it from normal order of operations (`*` first then `+`) to inverse order of operations used in a parallel universe (`+` first then `*`). You must remove any redundant parenthesis.
Note: The expression will stay exactly the same. All you need to change is the position of the parenthesis.
Variable names are guaranteed to be unique. Expressions are guaranteed to be valid, be matched, and contain no invalid characters. There will never be redundant parenthesis in the input.
You may substitute `*` and `+` with any other 2 unique characters if you prefer. You may substitute `()` with `[]` or `{}` if you prefer.
## Test cases
| Before | After |
| --- | --- |
| `a+b` | `a+b` |
| `a+b*c` | `a+(b*c)` |
| `(a+b)*c` | `a+b*c` |
| `((a+b)*(c+d)+e)*f` | `(a+b*c+d)+e*f` |
| `(a*b+c*d)*e+f` | `((a*b)+(c*d)*e)+f` |
| `a+b+c` | `a+b+c` |
| `a*b*c` | `a*b*c` |
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 100 bytes
```
F²⊞υ⟦⟧FS«F№)+ι«≔⊟υη⊞§υ±¹⎇⊖Lη⪫()⪫η*⊟η»F№⁺)βι«F№)ι≔⪫⊟υ+ι⊞§υ±¹ι»F№((+ι⊞υ⟦⟧»≔⊟υη≔⊟υθ⊞θ⎇∧θ⊖Lη⪫()⪫η*⪫η*⪫θ+
```
[Try it online!](https://tio.run/##hZFBT8QgEIXP7a8gnGbaetDrnhq9rDGmid6MB7ZlC0mFLQWjMfvbEWg3m@pGb8xj5s3HoxXMtJoN3u@1IXCDpHGTAFeRl1fc5EncqoOzT9ZI1QMi@cqzJN9qpyxQLGlF5Kxn9TTJXkGjD@CwIiJYZFlyrO1WdfwjOj/ynlkO1xg6nrlRzHzCHW8Nf@PK8g4euOqtABHv77VUQAHpchQVoQWNN3FHaIkbjiuiZnBTwAoTOzyTrZAX4oU2GZ@QaUnT1H/g8vdiCnDKYhXiMb8Qyw9pDFIaGs@Z1KqL5eVo/sxmVUbn8Hd2fuc4PxE33rMCdmVbdCXHYu@v3odv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υ⟦⟧
```
Start with two lists, one for the `+` group and one for the `*` group.
```
FS«
```
Loop over the characters in the input string.
```
F№)+ι«
```
If the current character is a `)` or `+`, then:
```
≔⊟υη
```
Remove the `*` group.
```
⊞§υ±¹⎇⊖Lη⪫()⪫η*⊟η
```
Join it with `*`s and wrap it in `()`s if there is more than one expression in the group, otherwise just push the expression to the `+` group.
```
»F№⁺)βι«
```
If the current character is a `)` or lowercase letter:
```
F№)ι
```
If it's a `)`, then...
```
≔⪫⊟υ+ι
```
... remove the `+` group and join it on `+`.
```
⊞§υ±¹ι
```
Push it to the (previous) `*` group.
```
»F№((+ι
```
If it's a `(` or `+`, then...
```
⊞υ⟦⟧
```
... for `+` restore the previously popped `*` group while for `(` push two new groups for `+` and `*`.
```
»≔⊟υη≔⊟υθ
```
Get the final `*` and `+` groups.
```
⊞θ⎇∧θ⊖Lη⪫()⪫η*⪫η*
```
Join the final `*` group on `*` and push it to the `+` group, wrapping it in `()`s if the `+` group is not empty.
```
⪫θ+
```
Join the `+` group on `+` and output the result.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 193 bytes
```
x=>g(eval(`[${x.replace(/./g,x=>x=='['|x==']'?x+',':`"${x}",`)}]`))
g=x=>x[1]?x.map(h=c=>h|=c==1?!!u.push(v=[]):v.push(c)&&c,u=[v=[]])|h-3?x.map(g).join``:u.map(v=>v[1]?`[${g(v)}]`:v).join`1`:x
```
[Try it online!](https://tio.run/##dY9NboMwEEb33CJRFc9g4oh0R2U4CEIydfiLKEYhWJZKzk5xMauWja153/OM557rfJCPpn@eO3Ur5lIpPhseV1DovAWRvn0b9ij6NpcFXNilCpbQcE5SMtkrI4mhJCCROC7m6xgIfGUC0au4FdMwSwz7ynuoueRxPS0nD5PDYWT9ONSgeZphpNdC4ukkg5GnlmY41ed397hCdldNJ0Q0/taax9q2tt@rQNuRkXZOKCIze6UdD4TQZSEwbOjb5ilArEoqHEAHsg1QsTVxwHfguuzkUOgQ3ZyrA77wpOoG1RasVRWUQHKC@PEH0s8dTOVO4P8bwJLgTrRmIOkNaYF@aaX5Bw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 207 bytes
```
x=>g(eval(`[${x.replace(/./g,x=>x=='('?'[':x==')'?'],':`"${x}",`)}]`))
g=x=>x[1]?x.map(h=c=>h|=c=='+'?!!u.push(v=[]):v.push(c)&&c=='*'?2:0,u=[v=[]])|h-3?x.map(g).join``:u.map(v=>v[1]?`(${g(v)})`:v).join`+`:x
```
[Try it online!](https://tio.run/##dY3djoIwEEbvfQuNsTMU6/7cdTPwIA1Ju7UUDQtEloZEeXaWrl7qzeT75pzMnE0wvb2cut990x7dXNI8UubBBVODVtvrKC6uq411cBAHny5wJGLAcqaYjBGXWKRM6s0iT5tU41RoxJWn6Kr3Ih/Fj@mgIktZdVsmMc7y9XoQ3dBXEEgVKMO9WNztopCw/EO@pQOpiAu8VfvPxx2P4tyeGq3l8N8DZSF@0bC9egg4oZbh4XAtx3ll26Zvayfq1kMJzPBvhvj1ZM3tC5A8BbAQfIHuDCw/IneYlFGa/wA "JavaScript (Node.js) – Try It Online")
Was strongly messing `+` and `*`
[Answer]
# [Python 3](https://docs.python.org/3/), 162 bytes
```
lambda s:g(compile(s,'','eval',1024).body,0)
def g(n,p):
if'N'in'%s'%n:return n.id
x='A'in'%s'%n.op;s=g(n.left,x)+'*+'[x]+g(n.right,x);return[s,f'({s})'][p-p*x]
```
[Try it online!](https://tio.run/##tVHNjtowED6vn2IuK8/EJoLdnljlAIc99gXSHAJJwMhxLNsUaNVnp3Ys2L5AI2U83/x883lsb@E4mff7Z/Xjrttx17Xg1wfcT6NVukcvOZe8/9lqLlfLt29U7qbuJpfEun6AAxppac1ADfw7V4a/ev5q1q4PZ2fAlKpjcK345pkqJ/vhq9hW6n4I8kqCF4LX10akmFOHYwp@ZILay4Hjb/@HeFPbhS2uzV2NdnIB/M2zWUFod1GlThrip6GCuvbBoYrMwGGYHChQBk7N7J@Sr5u5eGyvF9WFY@qJPo6tRd0bCYpIvH21/lIWC025ycVqXS8zsE6ZgHFOeZqUQVXq09kHvMgY4ZQZJFweJK5eL1aNfA4mAgFJpQBXxwz9S1rxIqnBZ7Hw5/ELwQLeKTekMW6@V71aN3kR/0Udy@uNzxkptsl84oYeZ1VtedMwlni1Mn3ijc9U@tApk1VtJGzT/mK29FargPkGumyt7U2HdaqQkOiyjaRp8OOV763YwUs0LP7FPrkYT2IYMeVAxAwzxr3oSPRUDPCCc2bGxRDri53YFx0VvUjJhElgjpAYEr/IdGLPYnLmTsdf "Python 3 – Try It Online")
Uses [ast](https://docs.python.org/3.7/library/ast.html).
[Answer]
# Rust + syn + quote, 315 bytes
```
use{syn::{*,Expr::*,BinOp::*},quote::*};
fn g(e:Expr,p:usize)->String{match
e{Path(e)=>e.to_token_stream().to_string(),Paren(e)=>g(*e.expr,p),Binary(e)=>{let
x=matches!(e.op,Add(_))as _;let
r=g(*e.left,x)+["*","+"][x]+&g(*e.right,x);[&r,&format!("({r})")][!x&p].into()}_=>loop{}}}let
f=|s|g(parse_str(s).unwrap(),0)
```
A port of [gsitcia's python answer](https://codegolf.stackexchange.com/a/255999). Handling ASTs in Rust is actually really nice, but a little verbose compared to python.
[Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=90472e5911026bce3949954af2bf7ecd)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 116 bytes
```
s=>(M=o=>s[(q=s[i++])<')'&&A(),i++]=='*'?q+='*'+M``:o&&q,A=o=>s[q=M()&&o+s[i]?`(${q})`:q,i-1]>')'?q+='+'+A``:q)(i=0)
```
[Try it online!](https://tio.run/##TVHLbsIwEDzjr/ChSna9IbRXqIM49MgXAFKMcdpUQAiOKiTEt6d@JIhLdmd3Zmes/Ko/ZfW1vnTTc3MwfSV7KwtYy0YWdgOttJuaaIefKaZJsgLMPJQyFemyJV9oXZbzJknabBVFrVwDJklDTrpblvB2bx9Yztusnn7sCncnCCmllRO2CLV8x74zttPKGsslL5miPZ@4j2@E9i24igwcxjhwmEHEoOmAZFBUfAJhE7CoHF/sSYsDCkN@6TESxAlS5e9TPEeaKa6CczAWrooxwOgfzvF4RT/TxDBKgFsiDxz2kowPkdgQhr@k8DO/CzPn4Fme7VjRM3Ao6nx9qmhUoe@Cn3MfWI405An@kT0m9BwxcGKy8X2OU@bdtT4B5vZyrDtIt@cU85O6wI3Lgt@G8WxraYbInn8tr5rrl9I/AJs642aHnn1nnOvmbJujyY/NN1RQo5Qm477BBXvgov8H "JavaScript (Node.js) – Try It Online")
A simple recursive descent parser with syntax
```
A ::= M ["+" A]?
M ::= ("a" .. "z" | "(" A ")") ["*" M]?
```
```
s=> // s: input expression
// i: index of current character (cursor)
(
M= // Function for parsing M ::= ("a" .. "z" | "(" A ")") ["*" M]?
o=> // o is undefined if invoked from A
// o is empty array if invoked from M
s[
(q=s[i++])<')'&&A(), // read next character as token "a" .. "z"
// or if we got a '(', read an expression A
// save the result to variable `q`
i++]=='*'? // if the following character is `*`
q+='*'+M``: // we read the optional `"*" M` part
// save the result to variable `q` and return it
// returns something truthy
o&&q, // we don't have the extra "*"
// if o is undefined (invoked from A), return undefined
// which means we do not need "()" pairs
// if we add `q` with other expressions
// if o is empty array (invoked from M), return the result
// so "q+='*'+M``" could work as expected
A= // Function for parsing A ::= M "+" A | M
o=> // o is undefined if invoked from from M
// o is 0 if invoked from outer
// o is empty array if invoked from A
// which means currently we are parsing a part of addition
// and we may need "()" in such case
s[
q=M()&& // read the M and the result is saved it to variable q
// M() returns truthy if we need "()" in case of adding it
// M() returns falsy if we do not need "()"
o+s[i]? // if o is undefined (from M) or 0 (from outer)
// and s[i] is undefined (the expression ends)
// so we do not have more things to add
// o+s[i] is NaN (falsy), means we do not need "()"
// in all other cases, o+s[i] is some non-empty string
// (truthy), means we need "()"
`(${q})`:q, // wrap `q` with "()" if needed, save result to `q`
i-1]>')'? // if we have more thing to add
// s[i-1] is "+" instead of ")"
q+='+'+A``:q // add them and parse following additions if needed
)(i=0) // initial cursor to 0
```
] |
[Question]
[
MD5 checksums are relatively easy to crack. For this challenge you will create two separate programs, the first one writing `Hello, World!` and the second one writing `Goodbye Cruel World!` but with the source code having identical MD5 hashes.
* The source code of both programs must not be identical.
* The programs can use the same or different languages.
* Trailing newlines are allowed, but the programs cannot write anything else to the output.
* Shortest combined byte code wins.
The following [TIO](https://tio.run/##Tc69CsIwFEDh2T5FrEMSaIOLIPgzSncH55Dc2kia1NwbsYjPXosurudbzk0/NJrkBqpDtDBNJgYkZhI7sAT37BIIbtI4UOSy@GGL/9gil7uvRA/Kx6swSZkEmqDR2Ane2w2XKg92LqJFNZM9OQ/nMRixrhjP1NZbLqWy7gpIouzgWUo5TSsXjM8W2B7Juqi6Y@ECsV67ICR7FYshE4qyAe9jxS4xebss55n3Bw) can be used to calculate the MD5 hashes for your programs.
[Answer]
## Python, ~~360 + 360 = 720 bytes~~ ~~206 + 206 = 412 bytes~~ 201 + 201 = 402
Hi, my two cents. This answer is inspired by [this blog by Nat McHugh](https://natmchugh.blogspot.com/2014/10/how-i-made-two-php-files-with-same-md5.html?m=1).
A short introduction to explain the idea behind the code.
### MD5 hash collision and exploitation.
MD5 works with blocks of 64 bytes.
If two blocks (with a length multiple of 64 bytes) A & B have the same hash,
then appending the same contents C to both will keep the same hash.
*hash(A) = hash(B) -> hash(A + C) = hash(B + C)*
Exploiting this simple principle is possible to get two different files with the same MD5.
There are several attacks to generate MD5 collision, here we are interested in attacks for files having **identical prefixes**.
These are the steps of the attack:
1. Define an arbitrary prefix with any content and length.
2. Pad the prefix to the next 64-byte block.
3. Compute collision blocks based on the prefix. The differences between the blocks are predetermined by the attack.
4. Concatenate the prefix with each of the two blocks to get two different sequences: the hash is the same for the two sequences despite the differences.
5. Add any arbitrary identical suffix to the sequences: the hash will remain the same for the two sequences.
The final structure of the two files will be the following:
| GOOD FILE | | EVIL FILE |
| --- | --- | --- |
| Prefix[n \* 64 bytes] | = | Prefix [n \* 64 bytes] |
| Collision A[128 bytes] | ≠ | Collision B[128 bytes] |
| Suffix[any length] | = | Suffix[any length] |
In the end, the files are almost identical, except for a few bits.
For the exploitation, we use an approach called **data exploit**: run code that
looks for differences and displays one content or the other (typically trivial since differences are known in advance).
In particular, we use [FastColl](https://www.win.tue.nl/hashclash/) to generate the two collision blocks, given the prefix.
Each collision block needs two MDS blocks (so it is 128 bytes long). This is the difference mask for the two collision blocks:
```
................
...X............
.............XX.
...........X....
................
...X............
.............XX.
...........X....
```
Looking at the difference mask, the 20th byte is the first byte that shows a difference (each . represents one byte).
So, we can use this information to trigger a different behavior in the two files. Knowing the expected value of the 20th
byte in the collision block, we can create an if based on this value.
Look at the following example showing two collision blocks (courtesy of <https://github.com/corkami/collisions>):
```
00: 37 75 C1 F1-C4 A7 5A E7-9C E0 DE 7A-5B 10 80 26 7u┴±─ºZτ£α▐z[►Ç&
10: 02 AB D9 39-C9 6C 5F 02-12 C2 7F DA-CD 0D A3 B0 ☻½┘9╔l_☻↕┬⌂┌═♪ú░
20: 8C ED FA F3-E1 A3 FD B4-EF 09 E7 FB-B1 C3 99 1D îφ·≤ßú²┤∩○τ√▒├Ö↔
30: CD 91 C8 45-E6 6E FD 3D-C7 BB 61 52-3E F4 E0 38 ═æ╚Eµn²=╟╗aR>⌠α8 \
40: 49 11 85 69-EB CC 17 9C-93 4F 40 EB-33 02 AD 20 I◄àiδ╠↨£ôO@δ3☻¡
50: A4 09 2D FB-15 FA 20 1D-D1 DB 17 CD-DD 29 59 1E ñ○-√§· ↔╤█↨═▌)Y▲ ................
60: 39 89 9E F6-79 46 9F E6-8B 85 C5 EF-DE 42 4F 46 9ë₧÷yFƒµïà┼∩▐BOF ...X............
70: C2 78 75 9D-8B 65 F4 50-EA 21 C5 59-18 62 FF 7B ┬xu¥ïe⌠PΩ!┼Y↑b { .............XX.
...........X....
................
00: 37 75 C1 F1-C4 A7 5A E7-9C E0 DE 7A-5B 10 80 26 7u┴±─ºZτ£α▐z[►Ç& ...X............
10: 02 AB D9 B9-C9 6C 5F 02-12 C2 7F DA-CD 0D A3 B0 ☻½┘╣╔l_☻↕┬⌂┌═♪ú░ .............XX.
20: 8C ED FA F3-E1 A3 FD B4-EF 09 E7 FB-B1 43 9A 1D îφ·≤ßú²┤∩○τ√▒CÜ↔ ...........X....
30: CD 91 C8 45-E6 6E FD 3D-C7 BB 61 D2-3E F4 E0 38 ═æ╚Eµn²=╟╗a╥>⌠α8
40: 49 11 85 69-EB CC 17 9C-93 4F 40 EB-33 02 AD 20 I◄àiδ╠↨£ôO@δ3☻¡ /
50: A4 09 2D 7B-15 FA 20 1D-D1 DB 17 CD-DD 29 59 1E ñ○-{§· ↔╤█↨═▌)Y▲
60: 39 89 9E F6-79 46 9F E6-8B 85 C5 EF-DE C2 4E 46 9ë₧÷yFƒµïà┼∩▐┬NF
70: C2 78 75 9D-8B 65 F4 50-EA 21 C5 D9-18 62 FF 7B ┬xu¥ïe⌠PΩ!┼┘↑b {
```
In the first collision block, the value of the 20th byte is 0x39, while in the second 0xB9.
We can exploit this difference by writing something like this:
```
if collision_block[20] = 0x39 then:
do a good thing
else:
do a bad thing
```
This is the idea used in the code to create the two source files with the same MD5 hash, but different behavior.
## References:
[1] <https://natmchugh.blogspot.com/2014/10/how-i-made-two-php-files-with-same-md5.html?m=1>
[2] <https://github.com/corkami/collisions>
## Files generated for this answer
These are two files with the same md5 hash:
```
MD5 (good.py) = 120909f9a5185bcbd7ef716d6c1f3787
MD5 (evil.py) = 120909f9a5185bcbd7ef716d6c1f3787
```
`good.py`
```
#coding: L1
# coding: L1
print('%s World!'%('Hello','Goodbye Cruel')['Z'>"""úzžù
WjmEò÷Sïå#nî˜ê-Z<fi #ûòûûîðŒ ‡k×T,qK=®=ˆÄ†ä7vÒ2¯áWü§›(0ã¢dÞåÅA4æø+tÐWOLeÁí-Åéòå«·Ùµë0š4zgqß?Í…fÿ¦¼Ôh¨îx"""[19]])
```
`evil.py`
```
# coding: L1
print('%s World!'%('Hello','Goodbye Cruel')['Z'>"""úzžù
WjmEò÷Sïå#nî˜ê-Z<fi #ûòûûîðŒ ‡k×T,qK=®=ˆÄ†ä7öÒ2¯áWü§›(0ã¢dÞåÅA4Žæø+tÐWOLeÁí-Åéòå«·Ùµë0š´ygqß?Í…fÿ¦¼Ôè¨îx"""[19]])
```
If you run `good.py`, you get:
```
>> python good.py
Hello World!
```
while for `evil.py`:
```
>> python evil.py
Goodbye Cruel World!
```
The length of the two files is the same, i.e., 201 bytes.
Note that, due to the presence of non-ASCII characters in the Python code, I cannot guarantee that a copy and paste of the above text can reproduce the results. So, here is the C code to create the two files:
```
#include <stdio.h>
// The number of bytes for the prefix and for the collision block
// must be 64 and 128 respectively to generate an MD5 collision
#define N_PREFIX_BYTES 64
#define N_COLLISION_BYTES 128
#define BYTE_TYPE unsigned char
void write_binary_file(
char *filepath,
BYTE_TYPE *prefix,
BYTE_TYPE *collision,
BYTE_TYPE *suffix,
size_t prefix_nbytes, size_t collision_nbytes, size_t suffix_nbytes
){
FILE *ptr;
ptr = fopen(filepath, "wb");
fwrite(prefix, sizeof(BYTE_TYPE), prefix_nbytes, ptr);
fwrite(collision, sizeof(BYTE_TYPE), collision_nbytes, ptr);
fwrite(suffix, sizeof(BYTE_TYPE), suffix_nbytes, ptr);
fclose (ptr);
}
int main(){
size_t n_suffix_bytes;
char *code_filepaths[2] = {"good.py", "evil.py"};
unsigned long tot_len=0, curr_len=0;
// Here the initial and final part of the output code;
// mind that the prefix must have a length of 64 bytes.
// The idea here is to take advantage of the slightly
// difference between the two collission blocks to generate
// different outputs in the two programs.
BYTE_TYPE source_code_prefix[N_PREFIX_BYTES] = "# coding: L1\nprint('%s World!'%('Hello','Goodbye Cruel')['Z'>\"\"\"";
// As you can see, the output code is in Python language.
//
// The different output string is created choosing its initial part
// between the elements of a tuple two strings ('Hello','Goodbye Cruel').
// In particular, the index is a condition on the first different character
// between the two collision blocks, i.e., the 20th.
// If this characher is less than 'Z', the condition is True,
// (i.e. it is equivalent to 1), so the second element of the
// tuple is selected; otherwise the condition
// is False (0), so the first element of the tuple is selected
// To recap, this is the ungolfed sketch of the code:
// is_evil = 'Z' > collision_block[19]
// initial_part = ('Hello','Goodbye Cruel')[is_evil]
// print('%s World!'%initial_part)
BYTE_TYPE source_code_suffix[9] = "\"\"\"[19]])";
// You can put one this two binary blocks between source_code_prefix and source_code_suffix
// and get the same MD5 hash, even if the two blocks are slightly different
BYTE_TYPE collision_blocks[2][N_COLLISION_BYTES] = {
{
0xfa, 0x7a, 0x9e, 0x18, 0xf9, 0x0a, 0x57, 0x6a, 0x11, 0x6d, 0x45, 0xf2, 0xf7, 0x53, 0xef, 0xe5,
0x23, 0x6e, 0xee, 0x8f, 0x98, 0xea, 0x2d, 0x15, 0x5a, 0x16, 0x3c, 0x66, 0x69, 0x20, 0x23, 0xfb,
0xf2, 0xfb, 0xfb, 0xee, 0xf0, 0x8c, 0x09, 0x87, 0x6b, 0x02, 0xd7, 0x54, 0x18, 0x10, 0x2c, 0xad,
0x71, 0x4b, 0x3d, 0xae, 0x3d, 0x88, 0xc4, 0x86, 0xe4, 0x19, 0x37, 0x76, 0xd2, 0x32, 0xaf, 0x15,
0x1c, 0xe1, 0x0c, 0x57, 0xfc, 0xa7, 0x9b, 0x1b, 0x28, 0x30, 0xe3, 0xa2, 0x64, 0xde, 0xe5, 0xc5,
0x41, 0x34, 0x1e, 0x0e, 0xe6, 0xf8, 0x18, 0x2b, 0x74, 0x0b, 0xd0, 0x57, 0x4f, 0x4c, 0x65, 0xc1,
0xed, 0x2d, 0xc5, 0xe9, 0xf2, 0xe5, 0xab, 0xb7, 0xd9, 0xb5, 0xeb, 0x30, 0x9a, 0x34, 0x7a, 0x67,
0x71, 0xdf, 0x3f, 0xcd, 0x85, 0x1e, 0x66, 0xff, 0xa6, 0xbc, 0xd4, 0x68, 0xa8, 0xee, 0x08, 0x78
},
{
0xfa, 0x7a, 0x9e, 0x18, 0xf9, 0x0a, 0x57, 0x6a, 0x11, 0x6d, 0x45, 0xf2, 0xf7, 0x53, 0xef, 0xe5,
0x23, 0x6e, 0xee, 0x0f, 0x98, 0xea, 0x2d, 0x15, 0x5a, 0x16, 0x3c, 0x66, 0x69, 0x20, 0x23, 0xfb,
0xf2, 0xfb, 0xfb, 0xee, 0xf0, 0x8c, 0x09, 0x87, 0x6b, 0x02, 0xd7, 0x54, 0x18, 0x90, 0x2c, 0xad,
0x71, 0x4b, 0x3d, 0xae, 0x3d, 0x88, 0xc4, 0x86, 0xe4, 0x19, 0x37, 0xf6, 0xd2, 0x32, 0xaf, 0x15,
0x1c, 0xe1, 0x0c, 0x57, 0xfc, 0xa7, 0x9b, 0x1b, 0x28, 0x30, 0xe3, 0xa2, 0x64, 0xde, 0xe5, 0xc5,
0x41, 0x34, 0x1e, 0x8e, 0xe6, 0xf8, 0x18, 0x2b, 0x74, 0x0b, 0xd0, 0x57, 0x4f, 0x4c, 0x65, 0xc1,
0xed, 0x2d, 0xc5, 0xe9, 0xf2, 0xe5, 0xab, 0xb7, 0xd9, 0xb5, 0xeb, 0x30, 0x9a, 0xb4, 0x79, 0x67,
0x71, 0xdf, 0x3f, 0xcd, 0x85, 0x1e, 0x66, 0xff, 0xa6, 0xbc, 0xd4, 0xe8, 0xa8, 0xee, 0x08, 0x78
}
};
// The number of bytes in the suffix can vary, depending on
// the code needed to make the source file meaningful
n_suffix_bytes=sizeof(source_code_suffix) / sizeof(BYTE_TYPE);
// Write good and evil files. The only thing different is the collision block
tot_len=0;
for(int i=0; i<2; ++i){
write_binary_file(
code_filepaths[i],
source_code_prefix, collision_blocks[i], source_code_suffix,
N_PREFIX_BYTES, N_COLLISION_BYTES, n_suffix_bytes
);
curr_len = N_PREFIX_BYTES + N_COLLISION_BYTES + n_suffix_bytes;
tot_len += curr_len;
printf("\nBytes in %s: %lu", code_filepaths[i], curr_len);
}
printf("\nTotal length: %lu\n", tot_len);
return(0);
}
```
You can download all the previous files from this [Github repo](https://github.com/piecot/md5_collision).
**Update 1**
Thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) and [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for the comment and suggestions to improve the answer.
**Update 2**
Refactor the code and improve of some bits
] |
[Question]
[
This question is inspired by [Kevin Cruijssen's question](https://codegolf.stackexchange.com/questions/182212/lay-out-the-carpet).
Now that the carpet is laid out, we want to roll it. Your task is to write a program that takes a string and returns a spiral made from this string (representing a rolled carpet viewed from the side).
The procedure for one step of rolling the carpet is the following. There is an example to illustrate what I mean. Notice that the example starts with a partially rolled carpet for better understanding:
```
ac
rpet
```
* separate the "head" from the "tail" of the carpet: the head is what has been rolled so far, the tail is what remains to be rolled.
```
Head: ac Tail:
rp et
```
* Rotate the head 90°, clockwise.
```
Rotated head: ra Tail (unchanged):
pc et
```
* if the width of the new head (here `2`) is less or equal than the length of the tail (here `2`)
+ then, put it on top of the tail
+ else, the carpet (as it was at the begining of the step) was rolled
```
New carpet: ra
pc
et
```
Repeat the procedure as many times as needed.
---
Two examples showing all steps of the carpet rolling:
```
carpet
c
arpet
ac
rpet
ra
pc
et
```
```
0123456789
0
123456789
10
23456789
21
30
456789
432
501
6789
```
---
## Some precisions:
* You don't need to show all intermediate steps, only the rolled carpet (e.g. if you find a non-iterative way to compute the result, it's perfect). Also, you don't need to print any leading whitespace, in the examples above, I only show them to align stuff.
* Input is a String, a list/array of char
* Output is printed to stdout or to a file.
* Input is nice: the length is at least 1 char, and at most a constant sufficiently small so that it doesn't cause problems, but you can't use that constant in your program; the content of the string is only nice characters ([a-zA-Z0-9]), encoding at your preference.
* 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.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, add an explanation for your answer if you think it is needed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
FS«F¬℅§KV⁰⟲⁶→Pι
```
[Try it online!](https://tio.run/##HY0xD4IwEEZn@BWM10QTJwediINhEAkm7g09oLHckXolBuNvrw1ve2/4vm7UvmPtYuzZF1DRHOQh3tIAShXfPNtyzQJ3byxpB6VUZPADDeLryVRjmDQRqF1xUImiZdGCcFTnPLvxgnBq7TDKpsGJndO4gE3@i7HxPHg9TemvCevq8F2SubDBK7s@7hf3Bw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FS«
```
Loop over the carpet.
```
F¬℅§KV⁰
```
Check whether there's anything above the cursor.
```
⟲⁶
```
If not then roll the carpet.
```
→Pι
```
Move right and output the current character.
Example: For the input `0123456789`, the following actions occur:
```
0
```
`0` is printed.
```
01
```
The cursor moves right and `1` is printed.
```
0
1
```
Since there is nothing above the `1`, the canvas is rotated.
```
0
12
```
The cursor moves right and the `2` is printed.
```
10
2
```
Since there is nothing above the `2`, the canvas is rotated.
```
10
23
```
The cursor moves right and the `3` is printed.
```
10
234
```
The cursor moves right and the `4` is printed.
```
21
30
4
```
Since there is nothing above the `4`, the canvas is rotated.
```
21
30
45
```
The cursor moves right and the `5` is printed.
```
21
30
456
```
The cursor moves right and the `6` is printed.
```
432
501
6
```
Since there is nothing above the `6`, the canvas is rotated.
```
432
501
67
```
The cursor moves right and the `7` is printed.
```
432
501
678
```
The cursor moves right and the `8` is printed.
```
432
501
6789
```
The cursor moves right and the `9` is printed.
[Answer]
# Pyth, 37 bytes
```
.U+j;bZ.WgleHJlhH,+_MChZ<eZJ>eZJ,]hQt
```
Try it online [here](https://pyth.herokuapp.com/?code=.U%2Bj%3BbZ.WgleHJlhH%2C%2B_MChZ%3CeZJ%3EeZJ%2C%5DhQt&input=%22ProgrammingPuzzlesAndCodeGolf%22&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=.U%2Bj%3BbZ.WgleHJlhH%2C%2B_MChZ%3CeZJ%3EeZJ%2C%5DhQt&test_suite=1&test_suite_input=%22carpet%22%0A%220123456789%22%0A%22ProgrammingPuzzlesAndCodeGolf%22&debug=0).
```
.U+j;bZ.WgleHJlhH,+_MChZ<eZJ>eZJ,]hQtQ Implicit: Q=eval(input())
Trailing Q inferred
]hQ First character of Q, wrapped in an array
tQ All but the first character of Q
, 2-element array of the two previous results
This yields array with rolled carpet (as array of strings) followed by the tail
.W While condition function is truthy, execute inner function, with initial value of the above:
gleHJlhH Condition function, input H
JlhH Number of layers in the current rolled carpet, store in J
leH Lenth of the tail
g J Is the above greater than or equal to J?
,+_MChZ<eZJ>eZJ Inner function, input Z
_MChZ Rotate the current rolled carpet (transpose, then reverse each row)
+ <eZJ Append the first J characters of the tail as a new row
, Pair the above with...
>eZJ ... all but the first J characters of the tail - this is the new tail
.U+j;bZ Join the carpet roll on newlines and append the tail, implicit print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 24 bytes
```
►S=ÖLmFȯ:T↔ø§z:oΘḣĠ+CṘ2N
```
[Try it online!](https://tio.run/##ATsAxP9odXNr///ilrpTPcOWTG1GyK86VOKGlMO4wqd6Om/OmOG4o8SgK0PhuZgyTv///yIwMTIzNDU2Nzg5Ig "Husk – Try It Online")
## Explanation
```
Implicit input, say s="carpets"
CṘ2N Break s into chunks:
N Natural numbers: [1,2,3,4,..
Ṙ2 Repeat each twice: [1,1,2,2,3,3,4,4,..
C Break s into chunks of these lengths: ["c","a","rp","et","s"]
The last chunk is shorter if we run out of characters.
§z:oΘḣĠ+ Attempt to merge suffix of chunks:
Ġ Cumulative reduce chunk list from right
+ by concatenation: ["carpets","arpets","rpets","ets","s"]
oΘḣ Prefixes of chunk list (empty and nonempty): [[],["c"],..,["c","a","rp","et","s"]]
§z Zip these by
: appending: [["carpets"],["c","arpets"],..,["c","a","rp","et","s"]]
These are all versions of the chunk list where some suffix has been merged.
mFȯ:T↔ø Roll each list:
m Map
F reduce from left
ø starting from empty character matrix
ȯ:T↔ by this function:
T↔ Reverse and transpose (rotating by 90 degrees)
ȯ: then append next chunk as new row.
Result: [["carpets"],["c","arpets"],..,["epr","tca","s"]]
►S=ÖL Select the matrix rolled by the correct amount:
► Find element that maximizes
S= being equal to
ÖL sort by length.
This selects a matrix whose rows have non-decreasing lengths.
Ties are broken by choosing the rightmost one.
Result: ["ra","pc","ets"]
Implicitly print each row separated by newlines.
```
[Answer]
# [J](http://jsoftware.com/), 69 bytes
*-3 bytes thanks to FrownyFrog*
```
[:(}:@[,{:@[,])&>/[:((|:@|.@[,#@[$]);#@[}.])&>/^:(<:&#&>/)^:_,.@{.;}.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o600aq0conWqQUSsppqdPlBEo8bKoUYPKKDsEK0Sq2kNpGr1wJJxVho2VmrKQJZmnFW8jp5DtZ51rd5/Ta7U5Ix8BYU0BfXkxKKC1BJ1LoiIOowBlDEwNDI2MTUzt7BUh0n@BwA "J – Try It Online")
## explanation
```
[: (}:@[ , {:@[ , ])&>/ [: ((|:@|.@[ , #@[ {. ]) ; #@[ }. ])&>/^:(<:&#&>/)^:_ }. ;~ 1 1 $ {.
```
The algorithm is straightforward despite being a bit verbose for J.
Overall Strategy: Reduce the input to a square table, with a (possibly empty)
leftover piece.
As we reduce, we'll use a 2 element list of boxes. Our "result so far" will be
the first box, and "items remaining to be processed" will be the 2nd box. The
first box will be initialized to the head of the input (but converted to a table):
```
1 1 $ {.
```
and "items remaining to be processed" will be the input's tail:
```
}. ;~
```
Now we have:
```
┌─┬─────┐
│c│arpet│
└─┴─────┘
```
where the 'c' is actually a 1x1 table.
We reduce that down using a J Do... While loop:
```
^:(...)^:_
```
Where the part in parenthesis is the "keep going" condition:
```
<:&#&>/
```
which says "keep going while the length of the right box is greater than or
equal to the length of the left box (ie, the side length of the square matrix)
What does "keep going" mean? That's defined in the verb to the left of the
first `^:`, which tells us how to take the current result and produce the
next iteration. That verb is:
```
((|:@|.@[ , #@[ {. ]) ; #@[ }. ])&>/
```
Let's break it down:
```
((|:@|.@[ , #@[ {. ]) ; #@[ }. ])&>/
( verb in parens )&>/ NB. put the verb in parens
NB. between the two items
NB. of our list, and unbox
NB. them into left / right
NB. args ([ / ]) for the verb
(|:@|.@[ , #@[ {. ]) ; #@[ }. ] NB. breaking down verb in
NB. parens...
; .... NB. new "remaining items":
}. ] NB. remove from remaining
#@[ NB. the size of a side of
NB. the result matrix
.... ; NB. new "result":
|:@|.@[ NB. rotate existing result
, NB. and put it on top of
#@[ {. ] NB. the items we removed
NB. from remaining items
```
That is, this is just algorithm described in the OP translated literally into J.
Finally we deal with the (possibly 0) leftover items, the tail of our carpet roll:
```
(}:@[ , {:@[ , ])&>/
```
This says "take all but the last elm of the result":
```
}:@[
```
and append it to `,` the last items of the result `{:@[` with the remaining
items appended to that last item `, ]`
[Answer]
# [R](https://www.r-project.org/), ~~146~~ 132 bytes
```
function(s){m=F[F]
while({m=rbind(t(m)[,F:0],s[1:F])
s=s[-1:-F]
length(s)>sum(F<-dim(m))})0
write(m[F:1,],1,F[1],,"")
cat(s,sep="")}
```
[Try it online!](https://tio.run/##fY5fa8IwFEff8ymkLyaQQrP/dnbg3OIefY9BujatgSQtSYrg8LN3twNBNtjjuZzD/fkx9EbHfYheu3a2TGfN4KqoO4cDUQbD/UfAgSYJIagBZbxSvmzBBZfoeNBGYSD/qV2NI7ZEUJ5nkgbBci4JCkUQKctTkI1ybTxA/RIGi/kyrbWFgJxJho5eR4Wt4DmjkjLKBZN0@o2qcloRVF8AnccGXy/HScZubu/uHx6fFrDzeZKTnYPst1eVvlfxf2fru9aX1gJsh9PJqLBy9bqr1aYzzSWd79z8b7p6Xb@9880HWOM3 "R – Try It Online")
Implements the carpet-rolling procedure. Takes input as a list of characters and prints to stdout.
Saved 14 bytes by finding a way to use a `do-while` loop and initializing using `F`.
```
function(s){
m=F[F] # logical(0); create an empty array (this gets automatically promoted to character(0) later
while( # do-while loop
{m=rbind(t(m)[,F:0],s[1:F]) # rotate m counterclockwise and add the first F characters of s to the bottom
s=s[-1:-F] # remove those characters
length(s)>sum(F<-dim(m))})0 # while the number of characters remaining is greater than the sum of m's dimensions
write(m[F:1,],1,F[1],,"") # write the rolled portion write writes down the columns, we reverse each column
cat(s,sep="") # and write the remaining characters
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Seems overly long...
```
ḢW,ðZU;Ls@¥©ḢWɗ,®Ẏ¤ð/ẈṢƑ$¿ḢY;Ɗ
```
**[Try it online!](https://tio.run/##y0rNyan8///hjkXhOoc3RIVa@xQ7HFp6aCVI4OR0nUPrHu7qO7Tk8Ab9h7s6Hu5cdGyiyqH9QLlI62Nd////VzIwNDI2MTUzt7BUAgA "Jelly – Try It Online")**
### How?
```
ḢW,ðZU;Ls@¥©ḢWɗ,®Ẏ¤ð/ẈṢƑ$¿ḢY;Ɗ - Main Link: list of characters
Ḣ - pop and yield head
W - wrap in a list
, - pair with (the remaining list after Ḣ)
¿ - while...
$ - ...condition: last two links as a monad:
Ẉ - length of each
Ƒ - is invariant under:
Ṣ - sort
/ - ...do: reduce by:
ð ð - the enclosed dyadic chain -- i.e. f(head, tail):
Z - transpose
U - reverse each (giving a rotated head)
ɗ - last three links as a dyad:
¥ - last two links as a dyad:
L - length (i.e. number of rows in current roll)
@ - with swapped arguments:
s - split (the tail) into chunks of that length
© - (copy to register for later)
Ḣ - pop and yield head (Note register "copy" is altered too)
W - wrap in a list
; - concatenate (the rotated head with the first chunk of the tail)
¤ - nilad followed by link(s) as a nilad:
® - recall from register (other chunks of tail, or an empty list)
Ẏ - tighten (the chunks to a flat list)
, - pair (the concatenate result with the tightened chunks)
Ɗ - last three links as a monad:
Ḣ - pop and yield head
Y - join with newline characters
; - concatenate (the remaining tail)
- when running as a full program implicitly prints
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g©L¦€DD2šηO®>‹Ï©IŽ8OS®g4α._.ΛðÜI®O®g->.$«
```
Way too long, but I wanted to use the Canvas.. Which was probably a bad choice now that I've finished it and it turned out to be this long..
[Try it online](https://tio.run/##AWQAm/9vc2FiaWX//2fCqUzCpuKCrEREMsWhzrdPwq4@4oC5w4/CqUnFvThPU8KuZzTOsS5fLs6bw7DDnEnCrk/CrmctPi4kwqv//1Byb2dyYW1taW5nUHV6emxlc0FuZENvZGVHb2xm). (No test suite, because there seems to be [a weird issue](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6mj5F9aAuHoVP5PP7TS59CyR01rXFyMji48t93/0Dq7Rw07D/cfWll5dK@Ff/Chdekm5zbqxeudm314w@E5lYfWAZWk69rpqRxa/V/n0Db7/9FKyYlFBaklSjoKSgaGRsYmpmbmFpaoPEcnZxdXN3cPT5BwQFF@elFibm5mXnpAaVVVTmqxY16Kc35Kqnt@TppSLAA) with the `.Λ` builtin..)
**Explanation:**
Let me start by giving a general explanation of the Canvas and what I wanted my code to accomplish. More detailed information can be found in [this relevant 05AB1E tip of mine](https://codegolf.stackexchange.com/a/175520/52210), but for this challenge I wanted to have do the following:
The Canvas builtin takes three parameters:
* \$a\$: The size(s) of the line(s). For this challenge, this would be a list `[2,2,3,3,4,4,5,5,...]`.
* \$b\$: The character(s) we want to display. For this challenge, this would simply be the input-string.
* \$c\$: The direction in which we want to draw these character-lines. For this challenge this would be the directions \$[2,0,6,4]\$ (\$[→,↑,←,↓]\$) rotated \$n\$ amount of times depending on the input-string to have a different starting direction (i.e. input `carpet` is \$[0,6,4,2]\$ instead and input `0123456789ABCDEFGHI` is \$[6,4,2,0]\$ instead).
As for the code:
```
g # Get the length of the (implicit) input-string
© # Store it in the register (without popping)
L # Create a list in the range [1,length]
¦ # Remove the first item to make the range [2,length]
€D # Duplicate each to get the list [2,2,3,3,4,4,5,5,...]
D2š # Create a copy and prepend a 2: [2,2,2,3,3,4,4,5,5,...]
η # Get the prefixes: [[2],[2,2],[2,2,2],[2,2,2,3],...]
O # Sum each prefix: [2,4,6,9,12,16,20,...]
® # Push the length from the register again
>‹ # Check for each summed prefix if it's <= length
Ï # And only leave the truthy values
© # And store this in the register (without popping)
# (This is our `a` for the Canvas builtin)
I # Push the input-string
# (This is our `b` for the Canvas builtin)
Ž8O # Push compressed integer 2064
S # Converted to a list of digits: [2,0,6,4]
®g # Push the list from the register, and get its length
4α # Get the absolute difference with 4
._ # And rotate the [2,0,6,4] that many times towards the left
# (This is our `c` for the Canvas builtin)
.Λ # Now use the Canvas builtin, without printing it yet
ðÜ # Remove any trailing spaces (since the Canvas implicitly makes a rectangle)
®O # Push the sum of the list from the register
®g- # Subtract the length of the list from the register
> # And add 1
I .$ # Remove that many leading characters from the input-string
« # And append it at the end of the roll created by the Canvas
# (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 `Ž8O` is `2064`.
[Answer]
# [Python 3](https://docs.python.org/3/), 112 bytes
```
r=lambda t,h=[[]]:len(h)>len(t)and h[:-1]+[h[-1]+list(t)]or r(t[len(h):],list(zip(*h[::-1]))+[list(t)[:len(h)]])
```
In this case, the output is the value of the function.
[Try it online!](https://tio.run/##PYzNDoIwEITP@hQNl3aFJiL@NoEXKT2sAmkTLE3tRY3PjlTRPexkZr9Zdw96sMU4@rLH67lBEjJdSqmU6FvLNFRRAqBtiJaC5yqVWkbpzS1MBzV44lmQX1qo7JM/jGOriY8FgFTOsJyfKgVjNxWRGEsYvaB3baAZoet8U2x3@8PxFB3GRUEsF84bG1iX0Ce@KOG8qm0Cv9gzhL@hteVxakthfAM "Python 3 – Try It Online")
If you prefer, here another (longer, **129 bytes**) solution that prints directly the rolled input:
```
r=lambda t,h=['']:len(h)>len(t)and set(map(print,h[:-1]+[h[-1]+t]))or r(t[len(h):],list(map(''.join,zip(*h[::-1])))+[t[:len(h)]])
```
[Try it online!](https://tio.run/##NY5LDsIwDETXcIqIjWPaIqB8K8FF0iwMLUpQ60YhG0CcvTR8vJjRaPxku3swHed97w8NtaeKREjNQQHooqlZGjxGC0hciVsdZEtOOm952FJFttCJMipa0IidF14G9eUKnTb29gUAZtfOcvqwTk4HLoKImKigfle0xv4y8CQsCwln8q4OkAqYL5b5ar3Z7vYxURTAYjz6/CAvE3jSC0SWHUue4HjkJeG/hJKzOCUD9m8 "Python 3 – Try It Online")
[Answer]
# [MATLAB](https://www.mathworks.com/products/matlab.html) / [Octave](https://www.gnu.org/software/octave/), 154 bytes
Not the shortest one, but to golf in MATLAB/Octave is always fun :)
```
function h=r(t,h);n=fliplr(h');s=size(n,2);q=numel(t);if s<=q h=r(t(max(s,1)+1:end),[n; t(1:max(s,1))]);elseif q>0 h(:,end+q)=' ';h(end,end-q+1:end)=t;end
```
[Try it online!](https://tio.run/##PY5NjsIwDIXX9BTZORZBIjDMTz2ZiyAWVUmVSCVtEoNGgzh7SQXMwrK@5/dsDy03FztN3Tm07IcgnEmSlUMKpuv92CfpACmb7P@sDGqDFE04n2wvGcl3In@b@AjJU/Mrs9K41LUNR1T7QIKlrl86HpBsn21JxZ@1cLJWxbeMaEAAOVlgFlbxucAwlTaVqthmzuYKbZNGy0Cw1pvt2@794/MLblR1QxLe6Pr52GzGanH0eXzA1d8Kp39Q@8NrDoDVfOUO "Octave – Try It Online")
] |
[Question]
[
[Hexagonal tessellations](https://en.wikipedia.org/wiki/Hexagonal_tiling), or tilings of the plane, are three-colorable -- meaning that using only three colors, such as Red, Blue, and Green, every hexagon can be colored without any two hexagons that share a border sharing a color. [A partial example](https://i.stack.imgur.com/F3N71.gif) showing such a pattern.
Given a partial hexagonal tiling in ASCII (via STDIN, reading from a file, etc.), change the characters' colors (via ANSI codes, image manipulation, etc.) to fit this coloring. The twist is the middle of the hexagons (the `*`, below) are the three colors, and the lines between need to be a mix of their two corresponding hex's `*` colors. If the line is on the outside border, it should match the corresponding `*`.
For example, given the partial hexagonal tiling of
```
/ \ / \ / \ / \
| * | * | * | * |
\ / \ / \ / \ /
| * | * | * |
\ / \ / \ /
```
suppose we decide to color the top-left hex `*` to be Red, and its two neighbors to be Blue and Green (going clockwise). Then the `|` line needs to be Magenta and the `/` line needs to be Yellow. If we keep coloring, we'll eventually end up with something like this (enlarged for clarity):
[](https://i.stack.imgur.com/y2YQC.png)
Or, for an input of
```
/ \
| * |
/ \ /
| * |
/ \ /
| * |
\ /
```
you might color it like so (enlarged for clarity):
[](https://i.stack.imgur.com/6M3qz.png)
A few additional test cases (your code should be able to handle these):
```
/ \ / \
| * | * |
\ / \ /
| * |
/ \ / \
| * | * |
\ / \ /
/ \
| * |
\ / \
| * |
/ \ /
| * |
\ /
/ \
| * |
\ /
```
## Rules
* The input is guaranteed to have at least one hexagon, and no input will have a "hole."
* You don't need to start your coloring with Red, so long as you maintain the three-color rule.
* If the partial tiling can be two-colored, you can do so without penalty (such as in the second example) - you don't necessarily need to extrapolate the partial tiling to a full tiling.
* The hexagon centers `*` must be colored with either Red, Blue, or Green, while the lines between must be either Cyan, Yellow, or Magenta. For example, having a Magenta `*` is not allowed, and a Red `|` or `\` or `/` must be on the outside border of the drawing. See *Colors*, below.
* If your console doesn't have these exact colors, please use the closest approximation and specify in your answer what approximation you're using.
* Leading or trailing whitespace, including trailing newlines, are acceptable so long as the characters line up.
* The partial tiling can be input with space-padding to form a rectangle, if that makes it easier for your code.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Output can be to the console, saved as an image, etc.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
### Colors and Color Mixtures:
The three available base colors are (with color codes in RGB decimal format):
* Red `(255,0,0)`
* Green `(0,255,0)`
* Blue `(0,0,255)`
The combinations are:
* Red and Green combine to make Yellow `(255,255,0)`
* Blue and Green combine to make Cyan `(0,255,255)`
* Red and Blue combine to make Magenta `(255,0,255)`
[Answer]
## JavaScript (ES6), ~~219~~ ~~203~~ 201 bytes
```
f=
s=>s.split`
`.map((b,i,a)=>b.replace(/./g,(c,j)=>`<font color=#${g=(x,y)=>((a[x+i]||``)[b=y+j]==`*`&&15<<b%3*4)|(y<0?8<<9:g(x,y-2)),(g(0,2)|g(-1,1)|g(1,1)).toString(16).slice(1)}>${c}</font>`)).join`
`
```
```
<input type=button value="Colourise!" onclick=i.innerHTML=f(i.textContent)>
<pre id=i contenteditable> / \ / \
| * | * |
\ / \ / \
| * | * |
/ \ / \ / \
| * | | * |
\ / \ / \ / \
| * | * | * |
/ \ / \ / \ /
| * | * |
\ / \ /</pre>
```
Explanation: Each character is wrapped in a `font` tag to set its colour, which is calculated by checking each square, plus the squares two to the left and right, plus the four squares one away diagonally, for `*`s and if so combining the colours of all `*`s found. The `*` colours are chosen simply by taking their horizontal coordinate modulo 3 and shifting a bitmask appropriately. Edit: Saved 2 bytes by switching from `#RRGGBB` to `#RGB` colours.
[Answer]
# JavaScript (ES6), 210 bytes (using HTML + CSS)
Similar to my [canvas approach](https://codegolf.stackexchange.com/a/147064/47097); locates all the `*`s in the input string and writes hexagons to the page in the form of absolutely positioned `<pre>` elements. Because `mix-blend-mode` is set to `lighten`, color addition is performed automatically when characters overlap.
```
s=>s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&document.write(`<pre style=position:fixed;mix-blend-mode:lighten;line-height:1;left:${x}ch;top:${y}em;color:${['red','lime','blue'][x%3]}> / \\
| * |
\\ /`)))
```
```
f=
s=>s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&document.write(`<pre style=position:fixed;mix-blend-mode:lighten;line-height:1;left:${x}ch;top:${y}em;color:${['red','lime','blue'][x%3]}> / \\
| * |
\\ /`)))
f(` / \\ / \\ / \\ / \\
| * | * | * | * |
\\ / \\ / \\ / \\ /
| * | * | * |
\\ / \\ / \\ /`)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 279 bytes
```
e=enumerate
x=input()
c=[[i,j]for i,t in e(x)for j,_ in e(t)if"*"==x[i][j]]
C=[[j%3*([i,j]in c)for j,_ in e(o)]for i,o in e(x)]
for J,K in c:
for i in-1,0,1:q=2-(i&1);_=C[i+J];_[K+q]=_[K-q]=_[K-q]|C[J][K]
for i,o in e(x):print"".join("[%dm"%(30+C[i][j])+x[i][j]for j,_ in e(o))
```
[Try it online!](https://tio.run/##XVDLioMwFF1PfmE2IeCQaLS13VmycqefkAYRjUykJtZGcKD/7viawXZxuZx7Hjmk/bHfRp/GUlZQ6ba3mESdtH2nYZO3@KYelppWaoyChQ6sMogEncxLTIJHe1MWo6tGhIySSd03ssutBAPbwkDBOFe0FpXpoKJ2egRKPJAZ1jRboSWqQi5ibOBK8FoIEE@u2jm7ePFOouLVYcgWaP4CBZgPCU3nQxGBj4WfgB/SIw2jOzv5WH2F5JKxmCsvEZeMp95dsGn5/@sZ80TwdE3bxUdtp7RFKKiNmj7jkztlgxx8Pnrx2pl4W/m3nmQc4QFe9wOe0IUvA14F8ADguwDu6V8 "Python 2 – Try It Online")
Golfed and fixed thanks to user202729!
-27 bytes thanks to Mr. Xcoder
-24 bytes thanks to Jonathan Frech
[Answer]
# [Python 2](https://docs.python.org/2/), ~~346~~ 331 bytes
```
e=enumerate
C='0132645'
def f(s):
c={(i,j):[1+(i/2%2+j/4)%3*2]for i,l in e(s)for j,x in e(l)if'*'==x}
for i,l in e(s):
r=''
for j,x in e(l):a=c.get((i,j),c.get((i-(x<'|'),j+[-1,1][x>'/']+(x>'z')),[]))+c.get((i+(x<'|'),j+[1,-1][x>'/']-(x>'z')),[])if' '<x else[0];r+='\033[3'+C[[sum(a)/len(a),6][set(a)=={5,1}]]+'m'+x
print r
```
[Try it online!](https://tio.run/##XY/BbsIwDIbveQoLCTkhKSUtcOjILjxGmkMF6ZaqlKotUjfg2buwiYn2YP229fm3XX91n@cqGgarbHU52SbrLNkrXMk42q43SI42h5y2LCFwUFfqRMESLTl1YTSPeBGu2TxeRCY/N@BECa4C6@lHWYj@ryyZy3GBSvV3AhPQ20KjEL1MZpJMHZYftqO/O8UzD2i/wxsyUXAdSCGN7t8xRMOp129kTGjDGH/i/AWXIvjHg1fcnwe468GWrdUr89ZwhekqjnWMfK91eznRjIWlrbyIrdGtt86YUteNkHdjOJ6Q9/6DunFVB82Q09lsRiCEdBTkBgsYBZkQIXiXMfXojAgAb65lYpZtXbqOYlr5N4Yf "Python 2 – Try It Online")
[Answer]
# HTML (Canvas) + JavaScript (ES6), 13 + 251 = 264 bytes
Locates all the `*`s in the input string and paints an ASCII hexagon on the canvas at the corresponding positions. Because `globalCompositeOperation='lighter'`, color addition is performed automatically when characters overlap.
### HTML
```
<canvas id=c>
```
### JavaScript
```
s=>{c.width=c.height=s.length
with(c.getContext`2d`)font='1px monospace',globalCompositeOperation='lighter',s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&[` / \\`,`| * |`,` \\ /`].map((t,i)=>fillText(t,x,y+i),fillStyle=['red','lime','blue'][x%3])))}
```
---
A multiplier and additional `scale()` command were added to the snippet for visibility.
```
// Unscaled
/*
f=
s=>{c.width=c.height=s.length
with(c.getContext`2d`)font='1px monospace',globalCompositeOperation='lighter',s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&[` / \\`,`| * |`,` \\ /`].map((t,i)=>fillText(t,x,y+i),fillStyle=['red','lime','blue'][x%3])))}
*/
// Scaled
let scaleFactor = 40
f=
s=>{c.width=c.height=s.length*scaleFactor
with(c.getContext`2d`)scale(scaleFactor,scaleFactor),font='1px monospace',globalCompositeOperation='lighter',s.split`
`.map((r,y)=>[...r].map((c,x)=>c=='*'&&[` / \\`,`| * |`,` \\ /`].map((t,i)=>fillText(t,x,y+i),fillStyle=['red','lime','blue'][x%3])))}
// Test
f(` / \\ / \\ / \\ / \\
| * | * | * | * |
\\ / \\ / \\ / \\ /
| * | * | * |
\\ / \\ / \\ /`)
```
```
<canvas id=c>
```
[](https://i.stack.imgur.com/AAwdY.png)
---
Also see my [CSS-based approach](https://codegolf.stackexchange.com/a/147066/47097).
[Answer]
# MATLAB/[Octave](https://www.gnu.org/software/octave/), 223 bytes
```
a=input('')';s=size(a);p=zeros([s 3]);[i,j]=ind2sub(s,find(a=='*'));
for f=1:nnz(i)
p((-2:2)+i(f),(-1:1)+j(f),mod(f+~mod(j(f)/2,2),3)+1)=1;end
for f=1:nnz(a)
[i,j]=ind2sub(s,f);text(i/s(1),1-j/s(2),a(i,j),'Co',p(i,j,:));end
```
In slightly neater code format:
```
a=input('')'; %Grab input as 2D array
s=size(a); %Get input size
p=zeros([s 3]); %Make empty colour matrix of matching size with RGB
[i,j]=ind2sub(s,find(a=='*')); %Find all *'s
for f=1:nnz(i) %For each *
%Fill a 5x3 box centred at the * on the colour channel for this box
%Overlapping regions between boxes will result in the correct mix.
p((-2:2)+i(f),(-1:1)+j(f),mod(f+~mod(j(f)/2,2),3)+1)=1;
end
%Display as text on a figure
for f=1:nnz(a)
[i,j]=ind2sub(s,f);
text(i/s(1),1-j/s(2),a(i,j),'Co',p(i,j,:))
end
```
The input is taken as a 2D array, such as entering the following when prompted for input:
```
[' / \ / \ / \ / \ ';'| * | * | * | * |';' \ / \ / \ / \ / ';' | * | * | * | ';' \ / \ / \ / ']
```
MATLAB so far as I'm aware doesn't have the ability to output colours to the console (except for dirty Java hacks which I am discounting). As such the output is instead printed to a figure.
Colouring is achieved by finding the location of all `*`'s in the input, and then in an RGB colour array (`p`), a 5x3 box of 1's (255 in MATLAB colour representation) are written centred about the `*`. The box is written to the colour corresponding with the mod-3 index along each line, with even lines having the colour index shifted by an offset.
This produces a colour matrix where any boxes that overlap will result in the required mixed colour. The example above produces the following colour matrix.
[](https://i.stack.imgur.com/TCLf4.png)
The white and black regions are irrelevant because at those locations a space is printed meaning we don't actually see the incorrect colour.
Once the colour matrix is created, we display each character on a figure using the `text` command, setting the colour of the text to the corresponding entry in the colour matrix. The above example will display:
[](https://i.stack.imgur.com/4vB8o.png)
] |
[Question]
[
Your task is to make a program that prints out its own source.
"Hey, we already have this challenge, and tons of variations of it! Why are you making another one?" you may ask, but this one is going to be one of the most difficult ones (hopefully, anyway).
Your quine must be "mutation-hardened", which means the quine, even when any one of its characters are duplicated in place, must output the source code of the original program.
For example, if you have a quine (the following example is not written in any language, it's just pseudocode):
```
abcd
```
These programs must all output `abcd`:
```
aabcd
abbcd
abccd
abcdd
```
(In each of those programs, `a`, `b`, `c` and `d` are each duplicated in-place, which means the duplicated character was placed directly after the original character.)
## Rules:
* Standard quine rules apply.
* A multi-byte character counts as one character, and the character is not "split" into its respective bytes when duplicated.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins!
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 56 bytes
```
^
.
+
8
f
0
o
a
o
~
:
?
~
:
?
:
-
*
4
8
:
^
^
}
*
3
d
'
```
[Try it online!](https://tio.run/##S8sszvj/P45Lj0uby4IrjcuAK58rEYjruKy47KGkFZculxaXCVDeiisOCGuBPGOuFC51rv//AQ "><> – Try It Online") or [verify all mutations](https://tio.run/##VU/BToNAED3zvmJS19BKllrrwaCt8WLSg3qwnlqbILBhDrIEFmND8Nfpgm3azmYm@@bNm5f5Csu0bRfP7zMqkjAmWcTkuhTpOMH3D/mc5ZXxDeu@5SsuU0DpgoZDphlN7onpgUR90dGNRZ43GqGGkxecGUUDUXdMEAhu9l@xYjn5bAY073cK/t96ULgvH8un5eLtlS5vqnUmD7HOXBIMJwrNqY6scGtSnU1prHMz7np98fPt2dycdGXsMRabX3O0O1pYBzgxK0WyPBs@ud1JolSjadsNfHi4g8I1NEKbfwjwuK8BJK5wa/kAG/sai6aI4WIH "Bash – Try It Online").
### How the original program works (outdated)
The interpreter starts in cell **(0, 0)**. `^` sets the direction to *upwards*, so the instruction pointer (IP) wraps around to cell **(0, 20)**.
`'` activates string mode: until the next `'` is encountered, all characters under the IP are pushed on the stack. The same `'` is found again after wrapping around, so we push
```
d3*}^^:84*=?~oao0f.^
```
The IP lands at **(0, 19)**, still going upwards. Executing `d3*}` pushes **13 = 0xd**, then **3**, multiplies both values (**39** / *single quote*), then rotates the stack to the right. This leaves the stack as follows.
```
'd3*}^^:84*=?~oao0f.^
```
The next two instructions (`^`) do nothing at this point.
`:84*=` duplicates the top of the stack, pushes **8** and **4**, multiplies them (**32** / *space*), then tests the duplicated character for equality with *space*. For the unaltered program, this will always push **0**.
`?` skips the next instruction if the top of the stack is falsy. For the original program, it always is, so `~` is always skipped.
`oao` pops and prints the top of the stack, pushes a **10** / *linefeed*, then pops and prints *linefeed*.
Finally `0f.` jumps to cell **(0, 15)** (the bottommost `^`), starting over with the next character on the stack.
Once the stack is empty, the entire source code has been printed. `:` will fail and the program exits.
### How the mutated programs work (outdated)
Duplicating any non-linefeed character will only extend the program horizontally. Since the program is executed vertically, these extra instructions will never get executed.
Duplicating any linefeed before the bottomost `^` will shift cells **(0, 14)** and **(0, 15)** to **(0, 15)** and **(0, 16)**. `0f.` will now jump to the cell before the bottommost `^`, which is also a `^`, so the program is not affected by the shift.
Finally, any duplicated linefeed character will also alter the string. Short lines are padded with spaces, so a **32** / *space* will be inserted at the linefeed's position. `84*=` will push **1** for space, so `?` doesn't skip the next instruction. In this case, `~` pops and discards *space*, so the following `o` will print the character above *space* instead.
] |
[Question]
[
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is *a* characters wide and *b* characters tall. For example, with '4' and '6':
```
****
* *
* *
* *
* *
****
```
Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be
```
4646
6 4
4 6
6 4
4 6
6464
```
A and B *may* be two-digit numbers. For example, the inputs "10" and "3" should output this:
```
1031031031
1 0
3013013013
```
In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to *positive* integers, '0' is an invalid input, which you do not have to handle.
Here are some more test cases:
```
Input: (3, 5)
Output:
353
5 5
3 3
5 5
353
Input: (1, 1)
Output:
1
Input: (4, 4)
Output:
4444
4 4
4 4
4444
Input: (27, 1)
Output:
271271271271271271271271271
Input: (1, 17)
Output:
1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1
Input: (12, 34):
Output:
123412341234
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
4 1
3 2
2 3
1 4
432143214321
```
You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~65~~ 51 bytes
```
~~juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ\_UhQ+R]0\_UeQ)m\*;hQeQ~~
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH
```
[Try it online!](http://pyth.herokuapp.com/?code=AQjuXGhHX%40GhHeH%40jkQ~hZ%7Bs%5B%2CL0G%2CRtGH_%2CLtHG_%2CR0H%29m%2a%3BGH&input=10%2C3&debug=0)
[Answer]
## C#, 301 bytes
I'm sure there is a lot more golfing that can be done here but I'm just happy I got a solution that worked.
I found a bug where the bottom line was in the wrong order, damnit!
```
a=>b=>{var s=new string[b];int i=4,c=b-2,k=a;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");for(;--k>=0;)s[b-1]+=t.Substring(a+c,a)[k];}return s;};
```
Old version: 280 bytes
```
a=>b=>{var s=new string[b];int i=4,c=b-2;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");s[b-1]=t.Substring(a+c,a);}return s;};
```
[Answer]
# Python 2, 199 bytes
```
w,h=input()
s=(`w`+`h`)*w*h
r=[s[:w]]+[[" "for i in[0]*w]for j in[0]*(h-2)]+[s[w+h-2:2*w+h-2][::-1]]*(h>1)
for y in range(1,h-1):r[y][w-1],r[y][0]=s[w+y-1],s[w+h+w-2-y]
print"\n".join(map("".join,r))
```
[Answer]
# Ruby, 128 bytes
```
->w,h{s="%d%d"%[w,h]*q=w+h;a=[s[0,w]];(h-2).times{|i|a<<(s[2*q-5-i].ljust(w-1)+s[w+i,1])[-w,w]};puts a,h>1?(s[q-2,w].reverse):p}
```
Outputs trailing newline if height is 1.
Ideone link: <https://ideone.com/96WYHt>
[Answer]
# JavaScript, ~~213~~ ~~212~~ 202
```
c=>a=>{for(a=$=a,c=_=c,l=c*a*2,b=0,s=Array(l+1).join(c+""+a),O=W=s.substr(0,a),W=W.substr(0,a-2).replace(/./g," ");--_;)O+="\n"+s[l-c+_]+W+s[$++];return O+"\n"+[...s.substr(l-a-c+1,a)].reverse().join``}
```
Surely has room for improvement.
**Edit:** Saved a byte thanks to TheLethalCoder
[Answer]
# C, 311 bytes
```
char s[5];sprintf(s,"%d%d",a, b);int z=strlen(s);int i=0;while(i<a){printf("%c",s[i++%z]);}if(b>2){i=1;while(i<b-1){char r=s[(a+i-1)%z];char l=s[(2*a+2*b-i-4)%z];if(a>1){printf("\n%c%*c",l,a-1,r);}else{printf("\n%c",l);}i++;}}printf("\n");if(b>1){i=0;while(i<a){printf("%c",s[(2*a+b-i-3)%z]);i++;}printf("\n");}
```
Uses automatically included libraries `stdio.h` and `string.h`.
[Answer]
## JavaScript (ES6), 171 bytes
```
(w,h)=>[...Array(h)].map((_,i)=>i?++i<h?(w>1?s[p+p+1-i]+` `.repeat(w-2):``)+s[w+i-2]:[...s.substr(p,w)].reverse().join``:s.slice(0,w),s=`${w}${h}`.repeat(p=w+h-2)).join`\n`
```
Where `\n` represents the literal newline character. Creates a repeated digit string, then decides what to concatenate based on which row we're on; top row is just the initial slice of the repeated digit string, bottom row (if any) is a reversed slice from the middle of the string, while intervening rows are built up using characters taken from other parts of the string.
[Answer]
# TSQL, 291 bytes
**Golfed:**
```
DECLARE @ INT=5,@2 INT=4
,@t INT,@z varchar(max)SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)v:PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)+isnull(space(@-2)+left(@z,1),''),reverse(@z)))SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))IF @<=len(@z)goto v
```
**Ungolfed:**
```
DECLARE @ INT=5,@2 INT=4
,@t INT,@z varchar(max)
SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)
v:
PRINT
iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)
+isnull(space(@-2)+left(@z,1),''),reverse(@z)))
SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))
IF @<=len(@z)goto v
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/526524/code-golf-abcs-the-ascii-box-challenge)**
[Answer]
# Python 3, ~~155~~ 148 bytes
Golfed off 7 more bytes:
```
p=print
def f(w,h):
s=((str(w)+str(h))*w*h)[:2*w+2*h-4or 1];p(s[:w])
for i in range(h-2):p(['',s[-i-1]][w>1]+' '*(w-2)+s[w+i])
p(s[1-h:1-h-w:-1])
```
Substituted `2*w+2*h-4or 1` for `max(1,2*w+2*h-4)` and
`['',s[-i-1]][w>1]` for `(s[-i-1]if w>1else'')`.
Prior version:
```
p=print
def f(w,h):
s=((str(w)+str(h))*w*h)[:max(1,2*w+2*h-4)];p(s[:w])
for i in range(h-2):p((s[-i-1]if w>1else'')+' '*(w-2)+s[w+i])
p(s[1-h:1-h-w:-1])
```
] |
[Question]
[
An [alternating sign matrix](https://en.wikipedia.org/wiki/Alternating_sign_matrix) is an `n` by `n` matrix consisting of the numbers -1, 0, 1, such that:
* The sum of each row and column is 1
* The nonzero entries in each row and column alternate in sign
These matrices generalise permutation matrices, and the number of such matrices for a given `n` was of interest for some time. They occur naturally during the Dodgson condensation method of computing matrix determinants (named after Charles Dodgson, better known as Lewis Carroll).
Here are some examples of 4 by 4 alternating sign matrices:
```
0 1 0 0 1 0 0 0 0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0 0 1 -1 1 1 0 -1 1
1 0 0 0 0 1 -1 1 1 -1 1 0 0 1 0 0
0 0 0 1 0 0 1 0 0 1 0 0 0 0 1 0
```
And here are some examples of 4 by 4 matrices which aren't alternating sign matrices:
```
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 -1 (last row and last column don't add to 1)
0 0 0 1
1 0 0 0
-1 1 1 0
1 0 0 0 (third row does not alternate correctly)
```
Your program or function will be given an `n` by `n` matrix (`n >= 1`) of -1s, 0s and 1s — output a [truthy value](http://meta.codegolf.stackexchange.com/questions/2190/interpretation-of-truthy-falsey) if the given matrix is an alternating sign matrix, otherwise output a falsy value.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the goal is to minimise the number of bytes used.
## Test cases
The following test cases are given in a Python-like 2D list format.
**Truthy:**
```
[[1]]
[[1,0],[0,1]]
[[0,1],[1,0]]
[[0,1,0],[0,0,1],[1,0,0]]
[[0,1,0],[1,-1,1],[0,1,0]]
[[0,1,0,0],[0,0,1,0],[1,0,0,0],[0,0,0,1]]
[[1,0,0,0],[0,0,1,0],[0,1,-1,1],[0,0,1,0]]
[[0,0,1,0],[0,1,-1,1],[1,-1,1,0],[0,1,0,0]]
[[0,0,1,0],[1,0,-1,1],[0,1,0,0],[0,0,1,0]]
[[0,0,1,0,0],[0,1,-1,1,0],[1,-1,1,0,0],[0,1,0,-1,1],[0,0,0,1,0]]
[[0,0,1,0,0,0,0,0],[1,0,-1,0,1,0,0,0],[0,0,0,1,-1,0,0,1],[0,0,1,-1,1,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,0,0],[0,1,-1,1,0,0,0,0],[0,0,1,0,0,0,0,0]]
[[0,0,0,0,1,0,0,0],[0,0,1,0,-1,1,0,0],[0,0,0,1,0,0,0,0],[1,0,0,-1,1,-1,1,0],[0,1,-1,1,-1,1,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,1]]
```
**Falsy:**
```
[[0]]
[[-1]]
[[1,0],[0,0]]
[[0,0],[0,1]]
[[-1,1],[1,0]]
[[0,1],[1,-1]]
[[0,0,0],[0,0,0],[0,0,0]]
[[0,1,0],[1,0,1],[0,1,0]]
[[-1,1,1],[1,-1,1],[1,1,-1]]
[[0,0,1],[1,0,0],[0,1,-1]]
[[0,1,0,0],[0,0,0,1],[1,0,0,0],[0,0,1,-1]]
[[0,0,1,0],[0,0,1,0],[1,0,-1,1],[0,1,0,0]]
[[0,0,0,1],[1,0,0,0],[-1,1,1,0],[1,0,0,0]]
[[1,0,1,0,-1],[0,1,0,0,0],[0,0,0,0,1],[0,0,0,1,0],[0,0,0,0,1]]
[[0,0,1,0,0],[0,1,-1,1,0],[1,-1,1,0,0],[0,1,1,-1,0],[0,0,-1,1,1]]
[[0,-1,0,1,1],[1,-1,1,-1,1],[0,1,1,0,-1],[1,1,-1,1,-1],[-1,1,0,0,1]]
[[0,0,1,0,0,0,0,0],[1,0,1,0,1,0,0,0],[0,0,0,1,-1,0,0,1],[0,0,1,-1,1,0,0,0],[0,0,0,0,0,0,1,0],[0,0,0,0,0,1,0,0],[0,1,-1,1,0,0,0,0],[0,0,1,0,0,0,0,0]]
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~62~~ ~~58~~ ~~56~~ 53 bytes
Byte count assumes ISO 8859-1 encoding, and the `\t` should be replaced with actual tabs (0x09 which would be turned into spaces by SE otherwise).
```
$
\t$`¶
O$#`...(?<=^[^\t]*(.+))
$.1
T` 0
^(1(-11)*\s)+$
```
Input format is a matrix where each column uses three right-aligned characters, e.g.:
```
0 0 1 0
1 0 -1 1
0 1 0 0
0 0 1 0
```
Output is either `0` (falsy) or `1` (truthy).
[Test suite.](http://retina.tryitonline.net/#code=JShTYF0sXFsKW11bXQoKKD88IS0pXGQKICQmCi0_XGQKICQmCiwKCiQKCSRgwrYKTyQjYC4uLig_PD1eW14JXSooLispKQokLjEKVGAgMApeKDEoLTExKSpccykrJA&input=W1sxXV0KW1sxLDBdLFswLDFdXQpbWzAsMV0sWzEsMF1dCltbMCwxLDBdLFswLDAsMV0sWzEsMCwwXV0KW1swLDEsMF0sWzEsLTEsMV0sWzAsMSwwXV0KW1swLDEsMCwwXSxbMCwwLDEsMF0sWzEsMCwwLDBdLFswLDAsMCwxXV0KW1sxLDAsMCwwXSxbMCwwLDEsMF0sWzAsMSwtMSwxXSxbMCwwLDEsMF1dCltbMCwwLDEsMF0sWzAsMSwtMSwxXSxbMSwtMSwxLDBdLFswLDEsMCwwXV0KW1swLDAsMSwwXSxbMSwwLC0xLDFdLFswLDEsMCwwXSxbMCwwLDEsMF1dCltbMCwwLDEsMCwwXSxbMCwxLC0xLDEsMF0sWzEsLTEsMSwwLDBdLFswLDEsMCwtMSwxXSxbMCwwLDAsMSwwXV0KW1swLDAsMSwwLDAsMCwwLDBdLFsxLDAsLTEsMCwxLDAsMCwwXSxbMCwwLDAsMSwtMSwwLDAsMV0sWzAsMCwxLC0xLDEsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDBdLFswLDAsMCwwLDAsMSwwLDBdLFswLDEsLTEsMSwwLDAsMCwwXSxbMCwwLDEsMCwwLDAsMCwwXV0KW1swLDAsMCwwLDEsMCwwLDBdLFswLDAsMSwwLC0xLDEsMCwwXSxbMCwwLDAsMSwwLDAsMCwwXSxbMSwwLDAsLTEsMSwtMSwxLDBdLFswLDEsLTEsMSwtMSwxLDAsMF0sWzAsMCwwLDAsMSwwLDAsMF0sWzAsMCwxLDAsMCwwLDAsMCwwXSxbMCwwLDAsMCwwLDAsMCwxXV0KW1swXV0KW1stMV1dCltbMCwwLDBdLFswLDAsMF0sWzAsMCwwXV0KW1swLDEsMF0sWzEsMCwxXSxbMCwxLDBdXQpbWy0xLDEsMV0sWzEsLTEsMV0sWzEsMSwtMV1dCltbMCwwLDFdLFsxLDAsMF0sWzAsMSwtMV1dCltbMCwwLDEsMCwwXSxbMCwxLC0xLDEsMF0sWzEsLTEsMSwwLDBdLFswLDEsMSwtMSwwXSxbMCwwLC0xLDEsMV1dCltbMCwtMSwwLDEsMV0sWzEsLTEsMSwtMSwxXSxbMCwxLDEsMCwtMV0sWzEsMSwtMSwxLC0xXSxbLTEsMSwwLDAsMV1dCltbMCwwLDEsMCwwLDAsMCwwXSxbMSwwLDEsMCwxLDAsMCwwXSxbMCwwLDAsMSwtMSwwLDAsMV0sWzAsMCwxLC0xLDEsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDBdLFswLDAsMCwwLDAsMSwwLDBdLFswLDEsLTEsMSwwLDAsMCwwXSxbMCwwLDEsMCwwLDAsMCwwXV0) (The first few lines transform the input format and let Retina run several test cases at once.)
### Explanation
Thankfully, the input is a square matrix: transposing squares is just about doable in Retina, whereas transposing rectangles is a massive pain.
```
$
\t$`¶
```
We start by appending a tab, the entire input again (using the prefix `$``) and then a linefeed at the end (using Retina's alias `¶`). We're using a tab to separate the two copies so that we can distinguish between them when we're transposing one of them, and by using a whitespace character we can save a couple of bytes later on.
```
O$#`...(?<=^[^\t]*(.+))
$.1
```
This is the trickiest bit: transposing the first copy of the matrix. The idea is to match cells in the first copy and then sorting them (stably) by the horizontal position. We match the cells with `...` (since they're always three characters wide) and then measure the horizontal position with `(.+)` inside the lookbehind. Then, to make sure that we only transpose the first copy, we check that we can reach the beginning of the string without moving past a tab.
You might notice that this will also match some three-byte strings (that don't even align with the cells) in the first row of the second copy, because the `.+` can pass through the tab. However, this is not an issue because the horizontal position of these matches is strictly greater than any inside the first copy, so these matches remain in their position.
The rest is fairly simple:
```
T` 0
```
We remove spaces and zeros from the input.
```
^(1(-11)*\s)+$
```
And finally we check that the entire input consists of whitespace-terminated rows of the form `1(-11)*`, i.e. an alternating sequence of `1` and `-1` that begins and ends with `1` (because otherwise it doesn't sum to `1`).
[Answer]
# Jelly, 15 bytes
```
;Zḟ€0;€-;@€-IFP
```
[Try it online!](http://jelly.tryitonline.net/#code=O1rhuJ_igqwwO-KCrC07QOKCrC1JRlA&input=&args=W1stMSwxXSxbMSwwXV0)
```
;Zḟ€0;€-;@€-IFP Main monadic chain. Argument: z
;Z Concatenate with its transpose.
ḟ€0 Remove zeros from each sub-list. At this point,
one expects lists of the form [1, -1, 1, -1, ..., 1] for truthy,
and any other arrays containing purely 1 and -1 for falsey.
;€- Append -1 to each sub-list.
;€@- Prepend -1 to each sub-list.
I Compute the difference between each term. At this point,
for truthy, one expects arrays filled with 2, and arrays
containing 0 otherwise.
FP Product of every item. This checks if any item is equal to zero.
```
[Answer]
# Pyth, 16 bytes
```
!sm-sM._+d_1U2+C
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%21sm-sM._%2Bd_1U2%2BC&input=%5B%5B0%2C0%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%5D%2C%5B1%2C-1%2C1%2C0%5D%2C%5B0%2C1%2C0%2C0%5D%5D&test_suite_input=%5B%5B1%5D%5D%0A%5B%5B1%2C0%5D%2C%5B0%2C1%5D%5D%0A%5B%5B0%2C1%5D%2C%5B1%2C0%5D%5D%0A%5B%5B0%2C1%2C0%5D%2C%5B0%2C0%2C1%5D%2C%5B1%2C0%2C0%5D%5D%0A%5B%5B0%2C1%2C0%5D%2C%5B1%2C-1%2C1%5D%2C%5B0%2C1%2C0%5D%5D%0A%5B%5B0%2C1%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%5D%2C%5B1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%5D%5D%0A%5B%5B1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%5D%2C%5B0%2C0%2C1%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%5D%2C%5B1%2C-1%2C1%2C0%5D%2C%5B0%2C1%2C0%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%5D%2C%5B1%2C0%2C-1%2C1%5D%2C%5B0%2C1%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%5D%2C%5B1%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C1%2C0%2C-1%2C1%5D%2C%5B0%2C0%2C0%2C1%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C-1%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C-1%2C0%2C0%2C1%5D%2C%5B0%2C0%2C1%2C-1%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C1%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%5D%0A%5B%5B0%2C0%2C0%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C0%2C-1%2C1%2C-1%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%5D%5D%0A%0A%5B%5B0%5D%5D%0A%5B%5B-1%5D%5D%0A%5B%5B0%2C0%2C0%5D%2C%5B0%2C0%2C0%5D%2C%5B0%2C0%2C0%5D%5D%0A%5B%5B0%2C1%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%5D%0A%5B%5B-1%2C1%2C1%5D%2C%5B1%2C-1%2C1%5D%2C%5B1%2C1%2C-1%5D%5D%0A%5B%5B0%2C0%2C1%5D%2C%5B1%2C0%2C0%5D%2C%5B0%2C1%2C-1%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%5D%2C%5B1%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C1%2C1%2C-1%2C0%5D%2C%5B0%2C0%2C-1%2C1%2C1%5D%5D%0A%5B%5B0%2C-1%2C0%2C1%2C1%5D%2C%5B1%2C-1%2C1%2C-1%2C1%5D%2C%5B0%2C1%2C1%2C0%2C-1%5D%2C%5B1%2C1%2C-1%2C1%2C-1%5D%2C%5B-1%2C1%2C0%2C0%2C1%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C1%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C-1%2C0%2C0%2C1%5D%2C%5B0%2C0%2C1%2C-1%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C1%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%5D&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=%21sm-sM._%2Bd_1U2%2BC&input=%5B%5B0%2C0%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%5D%2C%5B1%2C-1%2C1%2C0%5D%2C%5B0%2C1%2C0%2C0%5D%5D&test_suite=1&test_suite_input=%5B%5B1%5D%5D%0A%5B%5B1%2C0%5D%2C%5B0%2C1%5D%5D%0A%5B%5B0%2C1%5D%2C%5B1%2C0%5D%5D%0A%5B%5B0%2C1%2C0%5D%2C%5B0%2C0%2C1%5D%2C%5B1%2C0%2C0%5D%5D%0A%5B%5B0%2C1%2C0%5D%2C%5B1%2C-1%2C1%5D%2C%5B0%2C1%2C0%5D%5D%0A%5B%5B0%2C1%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%5D%2C%5B1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%5D%5D%0A%5B%5B1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%5D%2C%5B0%2C0%2C1%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%5D%2C%5B1%2C-1%2C1%2C0%5D%2C%5B0%2C1%2C0%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%5D%2C%5B1%2C0%2C-1%2C1%5D%2C%5B0%2C1%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%5D%2C%5B1%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C1%2C0%2C-1%2C1%5D%2C%5B0%2C0%2C0%2C1%2C0%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C-1%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C-1%2C0%2C0%2C1%5D%2C%5B0%2C0%2C1%2C-1%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C1%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%5D%0A%5B%5B0%2C0%2C0%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C0%2C-1%2C1%2C-1%2C1%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C0%2C1%5D%5D%0A%0A%5B%5B0%5D%5D%0A%5B%5B-1%5D%5D%0A%5B%5B0%2C0%2C0%5D%2C%5B0%2C0%2C0%5D%2C%5B0%2C0%2C0%5D%5D%0A%5B%5B0%2C1%2C0%5D%2C%5B1%2C0%2C1%5D%2C%5B0%2C1%2C0%5D%5D%0A%5B%5B-1%2C1%2C1%5D%2C%5B1%2C-1%2C1%5D%2C%5B1%2C1%2C-1%5D%5D%0A%5B%5B0%2C0%2C1%5D%2C%5B1%2C0%2C0%5D%2C%5B0%2C1%2C-1%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%5D%2C%5B1%2C-1%2C1%2C0%2C0%5D%2C%5B0%2C1%2C1%2C-1%2C0%5D%2C%5B0%2C0%2C-1%2C1%2C1%5D%5D%0A%5B%5B0%2C-1%2C0%2C1%2C1%5D%2C%5B1%2C-1%2C1%2C-1%2C1%5D%2C%5B0%2C1%2C1%2C0%2C-1%5D%2C%5B1%2C1%2C-1%2C1%2C-1%5D%2C%5B-1%2C1%2C0%2C0%2C1%5D%5D%0A%5B%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%2C%5B1%2C0%2C1%2C0%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C1%2C-1%2C0%2C0%2C1%5D%2C%5B0%2C0%2C1%2C-1%2C1%2C0%2C0%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C0%2C1%2C0%5D%2C%5B0%2C0%2C0%2C0%2C0%2C1%2C0%2C0%5D%2C%5B0%2C1%2C-1%2C1%2C0%2C0%2C0%2C0%5D%2C%5B0%2C0%2C1%2C0%2C0%2C0%2C0%2C0%5D%5D&debug=0)
# Explanation:
```
!sm-sM._+d_1U2+CQQ two implicit Qs (=input matrix) at the end
+CQQ zip Q and connect it with Q (=list of columns and rows)
m map each column/row d to:
+d_1 append -1 to d
._ compute all prefixes of ^
sM compute the sums of the prefixes
- U2 remove zeros and ones
a column/row is correct, if this gives an empty list
s connect up all resulting lists
! check, if this result is empty
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;Zj-+\ṚQḄ=2
```
Returns **1** for alternating sign matrices, **0** otherwise. [Try it online!](http://jelly.tryitonline.net/#code=O1pqLStc4bmaUeG4hD0y&input=&args=W1swLDAsMCwwLDEsMCwwLDBdLFswLDAsMSwwLC0xLDEsMCwwXSxbMCwwLDAsMSwwLDAsMCwwXSxbMSwwLDAsLTEsMSwtMSwxLDBdLFswLDEsLTEsMSwtMSwxLDAsMF0sWzAsMCwwLDAsMSwwLDAsMF0sWzAsMCwxLDAsMCwwLDAsMF0sWzAsMCwwLDAsMCwwLDAsMV1d) or [verify all test cases](http://jelly.tryitonline.net/#code=O1pqLStc4bmaUeG4hD0yCsOH4oKs4oKsRw&input=&args=W1tbMV1dLFtbMSwwXSxbMCwxXV0sW1swLDFdLFsxLDBdXSxbWzAsMSwwXSxbMCwwLDFdLFsxLDAsMF1dLFtbMCwxLDBdLFsxLC0xLDFdLFswLDEsMF1dLFtbMCwxLDAsMF0sWzAsMCwxLDBdLFsxLDAsMCwwXSxbMCwwLDAsMV1dLFtbMSwwLDAsMF0sWzAsMCwxLDBdLFswLDEsLTEsMV0sWzAsMCwxLDBdXSxbWzAsMCwxLDBdLFswLDEsLTEsMV0sWzEsLTEsMSwwXSxbMCwxLDAsMF1dLFtbMCwwLDEsMF0sWzEsMCwtMSwxXSxbMCwxLDAsMF0sWzAsMCwxLDBdXSxbWzAsMCwxLDAsMF0sWzAsMSwtMSwxLDBdLFsxLC0xLDEsMCwwXSxbMCwxLDAsLTEsMV0sWzAsMCwwLDEsMF1dLFtbMCwwLDEsMCwwLDAsMCwwXSxbMSwwLC0xLDAsMSwwLDAsMF0sWzAsMCwwLDEsLTEsMCwwLDFdLFswLDAsMSwtMSwxLDAsMCwwXSxbMCwwLDAsMCwwLDAsMSwwXSxbMCwwLDAsMCwwLDEsMCwwXSxbMCwxLC0xLDEsMCwwLDAsMF0sWzAsMCwxLDAsMCwwLDAsMF1dLFtbMCwwLDAsMCwxLDAsMCwwXSxbMCwwLDEsMCwtMSwxLDAsMF0sWzAsMCwwLDEsMCwwLDAsMF0sWzEsMCwwLC0xLDEsLTEsMSwwXSxbMCwxLC0xLDEsLTEsMSwwLDBdLFswLDAsMCwwLDEsMCwwLDBdLFswLDAsMSwwLDAsMCwwLDBdLFswLDAsMCwwLDAsMCwwLDFdXV0sIFtbWzBdXSxbWy0xXV0sW1sxLDBdLFswLDBdXSxbWzAsMF0sWzAsMV1dLFtbLTEsMV0sWzEsMF1dLFtbMCwxXSxbMSwtMV1dLFtbMCwwLDBdLFswLDAsMF0sWzAsMCwwXV0sW1swLDEsMF0sWzEsMCwxXSxbMCwxLDBdXSxbWy0xLDEsMV0sWzEsLTEsMV0sWzEsMSwtMV1dLFtbMCwwLDFdLFsxLDAsMF0sWzAsMSwtMV1dLFtbMCwxLDAsMF0sWzAsMCwwLDFdLFsxLDAsMCwwXSxbMCwwLDEsLTFdXSxbWzAsMCwxLDBdLFswLDAsMSwwXSxbMSwwLC0xLDFdLFswLDEsMCwwXV0sW1swLDAsMCwxXSxbMSwwLDAsMF0sWy0xLDEsMSwwXSxbMSwwLDAsMF1dLFtbMSwwLDEsMCwtMV0sWzAsMSwwLDAsMF0sWzAsMCwwLDAsMV0sWzAsMCwwLDEsMF0sWzAsMCwwLDAsMV1dLFtbMCwwLDEsMCwwXSxbMCwxLC0xLDEsMF0sWzEsLTEsMSwwLDBdLFswLDEsMSwtMSwwXSxbMCwwLC0xLDEsMV1dLFtbMCwtMSwwLDEsMV0sWzEsLTEsMSwtMSwxXSxbMCwxLDEsMCwtMV0sWzEsMSwtMSwxLC0xXSxbLTEsMSwwLDAsMV1dLFtbMCwwLDEsMCwwLDAsMCwwXSxbMSwwLDEsMCwxLDAsMCwwXSxbMCwwLDAsMSwtMSwwLDAsMV0sWzAsMCwxLC0xLDEsMCwwLDBdLFswLDAsMCwwLDAsMCwxLDBdLFswLDAsMCwwLDAsMSwwLDBdLFswLDEsLTEsMSwwLDAsMCwwXSxbMCwwLDEsMCwwLDAsMCwwXV1d).
### Background
Disregarding zeroes, each row and column has to consist of the pattern **(1, -1)\* 1**, i.e., alternating occurrences of **1** and **-1**, starting and ending with a **1** (so the sum is **1**).
To verify this is the case, we take the array of all rows and columns, and join them using **-1** as separator. Since all endpoints are **1**'s, the resulting flat array satisfies the pattern **(1, -1)\* 1** if and only if the rows and columns do.
For the actual test, we compute the cumulative sum of the array. For an alternating sign matrix, the result will be an array of **0**'s and **1**'s that ends with a **1**.
We reverse the cumulative sum and deduplicate it, keeping the order of the initial occurrences of all unique elements. For a truthy input, the result will be the list **[1, 0]**.
To output the corresponding Boolean, we convert the duplicated cumulative sums from binary to integer and test if the result is **2**.
### How it works
```
;Zj-+\ṚQḄ=2 Main link. Argument: M (matrix / 2D array)
Z Zip; transpose M's rows and columns.
; Concatenate M and zipped M.
j- Join, separating by -1.
+\ Take the cumulative sum of the result.
Ṛ Reverse the array of partial sums.
Q Unique; deduplicate the partial sums.
Ḅ Unbinary; convert from base 2 to integer.
=2 Test for equality with 2.
```
[Answer]
# MATL, ~~18~~ ~~16~~ ~~15~~ 13 bytes
*3 bytes saved thanks to @Luis*
```
t!h"@s1=@Xzdv
```
This solution accepts a 2D array as input and will output a [truthy or falsey](http://matl.tryitonline.net/#code=PwondHJ1dGh5Jwp9CidmYWxzeSc&input=WzEgMSAwIDFd) array. It is important to note that in MATL, a truthy array is composed of all non-zero elements while a falsey result has at least one zero element. [Here is another demonstration of truthy/falsey arrays](http://matl.tryitonline.net/#code=YAo_Cid0cnV0aHknCn0KJ2ZhbHN5JwpdCnRE&input=MQowClsxIDEgMSAxXQpbMSAxIDAgMV0KWy0xIDEgLTIgMl0K).
[**Try it Online**](http://matl.tryitonline.net/#code=dCFoIkBzMT1AWHpkdg&input=WzAgMCAxIDA7IDEgMCAtMSAxOyAwIDEgMCAwOyAwIDAgMSAwXQ)
[Modified version to show all test cases](http://matl.tryitonline.net/#code=YHQhaCJAczE9QFh6ZHZBXURUXQ&input=MQpbMSwwOyAwLDFdClswLDE7IDEsMF0KWzAsMSwwOyAwLDAsMTsgMSwwLDBdClswLDEsMDsgMSwtMSwxIDswLDEsMF0KWzAsMSwwLDA7IDAsMCwxLDA7IDEsMCwwLDA7IDAsMCwwLDFdClsxLDAsMCwwOyAwLDAsMSwwOyAwLDEsLTEsMTsgMCwwLDEsMF0KWzAsMCwxLDA7IDAsMSwtMSwxOyAxLC0xLDEsMDsgMCwxLDAsMF0KWzAsMCwxLDA7IDEsMCwtMSwxOyAwLDEsMCwwOyAwLDAsMSwwXQpbMCwwLDEsMCwwOyAwLDEsLTEsMSwwOyAxLC0xLDEsMCwwOyAwLDEsMCwtMSwxOyAwLDAsMCwxLDBdClswLDAsMSwwLDAsMCwwLDA7IDEsMCwtMSwwLDEsMCwwLDA7IDAsMCwwLDEsLTEsMCwwLDE7IDAsMCwxLC0xLDEsMCwwLDA7IDAsMCwwLDAsMCwwLDEsMDsgMCwwLDAsMCwwLDEsMCwwOyAwLDEsLTEsMSwwLDAsMCwwOyAwLDAsMSwwLDAsMCwwLDBdClswLDAsMCwwLDEsMCwwLDA7IDAsMCwxLDAsLTEsMSwwLDA7IDAsMCwwLDEsMCwwLDAsMDsgMSwwLDAsLTEsMSwtMSwxLDA7IDAsMSwtMSwxLC0xLDEsMCwwOyAwLDAsMCwwLDEsMCwwLDA7IDAsMCwxLDAsMCwwLDAsMDsgMCwwLDAsMCwwLDAsMCwxXQpbMF0KWy0xXQpbLTEsMTsxLDBdClswLDE7IDEsLTFdClswLDAsMDsgMCwwLDA7IDAsMCwwXQpbMCwxLDA7IDEsMCwxOyAwLDEsMF0KWy0xLDEsMTsgMSwtMSwxOyAxLDEsLTFdClswLDAsMTsgMSwwLDA7IDAsMSwtMV0KWzAsMSwwLDA7IDAsMCwwLDE7IDEsMCwwLDA7IDAsMCwxLC0xXQpbMCwwLDEsMDsgMCwwLDEsMDsgMSwwLC0xLDE7IDAsMSwwLDBdClswLDAsMCwxOyAxLDAsMCwwOyAtMSwxLDEsMDsgMSwwLDAsMF0KWzAsMCwxLDAsMDsgMCwxLC0xLDEsMDsgMSwtMSwxLDAsMDsgMCwxLDEsLTEsMDsgMCwwLC0xLDEsMV0KWzAsLTEsMCwxLDE7IDEsLTEsMSwtMSwxOyAwLDEsMSwwLC0xOyAxLDEsLTEsMSwtMTsgLTEsMSwwLDAsMV0KWzAsMCwxLDAsMCwwLDAsMDsgMSwwLDEsMCwxLDAsMCwwOyAwLDAsMCwxLC0xLDAsMCwxOyAwLDAsMSwtMSwxLDAsMCwwOyAwLDAsMCwwLDAsMCwxLDA7IDAsMCwwLDAsMCwxLDAsMDsgMCwxLC0xLDEsMCwwLDAsMDsgMCwwLDEsMCwwLDAsMCwwXQ)
**Explanation**
```
% Implicitly grab input matrix
t! % Duplicate and transpose input
h % Horizontally concatenate input with transpose. This allows us to
% process only columns since now the columns *also* contain the rows.
" % For each column (of our column/row combined matrix)
@s1= % Compute the sum and ensure it is equal to 1
@Xz % Get the non-zeros
d % Compute the element-to-element difference. The 1 and -1 alternate only if
% all these differences are non-zero
v % Vertically concatenate everything on the stack
% Implicit end of loop and implicitly display truthy/falsey value
```
[Answer]
# Julia, 36 bytes
```
!x=[x^0 x^0;-x -x'][:]|>cumsum⊆0:1
```
[Try it online!](http://julia.tryitonline.net/#code=IXg9W3heMCB4XjA7LXggLXgnXVs6XXw-Y3Vtc3Vt4oqGMDoxCgpmb3IgeCBpbiAoWzFdJywgWzEgMDswIDFdLCBbMCAxOzEgMF0sIFswIDEgMDswIDAgMTsxIDAgMF0sIFswIDEgMDsxIC0xIDE7MCAxIDBdLCBbMCAxIDAgMDswIDAgMSAwOzEgMCAwIDA7MCAwIDAgMV0sIFsxIDAgMCAwOzAgMCAxIDA7MCAxIC0xIDE7MCAwIDEgMF0sIFswIDAgMSAwOzAgMSAtMSAxOzEgLTEgMSAwOzAgMSAwIDBdLCBbMCAwIDEgMDsxIDAgLTEgMTswIDEgMCAwOzAgMCAxIDBdLCBbMCAwIDEgMCAwOzAgMSAtMSAxIDA7MSAtMSAxIDAgMDswIDEgMCAtMSAxOzAgMCAwIDEgMF0sIFswIDAgMSAwIDAgMCAwIDA7MSAwIC0xIDAgMSAwIDAgMDswIDAgMCAxIC0xIDAgMCAxOzAgMCAxIC0xIDEgMCAwIDA7MCAwIDAgMCAwIDAgMSAwOzAgMCAwIDAgMCAxIDAgMDswIDEgLTEgMSAwIDAgMCAwOzAgMCAxIDAgMCAwIDAgMF0sIFswIDAgMCAwIDEgMCAwIDA7MCAwIDEgMCAtMSAxIDAgMDswIDAgMCAxIDAgMCAwIDA7MSAwIDAgLTEgMSAtMSAxIDA7MCAxIC0xIDEgLTEgMSAwIDA7MCAwIDAgMCAxIDAgMCAwOzAgMCAxIDAgMCAwIDAgMDswIDAgMCAwIDAgMCAwIDFdLCBbMF0nLCBbLTFdJywgWzEgMDswIDBdLCBbMCAwOzAgMV0sIFstMSAxOzEgMF0sIFswIDE7MSAtMV0sIFswIDAgMDswIDAgMDswIDAgMF0sIFswIDEgMDsxIDAgMTswIDEgMF0sIFstMSAxIDE7MSAtMSAxOzEgMSAtMV0sIFswIDAgMTsxIDAgMDswIDEgLTFdLCBbMCAxIDAgMDswIDAgMCAxOzEgMCAwIDA7MCAwIDEgLTFdLCBbMCAwIDEgMDswIDAgMSAwOzEgMCAtMSAxOzAgMSAwIDBdLCBbMCAwIDAgMTsxIDAgMCAwOy0xIDEgMSAwOzEgMCAwIDBdLCBbMSAwIDEgMCAtMTswIDEgMCAwIDA7MCAwIDAgMCAxOzAgMCAwIDEgMDswIDAgMCAwIDFdLCBbMCAwIDEgMCAwOzAgMSAtMSAxIDA7MSAtMSAxIDAgMDswIDEgMSAtMSAwOzAgMCAtMSAxIDFdLCBbMCAtMSAwIDEgMTsxIC0xIDEgLTEgMTswIDEgMSAwIC0xOzEgMSAtMSAxIC0xOy0xIDEgMCAwIDFdLCBbMCAwIDEgMCAwIDAgMCAwOzEgMCAxIDAgMSAwIDAgMDswIDAgMCAxIC0xIDAgMCAxOzAgMCAxIC0xIDEgMCAwIDA7MCAwIDAgMCAwIDAgMSAwOzAgMCAwIDAgMCAxIDAgMDswIDEgLTEgMSAwIDAgMCAwOzAgMCAxIDAgMCAwIDAgMF0pCiAgICBwcmludGxuKCF4KQplbmQ&input=)
[Answer]
## JavaScript (ES6), ~~112~~ 100 bytes
```
a=>!/(^|,)(?!0*10*(-10*10*)*(,|$))/.test(a.map(b=>b.join``)+','+a.map((_,i)=>a.map(b=>b[i]).join``))
```
Flattens the array and its transpose into strings, then (ignoring `0`s) checks for the pattern `1-11...1-11` in each string.
Edit: Saved 12 bytes thanks to @PeterTaylor.
[Answer]
# Python 2, ~~63~~ 60 bytes
```
s=0;x=input()
for r in x+zip(*x):
for n in(-1,)+r:s+=[n][s]
```
Input is a list of tuples.
This terminates with [exit code](http://meta.codegolf.stackexchange.com/a/5330) **0** for alternating sign matrices and exit code **1** otherwise. This is what [true](http://linux.die.net/man/1/true "true(1): do nothing, successfully - Linux man page") and [false](http://linux.die.net/man/1/false "false(1): do nothing, unsuccessfully - Linux man page") do, and – as shown in the verification section – it can indeed be used as a condition in, e.g., a Bash script.
### Verification
**test-cases.txt**
```
[(1,)]
[(1, 0), (0, 1)]
[(0, 1), (1, 0)]
[(0, 1, 0), (0, 0, 1), (1, 0, 0)]
[(0, 1, 0), (1, -1, 1), (0, 1, 0)]
[(0, 1, 0, 0), (0, 0, 1, 0), (1, 0, 0, 0), (0, 0, 0, 1)]
[(1, 0, 0, 0), (0, 0, 1, 0), (0, 1, -1, 1), (0, 0, 1, 0)]
[(0, 0, 1, 0), (0, 1, -1, 1), (1, -1, 1, 0), (0, 1, 0, 0)]
[(0, 0, 1, 0), (1, 0, -1, 1), (0, 1, 0, 0), (0, 0, 1, 0)]
[(0, 0, 1, 0, 0), (0, 1, -1, 1, 0), (1, -1, 1, 0, 0), (0, 1, 0, -1, 1), (0, 0, 0, 1, 0)]
[(0, 0, 1, 0, 0, 0, 0, 0), (1, 0, -1, 0, 1, 0, 0, 0), (0, 0, 0, 1, -1, 0, 0, 1), (0, 0, 1, -1, 1, 0, 0, 0), (0, 0, 0, 0, 0, 0, 1, 0), (0, 0, 0, 0, 0, 1, 0, 0), (0, 1, -1, 1, 0, 0, 0, 0), (0, 0, 1, 0, 0, 0, 0, 0)]
[(0, 0, 0, 0, 1, 0, 0, 0), (0, 0, 1, 0, -1, 1, 0, 0), (0, 0, 0, 1, 0, 0, 0, 0), (1, 0, 0, -1, 1, -1, 1, 0), (0, 1, -1, 1, -1, 1, 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, 1)]
[(0,)]
[(-1,)]
[(1, 0), (0, 0)]
[(0, 0), (0, 1)]
[(-1, 1), (1, 0)]
[(0, 1), (1, -1)]
[(0, 0, 0), (0, 0, 0), (0, 0, 0)]
[(0, 1, 0), (1, 0, 1), (0, 1, 0)]
[(-1, 1, 1), (1, -1, 1), (1, 1, -1)]
[(0, 0, 1), (1, 0, 0), (0, 1, -1)]
[(0, 1, 0, 0), (0, 0, 0, 1), (1, 0, 0, 0), (0, 0, 1, -1)]
[(0, 0, 1, 0), (0, 0, 1, 0), (1, 0, -1, 1), (0, 1, 0, 0)]
[(0, 0, 0, 1), (1, 0, 0, 0), (-1, 1, 1, 0), (1, 0, 0, 0)]
[(1, 0, 1, 0, -1), (0, 1, 0, 0, 0), (0, 0, 0, 0, 1), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)]
[(0, 0, 1, 0, 0), (0, 1, -1, 1, 0), (1, -1, 1, 0, 0), (0, 1, 1, -1, 0), (0, 0, -1, 1, 1)]
[(0, -1, 0, 1, 1), (1, -1, 1, -1, 1), (0, 1, 1, 0, -1), (1, 1, -1, 1, -1), (-1, 1, 0, 0, 1)]
[(0, 0, 1, 0, 0, 0, 0, 0), (1, 0, 1, 0, 1, 0, 0, 0), (0, 0, 0, 1, -1, 0, 0, 1), (0, 0, 1, -1, 1, 0, 0, 0), (0, 0, 0, 0, 0, 0, 1, 0), (0, 0, 0, 0, 0, 1, 0, 0), (0, 1, -1, 1, 0, 0, 0, 0), (0, 0, 1, 0, 0, 0, 0, 0)]
```
**test-suite.sh**
```
while read; do
if python2 asmv.py <<< "$REPLY"; then
echo "true"
else
echo "false"
fi
done < test-cases.txt 2>&- | uniq -c
```
**Output**
```
$ bash test-suite.sh
12 true
17 false
```
### How it works
Disregarding zeroes, each row and column has to consist of the pattern **(1, -1)\* 1**, i.e., alternating occurrences of **1** and **-1**, starting and ending with a **1** (so the sum is **1**).
To verify this is the case, we zip/transpose the input matrix **M**, append the result to **M** (now consisting of a list of rows and columns), and prepend a **-1** to each row/column.
For example, if **M** is one of the following matrices (valid, invalid)
```
0 1 0 0 0 0
0 0 1 1 0 0
1 0 0 0 1 -1
```
the results are
```
-1 | 0 1 0 -1 | 0 0 0
-1 | 0 0 1 -1 | 1 0 0
-1 | 1 0 0 -1 | 0 1 -1
------------ ------------
-1 | 0 0 1 -1 | 0 1 0
-1 | 1 0 0 -1 | 0 0 1
-1 | 0 1 0 -1 | 0 0 -1
```
Reading the generated matrix row-wise must result in a flat sequence with pattern **(-1, 1)\***. To verify this is the case, we take the cumulative sum of all entries, beginning with the top row.
For the example matrices, this results in
```
-1 -1 0 0 -1 -1 -1 0 -1 0 0 0 -1 -1 -1 0 -1 0 0 0 -1 -1 0 0
-1 -1 -1 -1 -2 -1 -1 -1 -2 -2 -1 -2 -3 -3 -2 -2 -3 -3 -3 -2 -3 -3 -3 -4
```
For a valid alternating sign matrix, the output will consist of **-1**'s and **0**'s and – since every **-1** cancels out the previous **1** and vice versa – no other numbers.
At first glance, this may appear to fail checking if the last column ends with a **1**. However, for an **n × n** matrix containing **k** zeroes, valid rows will contain **n + k** ones. If all columns except the last were valid as well, there would be **n + k - 1** ones in the columns, which is impossible.
To test that there are no other numbers, we store the partial sums in a variable **s** and update them for each entry of with generated matrix with `s+=[n][s]`.
If **s = 0** or **s = -1**, this is equivalent to `s+=n`. However, for all other values of **s**, it causes an *IndexError*, so Python immediately terminates with exit code **1**. If this doesn't happen at any point, the program finishes cleanly with exit code **0**.
[Answer]
# R, 54 bytes
Anonymous function, uses the same logic as Dennis's Python 2, Jelly, and Julia answers.
```
function(x)all(abs(cumsum(rbind(-1,cbind(t(x),x))))<2)
```
] |
[Question]
[
Write a program or function that takes no input but prints or returns a constant textual depiction of a rectangle made of the 12 distinct [pentominoes](https://en.wikipedia.org/wiki/Pentomino):
[](https://i.stack.imgur.com/BRVgy.png)
The rectangle may have any dimensions and be in any orientation, but all 12 pentominoes must be used exactly once, so it will have area 60. Each different pentomino must be composed of a different [printable ASCII](https://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) character (you don't need to use the letters from above).
For example, if you chose to output this 20×3 pentomino rectangle solution:
[](https://i.stack.imgur.com/Ga6tF.png)
Your program's output might look something like this:
```
00.@@@ccccF111//=---
0...@@c))FFF1//8===-
00.ttttt)))F1/8888=-
```
Alternatively, you might find it easier to golf this 6×10 solution:
```
000111
203331
203431
22 444
2 46
57 666
57769!
58779!
58899!
5889!!
```
Any rectangle solution will do, your program only needs to print one. (A trailing newline in the output is fine.)
[This great website](http://puzzler.sourceforge.net/docs/pentominoes.html) has loads of solutions for various rectangle dimensions and it's probably worth browsing them to make sure your solution is as short as possible. This is code-golf, the shortest answer in bytes wins.
[Answer]
## CJam (44 bytes)
Given in xxd format because it contains control characters (including a raw tab, which plays *really* badly with MarkDown):
```
0000000: 2202 7e0d 8ef3 570d e085 e168 cf27 092c
0000010: a235 0c22 3235 3662 3562 332f 5f2c 2c2e
0000020: 7b32 2f27 412b 662b 7d7a 4e2a
```
which decodes to something along the lines of
```
"MAGIC STRING"256b5b3/_,,.{2/'A+f+}zN*
```
[Slightly ungolfed online demo](http://cjam.aditsu.net/#code=217118172301180534104344993852647398323468%0A5b3%2F_%2C%2C.%7B2%2F'A%2Bf%2B%7DzN*) which doesn't contain control characters and so plays nicely with browser URI decoding library functions.
The basic principle is that since no piece spans more than 5 rows we can encode an offset from a linear function of the row number compactly (in base 5, in fact, although I haven't tried to determine whether this would always be the case).
[Answer]
# Bash + common Linux utils, 50
```
xxd -s20 -p -c2 $0
#<30 bytes of binary data>
```
To recreate this from encoded base64:
```
base64 -d <<< eHhkIC1zMjAgLXAgLWMyICQwCiMiImaSaZlmkDAAMwSjRKNEqoGogYhRVVF7UXu7d3s= > pent.sh
```
Since there are 12 pentominoes, their colours are easily encoded in hex nybbles.
### Output:
```
$ ./pent.sh
2222
6692
6999
6690
3000
3304
a344
a344
aa81
a881
8851
5551
7b51
7bbb
777b
$
```
[Answer]
# J, 49 bytes
```
u:64++/\|:3#.inv 1377859090 1567813024 1337683230
```
You can choose the letters in a way that the maximal increments between vertically adjacent letters are 2. We use this fact to encode vertical increments in base3. After that we create the running sums and add an offset to get the ASCII codes of the letters.
Definitely golfable. (I yet to find a way to input extended precision base36 numbers but simple base36 should save 3 bytes alone.)
Output:
```
AAA
ABA
BBB
DBC
DCC
DCC
DEE
DFE
FFE
FGE
FGG
GGH
HHH
IIH
JII
JJI
JKK
JKL
KKL
LLL
```
[Try it online here.](http://tryj.tk/)
[Answer]
# [Microscript II](http://esolangs.org/wiki/Microscript_II), 66 bytes
Lets start with the simple answer.
```
"00.@@@ccccF111//=---\n0...@@c))FFF1//8===-\n00.ttttt)))F1/8888=-"
```
Hooray implicit printing.
[Answer]
# Pyth, 37 bytes
```
jc4.HC"&f3ªªwril3:[·)ÌDU[r)ÌDA»
```
[Demonstration](https://pyth.herokuapp.com/?code=jc4.HC%22%26f3%C2%AA%C2%AA%C2%85wril3%3A%C2%88%5B%C2%B7%29%C2%99%C3%8CD%C2%88U%5Br%29%C3%8CDA%11%11%C2%BB&debug=0)
Uses a very straightforward approach: Use hex bytes as numbers. Convert to a hex number, base 256 encode that. That gives the magic string above. To decode, use Pyth's base 256 decoder function, convert to hex, split into 4 chunks, and join on newlines.
[Answer]
# Ruby
# Rev 3, 55bytes
```
i=1
'S, OJ1*$HCH(#%0'.bytes{|e|puts "%x"%i+=e*130&9011}
```
As a further development on Randomra's idea, consider the output and difference table below. The difference table can be compressed as before, and expanded by multiplying by 65=binary 1000001 and applying a mask 11001100110011. However, Ruby does not work predictably with 8 bit characters (it tends to interpret them as Unicode.)
Surprisingly, the last column is entirely even. Because of this, in compression we can perform a rightshift on the data. This ensures all codes are 7 bit ASCII. In expansion we simply multiply by 65\*2=130 instead of 65.
The first column is also entirely even. Therefore we can add 1 to each element (32 to each byte) where necessary, to avoid any control characters. The unwanted 1 is removed by using the mask 10001100110011=9011 instead 11001100110011.
```
Solution 59 of document linked in question
Start0001
Out Diff
2223 2222
2433 0210
2433 0000
4445 2012
6555 2110
6577 0022
6687 0110
6887 0200
8897 2010
aa99 2202
caa9 2010
cab9 0010
cbbb 0102
cdbd 0202
cddd 0020
```
Although I use 15 bytes for the table, I only really use 6 bits of each byte, which is a total of 90 bits. There are in fact only 36 possible values for each byte, which is 2.21E23 possibities in total. That would fit in 77 bits of entropy.
# Rev 2, 58 bytes, using Randomra's incremental approach
```
i=0
'UPEIP@bPHPBETTEPRADT'.bytes{|e|puts "%x"%i+=e*65&819}
```
Finally, something shorter than the naive solution. Randomra's incremental approach, with the bytepacking method of Rev 1.
# Rev 1, 72 bytes, golfed version of rev 0
Some changes were made to the baseline to accomodate a reordering of the code for golfing reasons, but still came in longer than the naive solution.
```
i=0
'UPUIYD&!)$&V*).);c+*'.bytes{|e|i+=1;puts "%x"%(i/2*273+(e*65&819))}
```
The offsets are encoded into each character of the magic string in base 4 in format `BAC`, ie with the 1's representing the righthand symbol, the 16's representing the middle symbol, and the lefthand symbol shoehorned into the 4's position. In order to extract them, the ascii code is multiplied by 65 (binary 1000001) to give `BACBAC`, then it is anded with 819 (binary 1100110011) to give `.A.B.C`.
Some of the ascii codes have the 7th bit set, i.e. they are 64 higher than the required value, to avoid control characters. Because this bit is removed by the mask 819, this is inconsequential, except when the value of `C` is 3, which causes a carryover. This has to be corrected in one place only (instead of `g` we have to use `c`.)
# Rev 0, ungolfed version
```
a= %w{000 010 000 201 100 100 011 021 110 120 011 112 111 221 211 221 122 123 112 222}
i=2
a.each{|e|puts "%x"%(i/2*273+e.to_i(16));i+=1}
```
**Output**
```
111
121
222
423
433
433
455
465
665
675
677
778
888
998
a99
aa9
abb
abc
bbc
ccc
```
**Explanation**
From the following solution, I subtract the baseline, giving the offset which I store as data. The baseline is regenerated as a hexadecimal number in the code by `i/2*273` (273 decimal = 111 hex.)
```
solution baseline offset
AAA AAA 000
ABA AAA 010
BBB BBB 000
DBC BBB 201
DCC CCC 100
DCC CCC 100
DEE DDD 011
DFE DDD 021
FFE EEE 110
FGE EEE 120
FGG FFF 011
GGH FFF 112
HHH GGG 111
IIH GGG 221
JII HHH 211
JJI HHH 221
JKK III 122
JKL III 123
KKL JJJ 112
LLL JJJ 222
```
[Answer]
# Foo, 66 Bytes
```
"00.@@@ccccF111//=---\n0...@@c))FFF1//8===-\n00.ttttt)))F1/8888=-"
```
] |
[Question]
[
### Background
Last time, we [counted groups of a given size](https://codegolf.stackexchange.com/q/58408), which is a non-trivial problem.
This time, we'll only count *[Abelian groups](https://en.wikipedia.org/wiki/Abelian_group)*, i.e., groups with a commutative operation. Formally, a group **(G, ∗)** is Abelian if **x ∗ y = y ∗ x** for for all **x, y** in **G**.
The problem becomes much simpler this way, so we're going to count them efficiently.
### Task
Write a program or function that accepts a non-negative integer **n** as input and prints or returns the number of non-isomorphic Abelian groups of order **n**.
One way of calculating the number of groups – which we'll denote by **A(n)** – is by observing the following:
* **A(0) = 0**
* If **p** is a prime, **A(pk)** is equal to the number of integer partitions of **k**. (cfr. [OEIS A000041](https://oeis.org/A000041))
* If **n = mk**, and **m** and **k** are co-prime, **A(n) = A(m)A(k)**.
You may use this or any other method of calculating **A(n)**.
### Test cases
```
Input Output
0 0
1 1
2 1
3 1
4 2
5 1
6 1
7 1
8 3
9 2
10 1
11 1
12 2
13 1
14 1
15 1
16 5
17 1
18 2
19 1
20 2
4611686018427387904 1300156
5587736968198167552 155232
9223371994482243049 2
```
(taken from [OEIS A000688](https://oeis.org/A000688))
### Additional rules
* Given enough time, RAM and a register size that can hold the input, your code should work (in theory) for arbitrarily large integers.
* Your code must work for all integers between **0** and **263 - 1** and finish in under 10 minutes on my machine (Intel i7-3770, 16 GiB RAM, Fedora 21).
*Please make sure you time your code for the last three test cases before submitting your answer.*
* Built-ins that trivialize this task, such as Mathematica's [`FiniteAbelianGroupCount`](http://mathworld.wolfram.com/FiniteAbelianGroupCount.html), are not allowed.
* Built-ins that return or count the integer partitions of a number or the partitions of a list are not allowed.
* Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
[Answer]
# CJam, ~~50~~ ~~49~~ ~~47~~ 43 bytes
```
ri_mF{1=_L{1$0>{,f{):X-Xj}:+}{;!}?}2j}%:*e&
```
Uses CJam's builtin `mF` factorisation and a memoised port of this Python partition number function:
```
p=lambda n,x:n==0 or n>0and sum(p(n+~a,a+1)for a in range(x))
```
or ungolfed:
```
def p(n, x): # Call like p(n, n). n is number remaining, x is max part size
if n > 0:
return sum(p(n-a-1,a+1)for a in range(x))
else:
return (n==0)
```
Like @RetoKoradi's answer, the last case takes about 17 seconds on the offline interpreter because that's how long it takes CJam to factorise the number. Hence I've left it out of this [online test suite](http://cjam.aditsu.net/#code=21%2C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20This%20is%20%5B0%20...%2020%5D%20%0A%5B1024%204611686018427387904%205587736968198167552%5D%2B%20%20e%23%20Add%20some%20special%20cases%0A%0A%7B_oSo%0A%0Ai_mF%7B1%3D_L%7B1%240%3E%7B%2Cf%7B%29%3AX-Xj%7D%3A%2B%7D%7B%3B!%7D%3F%7D2j%7D%25%3A*e%26%0A%0Ap%7D%2F).
### Full explanation
```
[Main body]
ri Read input and convert to int
_ e& Logical AND input with final result to special case 0
mF Factorise input into [base, exponent] pairs
{...}% Map, converting each pair to a partition number
:* Take product
[Pair -> partition]
1=_ Get exponent and copy (n,x in above Python)
L Initialise empty cache
{ }2j Memoise with 2 arguments
1$0> Check if n > 0
{ }{ }? Execute first block if yes, else second block
;! Return (n == 0)
,f{ } For each a in range(x) ...
):X-Xj Call p(n-a-1,a+1) recursively
:+ Sum the results
```
[Answer]
## CJam (39 38 bytes)
```
qimF{~M\{_ee{~\)<1b}%1+a\+}*0=1be&}%:*
```
[Online demo](http://cjam.aditsu.net/#code=qimF%7B~M%5C%7B_ee%7B~%5C)%3C1b%7D%251%2Ba%5C%2B%7D*0%3D1be%26%7D%25%3A*&input=4611686018427387904)
This follows the suggested line of finding a prime factorisation (`mF`) and then calculating the partitions of each power and taking their product.
There are two special cases for `mF`: it factors `0` as `0^1` and `1` as `1^1`. The latter doesn't require special treatment: there is one Abelian group of size 1, and one partition of 1. However, zero does require a special case.
The partition counting uses a recurrence for `A008284(n, k)`, the number of partitions of `n` into `k` parts. In OEIS it is [given as](http://oeis.org/A008284)
```
T(n, k) = Sum_{i=1..k} T(n-k, i), for 1<=k<=n-1; T(n, n) = 1 for n >= 1.
```
but I think it's more useful to think of the sum as ranging from `1` to `min(k, n-k)`.
### Dissection
```
q~ e# Parse input into an integer
mF e# Factorise it
{ e# For each factor p^a
~ e# Split the array [p a]
e# The following lines count partitions of a
e# (Note: they would be buggy if a were ever 0, but it isn't)
M\{ e# Starting with a table of zero rows, repeat a times
_ee e# Copy table and pair each row with its index
{~\)<1b}% e# Extract that prepended index and use it to sum for each j
e# the first jth items of row j
1+ e# Append a 1 for P(i, i)
a\+ e# Prepend the new row to the table (which is stored in reverse)
}*
0=1b e# Sum the elements in the latest (first) row
e& e# If p was 0 then replace with 0
}%
:* e# Take the product
```
[Answer]
# CJam, 58 bytes
```
li_mF{1=_L{_1>{_2$<{\;_j}{\,f{)_@\-j}:+}?}{;;1}?}2j}%:*\g*
```
[Try it online](http://cjam.aditsu.net/#code=li_mF%7B1%3D_L%7B_1%3E%7B_2%24%3C%7B%5C%3B_j%7D%7B%5C%2Cf%7B)_%40%5C-j%7D%3A%2B%7D%3F%7D%7B%3B%3B1%7D%3F%7D2j%7D%25%3A*%5Cg*&input=5587736968198167552)
The very last test example takes forever (or at least longer than I was willing to wait) in the online interpreter, but finishes in 17 seconds with the offline version of CJam on my laptop. All other test examples are pretty much instantaneous.
This uses the CJam `mF` operator, which gives the prime factorization with exponents. The result is then the product of the partition counts for each exponent.
The main part of the code is calculating the partition counts. I implemented the recursive algorithm on the [wikipedia page](https://en.wikipedia.org/wiki/Partition_(number_theory)#Algorithm), using the `j` operator that supports recursion with memoization.
Explanation:
```
li Get input and convert to int.
_ Make a copy to handle 0 special case at the end.
mF Factorization with exponents.
{ Loop over factors.
1= Take exponent from [factor exponent] pair.
_ Repeat it, recursive calls are initiated with p(n, n).
L Empty list as start point of memoization state.
{ Start recursive block. Argument order is (m, n), opposite of Wikipedia.
_1> Check for n > 1.
{ Start n > 1 case.
_2$ Copy both m and n.
< Check for n < m.
{ n < m case.
\; Pop m.
_ Copy n.
j Make the p(n, n) recursive call.
} End n < m case.
{ Main part of algorithm that makes recursive calls in loop.
\, Generate [0 1 ... m-1] range for k.
f{ Start loop over k.
) Increment, since k goes from 1 to m.
_ Copy k.
@\ Rotate n to top, and swap. Now have k n k at top of stack.
- Subtract, now have k n-k at top of stack.
j Make the p(n-k, k) recursive call.
} End loop over k.
:+ Sum up all the values.
}? Ternaray operator for n < m condition.
} End n > 1 case.
{ n <= 1 case.
;;1 Pop m, n values, and produce 1 as result.
}? Ternary operator for n > 1 condition.
}2j Recursive call with memoization, using 2 values.
}% End loop over factors.
:* Multiply all values.
\ Swap original input to top.
g Signum.
* Multiply to get 0 output for 0 input.
```
[Answer]
# Mathematica, ~~96~~ ~~94~~ 88 bytes
```
f=1##&@@#&;f[SeriesCoefficient[1/f[1-x^Range@#],{x,0,#}]&/@Last/@FactorInteger@#]Sign@#&
```
I'm not that proficient with Mathematica, but I thought I'd give it a try. Thanks to @MartinBüttner for -6 bytes.
This uses the generating function formula for integer partitions.
] |
[Question]
[
Alice and Bob like to play a card game, with a deck of cards numbered with consecutive nonnegative integers.
Alice has a very particular way of shuffling the deck, though. First, she takes the top card from the deck and puts it at the bottom of the deck. Then she removes the next card, and starts a pile with it. Then, again she cycles the top card to the bottom, and puts the new top card onto the pile. She repeats this process until she's emptied the deck, at which point the pile is the new deck.
```
deck | pile
-----------+-----------
3 1 4 0 2 |
1 4 0 2 3 |
4 0 2 3 | 1
0 2 3 4 | 1
2 3 4 | 0 1
3 4 2 | 0 1
4 2 | 3 0 1
2 4 | 3 0 1
4 | 2 3 0 1
| 4 2 3 0 1
4 2 3 0 1 |
```
Figure 1: Alice performs her shuffle on the 5-card deck "3, 1, 4, 0, 2". The backs of the cards are all facing left.
One day, Bob announces he's taking a week's vacation. Alice, having nobody to play the game with, enlists her friend Eve. Now, Eve is a shameless cheater, so when she sees Alice's peculiar shuffle, she realizes that she can stack the deck beforehand to her advantage!
When Eve gets home after the first day, she does some analysis on the game and figures out that her best odds are when the cards are in the order 0, 1, 2, 3, 4, 5, ... She didn't catch how many cards were in the deck, though, so she hatches a harebrained scheme to write some code on her arm that, when run, takes the size of the deck and displays the order Eve needs to put the cards in, so that when Alice shuffles the deck, the final deck is in the order 0, 1, 2, 3, ...
It doesn't really matter to Eve what language the code is in (she knows them all), or whether the code is a function taking an integer argument and returning an array, or a full program taking input via a command line argument or STDIN and writing the results to STDOUT. She does, however, need the code as short as possible, to minimize the chance of Alice seeing it and catching her.
Immoral as it might be, can you guys help Eve out?
Example inputs and outputs:
```
in out
1 0
2 0 1
5 2 4 0 3 1
10 2 9 4 8 0 7 3 6 1 5
52 6 51 25 50 12 49 24 48 1 47 23 46 11 45 22 44 5 43 21 42 10 41 20 40 2 39 19
38 9 37 18 36 4 35 17 34 8 33 16 32 0 31 15 30 7 29 14 28 3 27 13 26
```
[Answer]
# GolfScript, ~~15~~ ~~14~~ 13 bytes
```
])~,{\+)\+}/`
```
[Try it online.](http://golfscript.apphb.com/?c=OyIxMCIgIyBTaW11bGF0ZSBpbnB1dCBmcm9tIFNURElOLgoKXSl%2BLHtcKylcK30vYA%3D%3D "Web GolfScript")
# Example
```
$ golfscript alice.gs <<< 10
[2 9 4 8 0 7 3 6 1 5]
```
### How it works
```
]) # Collect the stack into an array and pop. This leaves [] below the input string.
~ # Interpret the input string.
, # For input “N”, push the array [ 0 … N-1 ] (the pile).
{ # For each card on the pile:
\+ # Put the card on top of the deck.
) # Remove a card from the bottom of the deck.
\+ # Put the card on top of the deck.
}/ #
` # Convert the deck into a string.
```
[Answer]
# Julia, 83
```
u(n)=(a=[n-1:-1:0];l=Int[];[push!(l,shift!(push!(l,pop!(a)))) for i=1:length(a)];l)
```
The last element in the returned vector is the top of the deck.
[Answer]
## Mathematica, ~~92~~ ~~77~~ 46 bytes
Expects the input in variable `n`:
```
l={};(l=RotateRight[{#-1}~Join~l])&/@Range@n;l
```
It's just literally playing the shuffle backwards, by moving over a card and then putting the bottom card on top.
**EDIT:** No need to keep track of the output stack, just iterate through the integers.
[Answer]
# Python 2.7 - 57
```
d=[0]
for j in range(1,input()):d=[d.pop()]+[j]+d
print d
```
Nice and simple, just invert the shuffle. Fairly close to how Golfscript does it.
[Answer]
# J (13 chars) and K (9)
As it turns out, it's a simple process to undo the shuffle, and APL-likes have the fold adverb `/` to help them out in making this as short as possible.
J takes 13 char with `(_1|.,)/@i.@-`, while K only needs 9: `|(1!,)/!:`. APL would be similarly terse.
Here's a step-by-step trace of the J version.
```
(_1|.,)/@i.@- 4 NB. recall that J is right-associative
(_1|.,)/@i. - 4 NB. u@v y is u v y
(_1|.,)/@i. _4 NB. monad - is Negate
(_1|.,)/ i. _4 NB. @
(_1|.,)/ 3 2 1 0 NB. monad i. is Integers, negative arg reverses result
3 (_1|.,) 2 (_1|.,) 1 (_1|.,) 0 NB. u/ A,B,C is A u B u C
3 (_1|.,) 2 (_1|.,) _1 |. 1 , 0 NB. x (M f g) y is M f x g y
3 (_1|.,) 2 (_1|.,) _1 |. 1 0 NB. dyad , is Append
3 (_1|.,) 2 (_1|.,) 0 1 NB. dyad |. is Rotate
3 (_1|.,) _1 |. 2 , 0 1 NB. repeat ad nauseam
3 (_1|.,) _1 |. 2 0 1
3 (_1|.,) 1 2 0
_1 |. 3 , 1 2 0
_1 |. 3 1 2 0
0 3 1 2
```
You might notice that in the J, we reverse the array of integers first, but in the K we do it afterwards: this is because the K fold is more like a `foldl`, compared to the J's `foldr`.
] |
[Question]
[
Out of all of mathematics, there will always be a few theorems that go beyond all common sense. One of these is the fact that there are different sizes of infinity. Another interesting fact is the idea that many infinities which seem to be of different size are actually of the same size. There are just as many even numbers as integers, as there are rational numbers.
The general concept of this question is to confront the bizarre reality of infinity. In this challenge, your program will output a list which will:
* At any specific moment of time, always have a whole number of entries
* Eventually contain (if left to run long enough) any specific (non-zero) rational number precisely once on the entire list
* Contain an unbounded number of empty slots (entries on the list that are needlessly set to 0)
* Have a proportion of empty slots that approaches a limit of 100%
* For every positive integer N, have an infinite number of places with N consecutive empty slots
## The Challenge
Your challenge is to write that shortest possible program that will output a special list with the following rules:
1. All entries with an index that is not a square number should be set to zero. So, the first entry will be nonzero, the second and third will be zero, the fourth will nonzero, etc.
2. All rational numbers will be in the form of an improper fraction (such as 4/5 or 144/13) that has been simplified. The exception is zeroes, which will be simply `0`.
3. All (positive and negative) rational numbers should eventually appear on the list if your program runs for long enough and with enough memory. For any particular rational number, the time required may be an arbitrarily large, but always finite, amount of time.
4. If run for an infinite amount of time, no non-zero rational number should ever appear twice.
Rule 3 does allow for some variation, as in there is an infinite number of different possible legal outputs.
Output will be a stream of lines. Each line will be of the general form of `5: 2/3` where the first number is the entry number, then followed by the rational number. Note that `1: 0` will always be the first line of output.
## Example snippet of output:
```
1: 1/1
2: 0
3: 0
4: 2/1
5: 0
6: 0
7: 0
8: 0
9: -2/1
10: 0
etc...
```
## Rules, Regulations, and Notes
This is code golf. Standard code golf rules apply. Also, due to the variation allowed in the output, you need to at least show why you believe that your list will contain all possible rational numbers exactly once, and that your solution is correct.
*EDIT: Since the primes numbers did distract from the challenge, I am changing it to square numbers. This accomplishes the same purpose, and also shortens the solutions.*
[Answer]
## Haskell, 184 characters
```
main=putStr.unlines$zip[1..](s>>=g)>>=h
s=(1,1):(s>>=f)
f(a,b)=[(a,a+b),(a+b,b)]
g x@(a,b)=[x,(-a,b)]
h(i,(a,b))=(i^2)%(u a++'/':u b):map(%"0")[i^2+1..i*(i+2)]
i%s=u i++": "++s
u=show
```
This does a breadth-first traversal of the [Calkin-Wilf Tree](http://en.wikipedia.org/wiki/Calkin%E2%80%93Wilf_tree), yielding all positive rational numbers in reduced form exactly once. It then alternates between positive and negative to cover all the non-zero rational numbers and pads with zeroes between the square entries.
**Output (excluding zero lines for brevity):**
```
1: 1/1
4: -1/1
9: 1/2
16: -1/2
25: 2/1
36: -2/1
49: 1/3
64: -1/3
81: 3/2
100: -3/2
...
```
[Answer]
## Sage, 103 113 128
Sage can list the rationals with ease! Formatting to fit the program requirements, as always, ruins everything.
```
for i,q in enumerate(QQ):
for j in[(i-1)^2+1..i*i]:print'%d:'%j,[0,'%d/%d'%(q.numer(),q.denom())][j==i*i]
```
Sage enumerates `QQ` according to their *height*: the max absolute value of the numerator & denominator after GCD reduction.
[Answer]
## Python, 162
```
f=lambda n:f(n/2)if n%2 else f(n/2)+f(n/2-1)if n else 1
n=i=1
while 1:
print'%d:'%i,
if i-n*n:s=0
else: n+=1;s='%d/%d'%((-1)**n*f(n/2-1),f(n/2))
print s
i+=1
```
This uses the recursion given in [Recounting the Rationals](http://www.math.clemson.edu/~calkin/Papers/calkin_wilf_recounting_rationals.pdf) by Calkin & Wilf.
[Answer]
# Haskell, 55 bytes
```
mapM_ print$join$iterate(>>=(\x->[x+1,1/(1+1/x)]))[1%1]
```
outputs
```
1 % 1
2 % 1
1 % 2
3 % 1
2 % 3
3 % 2
1 % 3
4 % 1
...
```
1%1 is the root of the Calkin-Wilf tree;
the iterate adds both children of each node;
the join collapses the levels into a single list.
120 chars if you add proper imports, 0, and negatives:
```
import Data.Ratio
import Control.Monad
main=mapM_ print$0:(join(iterate(>>=(\x->[x+1,1/(1+1/x)]))[1%1])>>=(\x->[-x,x]))
```
outputs
```
0 % 1
(-1) % 1
1 % 1
(-2) % 1
2 % 1
(-1) % 2
1 % 2
(-3) % 1
3 % 1
(-2) % 3
2 % 3
(-3) % 2
3 % 2
(-1) % 3
1 % 3
(-4) % 1
4 % 1
...
```
outputting empty slots? that's in poor taste:(
you had me at "list of all positive rationals"
[Answer]
## PHP 105 bytes
*Note: This code must be saved as iso-8859-1 (ansi) in order to run correctly. Online interpretters which encode all input to utf8 by default (such as ideone) will generate the wrong output.*
```
<?for($f=µ;$i++<$j*$j||++$j%2||(--$$f?$$f--:$f^=C);)echo"$i: ",$i==$j*$j?$j%2?$x=++$ö.~Ð.++$µ:"-$x":0,~õ;
```
Using [Georg Cantor's](http://www.engr.iupui.edu/~orr/webpages/cpt120/mathbios/gcant.htm) enumeration (slightly modified for +/- values).
If you're having problems getting the above code to run (likely due to an excessive amount of NOTICE messages), use this instead (107 bytes):
```
<?for($f=µ;$i++<$j*$j||++$j%2||(--$$f?$$f--:$f^=C);)echo"$i: ",$i==$j*$j?$j%2?$x=++$ö.'/'.++$µ:"-$x":0,'
';
```
[Answer]
# Octave, 168 bytes
```
a=b=p=1;do for i=(p-1)^2+1:p^2-1 printf("%d: 0\n",i)end
printf("%d: %d/%d\n",p^2,a,b)
a=-a;if a>0do if b==1 b=a+1;a=1;else a++;b--;end until 1==gcd(a,b)end
p++;until 0
```
The solution is not very sophisticated, it is just a simple diagonal traversal of the "carpet" of rational numbers, discarding all fractions that can be simplified. After a positive number `a/b`, it's opposite `-a/b` is always printed before the next one from sequence goes.

Since all positive simple fractions will be printed and the opposite signed fractions to those will be printed, and it's never possible to two different simple fractions to have the same value, each non-zero rational number will be printed exactly once.
Degolfed:
```
a=b=p=1
do
for i=(p-1)^2+1:p^2-1
printf("%d: 0\n",i) # p=2,3,4: 1..3,5..8,10..15
end
printf("%d: %d/%d\n", p^2,a,b); # p=2,3,4: 4,9,16
a=-a;
if a>0 # the rule is: after a/b, a>0 output -a/b
do
if b==1 b=a+1;a=1; else a++;b--; end
until 1==gcd(a,b)
end
p++;
until 0
```
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/474/edit).
Closed 2 years ago.
[Improve this question](/posts/474/edit)
Write a program that determines whether its input is valid [JSON](http://json.org).
* **Input:** ASCII text: `[\x00-\x7F]*`
*Note: if ASCII is problematic, feel free to use another encoding, but indicate it in your post.*
* **Output:** `Valid` or `Invalid`. Trailing newline may be omitted.
* **Example:**
```
$ echo '{"key": "value"}' | ./json-validate
Valid
$ echo '{key: "value"}' | ./json-validate
Invalid
```
* **Rules:**
+ Do not use a JSON parsing library.
+ Partially-correct solutions are allowed, but frowned upon.
+ Post your test suite score (see below).
The **shortest correct** solution wins.
Please run [json-validate-test-suite.sh](https://raw.github.com/gist/3796234/json-validate-test-suite.sh) on your program, and post your score. Example:
```
$ ./json-validate-test-suite.sh ./buggy-prog
fail: should be invalid: [ 0.1e ]
fail: should be invalid: [ 0.1e+-1 ]
fail: should be invalid: [ 0.1e-+1 ]
score: 297/300
```
**Resources:**
* [json.org](http://json.org/) - Concise definition of the JSON grammar with easy-to-follow pictures.
* [RFC 4627](https://www.rfc-editor.org/rfc/rfc4627) - JSON specification
* [json-validate.c](https://raw.github.com/gist/3796234/json-validate.c) - A 200-line implementation that passes the testsuite.
---
The JSON grammar is as follows:
```
json: object | array
object: '{' members? '}'
members: pair (',' pair)*
pair: string ':' value
array: '[' elements? ']'
elements: value (',' value)*
value: string
| number
| object
| array
| 'true'
| 'false'
| 'null'
string: '"' char* '"'
char: [^"\\\x00-\x1F]
| '\' escape
escape: ["\\/bfnrt]
| u [0-9A-Fa-f]{4}
number: '-'? (0 | [1-9][0-9]*) ('.' [0-9]+)? ([Ee] [+-]? [0-9]+)?
```
Also, whitespace can appear before or after any of the six structural characters `{}[]:,`
```
ws = [\t\n\r ]*
```
Bear in mind the following:
* Be careful with functions like `isspace()`. Whitespace in JSON is `[\t\n\r ]`, but `isspace()` also treats `\v` (vertical tab) and `\f` (form feed) as space. Although word has it that `isdigit()` can [accept more than just `[0-9]`](https://stackoverflow.com/questions/2898228/can-isdigit-legitimately-be-locale-dependent-in-c), should be okay to use here, as we assume input is in ASCII.
* `\x7F` is technically a control character, but the JSON RFC doesn't mention it (it only mentions `[\x00-\x1F]`), and most JSON parsers tend to accept `\x7F` characters in strings. Because of this ambiguity, solutions may choose to either accept them or not.
[Answer]
# PHP : ~~297~~ ~~285~~ ~~264~~ 253 characters
```
<?=preg_match(<<<'R'
~([\h
]*)({(?1)((("([^"\\\0- ]| |\\(["\\/bfnrt]|u[\dA-Fa-f]{4}))*")(?1):(?1)((?5)|-?(0|[1-9]\d*)(\.\d+)?([Ee][+-]?\d+)?|(?2)|true|false|null))(((?1),(?1))(?4))*)?}|\[(?1)((?8)((?13)(?8))*)?(?1)])(?1)\z~A
R
,`cat`)?'Valid':'Invalid';
```
**score: 300/300**
This is a full, recursive implementation of the JSON grammar.
It works only on PHP ≥ 5.3 due to [nowdoc](http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc) syntax (heredoc would have required to double all `\`).
Readable version:
(this is the same regex, with named capture groups and extended syntax):
```
#!/usr/bin/env php
<?php
$re = <<< 'RE'
~\A (?P<ws>[\t\n\r ])* (
(?P<object>\{ (?P>ws)*
(?P<members>
(?P<pair>
(?P<string>
"(?P<char>
[^"\\\x00-\x1F]
|\\(?P<escape>
["\\/bfnrt]
|u [0-9A-Fa-f]{4}
)
)*"
) (?P>ws)* : (?P>ws)* (?P<value>
(?P>string)
| (?P<number>-? (0 | [1-9][0-9]*) (\. [0-9]+)? ([Ee] [+-]? [0-9]+)? )
| (?P>object)
| (?P>array)
| true
| false
| null
)
) ( (?P>ws)* , (?P>ws)* (?P>pair) )*
)?
\})
|(?P<array>\[ (?P>ws)*
(?P<elements>
(?P>value) ( (?P>ws)* , (?P>ws)* (?P>value) )*
)?
(?P>ws)* \])
) (?P>ws)* \z~x
RE;
if (preg_match($re, stream_get_contents(STDIN))) {
echo 'Valid';
} else {
echo 'Invalid';
}
```
[Answer]
## Python - ~~340~~ ~~314~~ ~~299~~ 292 chars
```
import re,os
r=x=re.sub
z=r('0\.0+','0',r('e[+-]?0+|[\t\n\r]',' ',r(r'"(\\["nrtb\\/]|[^\\"\0-\37])*"','1',r(r'true|false|null|\\u\w{4}|[1-9]\d*','0',os.read(0,99)))))
while z!=x:z,x=r('\{(1:\d)?(,\\1)*\}|\[(-?\d(,-?\d)*)?\]','0',r(' *([][{}:,]) *','\\1',z)),z
print['Inv','V'][z=='0']+'alid'
```
score
```
$ ./json-validate-test-suite.sh ./codegolf-474.py
score: 300/300
```
[Answer]
## Scala - 390 chars
```
import scala.util.parsing.combinator.JavaTokenParsers
object J extends JavaTokenParsers{def j=o|a
def o:Parser[Any]="{"~repsep(p,",")~"}"
def p=s~":"~v
def a:Parser[Any]="["~repsep(v,",")~"]"
def v=s|o|a|"true"|"false"|"null"
def s=stringLiteral
def n=floatingPointNumber}
object Main{def main(a:Array[String]){print(if(J.parseAll(J.j,readLine()).successful)"Valid"else"Invalid")}}
```
This is no-brainer soluton, using parser combinators. Written in 1 or 2 minutes, literally. Cannot get validator script, browser said that server not found.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [jq](https://stedolan.github.io/jq/), 29 bytes
```
jq -r '"Valid"'||echo Invalid
```
[Try it online!](https://tio.run/##S0oszvifmpyRr6BerVSWmFOaqmSloJSdWqlUq17zP6tQQbdIQV0pLDEnM0VJvaYGrNIzrwzE//8fAA "Bash – Try It Online")
TIO's bash instance conveniently has jq installed for us so try it online at your leisure!
] |
[Question]
[
Given a constructible point \$(x, y) \in \mathbb R^2\$, output the steps required to construct \$(x, y)\$
### Constructing a point
Consider the following "construction" of a point \$(\alpha, \beta)\$ in the Cartesian plane:
Begin with the points \$(0, 0)\$ and \$(1, 0)\$. Then, more points can be added by performing a finite number of the following steps:
* Draw the unique infinitely long line between two existing points \$(x, y)\$ and \$(x', y')\$
* Draw the unique circle centered on an existing point \$(x, y)\$ that passes through a distinct existing point \$(x', y')\$
* Add a point \$(x, y)\$ where any two lines or circles intersect
For example, if we draw the line connecting \$(0, 0)\$ and \$(1, 0)\$, then the circle centered on \$(1, 0)\$ with radius \$1\$ (passes through \$(0, 0)\$), we can construct the point \$(2, 0)\$ where the circle and line intersect. Now, if we draw the circles centered on \$(0, 0)\$ and \$(2, 0)\$ that pass through \$(2, 0)\$ and \$(0, 0)\$ respectively, we construct the point \$(1, \sqrt 3)\$, and so on.
If both \$x\$ and \$y\$ are [constructible numbers](https://en.wikipedia.org/wiki/Constructible_number) (i.e. there exists some closed form expression of \$x\$ and \$y\$ involving only integers, the 4 basic arithmetic operations and square roots), then \$(x, y)\$ can be constructed in a finite number of these steps.
---
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, where you are provided, in exact form, two constructible numbers, \$x\$ and \$y\$, and should output the steps to construct the point \$(x, y)\$, beginning from the initial set of points \$S = \{(0, 0), (1, 0)\}\$.
As both \$x\$ and \$y\$ are constructible, they can be expressed as a finite combination of addition, multiplication, division, subtraction and square roots of integers - termed here as "closed form numbers". You may take input in any form that exactly represents any closed form number. This could be as an exact symbolic number (if your language has these), a string unambiguously representing the composition of the 5 operations (e.g. `7*sqrt(2)-sqrt(3)`, `7*s2-s3` or even `sub(times(7, sqrt(2)), sqrt(3)))`, and so on. **You may not input as floating point values.** Note that the format you choose should be unambiguous for all possible inputs.
In short, you may choose any input format - not limited to strings - so long as that input format can represent any closed form number exactly and unambiguously. Additionally, be mindful of [this standard loophole](https://codegolf.meta.stackexchange.com/a/14110/66833) about encoding extra information into the input format - this is fairly loose, but try not to use formats that contain more information than just the 5 standard operations.
As output, you should produce some list of operations that, if followed, add the point \$(x, y)\$ to the set of constructed points \$S\$. By default, we will assume that all new points after each step are automatically added to \$S\$, and so you only need to output two possible instructions at each step:
* Draw a circle centered at a point \$(a, b)\$ going through a point \$(c, d)\$
* Draw a line through the points \$(a, b)\$ and \$(c, d)\$
This can be in any format that clearly includes both points necessary for each instruction, and which instruction is used. At the most basic, the options of `[0, a, b, c, d]` and `[1, a, b, c, d]` for circle and line respectively are completely fine. In short, you must be able to unambiguously distinguish each instruction from the next, the circle instruction from the line, and the two points \$(a, b)\$ and \$(c, d)\$. However, the values of \$a, b, c, d\$ must be exact constructible numbers.
Note that you may output *any* finite valid list of steps, not just the shortest.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the shortest code in each language wins
---
## Worked example
Take the point \$H = (\sqrt 3, \sqrt 3)\$. This can be constructed in 8 steps, with the first point in the circle instruction being the center:
```
Line: (0, 0), (1, 0)
Circle: (1, 0), (0, 0)
Circle: (2, 0), (0, 0)
Circle: (0, 0), (2, 0)
Circle: (4, 0), (2, 0)
Line: (1, 0), (1, √3)
Line: (1, √3), (3, √3)
Line: (0, 0), (1, 1)
```
The construction lines from this can be seen as:
[](https://i.stack.imgur.com/qbKB5.png)
This can be extended with 5 more lines to construct the more complicated point \$(\sqrt 3, \sqrt 2)\$:
```
Line: (2, 0), (1, 1)
Line: (1, -√3), (3, -√3)
Line: (0, 0), (1, -1)
Line: (2-√2, √2), (√2, √2)
Line: (√3, √3), (√3, -√3)
```
## Test cases
*To be completed*
Here, we use `C (a, b), (x, y)` to represent a circle with center \$(a, b)\$ and `L (a, b), (x, y)` a line that passes through the two points.
```
(x, y) -> Steps
(0, 0) -> []
(6, 0) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (4, 0), (2, 0)"]
(1, √3) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (0, 0), (2, 0)", "C (2, 0), (0, 0)"]
(1, 1) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (0, 0), (2, 0)", "C (4, 0), (2, 0)", "L (1, 0), (1, √3)"]
(-1/2, √2) -> ["L (0, 0), (1, 0)", "C (0, 0), (1, 0)", "C (-1, 0), (0, 0)", "L (-1/2, √3/2), (-1/2, -√3/2)", "C (1, 0), (0, 0)", "C (0, 0), (2, 0)", "C (2, 0), (0, 0)", "L (1, 0), (1, √3)", "L (0, 0), (1, 1)", "L (0, 0), (1, -1)", "L (√2, √2), (-√2, √2)"]
(1+√3+√2/2, 0) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (0, 0), (2, 0)", "L (1, √3), (1, 0)", "C (4, 0), (2, 0)", "L (1, √3), (3, √3)", "L (0, 0), (1, 1)", "L (2, 0), (1, 1)", "L (1, -√3), (3, -√3)", "L (√2, √2), (2, 0)", "L (2-√2, √2), (0, 0)", "C (1, 0), (1, 1+√2)", "L ((1+√2)/√2, 1/√2), ((1+√2)/√2, -1/√2)", "C ((1+√2)/√2, 0), ((1+√2)/2, √3))"]
(√2+√3, √5) -> ["L (0, 0), (1, 0)", "C (1, 0), (0, 0)", "C (2, 0), (0, 0)", "C (0, 0), (2, 0)", "L (1, √3), (1, 0)", "L (0, 0), (1, 1)", "L (0, 0), (1, -1)", "L (√2, √2), (√2, -√2)", "C (4, 0), (2, 0)", "L (1, √3), (3, √3)", "C (0, 0), (√2, √3)", "C (0, 0), (1, 0)", "C (√2, 0), (√2, √3)", "L (0, 1), (0, -1)", "C (0, √5), (0, 0)", "L (0, √5), (√5, √5)", "C (√2+√3, 0), (0, 0)", "L (√2+√3, 0), (√2+√3, √2+√3)"]
```
[Answer]
# [Python](https://www.python.org), 511 bytes
```
l=[(1,0,0,1,0)]
z,o='01'
def a(b,c):e=f'da{b}{c}2';v='dtm%s%ss32';l.extend([(0,b,0,c,0),(0,c,0,b,0),(1,e,v%(b,c),e,v%(c,b)),(0,e,0,0,0)]);return'a'+b+c
def m(b,c):l.append((0,0,0,c,0));return a(b,'m0'+c)
def t(b,c):l.append((1,0,p(b),p(c),p(m(b,o))));return't'+b+c
def d(b,c):l.append((1,0,1,p(b),p(m(o,c))));return'd'+b+c
def s(b):v=d(m(b,o),a(o,o));l.append((0,0,v,0,'m01'));return's'+b
def p(b):a(a(b,b),z);l.extend((a,c,b,e,d) for a,b,c,d,e in l[:]);return b
m(o,o)
def e(b,c):p(eval(b));p(eval(c));return l
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZJLTsMwEIbFtqfwJpqxYqoENihRTlKx8CuiUh5W4kbQqidh0w0cgqNwGRg7bQMIRXFmlH--f2bk13f34p_67nR62_n69uHz5qupNpiLjB46-eNqL_oKshxWxtZMohKaF7aqwciDOh708Q7KqQLj22RMxvGe0mZtn73tDG4wE4pAmkAC4zfkFOfCiimJsDnSQvGosdGajHk5WL8bOpCQqlRH-3a2b9bSuWCAURv5F3lsEdoMUs1jjf9bE4ZzqDgdOhwB2nN-JYBfDM1_xfmlvMWe_v6oNEvlSJJiqswZLyRpyaX83ftELzWbw8IYiREJwaSQGOYhtz1f9oqSRla0KsNZ3Q9MUqKFEZZtO9ZsiuvumFq10TcC7TyMQzvJhuC8PId62V4z34MPN2w7jxZhxHPnIBjsqc9ZcLkw3w)
If we can assume the user evaluated the functions (so we don't have to call `eval`), we can just do `e=lambda a,b:l`.
The function is `e`, it takes as input the two coordinates. `a` is addition, `m` subtraction, `t` multiplication, `d` division, and `s` square root. `o` has to be used in place of `1`, and `z` in place of 0.
Returns a list of objects to create, specifying coordinates in prefix notation, with single digits (so `a32 = 5`).
Here's how it works for \$(\sqrt2, 3)\$, for example:
[](https://i.stack.imgur.com/bS3Lm.gif)
The animation code:
```
import math
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Circle
def calc(s: str):
if type(s) is int:
return s, ''
if s[0].isdigit():
return int(s[0]), s[1:]
v1, rem = calc(s[1:])
if s[0] == 's':
return v1**.5, rem
v2, rem = calc(rem)
return (v1+v2 if s[0]=='a' else v1-v2 if s[0]=='m' else v1*v2 if s[0]=='t' else v1/v2 if s[0]=='d' else None), rem
var = plt.subplots()
fig : plt.Subplot = var[0]
ax : plt.Axes = var[1]
artists = []
points = set()
dat = e('s(a(o,o))','s(a(o,a(o,o)))')
print(len(dat))
ax.axis('equal')
ax.plot(2**.5, 3**.5, 'bo')
objects = set()
for a, b, c, d, e in dat:
b, c, d, e = (calc(x)[0] for x in (b, c, d, e))
if (a,b,c,d,e) in objects:
continue
objects.add((a,b,c,d,e))
if (b, c) not in points:
artists.append(ax.plot(b, c, 'ro')[0])
points.add((b, c))
if (d, e) not in points:
artists.append(ax.plot(d, e, 'ro')[0])
points.add((d, e))
if a == 1 and (b,c) != (d,e):
artists.append(ax.axline((b,c),(d,e)))
else:
artists.append(ax.add_patch(Circle((b,c), math.hypot(b-d, c-e), fill=False)))
def update(frame):
for i, art in enumerate(artists):
art.set_visible(i < frame)
ani = animation.FuncAnimation(fig=fig, func=update, frames=len(artists)+20, interval=100)
plt.interactive(True)
plt.show(block=True)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 366 bytes
```
P=(a,b=0,c=0,d=0,e=0)=>console.log(a,b,c,d,e)
L=x=>P(0,x)|P(x)|P(y=x+'/2',z=x+'/2*s3')|P(y,z,0,0,1)|P(x,z+'*2',x,0,1)
S=(b,a)=>`(${P(0,0,1,0,1),P(0,0,b)|P(b)|P(b+'/2',b+'/2*s3',a),b}-${a})`
D=(a,b)=>S(1,`(1-${P(a,0,S(a,b))|L(a)|L(1)|P(1,0,1,z=`(${a}/${b})`),z})`)
s=a=>P(S(0,1),0,a)|P(a,0,-1)|P(z=`(${a}-1)/2`,y=`(${a}+1)/2*s3`,z,-1+y,1)|P(z,0,a)|P(0,0,0,z='s'+a)||z
```
[Try it online!](https://tio.run/##NVDLboMwELzzFRyQbId1MenZOeWYAxI/gHmoahWFNo4qMPDtdHddjLxixp7ZWX@5X@e75@f3Sz/Gftj3ykoHrTXQ4e5xD9Yoe@nGhx/vw9t9/KBz6KCHQSU3O9lLJQ1Maq0kl9lOuSjOAkL8Ofl3wTwEMPiVfBNCLk54aWImqa1swWGfRmYL@SHLJxBBS6JYonl7WKMK2k1ni9tUk1w5PfrUsoRGlprcHBrUzKv1Jh0VDsEdMCb1dFuRLS1aKAhUE28dTVZLTmGwzRqdNGsPFaLi3MD8D3OCGKvBYXWZz3HacOgNv0CwwosciTXsV0zhJaWNnXClRZEiTv3P84UTSKOJTi2RzJ2V2v8A "JavaScript (Node.js) – Try It Online")
-24 from emanresu A
0 a b c d mean circle (a,b) through (c,d)
1 a b c d mean line through (a,b) and (c,d)
Should be quite golfable
* `L` provides line \$x=x\_0\$, assuming \$x\_0 \neq 0\$
* `S` subtracts two values
* `D` divides two values while creating point with given coords
* `s` gives square root
## Notes
* Need confirm
* Some free points may sometimes give good: To draw \$x=0\$, a sequence `Line((0,0),(1,0)), Circle((a,b),(0,0)), Line((2a,0),(a,b)), Line((0,2b)-(0,0))` should be shorter than always based on existing points, but that'd be complex-expressed
* Since taking a sequence of operations also "can represent any closed form number exactly and unambiguously", I assume it be a subset of `+-*/sqrt`
] |
[Question]
[
Given a directed network, with a single source and a single sink, it is possible to find the maximum flow through this network, from source to sink. For example, take the below network, \$G\$:
[](https://i.stack.imgur.com/iLXnn.png)
Here, the source is node **0** and the sink **5**. We can see, from the minimum cut-maximum flow theorem, that the maximum flow through this network is \$70\$ (given by the cut \$\{0\} / \{1, 2, 3, 4, 5\}\$)
### Minimum cut-maximum flow theorem
For a network, a cut is a line that divides a network in two, with the sink and source in different halves. For the above network, one such cut, \$C\$, is \$\{0, 1, 3\} / \{2, 4, 5\}\$. Every cut has a value, which depends on which edges in the network is passes through. The above cut, \$C\$, passes through the edges \$1-2, 3-2\$ and \$3-4\$, which have the weights \$40, 45\$ and \$30\$ respectively. The value of a cut is defined, for the set of crossed edges \$S\$, as
>
> The sum of the weights of all the edges in \$S\$ which pass **from** the source **to** the sink
>
>
>
Therefore, the value of \$C\$ is \$40 + 45 + 30 = 115\$ but the value of the cut \$\{0, 3\} / \{1, 2, 4, 5\}\$ would be \$20 + 45 + 30 = 95\$ (Note that \$10\$ is not included as it passes from the sink towards the source).
The minimum cut-maximum flow theorem states that
>
> The maximum flow through a network is equal to the minimum value of all cuts in that network
>
>
>
The minimum cut of all the cuts in \$G\$ is \$\{0\} / \{1, 2, 3, 4, 5\}\$ which has a value of \$70\$. Therefore, the maximum flow through \$G\$ is also \$70\$.
## Challenge
Write a function of full program that, when given a directed network as input, outputs the maximum flow through that network. You may, of course, use any method or algorithm to compute the maximum flow, not just the minimum cut-maximum flow theorem. This was simply included as one method.
You may take input in any [convenient method or format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), such as an adjacency matrix, a list of nodes and edges, etc. The input will always have 2 or more nodes, will be a connected graph, and will have exactly 1 source and 1 sink. The weights of the edges will always be natural numbers, as will the maximum flow. The output should reflect this, and can also be in any convenient method or format.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, in bytes, wins.
## Test cases
Both the network and the adjacency matrix are included for each test case.
Network \$G\$ (above):
```
[[ 0, 20, 0, 50, 0, 0],
[ 0, 0, 40, 10, 0, 0],
[ 0, 0, 0, 0, 25, 25],
[ 0, 0, 45, 0, 30, 0],
[ 0, 0, 0, 0, 0, 50],
[ 0, 0, 0, 0, 0, 0]] -> 70 ({0} / {1, 2, 3, 4, 5})
```
---
[](https://i.stack.imgur.com/ygSqP.png)
```
[[ 0, 10, 17, 0, 0, 0, 0],
[ 0, 0, 0, 2, 13, 0, 0],
[ 0, 5, 0, 0, 4, 8, 0],
[ 0, 0, 0, 0, 0, 0, 20],
[ 0, 0, 0, 18, 0, 0, 0],
[ 0, 0, 0, 0, 1, 0, 7],
[ 0, 0, 0, 0, 0, 0, 0]] -> 27 (Multiple cuts e.g. {0, 1, 2} / {3, 4, 5, 6})
```
---
[](https://i.stack.imgur.com/L8dnF.png)
```
[[ 0, 6, 2, 7, 4, 0, 0, 0],
[ 0, 0, 0, 0, 0, 10, 0, 0],
[ 0, 8, 0, 0, 0, 0, 9, 4],
[ 0, 0, 11, 0, 0, 0, 0, 0],
[ 0, 0, 0, 5, 0, 0, 0, 0],
[ 0, 0, 13, 0, 0, 0, 0, 16],
[ 0, 0, 0, 14, 0, 0, 0, 12],
[ 0, 0, 0, 0, 0, 0, 0, 0]] -> 19 ({0} / {1, 2, 3, 4, 5, 6, 7})
```
---
[](https://i.stack.imgur.com/26yCi.png)
```
[[ 0, 40, 50, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 30, 10, 0, 0, 0, 0],
[ 0, 0, 0, 40, 0, 0, 10, 0, 0],
[ 0, 0, 0, 0, 15, 10, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 20],
[ 0, 0, 0, 0, 0, 0, 15, 20, 0],
[ 0, 0, 0, 0, 0, 0, 0, 30, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 50],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0]] -> 40 ({0, 1, 2, 3, 4} / {5, 6, 7, 8})
```
---
[](https://i.stack.imgur.com/MDFuH.png)
```
[[ 0, 5, 8, 3, 3, 7, 0, 0, 0, 7],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 9],
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 4, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 6, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 6],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] -> 28 ({0, 1, 3, 5, 8} / {2, 4, 6, 7, 9})
```
---
[](https://i.stack.imgur.com/QwiM4.png)
```
[[0, 5],
[0, 0]] -> 5
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~37~~ ~~36~~ 34 bytes
```
I⌊EEX²⁻Lθ²↨⁺X²⊖Lθ⊗ι²ΣEθ∧§ιμΣΦ묧ιξ
```
[Try it online!](https://tio.run/##hY5RC4IwFIXf@xX38QoL0gqDnqwIggyhR/Fh6ajBnKmz/PdrhqWB1eDbHfecc@/iCy3ijAqtg4JLhWtaKvS55GmVok@vT4Lszgp0CBihKnHP5FldMLcIOJa5VrRkGAijvI0bFhcsZVKxpLM33k1WnYRpcuuVPraLcgKeTNBTO5mwGjmBtFW3XCgzVhA4ZKpvqK3XWWodhiFMCNgNLoHm3RGREUD40TO/tKcD@rznmRkWX/I9nAHdXvzZ32C31f093@SjSI9v4gE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
E…X²⁻Lθ²X²⊖Lθ Loop over all cuts...
E ↨⊗ι² ... converted to base 2
ΣEθ∧§ιμ Sum rows in source cut
ΣΦ묧ιξ Sum columns in sink cut
I⌊ Print the minimum
```
The range is constructed so that the base 2 values are `100...000` to `111...110` whereby the `1` bits refer to the source cut (thus the left bit, which is actually element `0`, is the source itself) and the `0` bits refer to the sink cut.
[Answer]
# JavaScript (ES6), 96 bytes
```
f=(m,k=1,b)=>k*2>>m.length?b:f(m,k+2,m.map((r,y)=>r.map((v,x)=>t+=k>>y&~k>>x&1&&v),t=0)|t>b?b:t)
```
[Try it online!](https://tio.run/##jVRRb4IwEH7nV/SJwOyUlhZwCeyHGB/AgdsQMUiIJsv@OrsOVBBKSe4ozX333d1Hy3dYhedd8XUqX4/5R1zXiW9kOPUJjkw/SF9oEGTLQ3zcl5/v0VsiYguKs2UWngyjwFcAFc2mwhfYlAs/DYKr/gvPi050vTJx6VvmTxlEQFCa9S4/nvNDvDzkeyMxNhraIAsjCi5W3q7I2uI2JJyBk/HQzSkX3s/izWrLs5qa0hBkaVvTRKsVci1NG@9dNEbcQeKAkwLMHoZ5B8LAvclmG7EGYeJN1xZO2tWdJO@MTF3ZyMhp5kFu27SitOTzeSPl14Kxx0LIaJeDQnwS8pC@05MzFJI9QahCrZ5iZC1TjPUOt3IYu6eYFMYUAnfD/JlxxmCjZ@2Zlc5js@cX5fNgHeGZ9HZCg3DM7H@D02rd7HELZMaUiLUMQe7vExxMiQBzlAhRTolwlAiuRHR@DN6Y2neSHpbXfw "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
m, // m[] = adjacency matrix
k = 1, // k = counter, initialized to 1 and always odd
b // b = best value so far, initially undefined
) => //
k * 2 >> m.length ? // if k is greater than or equal to 2 ** (m.length - 1):
b // stop the recursion and return b
: // else:
f( // do a recursive call to f:
m, // pass m[] unchanged
k + 2, // add 2 to k
// we make sure that k remains odd so that the source
// is always included in the 1st half of the cut
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((v, x) => // for each value v at position x in r[]:
t += // update t:
k >> y & // if the y-th bit in k is set
~k >> x & 1 // and the x-th bit in k is not set:
&& v // add v to t, otherwise add nothing
), // end of inner map()
t = 0 // start with t = 0
) | // end of outer map()
t > b ? b : t // if t <= b or b is still undefined, update b to t
) // end of recursive call
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 27 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā2.ŒʒD{Q}<ʒZ%PË}εнèøyθè˜O}ß
```
Takes the input in a similar format as the test cases in the challenge description.
[Try it online](https://tio.run/##yy9OTMpM/f//SKOR3tFJpya5VAfW2pyaFKUacLi79tzWC3sPrzi8o/LcjsMrTs/xrz08////6GgDHSMDHQMdUxBhEKsTDaJNDHQMkfkgaGQKRDB5UyBhjCoPMgKFaxAbCwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX3lopS2Xkn9pCZT//0ijkd7RSacmuVQH1tqcmhSlGnC4u/bc1kPrii/sPbzi8I7KczsOrzg9x7/28Pz/Ooe22f@Pjo420DEy0DHQMQURBrE60SDaxEDHEJkPgkamQASTNwUSxqjyICNQuAaxsToKIPOBRhmawwVhSox0DI3hAqZgIRMdCzQjQY6DCxha6KA7yhCIzdF0wO01A9phDjQUXROK5yzggpY6JlBFhoZIhsH0maKJQFwPMc4M4UYTmJgRurMQDjOBBTeGJcYwt6GImmC4GipgCleNaRlyyMGVG2FTaoxdvyk2QbgfTIEhZwyEsIg1x6YYHqKo0BLdYTj8YILDZ2ZYRYHmYBU1wypqilUU4T2IdGxsLAA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
# (without popping the input itself)
2.Œ # Get all partitions of two parts of this list
# (note: this also contains partitions with empty parts, but that doesn't
# matter, since the second filter also takes care of those)
ʒ } # Filter out partitions where the first item of the first part is larger
# than the first item of the second part, by:
D{ # Sorting the two parts of a copy (based on their first items)
Q # Check that the partition and sorted partition are still the same
< # Now decrease the values of each remaining partition by 1
ʒ } # Filter out partitions where the sink and source are in the same part, by:
Z # Getting the flattened maximum (without popping)
% # Modulo this maximum on each value,
# this causes this maximum (the sink) to become 0 as well
P # Take the product of both partitions (empty parts become 1)
Ë # And check that both products are the same (thus both 0)
ε } # Now that we have all valid cuts left, we map the partitions to:
н # Get the first part of the current partition
è # Index its values into the (implicit) input-matrix
ø # Zip/transpose; swapping rows/columns
yθ # Get the last part of the current partition
è # Index its values into this transposed list of lists
˜O # And get the flattened sum
ß # After the map: pop and push the minimum
# (after which it is output implicitly as result)
```
[Try it online to see a step-by-step input to output process.](https://tio.run/##fZHBSgMxEIbvPsVQEBSibFd7EUWEIvTUSm8ue0h3p91gNilJtrqIB8/e@gJe@wKKFy@uXjwU32hNsiu0F0lImJkv/z9MpKYThnXdGYh5YU6gQ84@Xs93OlGXAEcxM1kMnGlf@XxsaiOqDDNMCg1yCiHMbawdEB5@LRvkkiltYMq4QQV7CnO5QM@170xGDVCFwEQilcLE8BKkSlFguu@kvpf9@6uHRqyPiUKqEZAmGSwoLxAmJXQdd9ogY0ykSP8xvM3QupkMQctCJQjU4pqJm7YLkKLhW/fr3VH11PoPRIp3QDkHq0uZYGK2Kc2EkV6ZuREe@P78ONYvP@/Vqnor12/VqtUaF7llpUYHDIdN8sK3LqxDCTM0Xiy3PrmDpU/Zpq27Lrj/ieqZ1HUUBSQMSEB67ghiErn7OCDdzditsGf3X71nj6PtupPYCoM4/gU)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
JṖŒPỊẸ$Ƈ,ḟ@Œp;U$ʋ€Jœị⁸§Ṃ
```
A monadic Link accepting a list of lists of non-negative integers (an adjacency matrix), which yields the maximal flow integer.
**[Try it online!](https://tio.run/##y0rNyan8/9/r4c5pRycFPNzd9XDXDpVj7ToPd8x3ODqpwDpU5VT3o6Y1XkcnP9zd/ahxx6HlD3c2/f//PzpawUBHwQiIQbQplFYwiNXhUohWgHJNgNgQuxQMG5mCMKouUwhtjFsXxE6cUkBdsQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##lVK9TsMwEN55Cg8dM8R/SSoW5k4sTFFHFtSBlZEulejWSqyMLDxASjdQGHgL90XMGSc0dmxfkO50ju@7u89f7u52tXrQeqEOz@3uWh2f1Hsz@9pkqnm5anf3lzez7@1p/bZo9@q4PT02H6/qsNafG7jTuq5rkmeEgZsou0jyZXZBSE26bwFOI7nemTTu1UkbeaLOzo3noM4kLVFDgpYjwLiYAY4H8nKAEeBVmpgVZ5ynFTLfOO1ime7vPJAUljwpO4LYkNifqQKD5qan24fSIKHxLJnGnMUe8CoCwgkPwzBxPIGEs6Y4ce4IFMcJTNBhXvo9pzwivEl@XzaxH//HXDkR5wgNXGCH@K/BMua9DbY5ZgKHzKMQ@ndOdRE4BKzAIWYiDilwiMQhvbxntL1c/gA "Jelly – Try It Online").
### How?
Implements the minimum-cut maximal-flow method.
```
JṖŒPỊẸ$Ƈ,ḟ@Œp;U$ʋ€Jœị⁸§Ṃ - Link: adjacency matrix, A (n by n)
J - range of length (A) -> [1,2,3,...,n]
Ṗ - pop -> [1,2,3,...,n-1]
ŒP - power-set (all posible selections)
Ƈ - keep only those for which:
$ - last two links as a monad:
Ị - insignificant (true for 1, false for 2,3,...)
Ẹ - any? (i.e. only the selections containing a 1)
€ - for each:
J - with range of length (A) as the right argument of
ʋ - last four links as a dyad - i.e. f(selections, J)
@ - with swapped arguments:
ḟ - filter discard those from (J) which are in (selection)
, - (selection) pair (that) - i.e. a cut
Œp - Cartesian product - i.e. all pairs of nodes where lines
could be present across this cut
$ - last two links as a monad:
U - reverse each
; - concatenate (giving us the pairs of nodes in both orders)
⁸ - chain's left agument, A
œị - (pair) multi-dimensional index into (A) (vectorises)
§ - sum each resulting list of weights
Ṃ - minimum
```
] |
[Question]
[
The Golden Ratio Bureau is obsessed with this new thing they call base-phi. You see it and decide to code-golf, as is your natural instinct.
To be specific, base-phi is a number system like base 10, except it uses the number phi, or the golden ratio, as its base. A ones digit would be x\*10^y, but in base phi 10 is replaced with phi. Base phi also uses 2 digits, 0 and 1.
Your goal is to accept input that is a base 10 positive natural number, then treat it as such and convert it to base phi.
Due to base phi being able to represent all numbers in more than one way, your program should convert input to its "minimal" representation. This is the representation with the least 1 digits.
Output can have trailing characters but only if the language must output them with no circumvention.
Do not use any built-ins for base conversion. You may use a built-in for phi, but the base conversion should rely on string manipulation and other mathematical operations.
Your program must support inputs up to 2147483647, or lower, depending on your language's limit for integers.
Your program can deal with any undefined behavior as you wish.
Testing cases for accuracy can be done at [this link.](http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/phigits.html#phigitsCALC) In case you do not wish to use the link, here are the numbers 1-15 in base phi.
```
1 = 1
2 = 10.01
3 = 100.01
4 = 101.01
5 = 1000.1001
6 = 1010.0001
7 = 10000.0001
8 = 10001.0001
9 = 10010.0101
10 = 10100.0101
11 = 10101.0101
12 = 100000.101001
13 = 100010.001001
14 = 100100.001001
15 = 100101.001001
```
The shortest program following these rules wins. Have fun.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~81~~ 80 bytes
```
K`0.
"$+"{+`(1(\.)|(1\.(0?1)*0?)1)(00|$)
${3}0${2}11
0\.
1.
+0`0?1(\.?)1
10${1}0
```
[Try it online!](https://tio.run/##DcshDoAwEERRv8doKnZpspkBg@MAXKGiCAQGQXClZy/V//3nfK/7YO97gUuIKdRUlJrdPmV2xUabsBlNgS@axLo0xDo3UpBd6JJQBhvPYMIR2dA71x8 "Retina – Try It Online") Works by repeatedly adding \$ 1 \$. Explanation:
```
K`0.
```
Start off with \$ 0. \$.
```
"$+"{`
```
Repeat the number of times given by the input.
```
+`(1(\.)|(1\.(0?1)*0?)1)(00|$)
${3}0${2}11
```
If the \$ \phi^0 \$ bit is set, use the identity \$ \phi^0 = \phi^{-1} + \phi^{-2} \$ to move bits away until there is enough room.
```
0\.
1.
```
Add \$ 1 \$.
```
+0`0?1(\.?)1
10${1}0
```
Minimise the number of bits by reversing the above identity.
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~107~~ ~~106~~ ~~110~~ 109 bytes
```
[0sD]sZ0ddsRsK?dsXZF*dkdsN-sM[lX5v1dsD+2/lN^dsY>ZlXlDlY*-sXlDdAlN^*lR+sRlKdlN+lD*-sKlN1-dsNlM!>L]dsLxlRlKk1/p
```
[Try it online!](https://tio.run/##DYyxCsMgAAW/pasiiYWsKQXpYuLgZAzp0rflDYUHoX9vnQ7u4PBpbR8VDtURUFZ8QKW@DE4oOa07y3R5KNj7wPSGtrmyMHAzTp14dmuYrTIjmCxDD5HJuz7gepuXA1p@7Pn0w7c1P/0B "dc – Try It Online")
Or [verify the test suite](https://tio.run/##RY/BasJQEEX3@YppcJXwNJPkGRc2UkjdRCNkFSMWYkZrcfoimVIKbb89fYjQzQycw53hHho5D23zAem171775h3mc/d5s3SHXSDZXuqASErJFyRVvfToQlIoWe@40p9IkvnhhIsXkm1ac8UZbz0ldtOTpR6XvpScExc@Z1bkXKCyB3j9kK72JKsvtvqCk@tgXzrOqevBwJuBbxyPUf9CiHESz6JpnEAc6iQKtMZphBhGDgB1dgAc23MHyoA7MvCYgvsPLfgBakGd4F7uljLH4Q8): the OP's test cases, 2147483647, and a very large Lucas number (over 400 trillion) which comes out neatly in base \$\varphi\$ (see screenshot below for that last test case by itself).
*The program should now work for arbitrarily large numbers, restricted only by the memory capacity of the computer.*
[](https://i.stack.imgur.com/cOaMP.png)
**How it works:**
```
[0sD]sZ Macro Z, sets D to 0 when called.
0ddsRsK Initialize R and K to 0, leaving 0 on the stack.
?dsX Input number, store it in X,
ZF*dkdsN store 15 times its number of decimal digits in N,
also set that as the number of decimal places for
computations,
-sM and store the negative of that in M.
M and N are bounds on the powers of phi which
will be needed for the representation.
Multiplying by 15 is far more than is needed:
For M and N, we could have multiplied by just 5,
because ln(10)/ln(phi) < 5.
We need some additional decimal places in the
computations to handle possible round-off errors,
so we conservatively multiply by 15.
[ Start a macro (which will be used as a loop).
lX Push X onto the stack.
5v1dsD+2/lN^ Set D=1. Compute phi^N,
dsY and store it in Y.
>Z If phi^N > X, use macro Z to set D=0.
lXlDlY*-sX If D is 1, set X = X - phi^N.
lDdAlN^*lR+sR R += D * 10^N.
This places the digit D in R in the right
position, treating R as a number in base 10.
lKdlN+lD*-sK If D is 1, set K = -N.
(K is used as the number of "decimal"
places to print.)
lN1-dsN Set N = N-1, leaving the new value of N
at the top of the stack.
lM!>L If M <= N, call macro L recursively (in
other words, start another loop iteration).
] End the macro,
dsL save it in register L,
x and execute it.
Once the loop is done:
lR Load the result R.
lKk Set the precision (number of decimal places) to K.
1/ Divide R by 1 to convert it to the desired precision.
p Print it.
```
[Answer]
# [Perl 5](https://www.perl.org/), 135 bytes
```
sub f{(0,1,10.01)[$_=pop]||do{$_=f($_-1);$_.=0until/\..{99}/;s/.\./$&+1/e;1while s/.?2../$&+801/e+s,0?11,100,;s,.{99}$,.$&,;/1.*1/;$&}}
```
[Try it online!](https://tio.run/##bZfdbptAEIXv8xTIQg7YGHb4MRBE0hfoXe/qKmpjklhybNc4aiPHfXWXv2XPsOTCsuc7LLuzM2ezh@K4ja7X8v2X8Xy2hEMOCVeQ/d18zA/7w4/Pz/X@XH1/tszHBdmZ@ejm4n132my9leue0/TiZaXnrlzPnM7JKzL687rZFkYVe/DdJpqIKj4vHfFA9ejCyUqnedJ0XHPqZB65M/Iyc3q5XN/LwvhWlKe7u6/7Y2Gcqq9lfl89NPOzm7ePL3Ugt26M6o@M/N64pVun@eW3v@q5d5Ggi0Ao7EKkQpFUCbf6kNGlFFYPq2jca1k46cOE4VSGm0n1YRL92DxOfZxY3FdvrecIs6RAvbmeEaJQvX2IIoVogNS623wAitX0mtUDSmCGQ5YCI858oVibI2AESxsyHxgNWADrbrdUMchJt7GKRbDyIcOs0ICptMh9ViyBlA1ZCow4CwTms91z2KSAMKXt5iL2Mas6DhCThkPMe1sDiCNMfbvXiJeYfR3HiEnDCeCuIBCnuH0aDgVi0jDhBneNBNjHPe46BnCA26zjEDFpOMJC6BoL8BJroWsgwDErB52z9pNNBhxbsG80xSPB6knnvN5I47zguqYDziuuay7gvOR0HjFOGl8il00IPGY1q/OEcdJ4yopaerA6KwSraum2ihMra537jJPGA1b30pcVZ7bWm7PizNqEzpeMk8Zj5L1RK56w1tF5yjgNeSxYb0nTVpxYc0lzVtxn3aXzgHHSeIi8N3HFI9aeOuftSxof9K80dDCneNDC0rVRMujiEUkiuIRGJLyXe4NHic/bXbo4SgLe8WOSkEtoRBIxSW/4KFly6xiTxFxCI5KEG4w0f5Sk3GOkw4MkFdxmxiTEJTQi8bkZycMAJQH3I2n4KAm5JY1JIi6hEQk/rfuTASX8xBZjkoRLaESScgeURwT@5ykEd0F5DDSaRmJnN83VwmouAfa5Cb59WOZmd3DM4u/BzsvDdvNUNNwRTnVjaCWG@bI/1TeYSmm3wU1p1cHmOWdSxfMaGtWvvA4Z9QO1YFLp@1HqcXc/34p80txLjKf98Vg8nXZFWRr75@YtE/XOw@smt2he/j6erMi2PZjOuhk7/@dZq/Xctlbup2l7D9ti93J6tUyyF3S33hRKX@Yiqz7nuTmd1ePOZuZ6sTDam1Y7VOmt1p6nFlc6bV7knKt1XK7/AQ "Perl 5 – Try It Online")
This function is no speed monster, but it's O(n). `f(1000000)` returns `10100000100010010000100010001.0001000010100101000100000101` in 15 secs on my laptop.
[Answer]
# [PHP](https://php.net/), 173 bytes
```
$p=.5+sqrt(5)/2;for($i=45,$a=$argn,$f=1;$a>=.01;){$i?:$a*=$f=1e6;$b=$p**$i*$f;if($i--==-1)$n.='.';if((float)number_format($a-$b,3)>=0){$a-=$b;$n.=1;}else$n.=$n?0:'';}echo$n;
```
[Try it online!](https://tio.run/##FY3BDoIwGINfpgkMGTIVD8xfbr6GGYbJEtgmzJPx1cWth6b5krZ@9Nul89HhqWp262sJecP2B6ndksPQqSmhCGp52hKahIS6UlULyT4wXQtVUMLDWaIn@KKAKaCl0bHMOREXDLairMoSy/XkVGD2PffDco8Xswo5FEdfHtmV6jiqOKGXqSPkd5jWIUXYrm6zLILH6GDltok66ed8MM6uG7/9AQ "PHP – Try It Online")
It was a real pain mostly because of errors in comparisons and subtraction when values get really small, I had to find a way to circumvent them:
```
$p=(1+sqrt(5))/2; //ϕ
for($i=45,$a=$argn,$f=1;$a>=.1;){ //no need to go beyond ϕ^45 to go up to 2147483647. $a is the input, $f a factor
$i?:$a*=$f=1e7; //small numbers fix: multiplying $a and factor $f by 1000000 for following test and exit condition to work (also shortens this condition)
$b=$p**$i*$f; //current power of ϕ multiplied by the factor
if($i--==-1)$n.='.'; //decrement $i + if we get to power -1 add the dot '.'
if((float)number_format($a-$b,3)>=0){ //second fix to be right when difference is very small
$a-=$b; //subtract the current power when ok
$n.=1; //adding a '1'
}else $n.=$n?0:''; //or else a '0' (test $n to avoid leading zeroes)
}
echo$n; //et voilà!
```
I think I can golf it more, we'll see later, I'm open to suggestions. Note that my version of 2147483647 is slightly different than what I saw [here](http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/phigits.html#phigitsCALC), but of course it's me who's right. Haven't tried other big values..
EDIT: saved 1 byte thanks to @mathjunkie and lowered the exit threshold to 0.01 for the 111 case as rightly noticed by @MitchellSpector.. no change to the score
EDIT2: changed the factor from 10000000 to 1000000 to handle another case found by @MitchellSpector, I guess I'll have to do automated tests to detect other cases :D
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 94 [bytes](https://github.com/abrudz/SBCS)
```
{w←{+\∘⌽⍣⍵⊢1 0}¨⍵-⍳k←2×⍵⋄s/⍨(∨\'0'≠s)∧⌽∨\'1'=⌽s←⍵(↑,'.',↓)⊃∘⍕¨⊢/b/⍨(w+.×b←(0∘⍪,1∘⍪)⍣k⍪⍬)≡¨⊂⍵0}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7r8UduEau2YRx0zHvXsfdS7@FHv1kddiwwVDGoPrQCydR/1bs4GKjE6PB0k091SrP@od4XGo44VMeoG6o86FxRrPupYDtIKEjFUtwUyi4HqgYo1HrVN1FHXU9d51DZZ81FXM8iK3qlAU7sW6SeBTSnX1js8PQmoWsMALLlKxxBCawIdkg2kH/Wu0XzUuRCkpwlookHt/zSw2X1A4w6tNwZa8KhvanCQM5AM8fAM/p@mYMiVpmAExMZAbALEpkBsBsTmQGwBAA "APL (Dyalog Unicode) – Try It Online")
Inefficient as hell. Basically, given n as input, generate all bit patterns with n bits above and n bits below the decimal point, symbolically evaluate it as base phi (to the form `a+b*phi`), extract all patterns whose value is `n+0*phi`, pick the one that is lexicographically highest, and then trim unnecessary zeros/decimal point from both ends.
### Ungolfed with comments
```
f←{ ⍝ Input: ⍵←n
v←⍵-⍳2×⍵ ⍝ Vector of n-1, n-2, ..., -n
w←{+\∘⌽⍣⍵⊢1 0}¨v ⍝ Reduced base-phi values (a+b×phi) of phi^v
{ }¨v ⍝ For each value of v,
1 0 ⍝ Start with 1+0×phi
+\∘⌽ ⍝ Apply "reverse then cumulative sum"
⍣⍵ ⍝ v times (for negative v, inverse of it |v| times)
b←(0∘⍪,1∘⍪)⍣(2×⍵)⍪⍬ ⍝ Matrix of all possible bit patterns for 2n bits
⍪⍬ ⍝ Empty matrix of 0 row, 1 column
(0∘⍪,1∘⍪) ⍝ Apply "horizontally concat the matrix with
⍝ a 0-row prepended with the one with a 1-row"
⍣(2×⍵) ⍝ 2n times
a←⊢/b/⍨(w+.×b)≡¨⊂⍵0 ⍝ Find target bit pattern
(w+.×b) ⍝ Evaluate each bit pattern as base phi
≡¨⊂⍵0 ⍝ Compare with n+0×phi
b/⍨ ⍝ Filter columns of b where ^ is true
⊢/ ⍝ Pick the rightmost one
s←⍵(↑,'.',↓)⊃∘⍕¨a ⍝ Convert to string
⊃∘⍕¨a ⍝ Char-ify each digit
⍵(↑,'.',↓) ⍝ Insert decimal point after n chars
s/⍨(∨\'0'≠s)∧⌽∨\'1'=⌽s ⍝ Filter away trailing non-ones and leading zeros
⌽∨\'1'=⌽s ⍝ Boolean mask to filter away trailing non-ones
∧ ⍝ And
(∨\'0'≠s) ⍝ Boolean mask to filter away leading zeros
s/⍨ ⍝ Filter s using ^
}
```
] |
[Question]
[
# Definitions
* **Euler Phi Function** (AKA **totient function**): a function which takes in a positive number and returns the number of positive numbers less than the given number which are co-prime with given number. It is denoted as `φ(n)`.
* **Reachable number**: if there exists a positive integer `x` such that `φ(x) == n`, then `n` is **reachable**.
# Task
Write a function/program to determine if a given positive integer is reachable.
# Input
A positive number, in any reasonable format. One can assume that the number is within the capability of the language. Unary input is accepted.
# Output
Two consistent values, one for reachable numbers, and the other for unreachable numbers. The two values can be anything, as long as they are consistent.
# Testcases
The reachable numbers bellow `100` are:
>
> 1, 2, 4, 6, 8, 10, 12, 16, 18, 20, 22, 24, 28, 30, 32, 36, 40, 42, 44, 46, 48, 52, 54, 56, 58, 60, 64, 66, 70, 72, 78, 80, 82, 84, 88, 92, 96
>
>
>
([A002202](https://oeis.org/A002202) on OEIS)
# Rules
[Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/48934) apply.
# Winning criterion
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Submission with lowest byte-count wins.
# References
* [Euler Phi Function](https://proofwiki.org/wiki/Definition:Euler_Phi_Function)
* [OEIS A002202](https://oeis.org/A002202)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes
```
²RÆṪe@
```
Not exactly fast. Returns **1** or **0**.
[Try it online!](https://tio.run/nexus/jelly#@39oU9Dhtoc7V6U6/Le0PNx@eELafwA "Jelly – TIO Nexus")
### How it works
```
²RÆṪe@ Main link. Argument: n
² Square; yield n².
R Range; yield [1, ..., n²].
ÆṪ Compute the totient of each integer in the range.
e@ Exists swap; test if n occurs in the generated array.
```
[Answer]
# Mathematica, 28 bytes
```
EulerPhi@Range[#^2]~FreeQ~#&
```
Like Dennis's Jelly answer, we compute the φ-values of all the numbers up to the square of the input and see if the input appears therein. Returns `False` if the input is reachable and `True` if it's not. Yep, that's confusing. But `FreeQ` is a byte shorter than `MatchQ`, and hey, the spec said any two consistent values >:)
[Answer]
## JavaScript (ES6), ~~90~~ 82 bytes
Returns `0` or `true`.
```
f=(n,x=n*2)=>x?(p=i=>(c=(a,b)=>a?c(b%a,a):b<2)(i,x)+(i&&p(--i)))(x)==n||f(n,x-1):0
```
This is based on the assumption that if ***x*** exists then ***x ≤ 2n***. If proven false, this should be updated to use `x=n*n` instead of `x=n*2` (same size, much slower).
An edge case is ***n = 128*** which requires to compute ***ϕ(255)***.
### Demo
```
f=(n,x=n*2)=>x?(p=i=>(c=(a,b)=>a?c(b%a,a):b<2)(i,x)+(i&&p(--i)))(x)==n||f(n,x-1):0
for(n = 1; n <= 50; n++) {
console.log(n, f(n));
}
```
[Answer]
# Axiom, 56 bytes
```
f(x:PI):Boolean==member?(x,[eulerPhi(i)for i in 1..2*x])
```
i don't know if it is right...test code and results
```
(35) -> [i for i in 1..100|f(i)]
(35)
[1, 2, 4, 6, 8, 10, 12, 16, 18, 20, 22, 24, 28, 30, 32, 36, 40, 42, 44, 46,
48, 52, 54, 56, 58, 60, 64, 66, 70, 72, 78, 80, 82, 84, 88, 92, 96, 100]
```
The range 1..(2\*x) would be ok until input x=500...
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 34 bytes
```
x->![n|n<-[1..x^2],eulerphi(n)==x]
```
Returns `0` if reachable, `1` if not.
[Try it online!](https://tio.run/nexus/pari-gp#S1OwVfhfoWunGJ1Xk2ejG22op1cRZxSrk1qak1pUkJGpkadpa1sR@z8tv0ijAqjWUEfB0MBAR6GgKDOvBCiipKBrByTSNCo0NTX/AwA "Pari/GP – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
```
nLÕså
```
Explanation:
```
n Square [implicit] input
L Range [1 .. a]
Õ Euler totient
s Put first input at the top of the stack
å Is it in the list?
```
[Try it online!](https://tio.run/nexus/05ab1e#@5/nc3hq8eGl//8bGgAA "05AB1E – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 12 bytes
**EDIT**: Saved a byte because input is reused if the stack doesn't have enough elements.
Outputs 1 if reachable, 0 if not.
Relies on assumption that x ≤ 2n if it exists.
```
xGNÕQi1,q}}0
```
[Try it online!](https://tio.run/nexus/05ab1e#@1/h7nd4amCmoU5hba3B//@GBgA "05AB1E – TIO Nexus")
How it works
```
# implicit input
x # push input, 2 * input
G # for N in 1..2*input
# implicit push input
N # push N
Õ # push totient of N
Q # check if both are equal
i. # if equal
1, # print 1
q # quit program
} # end if
} # end for
0 # push 0 if condition never reached
# implicit print
```
[Answer]
# C, 123 bytes
```
g(a,b){return!a?b:g(b%a,a);}
i;r;f(n){for(i=2,r=1;i<n;i++)r+=(g(i,n)==1);}
t;k;s(m){for(k=m,t=0;!t&(k<m*m);)f(++k),t=(r==m);}
```
[**Try Online**](http://ideone.com/I1COys)
```
#include <stdio.h>
// gcd function
g(a,b){return!a?b:g(b%a,a);}
// Euler phi(x) function
i;r;f(n){for(i=2,r=1;i<n;i++)r+=(g(i,n)==1);}
// check if m is reachable, phi(x) for x in (m , m^2]
t;k;s(m){for(k=m,t=0;!t&(k<m*m);)f(++k),t=(r==m);}
main()
{
// print all reachable number below 50
for(int x=1; x<50; x++)
{
s(x);
if(t)
{
printf(" %d ~ phi(%d) \n", x, k);
}
}
}
```
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 63 bytes
```
> Input
>> 1²
>> [2]
>> φ(L)
>> Each 4 3
>> 1∈5
>> Output 6
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hMvOTsHw0CYQFW0UC6LOt2n4aIIYronJGQomCsZgJY86OkxBDP/SEqAuBbP//80MAA "Whispers v2 – Try It Online")
Works by brute force. We square the input, then generate the range `[1, 2, ..., x²]`. Next we calculate \$\phi(i)\$ for each \$i\$ in this range. Finally, we check if the original input \$x\$ is in the array of \$\phi(i)\$ values.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
┬$τ▀Ω♀
```
[Run and debug it](https://staxlang.xyz/#p=c224e7dfea0c&i=3)
I'm not sure why 3 golflangs have an Euler Totient function, but I guess it's convenient for these challenges.
0 for reachable and 1 for non-reachable.
] |
[Question]
[
Here's a relatively simple challenge for you:
Given a list of positive integers:
* Line them up in a grid, and sum each column. For example, if the input was `[123, 7, 49, 681]`, the grid would look like this:
```
1 2 3
7
4 9
6 8 1
```
And the sum of each column would be `[18, 19, 4]`:
```
1 2 3
7
4 9
6 8 1
--------
18 19 4
```
* Find the maximum of these sums, which in this case would be 19, and then
* Output every digit that is at the same index as this maximum column. In this case, that would be
```
2
9
8
```
You do not have to output these numbers in any particular order.
Note that there are only three outputs, even though we had 4 inputs. In the case of a tie, pick the earliest index. For example, if the input was `[25, 223, 302]`, your grid is:
```
2 5
2 2 3
3 0 2
-------
7 7 5
```
You should output
```
2
2
3
```
You can print these numbers in any format you like. List format, newline separated, space separated, etc. You may not take the input as a 2D array of digits, e.g.
```
[[1, 2, 3],
[7],
[4, 9],
[6, 8, 1]
```
But other than that, you can take input as a list of strings, a list of digits, or any other reasonable format.
You may also assume that all inputs will be valid and contain at least two numbers.
As usual, the shortest answer in bytes wins!
# Test IO:
```
#Input #Output
[1, 11, 111, 1111] --> [1, 1, 1, 1]
[1, 12, 123] --> [2, 2]
[987654321, 111] --> [9, 1]
[111, 123456789] --> [9]
[4, 8, 15, 16, 23, 42] --> [4, 8, 1, 1, 2, 4]
[4, 8, 12, 26, 27, 38] --> [2, 6, 7, 8]
[24, 53] --> [2, 5]
[12, 304, 506] --> [4, 6]
[30, 285, 121] --> [0, 8, 2]
```
[Answer]
## Haskell, 63 bytes
```
import Data.Lists
argmax sum.transpose.map(map(read.pure).show)
```
Usage example: `argmax sum.transpose.map(map(read.pure).show) $ [12,304,506]` -> `[4,6]`.
How it works:
```
map -- for each number
map(read.pure).show -- turn into list of digits
transpose -- transpose the list of list
argmax sum -- find the element with the
-- largest sum
```
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DZṚSÞṪ
```
[Try it online!](http://jelly.tryitonline.net/#code=RFrhuZpTw57huao&input=&args=WzM1MywgMjI0N10). This is a relatively straightforward implementation of the question.
```
D Convert each number in the input to a list of digits, e.g.
[353, 2247] -> [[3, 5, 3], [2, 2, 4, 7]]
Z Zip the lists together, e.g. [[3, 2], [5, 2], [3, 4], [7]]
Ṛ Reverse the list of lists so that first occurrences are now
at the end, e.g. [[7], [3, 4], [5, 2], [3, 2]]
SÞ Sort by sum - this uses Python's sorted function, which is stable
so equal elements end up in order of appearance, e.g.
[[3, 2], [7], [3, 4], [5, 2]]
Ṫ Tail - get the last element, e.g. [5, 2]
```
[Answer]
## Ruby, ~~100~~ 97 bytes
```
a=$<.map &:chomp
puts a.map(&:size).max.times.map{|i|a.map{|e|e[i]}.compact}.max_by{|e|eval e*?+}
```
[Answer]
# Mathematica 82 bytes
This pads the digits of each number with x's to the right, transposes the matrix, removes the dummy x's, orders by sum of the digits and takes the greatest.
```
SortBy[#~Select~NumberQ&/@Transpose[PadRight[#,30,x]&/@IntegerDigits@#],Tr][[-1]]&
```
---
There ought to be some way to use the superscript-T form of `Transpose` to save a few bytes.
[Answer]
# Perl, ~~49~~ 48 bytes
Includes +1 for `-p`
Run with the input on STDIN, prints to STDOUT the column numbers prefixed by `+`
```
lcolumn.pl
123
7
49
681
```
`lcolumn.pl`:
```
#!/usr/bin/perl -p
s/./@;[@-].="+$&"/eg}{($_)=sort{eval"$b<=>$a"}@
```
[Answer]
## Javascript (ES6), ~~108~~ ~~103~~ 100 bytes
It's a bit verbose and could probably be golfed some more with a different approach. I wish I could get rid of this `.filter(n=>n)`.
*Saved 5 bytes thanks to Neil*
*Saved 3 bytes thanks to edc65*
```
l=>l.map(n=>[...n].map((d,x)=>(m=(s[x]=(s[x]|0)-d)<m?s[c=x]:m,d)),s=[m=0]).map(n=>n[c]).filter(n=>n)
```
### Demo
```
let f =
l=>l.map(n=>[...n].map((d,x)=>(m=(s[x]=(s[x]|0)-d)<m?s[c=x]:m,d)),s=[m=0]).map(n=>n[c]).filter(n=>n)
console.log(f(["1", "11", "111", "1111"]).join`,`); // --> [1, 1, 1, 1]
console.log(f(["1", "12", "123"]).join`,`); // --> [2, 2]
console.log(f(["987654321", "111"]).join`,`); // --> [9, 1]
console.log(f(["111", "123456789"]).join`,`); // --> [9]
console.log(f(["4", "8", "15", "16", "23", "42"]).join`,`); // --> [4, 8, 1, 1, 2, 4]
console.log(f(["4", "8", "12", "26", "27", "38"]).join`,`); // --> [2, 6, 7, 8]
console.log(f(["24", "53"]).join`,`); // --> [2, 5]
console.log(f(["12", "304", "506"]).join`,`); // --> [4, 6]
console.log(f(["30", "285", "121"]).join`,`); // --> [0, 8, 2]
```
[Answer]
# Pyth, ~~5~~ 8 bytes
```
esDsMM.T
```
Takes in input as a list of strings, outputs as a nothing-separated list of digits.
[Try it online!](http://pyth.herokuapp.com/?code=esDsMM.T&input=%5B%2230%22%2C+%22285%22%2C+%22121%22%5D&debug=0)
Explanation:
```
.T Transpose input to zip together corresponding columns
sMM Cast to digit lists
sD sort(D) by (s)um
e take last element, implicitly print
```
[Answer]
# Pyth, 11 bytes
```
h.MsZ.TmjdT
```
A program that takes input of a list of integers on STDIN and prints a list.
[Try it online](https://pyth.herokuapp.com/?code=h.MsZ.TmjdT&test_suite=1&test_suite_input=%5B1%2C+11%2C+111%2C+1111%5D%0A%5B1%2C+12%2C+123%5D%0A%5B987654321%2C+111%5D%0A%5B111%2C+123456789%5D%0A%5B4%2C+8%2C+15%2C+16%2C+23%2C+42%5D%0A%5B4%2C+8%2C+12%2C+26%2C+27%2C+38%5D%0A%5B24%2C+53%5D%0A%5B12%2C+304%2C+506%5D%0A%5B30%2C+285%2C+121%5D&debug=0)
**How it works**
```
h.MsZ.TmjdT Program. Input: Q
j T Yield the base-10 representation, giving a list of digits
m d Map that over Q (implicit input fill)
.T Justified transpose, giving each column as a list
.MsZ Filter the above by maximum sum
h First element of above
Implicitly print
```
[Answer]
# JavaScript (ES6), 90
```
(l,x)=>[...l+0].map((t,i)=>l.map(n=>(n=n[i])&&(v-=n,t.push(n)),v=t=[])|v>=x||(x=v,r=t))&&r
```
```
f=(l,x)=>[...l+0].map((t,i)=>l.map(n=>(n=n[i])&&(v-=n,t.push(n)),v=t=[])|v>=x||(x=v,r=t))&&r
;[
[[123, 7, 49, 681] , [2,9,8]]
,[[25, 223, 302] , [2, 2, 3]]
,[[1, 11, 111, 1111] , [1, 1, 1, 1]]
,[[1, 12, 123] , [2, 2]]
,[[987654321, 111] , [9, 1]]
,[[111, 123456789] , [9]]
,[[4, 8, 15, 16, 23, 42] , [4, 8, 1, 1, 2, 4]]
,[[4, 8, 12, 26, 27, 38] , [2, 6, 7, 8]]
,[[24, 53] , [2, 5]]
,[[12, 304, 506] , [4, 6]]
,[[30, 285, 121] , [0, 8, 2]]]
.forEach(t=>{
var i=t[0], o=t[1], r, ok
i=i.map(x=>x+'') // convert i to a string list
r=f(i)
ok = (r+'')==(o+'') // compare r and o as comma separated strings
console.log(ok?'OK':'KO', i+' -> '+ r)
})
```
[Answer]
# Pyth - 9 bytes
```
esD_.TjRT
```
[Test Suite](http://pyth.herokuapp.com/?code=esD_.TjRT&test_suite=1&test_suite_input=%5B1%2C+11%2C+111%2C+1111%5D%0A%5B1%2C+12%2C+123%5D%0A%5B987654321%2C+111%5D%0A%5B111%2C+123456789%5D%0A%5B4%2C+8%2C+15%2C+16%2C+23%2C+42%5D%0A%5B4%2C+8%2C+12%2C+26%2C+27%2C+38%5D%0A%5B24%2C+53%5D%0A%5B12%2C+304%2C+506%5D%0A%5B30%2C+285%2C+121%5D&debug=0).
] |
[Question]
[
# Rolling the Dice
So, I was rolling dice a while ago and thought of a challenge.
Given the cube with a net taken from input and a list of moves, find the square on the bottom at the end.

I will use this image for the examples here.
### Input
You take in a string with a list of moves. The string contains only the capital ASCII letters N, S, W, and E. These correspond to rolling the cube one step into that direction.
In the picture, one N would make the bottom face a 6. In this image, North is away from the camera, South is towards, East is right, and West is left.
You also take in a string in the following format: 1P 2P 3P 4P 5P 6P, where each P is a position from N, S, W, E, T, and B. T & B are bottom and top.
The numbers are the face with that number, and the letter represents the position the face is in. In case it isn't clear, the net will always be ordered by the number, so 1P 2P 3P 4P 5P 6P, never 2B 1T 3N 4S 5W 6E.
The position in the image is 1S 2B 3E 4W 5T 6N.
### Output
Your program should output a number representing the bottom side.
### Test Cases
```
(nothing), 1S 2B 3E 4W 5T 6N -> 2
N, 1S 2B 3E 4W 5T 6N -> 6
NS, 1S 2B 3E 4W 5T 6N -> 2
NWS, 1S 2B 3E 4W 5T 6N -> 2
NWSNWS, 1S 2B 3E 4W 5T 6N -> 2
NWSS, 1S 2B 3E 4W 5T 6N -> 3
NNNNNN, 1S 2B 3E 4W 5T 6N -> 5
SNWEEWS, 1N 2T 3E 4W 5B 6S, 6
SNEEWS, 1N 2T 3W 4S 5B 6E, 4
```
### Other Rules
You may also assume the cube is on a infinite flat plane, probably with some sort of friction.
Standard loopholes disallowed, even though I can't find any.
For invalid input, your code may do anything except start the apocalypse.
Because this program should fit on my dice, it should be as small as possible. I count in bytes, with some exceptions for languages like [Folders](https://esolangs.org/wiki/Folders).
[Answer]
## CJam, ~~43~~ ~~40~~ ~~37~~ 34 bytes
*Thanks to Dennis for helping me save 6 bytes.*
```
lW%3/$1f=q{i8%"ÉĔɠƂ!"=i\m!=}/c
```
[Test it here.](http://cjam.aditsu.net/#code=lW%253%2F%241f%3Dq%7Bi8%25%22%C3%89%C4%94%C9%A0%C6%82!%22%3Di6e!%3D%5Cf%3D%7D%2Fc&input=1N%202T%203W%204S%205B%206E%0ASNEEWS)
### Explanation
```
lW% e# Read the first line and reverse it.
S/ e# Split it around spaces.
$ e# Sort it. This puts the faces in order [B E N S T W].
1f= e# Select the second character from each face, which is the number.
q e# Read the remainder of the input (the instructions).
{ e# For each instruction...
i8% e# Convert the character (NWSE) to an integer and take modulo 8.
"ÉĔɠƂ!"=i
e# Use that to (cyclically) index this string and convert *that* character
e# to an integer.
\ e# Swap with the list of faces.
m! e# Generate all permutations of the faces.
= e# Select the permutation corresponding to the above integer.
}/ e# At the end of the loop, the bottom face will be the first character.
c e# Convert the string to a character, which discards everything but the bottom face.
```
As for how the mapping of instruction characters to permutations works, here is a handy table:
```
i 8% 5% ""= i [0 1 2 3 4 5]m!=
N 78 6 1 Ĕ 276 [2 1 4 0 3 5]
W 87 7 2 …† 608 [5 0 2 3 1 4]
S 83 3 3 Ƃ 386 [3 1 0 4 2 5]
E 69 5 0 É 201 [1 4 2 3 5 0]
```
I've included the `5%` column because that is what the cyclic indexing into the string does implicitly. For the four permutations we can see that each of them leaves two (opposite) sides untouched and cyclically permutes the other four.
[Answer]
## Perl, ~~166~~ ~~158~~ ~~154~~ ~~144~~ ~~139~~ ~~135~~ ~~134~~ ~~132~~ 116 bytes
*includes +1 for `-p`*
```
s/(\d)(.)/$h{$2}=$1/eg;$N='NTSB',$S='STNB',$E='ETWB',$W='WTEB';map{@h{@l}=@h{(@l=$$_=~/./g)[1..3,0]}}/\w/g;$_=$h{B}
```
## With comments:
```
# example input: "NS, 1S 2B 3E 4W 5T 6N"
s/(\d)(.)/$h{$2}=$1/eg; # construct %h ( S=>1, B=>2, E=>3, W=>4, B=>2, N=>6 )
# = Transformations =
$N='NTSB', # N becomes T, T becomes S, S becomes B, B becomes N
$S='STNB',
$E='ETWB',
$W='WTEB';
map { # iterate the moves "NS"
@h{ @l } = # LHS: bulk-assign new values; @l defined in RHS
@h{ # RHS: init @l, transform
(@l=$$_=~/./g) # get transform, put ('N','T','S','B') in @l for LHS
[1..3,0] # construct a rotated slice for RHS
}
} /\w/g; # match the movements in list context
$_=$h{B} # assign the bottom face to output.
```
---
Input file:
```
, 1S 2B 3E 4W 5T 6N
N, 1S 2B 3E 4W 5T 6N
NS, 1S 2B 3E 4W 5T 6N
NWS, 1S 2B 3E 4W 5T 6N
NWSNWS, 1S 2B 3E 4W 5T 6N
NWSS, 1S 2B 3E 4W 5T 6N
NNNNNN, 1S 2B 3E 4W 5T 6N
SNWEEWS, 1N 2T 3E 4W 5B 6S
SNEEWS, 1N 2T 3W 4S 5B 6E
```
Run with
```
perl -p dice.pl < input.txt
```
Output: `262223564`
---
* *update 158* Using `$N, $S, $E, $W` global variables instead of `%t = {N=>, S=>, E=>, $W=>}` saves 8 bytes.
* *update 154* Since the requirement is that the program output a number, not printing the newline `print "$h{B}\n"` saves 4 bytes: `print $h{B}`.
* *update 144* Save 10 bytes by doing
```
($s)=/^(\w+),/; s/(\d)(.)/$h{$2}=$1/eg;
```
instead of
```
($s,@i)=split /,? |\n/; %h=reverse map{split//}@i;
```
* *update 139* Move the regex for the command to the end to eliminate a variable, saving 6 bytes.
* *update 135* Save 4 bytes on `@l[0..3,0]` instead of `@l[1..3],$l[0]`.
* *update 134* Save 1 byte by using assignment `@l=split//,$$_` as value.
* *update 132* Save 2 bytes by doing `/^\w+/ && $&` instead of `/^(\w+)/ && $1`.
* *update 129* Save 3 bytes by using `-p` instead of `-n` and assigning $\_ for print.
* *update 116* Save 13 bytes by rewriting `split//, /^\w+/ && $&` into `/^\w+/g`.
[Answer]
# Python 2, 204 bytes
Thought it was time to respond to my own question.
```
def x(p,m):
d={p[3*i-2]:i for i in range(1,7)}
for j in m:n=2if j in'NE'else-2;x='BSTN'if j in'NS'else'BETW';d[x[0]],d[x[1]],d[x[2]],d[x[3]]=d[x[1+n]],d[x[(2+n)%4]],d[x[(3+n)%4]],d[x[0+n]]
print d['B']
```
Not very short, but works.
Run as:
```
x('1B 2T 3N 4S 5W 6E','SNEEWS')
#Output: 4
```
**Edit**: Counted bytes wrong. Now longer. :(
] |
[Question]
[
You are given a nonnegative integer `n` and an integer `p >= 2`. You need to add some `p`-th powers (`p=2` means squares, `p=3` means cubes) together to get `n`. This is always for any nonnegative `n`, but you don't know many `p`-th powers (of any **positive** integer) you'll need.
This is your task: find the minimum number of `p`-th powers that can sum to `n`.
**Examples**
```
>>> min_powers(7, 2)
4 # you need at least four squares to add to 7
# Example: (2)^2 + (1)^2 + (1)^2 + (1)^2 = 4 + 1 + 1 + 1 = 7
>>> min_powers(4, 2)
1 # you need at least one square to add to 4
# Example: (2)^2 = 4
>>> min_powers(7, 3)
7 # you need at least seven cubes to add to 7
# Example: 7*(1)^3 = 7
>>> min_powers(23, 3)
9 # you need at least nine cubes to add to 23
# Example: 2*(2)^3 + 7*(1)^2 = 2*8 + 7*1 = 23
```
A related Wikipedia article on this problem, [Waring's problem](https://en.wikipedia.org/wiki/Waring's_problem).
**Rules**
* Your code *must* be a program or a function.
* Input is two integers `n` and `p` in any order. You can assume all inputs are valid (`n` is any positive integer, `p >= 2`
* Output is an integer representing the number of powers needed to sum to `n`.
* This is code golf, so **the shortest program** wins., not necessarily the most efficient.
* Any and all built-ins are allowed.
As always, if the problem is unclear, please let me know. Good luck and good golfing!
[Answer]
# Mathematica ~~61~~ 50 bytes
With 11 bytes saved by LegionMammal978.
When restricted to powers of counting numbers, this problem is straightforward (in Mathematica). When extended to include powers of integers, it's a nightmare.
```
(k=0;While[PowersRepresentations[#,++k,#2]=={}];k)&
```
---
**Test Cases**
```
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[7, 2]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[4, 2]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[7, 3]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[23, 3]
```
>
> 4
>
>
> 1
>
>
> 7
>
>
> 9
>
>
>
---
`PowersRepresentationsp[n,k,p]` finds all the cases in which `n` can be expressed as a sum of `k` positive integers raised to the `p`-th power.
---
For example,
```
PowersRepresentations[1729, 2, 3]
```
>
> {{1, 12}, {9, 10}}
>
>
>
Checking,
```
1^3 + 12^3
```
>
> 1729
>
>
>
---
```
9^3 + 10^3
```
>
> 1729
>
>
>
[Answer]
# Pyth, ~~20~~ 19 bytes
*Saved [1 byte](https://codegolf.stackexchange.com/questions/65473/how-many-squares-cubes-fourth-powers-etc-do-i-need-to-sum-to-n/65489?noredirect=1#comment158523_65489) thanks to FryAmTheEggman.*
```
L&bhSmhy-b^dQS@bQyE
```
Takes input on two lines, `p` first and then `n`.
[Try it online.](https://pyth.herokuapp.com/?code=L%26bhSmhy-b%5EdQS%40bQyE&input=3%0A23&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=L%26bhSmhy-b%5EdQS%40bQyE&test_suite=1&test_suite_input=2%0A7%0A2%0A4%0A3%0A7%0A3%0A23&debug=0&input_size=2)
### Explanation
The code defines a recursive function `y(b)` that returns the result for `min_powers(b, p)`.
```
L define a function y(b):
&b return b if it's 0
S get a list of positive integers less than or equal to
@bQ the p:th root of b
m map the integers to:
-b subtract from b
^dQ the p:th power of the current integer
y recurse on the above
h increment the result
hS find the smallest result number and return it
yE calculate y(n) and print
```
[Answer]
## Java - 183 177 bytes
```
int p(int a,int b){int P,c,t,l=P=t=a,f=0;double p;while(P>0){a=t=l;c=0;while(t>0){if(a-(p=Math.pow(t,b))>=0&&t<=P){while((a-=p)>=0)c++;a+=p;}t--;}f=c<f||f==0?c:f;P--;}return f;}
```
---
**183 bytes**
```
int p(int a,int b){int P,c,t,l,f=0;P=t=l=a;double p;while(P>0){a=t=l;c=0;while(t>0){if(a-(p=Math.pow(t,b))>=0&&t<=P){while((a-=p)>=0){c++;}a+=p;}t--;}f=c<f||f==0?c:f;P--;}return f;}
```
## Ungolfed
```
int p(int a, int b){
int P,c,t,l=P=t=a,f=0;
double p;
while (P>0){
a=t=l;
c=0;
while (t>0){
if (a-(p=Math.pow(t, b))>=0 && t<=P){
while((a-=p)>=0)c++;
a+=p;
}
t--;
}
f=c<f||f==0?c:f;
P--;
}
return f;
}
```
---
## Result
```
System.out.println(p(7, 2)); // 4
System.out.println(p(4,2)); // 1
System.out.println(p(7,3)); // 7
System.out.println(p(23,3)); // 9
```
[Answer]
# Python 2, 66 bytes
```
f=lambda n,p:n and-~min(f(n-k**p,p)for k in range(1,n+1)if n/k**p)
```
Recursively tries subtracting each `p`-th power which leaves the remainder non-negative, computing its value on each remainder, and taking the minimum plus 1. On 0, outputs 0.
The ugly check `if n/k**p` (equivalent to `if k**p<=n`) is to stop the function from going into the negatives and trying to take the `min` of the empty list. If Python has `min([])=infinity`, this wouldn't be needed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 122 bytes
```
r(n,p,k,s,j,b){if(!k)return n!=s;for(b=j=1;j<n;b*=r(n,p,~-k,s+(int)pow(j++,p)));n=b;}f(n,p,k){for(k=0;r(n,p,++k,0););n=k;}
```
[Try it online!](https://tio.run/##JYzNDoIwEAbvPgVoSHbtkiiYeKi98hRe5KeGFldSNB4IPrq1wGX2sN9Mld6rynsHTD1ZGshQiWOrIbbomtfbccSxGqR@OiiVUUdpLizLvVqNbxocAS2/sH9@wAhBPSJKVqWc9BrFcZatOsjVEcLSAeU8snLyu7rRLTdRMT@xd6GlYashqSlKaoxU4JW3NKtLMeQ3j1vLgGMBZ8qwgNPCM@WBWR7O5H@V7m73wafd4w8 "C (gcc) – Try It Online")
] |
[Question]
[
[The International Code of Signals flag alphabet](http://en.wikipedia.org/wiki/International_maritime_signal_flags) is used by ships for communication, particularly for static signals.
Your challenge is to write a program or function that will take a string from STDIN or as an argument, and display the corresponding text in the ICS flag alphabet. If your language does not display to the screen, saving to a file is acceptable.
Your program or function shall support letters **A-Z** in upper and lower case, plus **Space** and **Newline**. Behaviour with other characters is undefined.
The display shall be ~~large enough to display~~ *capable of displaying* at least 8 flags horizontally and 6 flags vertically. Behaviour is undefined if the right hand edge is reached before a newline is received, or if the message is too long to fit the display vertically.
The flag alphabet is as shown below (Roman letters are for reference only, they are not required in the output.)

**Dimensions**
There is no universally agreed standard for the dimensions of these flags, so for the purpose of this challenge the following shall apply:
Flags shall be 60x60 pixels, with a 30 pixel gap between them both horizontally and vertically.
The swallowtail cut on A and B shall be 15 pixels deep.
All other lines shall be horizontal, vertical, or at 45 degrees.
**The features shall be located by dividing the flag into an imaginary NxN grid of side 3,4,5 or 6 squares. Refer to the above image, but for further clarification:**
*A,E,H,K, L and U are based on a 2x2 grid : width of each colour zone shall be 30pixels. Also the points of the diamond in F shall be halfway along each side of the flag.*
*J and T are based on a 3x3 grid: each band shall be 20 pixels.*
*P,N and S are based on a 4x4 grid. Also the diagonal lines of Y shall split the edges of the flag into 4.*
*C,D,R and X shall be based on a 5x5 grid. Bands and arms of crosses shall be 12 pixels wide.*
*G,W,M,V are based on a 6x6 grid. Bands of G and borders of W shall be 10 pixels wide.
Arms of crosses on M and V shall cover the first and last 10 pixels of each edge of the flag, leaving triangle zones measuring 40 pixels along the long edge.*
*The circle of I shall be in the centre of the flag and have diameter 30 pixels.*
An error of +/-1 pixel from the above text is permitted. If your language only supports scalable graphics, you may interpret "pixels" to mean "units."
**Colours**
Colours shall be red, white, blue, yellow and black as defined by your language or its documentation. If your language does not define colours, you may use the following:
Red FF0000,
White FFFFFF,
Blue 0000FF,
Yellow FFFF00,
Black 0000000.
Background shall be grey (r,g and b channels equal, between 25% and 75% intensity.)
**Scoring /Loopholes**
This is codegolf. Shortest code in bytes wins.
[Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/15599) are disallowed.
No builtin or library functions for displaying flags may be used. Output shall be non-text (and in particular, unicode characters shall not be used to build up the flag shape.)
**Example**
```
JFK got
my VHS
PC
and XLR
web quiz
```
should produce the following

[Answer]
# CJam, 464 bytes
You thought CJam didn't have image manipulation functions? Well, you thought right! But I wasn't going to let that stop me.
```
"P3
690 690 4
"3a3*a690_@*a*qeuN/{0:U;{_'C<.5*:N;i[{XY+Z<[E8][9C]?XY<=}WWWW{XH<9F?}C{YC/[9FCF]=}{YC/3&9E?}{YH<9F?}{X29.5:R-zYR-z+H>FC?}{XA/1&9E?}{XH<FC?}{XR-_*YR-_*+F_*>E8?}{YK/(9F?}{XH<E9?}{XH<YH<^8E?}{XY+Z-A/XY-A/e&9F?}{XF/YF/^1&F9?}{XY<EC?}{XH-F/YH-F/|9F?}E{XHm6/YHm6/e&CE?}{XH-F/YH-F/|F9?}{XK/[CF9]=}{XH<YH<^FC?}{XY+Z-A/XY-A/e&FC?}{XR-zYR-ze>iA/[CF9]=}{XHm6/YHm6/e&F9?}{XY+F/1&CE?}]=:P~!!{60:Z{Z30:HYH-z-N*-{YV+_2$=XU+P2b1>4f*tt}fX}fY}*U90+:U;}/V90+:V;}/`"[]"-
```
This program outputs the image in the best way CJam can: as text that represents the image when saved as a [PPM file](http://en.wikipedia.org/wiki/Netpbm_format#PPM_example). Don't even try running it with the online interpreter, by the way; you'll blow the stack. Run it with the [Java interpreter](https://sourceforge.net/projects/cjam/) and pipe the output to a file with a command like `java -jar cjam-0.6.4.jar flags.cjam > flags.ppm`. Once you've provided your input, send an EOF (may need to be immediately after a newline) with ctrl+D on Unix or ctrl+Z on Windows.
### Sample
If it's really desired, I can try to paste the original ~3MB image source somewhere. But here's the result opened in GIMP and conerted to a PNG:
```
ABCDEFG
hijklmn
OPQRSTU
vwxyz z
```

### Explanation
The image header, easily identifiable in the source, consists of the magic number, width, height, and maximum channel value. So the output is a 690\*690 image (enough for 8\*8 60px flags with 30px of spacing between them) with each R, G, and B value ranging from 0 to 4.
The image data is initialized as a 690\*690\*3 array filled with 3's, making the whole image light gray. Then the input is read, converted to uppercase, and split into lines. The lines are processed in a loop, incrementing the flag Y coordinate by 90 each iteration, and in each line, each character is processed in a loop, incrementing the flag X coordinate by 90 each iteration. Now the magic begins.
Each character is mapped to a flag's pixel function that, when called, returns the color of the pixel at the position (X, Y) on the flag. This is where most of the hard work went: concisely describing 26 images as mathematical functions. Each of these functions returns a color value from 8-15. This range takes advantage of the fact that, when converted to base 2, the resulting bit array can be interpreted as [1, R, G, B]. The first element can be removed and the rest multiplied by 4 to easily give a pixel value in the desired format that covers all the possible flag colors (as well as green, cyan, and magenta). It also works out nicely that there are one-character variables initialized to 10-15, and since varaibles don't need a space to syntactically separate them, any two colors besides black and blue can be entered next to each other without needing any spacing.
Once the function is retrieved, it's just a matter of iterating over both of X and Y from 0-60, calling the function at each step, and writing the result back to the image data array. An astute observer might notice that the color values returned by each flag function don't allow gray, though. So there's a bit of extra logic to skip spaces. But there are still the swallowtail cuts on 'A' and 'B'. So there's a bit of extra logic there, too. If the character value is less than 'C', a value is set such that the upper bound on the X loop varies correctly with respect to Y and the cut-out areas are never drawn.
Overall, I'm pretty happy with how this came out. It took a lot of work, but it was fun. Some flags don't perfectly match the reference image, but I think I got all the shapes to be within 1px of the target (if any are off by more than that, let me know and I'll fix them). And there's definitely still potential to optimize, as there's a fair amount of redundancy between the 26 flag functions.
---
# Ineresting first attempt, 559 bytes
Altough I never quite finished this, I'll post it too, because it's pretty interesting. Instead of modelling each flag by a function of (X, Y) → color, flags are drawn as a composition of simple shapes. But I was worried about needing to write a substantial amount of rendering code for each different shape. After a lot of pondering, I realized I could render them all, with some clever overlapping and overdrawing, with just one pseudo-shape: all the points within a specified distance of a specified point, where the definition of "distance" is variable. Chessboard distance gives a square, Manhattan distance gives a diamond, and Euclidean distance gives a circle. This meant every shape had the same five parameters (color, distance mode, x, y, and max distance) and I only needed to write one shape data decoder and one rendering function with a small bit of distance mode logic.
```
"P3
690 690 4
"3a3*a690_@*a*qeuN/{0:U;{_'C<.5*:N;i[[8EX30:Q0Q9X60:ZQQCXQZQ]LLLL[F9TTQQ]Ca[9FTQ42QCTQ54QFTQ66Q9TQ78Q][E9TIQI9T42QI][9FTQZQ][FCXQQQ][E9T40QQET50QQ9TZQQET70QQ9T80QQ][FCTZQQ][E8YQQF][9FTQAQ9TQ9~Q][E9TZQQ][8ETTTQETZZQ][F9XQTK9XZQK9XQZK9XTQK][F4{4{JW^1&6*9+TJ)F*W)F*F}fJ}fW][CEX0ZZ][9FTQQF]Ea[E[TZ]_m*{CT@~24}/][F9TQQF][9FTAQQCT9~QQ][FCTTTQCTZZQ]C9$1>9a/Fa*+[9FTQQKCTQQA]9 6$1>Ca/Fa*+[C7{7\-_1&2*C+X@TT@F*}/]]=_!!{([TQQQ]+\+}*5/{~:R;.5-:H;.5-:G;:M;2b1>4f*:O;Z{ZQWQ-z-N*-{JG-{zM_!+#}:P~WH-PM{+}{e>}?RP<{WV+_2$=JU+Ott}*}fJ}fW}/U90+:U;}/V90+:V;}/`"[]"-
```
[Answer]
# PHP, 811 bytes
```
function f($s){echo"<body bgcolor=#ccc>";$z=split("\n",gzinflate(base64_decode("vVfNasMwDL7vKQK7xlT+iaHQ9LDTLnuIQus6ENhgxS19+kmO0yRrkhbqGIxtyV8sWbIkZ/Prjtm52p9suYbMHqqjPdHMVYfzx/elhBzyNbXtZoXQ7dvm+Q9+dieb7csvZFkJToNlEq6Zqeq6fAcw2arDqCKXUPMCEYQicIc1xmNfUkBDzXgQkpMQ3W0PEGF7fz49dT7IuSCQ1APJ5h9IKAIhdGn1jIHH6oUzvCpZzhtGjoDiePzuzAPJEkG1JPk1uw29G5rC7pxAvAFxuHqd+nQxpCP65S4gR6wzAkphE4rPHfbYaAueky59BrmrZ4wU0Ss8SES/pCNugMduiBSYs25oJTeBSYNMbHO6+bUg22PPhA8E5LCWhT3SFBjEwxaWiOMYD1+FtZSZxateEAZ7pvsEL7w1aQxD3HxLcmayfNA9ZeXzcdteJLm0H5ZITzAwolDkXeGwVAvlSzUOSDDkMRqRxDkuLquVecbKMRKFaESLSYOMg4b6qVHQMnkMns5jyZLBAnksRehirQWrwClEqakDNrqKpjqKpZ8K5rVYTFE56ZmCyT68KinJX+n/puFpyHXg4RRLwg1oW6YipqfimfJTt6/c6XIv6Tnc/HxNXIj+a9nORdwN5Qa3qzvGHw==")));while($c=ord(ucfirst($s))){$s=substr($s,1);echo$c<32?'<br>':($c^32?$z[$c-64]:$z[0]);}}
```
The compressed blob contains SVG code for each of the 26 flags. A simple loop then extracts and outputs the SVG image corresponding to each character of the input.
## Sample output for "This is`\n`a test":
```
<body bgcolor=#ccc><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h20v60h-20z fill=#f00 /><path d=M20,0h20v60h-20z fill=#fff /><path d=M40,0h20v60h-20z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h30v60h-30z fill=#fff /><path d=M30,0h30v60h-30z fill=#f00 /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#ff0 /><path d=M15,30a15,15,0,0,1,30,0a15,15,0,0,1-30,0z fill=#000 /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#fff /><path d=M15,15h30v30h-30z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#ff0 /><path d=M15,30a15,15,0,0,1,30,0a15,15,0,0,1-30,0z fill=#000 /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#fff /><path d=M15,15h30v30h-30z fill=#00f /></svg><br><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h30v60h-30z fill=#00f /><path d=M45,30l15-30h-30v60h30z fill=#fff /></svg><svg width=90 height=90 viewBox=0,0,90,90></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h20v60h-20z fill=#f00 /><path d=M20,0h20v60h-20z fill=#fff /><path d=M40,0h20v60h-20z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v30h-60z fill=#00f /><path d=M0,30h60v30h-60z fill=#fff /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h60v60h-60z fill=#fff /><path d=M15,15h30v30h-30z fill=#00f /></svg><svg width=90 height=90 viewBox=0,0,90,90><path d=M0,0h20v60h-20z fill=#f00 /><path d=M20,0h20v60h-20z fill=#fff /><path d=M40,0h20v60h-20z fill=#00f /></svg>
```
([You can try it out at ideone](http://ideone.com/u1yiOr), although it won't render the page for you.)
] |
[Question]
[
A [**cyclic tag system**](http://en.wikipedia.org/wiki/Tag_system#Cyclic_tag_systems) is a tiny, Turing-complete computational model consisting of a two-symbol alphabet (I'll use `{0,1}`), a finite, nonempty cyclic list of *productions* that consist of those two symbols, and an unbounded *word* which also consists of those two symbols.
At each step:
* the first element in the *word* is removed
* if it was `0` the current *production* is skipped
* if it was `1` the current *production* is appended to the end of the *word*.
* the next *production* becomes active. If this was the last production, go back to the first one.
The system *halts* when the *word* becomes empty.
An example (from Wikipedia):
```
Productions: (010, 000, 1111)
Initial word: 11001
Generation Production Word (before) Word (after)
0 010 11001 → 1001010
1 000 1001010 → 001010000
2 1111 001010000 → 01010000
3 010 01010000 → 1010000
4 000 1010000 → 010000000
5 1111 010000000 → 10000000
6 010 10000000 → 0000000010
7 000 0000000010 → 000000010
8 1111 000000010 → 00000010
9 010 00000010 → 0000010
```
Your task, if you choose to accept it, is to write a program or function that takes:
* a list of productions,
* the initial word, and
* a generation,
and prints or returns the *word* at that generation.
For example,
```
cyclic_tag(
prod=[[0,1,0],[0,0,0],[1,1,1,1]],
word=[1,1,0,0,1],
gen=4) => [1,0,1,0,0,0,0]
```
Implementation details:
* The alphabet does not matter. You may use `0` and `1`, `True` and `False`, `T` and `NIL`, `A` and `B`, or even `1` and `0`, or whatever else you may come up with, as long as you are consistent. All input and output must use the same alphabet, and you must indicate what you are using for `0` and what for `1`.
* The length of the *word* must be theoretically unbounded. That is, you may not hardcode a maximum word length. If I run your program on an ideal computer with an infinite amount of memory, your program must theoretically be able to make use of it. (You may ignore your interpreter's/compiler's limits.)
* If the given system halts before the given generation is reached, you must return or print the empty word.
* The empty production exists, and you must be able to handle it. If you write a full program, your I/O must also be able to handle it.
**Edit**: I had originally intended for generation `0` to be the input word itself, and generation `1` to be the result of the first step. I.e., I had intended for you to return the *before* column. *However*, as I have not been clear enough in stating this, **I will accept both options**; for each generation you may return the value in either the *before* or the *after* column. **You must state that you are following the *after* column, if you are doing so.** You must also be consistent in which column you choose.
I will award the smallest code a week from now (10/27/2014).
[Answer]
# Haskell, ~~55~~ ~~53~~ 51
```
(t:w)%p|t=w++p|0<1=w
x%_=x
e w=(!!).scanl(%)w.cycle
```
this uses `True` as `1` and `False` as `0`.
example run:
```
*Main> let t=True ; f=False
*Main> e [t,f,t] [[f,f,f],[t,t,t]] 4
[False,False,False,False,False]
```
[Answer]
## GolfScript (17 to 19 bytes depending on input format and accepted output format)
18 bytes:
```
~.@*<{\1,or(@*+}/`
```
Takes input in the form `[1 1 0 0 1] [[0 1 0] [0 0 0] [1 1 1 1]] 4` and gives output in the form `[1 0 1 0 0 0 0]`. (Could be **17 bytes** without the last ``` if output as `1010000` is acceptable).
[Online demo](http://golfscript.apphb.com/?c=OydbMSAxIDAgMCAxXVtbMCAxIDBdWzAgMCAwXVsxIDEgMSAxXV00JwoKfi5AKjx7XDEsb3IoQCorfS9g)
19 bytes:
```
~.@*<{\0`or(1&@*+}/
```
Takes input in the form `"11001" ["010" "000" "1111"] 4`.
[Online demo](http://golfscript.apphb.com/?c=OyciMTEwMDEiWyIwMTAiIjAwMCIiMTExMSJdNCcKCn4uQCo8e1wwYG9yKDEmQCorfS8%3D)
### Dissection
```
~ # Evaluate input: stack: word productions gen
.@*< # Produce a list of the right number of productions with suitable repetition
{ # For each of those productions:
\ # Bring the word to the top
0`or # Ensure that we don't get an error if the word is empty
(1& # Pop the first char from the word and evaluate it
@* # Repeat the production that many times
+ # Concatenate 0 or 1 copies of the production to the rest of the word
}/ # Endforeach
```
Credit to [Martin Büttner](https://codegolf.stackexchange.com/users/8478)'s [CJam solution](https://codegolf.stackexchange.com/a/40314/194) for the idea of generating the list of productions by repetition and truncation.
[Answer]
## CJam, ~~31~~ ~~30~~ ~~28~~ ~~27~~ ~~24~~ 18 bytes
```
{_@*<{\_0a?(@*+}/}
```
This defines a block (the closest thing to a functioN), which expects the input to reside on the stack like this
```
[1 1 0 0 1] [[0 1 0] [0 0 0] [1 1 1 1]] 9
```
It will similarly leave an array of `0`s and `1`s on the stack.
[Test it here.](http://cjam.aditsu.net/) Paste the input one the first line, the code on the third line, and append a `~` to actually evaluate the block. E.g.
```
[1 1 0 0 1] [[0 1 0] [0 0 0] [1 1 1 1]] 9
{_@*<{\_0a?(@*+}/}~
```
If output does not have to have the same form as input
Explanation:
```
_@*<{\_0a?(@*+}/
_@ "Duplicate the generation and pull the productions to the top.";
*< "Repeat the productions N times and take the first N elements.";
{ }/ "For each element in that list, run this block.";
\ "Swap production and current word W.";
_0a? "W = (W != []) ? W : [0]. This is to ensure we can unshift an element.";
( "Unshift the first 0 or 1 from the word.";
@ "Rotate the stack, pulling the production to the top.";
* "Repeat it 0 or 1 times.";
+ "Append to the word.";
```
The final state of the word is left on the stack.
Thanks to Peter Taylor for making me revisit this.
[Answer]
# Mathematica, ~~84 80~~ 77 chars
```
f[_,w_,_]=w;f[p_,{x_,y___},n_/;n>0]:=f[RotateLeft@p,Flatten@{y,p~Take~x},n-1]
```
Example:
```
f[{{0, 1, 0}, {0, 0, 0}, {1, 1, 1, 1}}, {1, 1, 0, 0, 1}, 4]
```
>
> {1, 0, 1, 0, 0, 0, 0}
>
>
>
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) 22
Requires all 3 arguments as separate inputs.
```
#Vvw=z+tz*@Q%NlQshz)zq
```
Takes arguments like:
```
11001
["010","000","1111"]
4
```
Explanation:
```
: Implicit: z = input(); Q=eval(input())
# : Loop until an exception is thrown
Vvw ) : for N in range(eval(input()))
=z : assign to z
+tz : the sum of the tail of z and
*@Q%NlQ : Q[N%len(Q)] times
shz : the numeric value of the first character in z
zq : print z then throw exception
```
---
## Python 2 - 61 ~~67 91 105 124~~
```
c=lambda p,w,g:g*w and c(p[1:]+p[:1],w[1:]+w[0]*p[0],g-1)or w
```
Pretty Joe-Basic answer. Assumes the empty production is `[[]]`.
Thanks to @xnor, for pointing out that golfing at 2 a.m. is a poor decision.
Additional thanks to @xnor, to whom I seem to owe 50% of my score.
Sample:
```
>>> c([[0,1,0],[0,0,0],[1,1,1,1]],[1,1,0,0,1],4)
[1, 0, 1, 0, 0, 0, 0]
```
[Answer]
# Javascript ES6 - 88 bytes
```
f=(p,w,g,n)=>g?w.replace(/(.)(.*)/,(_,a,b)=>f(p,a*1?b+p[(n=n||0)%p.length]:b,g-1,n+1)):w
```
Looks eerily similar to Fry's answer which just popped up in my browser. (No copying, I do solemnly swear.)
It would appear he went the array route while I went the string/regex route, however.
### Expanded:
```
f = (p,w,g,n) =>
g ?
w.replace( /(.)(.*)/, (_,a,b) =>
f( p, a*1 ? b + p[(n=n||0)%p.length] : b, g-1, n+1 )
)
:
w
```
### Sample Output
```
f(['010','000','1111'],'11001',4)
"1010000"
```
Now watch the golf languages come in and massacre both of us. :D
] |
[Question]
[
# Flavour text
The stack-based esolang [Underload](http://esolangs.org/wiki/Underload) has some interesting ties to functional programming. One of them is its treatment of the numerical datatype—like the lambda calculus, you represent the natural number N by a function which perform an action N times.
To make things simple, we will only consider only the following subset of Underload commands:
* `:` - This command duplicates the top item on the stack.
* `*` - This command concatenates the top two items on the stack into a single item.
We define an *Underload numeral N* as a string of `:` and `*` which, when executed, consume the top item on the stack, and produce N copies of that item concatenated together. Some examples:
* There are no Underload numerals 0, -1, 1/2, π.
* The empty string is the Underload numeral 1, because it leaves the stack untouched.
* `:*` is the Underload numeral 2, because it duplicates the top item, and then concatenates those two copies together into a single item: `(A):*` = `(A)(A)*` = `(AA)`.
* `::**` is the Underload numeral 3: `(A)::**` = `(A)(A):**` = `(A)(AA)*` =
`(AAA)`.
* `:::***` is the Underload numeral 4.
* `:*:*` is also the Underload numeral 4: `(A):*:*` = `(AA):*` = `(AA)(AA)*` = `(AAAA)`.
In general, you will find that, if `M` and `N` are the Underload numerals M and N, then `:N*` is the numeral N+1, and `MN` is the numeral M×N.
# The challenge
Your task is to write the shortest program (taking input on STDIN) or function (taking input via argument) which produces the **shortest representation of the Underload numeral for its input** as a string. That is to say, if the input is a positive natural number N > 1, you must produce an Underload numeral N whose length in characters is less than or equal to that of every other Underload numeral N.
Sample inputs and outputs: ("Input - `OUTPUT`.")
* 1 - .
* 2 - `:*`.
* 5 - `::*:**` (2×2+1).
* 7 - `::*::***` (2×3+1) or `:::**:**` (3×2+1).
* 33 - `::*:*:*:*:**` (2×2×2×2×2+1).
* 49 - `::*:*:*:*::***` (16×3+1, length 14) but not `::*::***::*::***` (7×7, length 16).
If the input is not a positive natural number, you are free to return an error, produce undefined behaviour, or even fail to terminate. An explanation of your submission's method of finding the answer is appreciated.
Standard loophole restrictions apply: no extra input, no web requests, output/return value must be exactly the answer and not an infinite random stream of `:` and `*`, etc.
[Answer]
## GolfScript (61 60 55 54 53 chars)
```
~:X'']({:A{.'.+'\*A{2$+}%~}%}*{,}${1\~X=}?{44/'*:'=}%
```
This is less tricky than my earlier version and takes a slightly different approach, but it's still brute force. We know that `':'X*'*'X*+` is a candidate solution, so if we generate all well-balanced strings up to that length and take the shortest one which evaluates to the right thing we can be certain to find one.
```
# Evaluate input and store the target number in X
~:X
# Seed the generator with the empty string
'']
# X times...
({
# Store the array of strings so far into A
:A
# Generate A' by mapping each element
{
# Dup: this leaves an untouched copy of the current string
.
# Wrap the duplicate in .+
'.+'\*
# For each element in A, generate that element suffixed with the current string
A{2$+}%~
}%
}*
# Order by length
{,}$
# Find the first element which evaluates to X
{1\~X=}?
# tr .+ :*
{44/'*:'=}%
```
Thanks to Howard, from whose solution I've stolen a couple of 1-char tweaks.
[Answer]
## GolfScript (54 53 chars)
This is an approach which is in the spirit of Howard's (build strings which evaluate to the correct value and select the shortest, rather than brute force through candidate strings to find those which evaluate to the correct value), but is sufficiently different that I think it belongs in a separate answer.
```
~.''':*':s@,{):x,2>{:^~$x^/~$+{s\*}x^%*}%{,}$0=}/]((=
```
Online demo not available because it runs a buggy version of the interpreter.
```
# Let <N> denote the string which evaluates to N
# We want to enter the main loop with three values on the stack: <0> <1> <2>
# However, we'll never use <0>, so we can actually replace that with any value at all.
# Getting the input from underneath 3 items would normally use two stack manipulations.
# Trick: let's use the input value for <0>! (This gives a further bonus later).
# NB We store the value of <2> in the variable s
~.''':*':s@
# for x=1 to input_value ...
,{):x
# for ^=2 to x-1 ...
,2>{:^
# Use negative stack offsets to index the stack from the start
# I.e. -1$ gets the first item on the stack, which is <0>
# -2$ gets the second item on the stack, which is <1>
# In general, val~$ gets <val>
~$x^/~$+
# We have the string <^><x / ^> on the stack.
# Increment it (x % ^) times to get a candidate <x>.
{s\*}x^%*
}%
# Select a shortest string.
{,}$0=
}/
# Group the stack into one array and select the appropriate offset,
# reusing that hacky <0> substitute for the offset.
]((=
```
[Answer]
# Python 2.7 - 87 84 92
```
u=lambda n:n>1and min([u(i)+u(n/i)for i in range(2,n)if n%i<1]+[':'+u(n-1)+'*'],key=len)or''
```
**Explanation:**
This is a pretty straightforward solution. It recursively tests all possible representations of n as either the product of two numbers or as `:(n-1)*`, and then finds the minimum length solution. range(2,n) is necessary so that the recursion has bounded depth, and n<2 gives the base case.
**Notes:**
i and n/i are the two factors of n. The ... and ... or ... replacement for ... if ... else ... doesn't work because '' evaluates to false. min of strings gives one of the shortest strings. Python 2.7 saves 1 character by using / instead of //.
Edit: Moved the base case to the back of the expression, allowing me to use ... and ... or ... and shave a couple spaces.
**Test cases:**
```
u(1)
''
u(5)
'::*:**'
u(49)
'::*:*:*:*::***'
```
[Answer]
### GolfScript, 63 58 56 characters
```
~n./\{:v~[':*'1$*v,,2>{v,\%!},{.v=v,@/v=+}/]{,}$0=]}*-2=
```
The code takes input on STDIN and prints the result.
Examples:
```
> 49
:::**:*:*:*:**
> 1234
::::*:*:*:**:*:*:**::**::***
```
You can test your own cases [online](http://golfscript.apphb.com/?c=OyI0OSIKCn4nJy5dKHs6dlsnOiondi4sOngoPSp4LDI%2Be3hcJSF9LHsudj14QC92PSt9L117LH0kMTwrfSotMj0K&run=true).
[Answer]
# [Brachylog 2](https://github.com/JCumin/Brachylog), 30 (maybe eventually 26) bytes, language postdates challenge
Here's a function which works with the current Brachylog 2 implementation (and returns a list of character codes because the current implementation is having some issues with string handling):
```
∧.l∧?{ḋp~c×ᵐ{-₁↰₁:[42,58]c↻}ᵐc}
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oY7leDpCwr364o7ugLvnw9IdbJ1TrPmpqfNS2AUhaRZsY6ZhaxCY/attdC5RKrv3//38UAA "Brachylog – TIO Nexus")
The language is still very new. Here's a **26 byte** version of the program that should work according to the specification, but uses some unimplemented features, and thus isn't valid yet, but maybe will be in future (it's also even less efficient):
```
{ḋp~c×ᵐ{-₁↰₁:"*:"c↻}ᵐc}ᶠlᵒh
```
## Explanation
```
∧.l∧?{ḋp~c×ᵐ{-₁↰₁:[42,58]c↻}ᵐc}
∧.l∧? Evaluation hint: try shortest outputs first
{ } Define an inner function
ḋ Prime factor decomposition of the input
p Find a permutation
~c Find an inverse concatenation (i.e. partition)
×ᵐ Take the product of each set inside the partition
ḋp~c×ᵐ Find a decomposition into factors ≥ 2
{ }ᵐ For each of those factors:
-₁ Decrement it
↰₁ Call the inner function recursively
:[42,58]c Append "*:" (as character codes)
↻ Move the last element to the start
c Append the results together
```
The basic idea is fairly simple: we alternate between decomposing the number into (1 or more) factors (not necessarily prime factors, but factors of 1 are not allowed), and expressing each of those as 1 + (a representation obtained from a recursive call). This is guaranteed to search all possible Underload representations of the number (we can apply a multiplication stage "twice in a row" by multiplying together more than 2 numbers, and an increment stage twice in a row via separating them with a multiplication stage that multiplies together just one number). We don't need an explicit base case, because decomposing 1 into prime factors gives us an empty list, and thus we construct it with a multiplication stage that multiplies zero numbers together.
The program is fairly inefficient, especially because the evaluation order hint I gave (generate answers shortest to longest in terms of the size of the eventual output), while solving the "shortest" part of the question, isn't that great in terms of actually making the program complete quickly (a much more *useful* hint would be "generate only the shortest answer at each recursive stage", but that takes more bytes…). Additionally, `ḋp~c×ᵐ` can generate multiplicative partitions several times each, making the program do a lot of redundant work.
[Answer]
# J - 81 char
For posterity, this was the best that I could do in J.
```
_2{::(0&(][,0{<@;"1@({~#(#~]-:"1<.)@(],.%)2}.i.@#)(/:#&>)@,':'<@,'*',~>@{:),~)&a:
```
We create a list of results, beginning with two empty strings (that's the `,~` and `a:`) representing 0 (never used) and 1, and then iterate a verb over them (sneaky use of hooks, trains and `&`) that appends the next number's shortest representation.
The actual verb that we iterate uses the length of the list as an indicator of what number we are operating on. First, we factor this number into pairs of factors (`#(#~]-:"1<.)@(],.%)2}.i.@#`), and retrieve each pair by pulling from the array (`{~`). We turn each of those pairs (there could be 0 of them if the number is prime) into single strings (`<@;"1`).
Then we append to that list the entry for the previous result bracketed by `:` and `*`, and sort this list by length (`(/:#&>)`). Finally, we take the first result from this list (`0{`) and append that to the end of the base array (`[,`). When the loop is done iterating, we have a list of length 2 more than the input, starting at 0. So what we have to return is the next-to-last string (`_2{::`).
```
un =: _2{::(0&(][,0{<@;"1@({~#(#~]-:"1<.)@(],.%)2}.i.@#)(/:#&>)@,':'<@,'*',~>@{:),~)&a:
un 49
::*:*:*:*::***
un 1234
:*::*:*:*::*::***::*::*:****
un 10010
:*::*:*::***::*:*:*:*:*:*:*::***
2 * (1 + 3 * 2^2) * (1 + 3 * 2^7)
10010
6!:2 'un 10010' NB. time in seconds
19.5539
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes, language postdates challenge
```
ÆḌḊµ⁹÷Ñ;Ñð€
’ß”:;;”*W;ÇLÞḢµ“”>1$?
```
[Try it online!](https://tio.run/nexus/jelly#@3@47eGOnoc7ug5tfdS48/D2wxOtD088vOFR0xquRw0zD89/1DDXytoaSGqFWx9u9zk87@GORUClDXOAQnaGKvb///83NgYA "Jelly – TIO Nexus")
A straightforward brute force solution.
## Explanation
### Main program
```
’ß”:;;”*W;ÇLÞḢµ“”>1$?
µ >1$? If input is greater than 1, then:
’ß Run recursively on the input - 1
”:; Prepend a colon
;”* Append an asterisk
W; Cons to:
Ç the result of the helper, on {the original input}
LÞ Sort by length
Ḣ Take the first (i.e. shortest) result
“” Otherwise, return an empty string
```
The main program uses the helper function to enumerate all possible ways to produce the value via multiplication, then tries producing the value by addition, and returns the shortest possibility. It also handles the base case (an input of `1`).
### Helper function
```
ÆḌḊµ⁹÷Ñ;Ñð€
ÆḌ µ ð€ For all proper factors of the input
Ḋ except the first (i.e. 1):
⁹÷ Divide it into the input;
Ñ Run the main program on it;
; Append the result of:
Ñ the main program run on {the factor}
```
The helper function tries all possible methods of expressing the input as a multiplication of two numbers, and mutual-recursively calls the main program in order to get at their shortest representations.
[Answer]
# GNU Prolog, 96 bytes
```
v(N)-->{N#=1};{N#=A*B,A#<B,B#<N},v(A),v(B);{N#=M+1},":",v(M),"*".
s(N,S):-length(S,_),v(N,S,[]).
```
The first line is a grammar that implements Underload evaluation, and works in the reverse direction (actually, it doesn't quite work in the forward direction due to the `A#<B` constraint; change this to `A#<N` for a slower program that works both ways round). The second line defines the function-like predicate `s` (which is the function that's implemented as a solution to this program) which finds the shortest possible string which evaluates to the number given as input (this is frustratingly verbose for what's a relatively simple task, but that's Prolog for you…).
The program should be pretty self-explanatory, given that it's more or less a direct translation of the specification to a grammar, and then to Prolog syntax; the definition of `v` says that `N` is 1 in an empty string, or `N` is `A` × `B` (with `A` less than `B` less than `N`) and the string is the concatenation of `v(A)` and `v(B)`, or `N` is `M` + 1 and the string is `:` concatenated with `v(M)` concatenated with `*`. The second line is a bit subtler; `length(S,_)` means "S has some length", but specifying this as the first thing on the line acts as a hint to the Prolog implementation that it should check the shortest lengths first (which means we'll get the shortest possible length for a return value).
] |
[Question]
[
I'd like to introduce a new? programming language I call Shue (Simplified Thue). It has very simple syntax.
Here is a program that checks if an input is divisible by three:
```
yes
no
3=0
4=1
5=2
6=0
7=1
8=2
9=0
00=0
01=1
02=2
10=1
11=2
12=0
20=2
21=0
22=1
0=yes
1=no
2=no
```
[Try it online!](https://tio.run/##lVVNj5swEL3zKyxOdpNSTHb7gYR62j1V2h6qXpK0cmCSWAIb2bDbaDe/PR2bkCXsptpyIPPx/Dwzfib1rtlqNTvIqtamIQamxO5sYICTDL0o11UtS6BmFVI6/5UtnxaLjL1jNBt6X0MWBAWsSavA5qIGKlkaEHwMNEi0CkPvYRK92NtrbUhOpCKyQ7pHrj1EqAJTmVu3WITP6SPh5Jg4iw@pvV@@JMsucGX/T6UulaXexjVaLaQF8lOULdwYow1dh9@FsWAIODclG92QfCuMyBsMPuZ7ItbOwimwc@5Lc@sK4QOwhVdb2DVg6Txfdrzjat9U6c3dtw83d7fjGnGD1ij3E3Rqqd3Kk1QQW0klGm0sVmqhocdlbQnnkVIqH5GRrUvZUD92dlJV6VTlMc91V17OPKpEk29pyYaSq6KN0W1NZ2w0ELfxU0Ye6UnWPZQzNiUvojM25@mSsf0/pjzo0lG/xrwfTmuAn3YVdbODP5C3DdB8SoYD7EHYbjfdvGu1VfIe0Mf4o@w2qHSB3g/TgncftnjPXXAwNI@4FdjEKabg4feA7PlQ@ulbN/0ecd47ztpnfaHpsUH71tUuLaYrB/Atnmd7hPZ5oTZAS1DUsglnL5F9NXOd6onDCbZ0F0e8Dh037k7OzlO9nKwmyHFkSJf7i6tHwx4dyZA7uHTNjN4YUfX3TGlUSF2KHCpQjSXCAKm1tXKFp4iCRY3gDSjICrbiXurWMPeNDnJd4Ib4PQ4PO5SS0sEsi4OrjAfXWRJ8RPsT2p/R/oJ2HLsXx0icYIjHaHHurAQTSYxWwp2VOEjmGHmGnAm@DrgHXof3fBkEUtVOKzsb2aaQKjIgCsoiUK4c1A/@3zjFnjSNUZS1qllQG6kaiumogA7MDvwquZ79BQ "Python 3 – Try It Online")
At the top we can see two lines. These are the output strings, "yes" and "no".
Next are the replacement rules. Let's look at `3=0`. This means that whenever we see a `3` we can replace it by `0` (but not the other way round). `12=0` means that the string `12` can be replaced with the string `0`.
Then these replacements are performed non-deterministically on the input string until we reach an output state.
For example, if we have the input `14253`, it can be reduced to an output state like so:
```
14253
11253 - 4=1
11223 - 5=2
2223 - 11=2
2220 - 3=0
210 - 22=1
00 - 21=0
0 - 00=0
yes - 0=yes
```
Here the answer is `yes`, and it's pretty easy to prove that `yes` is the only output state reachable using these rules and this input. This means that the program is well-defined. A program is well-defined if there is at most one output state reachable for every input.
That's it! There are basically no other rules or syntax. There is no way to restrict where or when a substring is replaced (as long as it's possible it will happen). There are no special characters or patterns that match the start or end of the string. Shue is Turing-complete, but only capable of having a finite output set. If the syntax or execution of a Shue program is not completely clear, there are more formal and more precise rules later.
Here are some possibly useful example programs:
### Recognize the string "a"\*x+"b"\*x
```
yes
no
=|
a|b=|
|=yes
=L
=R
a|R=|R
L|b=L|
a|R=no
L|b=no
ba=#
#a=#
#b=#
a#=#
b#=#
#=no
```
[Try it online!](https://tio.run/##lVXBjpswEL37KyxysZuUFu0NCfW0e4q01arqJaGVgUliCWxkw26jJd@ejk1ICLupthwcZub5eWb8htT7ZqfV3VFWtTYNNbCgdm@JgYgmaIW5rmpZAjNZwNjqV5J263XCP3GWjK1vASekgA1tFdhc1MAkjwnFx0CDRFkQeAuDaH317xttaE6lorJHukduPESoAkOJ27deB5fwiXB@Clz5x9TeLt@SJTe4kv@nUrfSUh/jmuwW0gL9KcoW7o3Rhm2C78JYMBScGdOtbmi@E0bkDTpf8wMVG/eGXeDX3Lf61icSjcAW3i1h34BlqzzteafZfijT@8fll/vHh2mOeEBrlPshvVpqt/MsFcRWUolGG4uZWmjYaVtbwrWnlMp7ZGjrUjbMt52fVVU6VXnMJe/KyzkKK9HkO1byseSqcGt0W7M7PmmIO7hL6Cs7y3qARpwv6BvvHV9Fccr54R9dHlXpqN9jPoy7NcIv@oz63sEfyNsGWL6g4wYOICy3727el9oq@Qxoo/9V9gdUukDrh2nBmy87nHPnHDXNIx4EFnH2KXj5PSK7XMrQfeu6PyCua8de@6hPND4VaD@624XFInMAX@J1dEBoHxdqC6wExSyfR/wtcshmpWM9dzjBUzc44n3otHB3c3YV63SezZHjxBCnh5u7J82eXMmYm9waM6O3RlTDnCmNCqlLkUMFqrFUGKC1tlZmeIsoWNQITkBBM9iJZ6lbw903muS6wAPxexwc9yglpUnSEdFluHaJ8yRLkjyh5ynpnsgSA8vOW4h0Fv5kIpmRmV8yXMQMl8wtM4wekRmH4HOUEiJV7RSyt6FtCqlCA6JgPATlkkDV4L@M0@lZyehFMauak9pI1TAMhwX0YH4UQmRZ9hc "Python 3 – Try It Online")
### Semi-recognize the string "a"\*x+"b"\*y+"c"\*(x+y)
```
yes
=|
=!
a|=|b
b!c=!
|!=yes
```
[Try it online!](https://tio.run/##lVXBjpswEL3zFV5OdpPSor0hoZ6yp0rbQ9VLQitjJoklsJFtdhsl@fZ0bEKWsJvVlkuYmefnmedn0u7cVqv7k2xabRwxMCd2ZyMDKckxSoRuWlkDNWVM6fJ3XhxWq5x9YjQfR99iFkUVrEmnwAreApUsiwg@BhwSlXEcIixi9DW8r7UhgkhFZI/0j1wHCFcVlnK/brWKX8pnwtm5cJUfU4e4fk2W3@DK/59K3WpLfYxrsppLC@QXrztYGKMNXcc/uLFgCPgwIxvtiNhyw4XD5F4cCV/7N1SBXXPf0q1vJB2BLbw5ws6BpUtR9LzTbj/U6eLx@5fF48O0R9ygM8r/RL1bWr/yYhXENlJxp43FTi04el7W1XCdqaUKGZnYtpaOBtnZxVW1d1XAvPTdBDunScOd2NKajS3XJBuju5bes4kgfuNDTvb0YusBmjI2J6@y92yZZgVjx3dUHk3pqd9iPo7VGuHnfUe9dvAXROeAijkZCziAcNxeXdGP2in5BBhjfi/7DRpdYfTTdBDC5y3ec58ciRYQDxyHuOQUPP8Zkb0cyqC@9eoPiOvZUetQDY1m5wHtR1f7Mp@XHhBGvK4OCB3qXG2A1qCoZbOUvUYO3Sx1pmcex1nhLw5/Gzod3J@cXWa6mJUz5DgzZMXx5uqJ2JMjGXNHt66Z0RvDm@GeKY0OaWsuoAHlLOEGSKutlSWeIhoWPYI3oCIlbPmT1J1h/hsdCV3hhvg9jk87tFJ@iPK7iB/yQxmVdwLfD3c5Fk4IQC9/Tosokqr1B72ziXWVVIkBXlGWgPJcePj4Z@HtdjEkZtGTqmVRa6RyFMtJBT2YnXgpxD8 "Python 3 – Try It Online")
### Recognize the string "a"\*x+"b"\*y+"c"\*(x+y)
```
yes
no
=|
=!
a|=|b
b!c=!
|!=yes
b!=!B
BB=B
|!c=C|!
CC=C
C|!=no
|!B=no
ba=#
ca=#
cb=#
#a=#
#b=#
#c=#
a#=#
b#=#
c#=#
#=no
```
[Try it online!](https://tio.run/##lVXBjtowEL37Kwxc7ELTor1FsiqBdk@VtoeqF6CV4wxgKbEjO9kWbfh2OnaADexSbXMwnpk3zzOT51Dt6q01dwddVtbV1MGE@p0nDqZUoJUoW1a6AOayIWOLn2LVLpeCf@BM9K0vQ05IDmvaGPBKVsA0TwnFx0GNRNlwGC0MovU57tfWUUW1obpDhkevI0SaHEMi5C2Xw5fwkXB8DFz4@9TRLl6TiRtc4v@pzK2yzPu4rrKl9kB/yKKBe@esY@vhN@k8OArBTOnG1lRtpZOqRuez2lO5DjucAr/kvjW3rpBpD@zhzRZ2NXi2UKuO97rad1V6//j10/3jw3WNeEDjTPghnVqqkHmWCmJLbWRtncdKPdTsmNYUcOkptIkenfiq0DWLY@dnVRVBVRHzUncZ5TxNSlmrLSt4X3JlsnG2qdgdvxpIOLgV9JmdZX2CTjmf0FfeO76YpivO9/@Ycq/LQP0W874/rR5@0lXUzQ7@gGpqYGpC@wM8gbDdbrqqa7Ux@gnQRv@z7g4obY7Wd9dANH9v8Z4HZ29oEfEgsYmzz8DvXz2yl5dymr4P0z8hLnvHWcdoLDQ9Nujfmx3CcpIFQGzxMnpC2BiXZgOsAMM8H0/5a@SpmoVN7TjgJF@FiyPfhl43Ht6cX6R2Nc7GyHFkSFf7m9lXw756JX1ucuuaObtxsjzdM2NRIVUhFZRgak@lA1pZ73WGbxEFixrBG5DTDLbySdvG8fCNJsrmeCB@j4eHHUrJWCJaIgZEtqLNSDZQuG8HIsSygRjMyGwmZuhRYt4OyHwu5gQ3AvPawSz8ZFKMiIpLhsso7EZxp3CRI1yysKiwjDDjgGfjNfk4XRGiTRU0tPOJr3NtEgcyZzwBE8pEXeH/UFDyWevoRbmbipPKaVMzDCc5dGB@kJlSfwE "Python 3 – Try It Online")
### Semi-recognize the string "a"\*x+"b"\*x+"c"\*x
```
yes
=|
=!
a|b=|>
>b=b>
>!c=!
|!=yes
```
[Try it online!](https://tio.run/##lVWxbtswEN31FYwmsnbVCtkEKJ2SqUA6FF1staCos01AIgWSSmrE/nb3SFm2rMRB6sHW3T0@3j0@yu3WbbS6Pcim1cYRA3NitzYykJIco0ToppU1UFPGlC5@58VuuczZJ0bzcfQtZlFUwYp0CqzgLVDJsojgx4BDojKOQ4RFjL6G55U2RBCpiOyR/iNXAcJVhaXcr1su43P5SDg7Fi7yY@oQ16/J8itc@f9TqWttqY9xTVZzaYH84nUH98ZoQ1fxD24sGAI@zMhaOyI23HDhMPki9oSv/BOqwC65r@nWN5KOwBbeHGHrwNKFKHreabcf6vT@8fuX@8eHaY@4QWeU/4l6t7R@5ckqiG2k4k4bi51acPS4rKvhMlNLFTIysW0tHQ2ys5Orau@qgDn33QQ7p0nDndjQmo0t1yRro7uW3rKJIH7jXU5e6MnWAzRlbE5eZW/ZIs0KxvbvqDya0lO/xbwfqzXCz/uOeu3gL4jOARVzMhZwAOG4vbqiH7VT8gkwxvyL7DdodIXRT9NBCJ83eM99ciRaQDxwHOKUU/D8Z0R2PpRBfevVHxCXs6PWoRoazY4D2o@u9mU@Lz0gjHhZHRA61LlaA61BUctmKXuNHLpZ6EzPPI6zwl8c/jZ0Org/ObvIdDErZ8hxZMiK/dXVE7EnRzLmjq5dM6PXhjfDPVMaHdLWXEADylnCDZBWWytLPEU0LHoEb0BFStjwJ6k7w/w7OhK6wg3xfRwftmilfBflNxHflfnuLror8xK/bwSmdjc51g@IQ0t/Tosokqr15721iXWVVIkBXlGWgPKU6AH8z/CuO/kSs2hN1bKoNVI5iuWkgh7MDrwU/wA "Python 3 – Try It Online")
## Exact definition of Shue
The source code is interpreted as a list of bytes. The only characters with special meaning are the newline, the equals sign and the backslash. `\n` corresponds to a literal newline, `\=` to a literal equals sign and `\\` to a literal backslash. Any other use of `\` is an error. Every line must contain 0 or 1 unescaped equals signs.
Or in other words, to be syntactically valid, the program has to match the following regex: `/([^\n=\\]|\\=|\\n|\\\\)*(=([^\n=\\]|\\=|\\n|\\\\)*)?(\n([^\n=\\]|\\=|\\n|\\\\)*(=([^\n=\\]|\\=|\\n|\\\\)*)?)*/`
Here is the mathematical definition of a Shue program:
A Shue program is a set of terminator strings \$T\_e\$, and a set of transformation rules \$T\_r\$, which are pairs of strings.
The execution of a Shue program on a input string \$i\$ is defined as follows. Let \$U\$ be the minimal set, so that \$i\in U\$ and \$\forall a,x,y,b: axb \in U \land (x,y) \in T\_r \rightarrow ayb \in U\$. Let \$S=U\cap T\_e\$.
If \$S=\{x\}\$, then the program will terminate, and \$x\$ will be printed to stdout.
If \$S=\emptyset\$ and \$|U|=\aleph\_0\$, then the program will enter an infinite loop.
In all other cases, the behavior is undefined (yes, Shue isn't memory safe).
## A compiler
Speaking of not being memory safe, here is the [Optimizing Shue Transpiler (osht) version 0.0.2](https://pastebin.com/XpZZiUCx). This is a python program that transpiles a Shue program to C. I wouldn't recommend reading the source code (it even contains some debug prints). But the binaries produced are faster than the interpreter, and *seem* to work just fine with most inputs.
## The actual challenge
Your task is to make a program that checks if a unary input (string matching regex /1\*/) is prime in this programming language. That is, is the length of the input string a prime. You must have two output states, one for yes and the other one for no. Shortest code wins.
## Test cases (You can use other strings for yes and no)
```
"" -> "no"
"1" -> "no"
"11" -> "yes"
"111" -> "yes"
"1111" -> "no"
"11111" -> "yes"
```
[Answer]
# Shue, ~~533~~ ~~218~~ ~~208~~ 204 bytes
My original solution was very Turing machine-esque, so here is an improved solution. Unfortunately this solution is difficult to simulate as it's very highly nondeterministic, so there is no TIO link available.
The semi-Thue outputs and productions appear with comments below. Byte count is exclusive of comments.
```
// [x] is the count of character x.
// Output states: (> prime, (} not prime.
(>
(}
// Start.
=[
=)
// Special cases: 0, 1 not prime.
[)=(}
[1)=(}
// 1. L->R: [a] := [1] - 1.
[1=(1B
B1=a1B
// Move as right of 1s.
a1=1a
// 2. Start of a loop where [a] decreases,
// and we have checked all divisors between [1] - 1
// and [a] + 1.
// Prime exit: succeed if [a] == 1.
aB)=>
1>=>
// 3. Begin to check [a].
// R->L: [b] := x, 0 <= x < [a]; change ) to ] at right if x = 0.
aB)=Cab)
aB)=Da]
aC=Cab
aC=Da
aD=Da
// Move as right of bs.
ab=ba
// 4. R->L: We add [1] ds and y cs, where 0 <= y <= [1] - 1.
// The cs are allowed to move freely to the right, and add one b
// when they pass right of an a; they may vanish at the right end.
// Also, ds move right of 1s, and ds and bs may annihilate each other.
// Overall, the effect is that there is an invariant
// I := [b] - [d] + sum_{each c present} [a to the right of the c]
// = x + y [a] - [1].
1D=Ed1
1E=Ecd1
1E=Ed1
cd=dc
c1=1c
ca=abc
cb=bc
c]=]
c)=)
d1=1d
db=
// 5. L->R: Move right without passing bs, cs and ds.
// We can only reach the right end if I = 0, i.e., [1] = x + y [a].
(E=(F
F1=1F
Fa=aF
// 6. Composite exit: If ] is at the right, then x = 0, so [1] = y [a] is composite.
F]=}
a}=}
1}=}
// 7. If there is ) at the right, then [1] = x + y [a] with 0 < x < [a],
// so [1] is not divisible by [a]. Decrement [a] and return to step 2.
Fa)=B)
```
[Answer]
# 136 bytes
```
P!
C!
=C!
1=C!
=P
11=nq!
qn=nq
rn=nr
r1=1r
1n=r
n1=r
P=P;
;1=1;
;n=.
.n=n.
.r=1.
.q=q.
.!=q!
;r=n,
,q=nq,
,r=r,
,!=!
Pq=P
P1=C
Cq=C
C1=C
```
### Explanation
It implements this primality-testing algorithm (for \$x\ge 2\$):
```
def isprime(x):
# r+s+1 is the current divisor (starts at x-1 and counts down)
# q and r are the quotient and remainder of the division
# n is the unprocessed part of x
n, q, r, s = 1, 1, 0, x-2
while True:
assert (r + s + 1) * q + r + n == x
if n and s: # (1) decrement n, increment remainder
n, r, s = n-1, r+1, s-1
elif n: # (2) clear remainder, increment quotient
n, q, r, s = n-1, q+1, 0, r
elif r: # (3) decrement divisor
n, r = q+1, r-1
else: # prime iff the first divisor was 1
return s == 0
```
The values of \$n\$, \$q\$, \$r\$, \$s\$ are stored as the number of `n`, `q`, `r`, `1` [sic] characters in the string.
`=C!`, `1=C!`, `=P`, `11=nq!` are scary angelic nondeterminism rules that handle the 0 and 1 special cases, and convert a longer string like `11111` to `P111nq!`. See below for a proof that they do nothing else.
`qn=nq`, `rn=nr`, `r1=1r` bubble sort the variables into the order `[1n]rq`.
`1n=r`, `n1=r` implement transition (1).
`P=P;`, `;1=1;` start a left-to-right update pass that will implement transition (2) or (3).
`;n=.`, `.n=n.`, `.r=1.`, `.q=q.`, `.!=q!` implement transition (2).
`;r=n,`, `,q=nq,`, `,r=r,`, `,!=!` implement transition (3).
`Pq=P`, `P1=C`, `Cq=C`, `C1=C` run when \$n=r=0\$, and turn the string into `C!` if it contains any `1`s and `P!` otherwise.
### "Proof" that it works
There is a clear path from any input to the correct final state. I've verified that it works in a simulator if you always apply the earliest applicable rule at the leftmost position, except that the first four rules are handled specially and `P=P;` is moved to just above `Pq=P` and chosen only if there is a `n` or `r` in the string.
Proving that there is no path to the incorrect final state is harder, but I'll attempt it and handwave some parts.
The first four rules: All other rules conserve the number of `PC` and `!` characters, so unless the first or second rule is used exactly once, or the third and fourth rules once each, the string will never evolve to either of the two terminal states. There are no rules that can delete all the characters left of `P` or `C` or right of `!`, so if `C!` is added here, it must be the whole string, and if `P` and `!` are added they must be at the ends.
The final four rules: All other rules keep all `q`s to the right of all `r`s and `1`s, so if `Pq=P` matches, there must be only `q` and `n` and punctuation to the right of it. If there are any `n`s, it will get stuck, so `Pq=P` can only lead to a final state if \$n=r=s=0\$ after any ongoing updates complete, i.e., if the number is prime. The other three teardown rules delete the only `P`, which halts updates. So they can't violate the invariants of the main algorithm while it's still running; they can stop it early, but they'll just get stuck unless \$n=r=0\$.
The middle rules: It's tricky to define invariants that are preserved by each individual rule while there are arbitrarily many rolling updates in progress, but the updates as a whole preserve the invariants of the primality-testing algorithm. These rules seem safe and well behaved to me compared to the first and last four which violate the invariants, so I'm going to handwave it and say they're fine.
---
### An interesting no-go result that I found while writing this
**Theorem:** A Shue program that solves this challenge can't be a POSIX-compliant text file.
**Proof:** POSIX requires nonempty text files to end with a newline. Per the Shue spec, that means that ϵ is a valid output state. It is also a valid input state which must be judged composite, so ϵ must mean composite. `1` must also be judged composite, so there must be a path by which `1` evolves into ϵ. Therefore, there is a path by which any unary input evolves into ϵ.
So my program contains no final newline not merely to save bytes, but because it would be incorrect otherwise.
] |
[Question]
[
## Background
Related: [a golflang theory I posted in TNB a while ago](https://chat.stackexchange.com/transcript/240?m=58722627#58722627)
**At-most-\$n\$-ary trees** are rooted trees where each internal node has between 1 and \$n\$ children (inclusive). Two trees are considered identical only if the shapes exactly match without re-ordering each node's children. In other words, the left-to-right order of children matters.
For example, the following is an example of an at-most-ternary tree (each node is marked with its out-degree, the leaves being zeros):
```
2
/ \
1 2
| / \
3 0 1
/|\ |
0 0 0 0
```
Related OEIS sequences: [A006318](https://oeis.org/A006318) is the number of at-most-binary trees having \$n\$ internal nodes, and [A107708](https://oeis.org/A107708) is for at-most-ternary trees.
Note that a single-node tree is a valid at-most-\$n\$-ary tree for any value of \$n\$, since it has no internal nodes.
## Challenge
Write a function or program that, given a positive integer \$n\$ (1st input), maps a natural number (2nd input) to a unique at-most-\$n\$-ary tree. It must be a bijection; every tree must have a unique natural number that maps to the tree. Only the code going from a number to a tree is considered for scoring, but it is recommended to provide the opposite side to demonstrate that it is indeed a bijection.
The output format for the tree is flexible (nested arrays, string/flat array representations including parentheses or prefix notation). You can also choose the "natural number" to start at 0 or 1.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 107 bytes
```
def f(n,x):
def g(m):r=y[0]%m;y[0]//=m;return[g(n+1)for i in y*r]
y=[x-1];return x and g(n)+[f(n,*y)]or[]
```
[Try it online!](https://tio.run/##LYzLCsMgEADv@Yq9FNwkJbX2meCXiIdCYpqDa1gs6NfbCj0NA8PsOb4DqVLmxYET1CccG6iyCo8j62xO9uCnimHQfuIlfpjMKqiT6ALDBhtBbtk2kLVJR2n/DSR40fz7EHamrtuMNrCxZeeNonBC9fB83G/XizpLxPIF "Python 3 – Try It Online")
Naturals start at 0. Inverse map:
```
def g(n,t):
x=0;y=1;q=t,
while q:*q,u=q;x+=len(u)*y;y*=n+bool(q);q+=u[::-1]
return x
```
[Try it online!](https://tio.run/##VUpJCsMgFN17ir90KjRkp/yTBDelNgmIRlGqp7djSvoWb95aXoIfe7/aG8zUy8wUgYpn3XDQEbMkcF9WZyEqHmXBqKtAZz0tjDfdOHpxCcHRyHQUWCalToMhkGwuyUPtW1p9pjMdJUwvmKear9/zZN7th/bDwfxXx/NvYKw/AA "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 32 bytes
```
⁴‘ßƊḢd¥ɼṪ$СḊ
¹©ṛ’ɼ⁴çƊḢɼпḊṚṭƒ“”
```
[Try it online!](https://tio.run/##y0rNyan8//9R45ZHDTMOzz/W9XDHopRDS0/uebhzlcrhCYcWPtzRxXVo56GVD3fOftQw8@QeoMrDy8HKTu4Byu8Hyj/cOevhzrXHJj1qmPOoYe7/hzu2HV5@dNLDnTN0HB417jjV/ahpjTcQR/7/b2hg8N8YAA "Jelly – Try It Online")
A dyadic link taking \$n\$ as the right argument and a natural number as the left argument and returning a nested list.
This uses the same algorithm as [@AndersKaseorg’s Python answer](https://codegolf.stackexchange.com/a/233281/42248) (so be sure to vote that one up too!). However, despite Jelly’s Python base, this was not trivial to translate. The main function was changed from using recursion to a while loop followed by a `reduce`, but a recursive method was preserved for the subsidiary function (`g()` in the Python code).
Full explanation to follow.
[Answer]
# [Python 3](https://docs.python.org/3/), 83 bytes
```
f=lambda n,x:[f(n,int(str(~-x//n)[~i::~(x%n)][::-1]or 0))for i in range(x%n+(x>0))]
```
[Try it online!](https://tio.run/##FYzLDoIwEEV/pRuTNkKYmb6b6I8QFhhFSXQglQVu@PUKOYu7ODdn/i2viXUpw@Xdf273XnC1pnaQXI28yO@S5VavTcOq3caUNrmeWHVtSjV2Uxag1LDPKEYWuefn4/BnuV530ZU5H41BmkpY0t4Y7YE8gg20gxHImagtBnI6GOcQgrEeEEiDjt45sEiRMETYDzY6b4JDUqr8AQ "Python 3 – Try It Online")
0 yields the trivial tree with only one node. Other numbers are broken down into \$ 1 \le k \le n\$ and \$ x' \ge 0\$ using modulo; \$ k\$ is used as the number of children of the root, and the decimal digits of \$ x' \$ are distributed among those children by taking every \$ k \textrm{th} \$ digit starting from different low places, recursively applying the same procedure for each child.
Inverse:
```
import itertools
def invf(n, l):
assert type(n) == int and n > 0 and type(l) == list and len(l) <= n
return 0 if not l else int(''.join(''.join(t) for t in itertools.zip_longest(*[str(invf(n, m))[::-1] for m in l], fillvalue='0'))[::-1]) * n + (len(l) - 1 or n)
```
[Try it online!](https://tio.run/##fZLRboMgFIbvfYpzp3S2abNdmbkXMWYxKW4seDBAm3Qv7xCrAuK4QPB8/@Hn1/6hvwW@DgPreiE1ME2lFoKr5EpbYHhvM8yBkyIBMxqlTBn0o6cZEihLQ2ho8AoIH3C2K1vktsiZmqqc4vjqvQS0fSTVN4lGwFpAoYED5YqOzbI0Pf0IhstTE2iFBOMMV3OnX9Z/coFfVOnsUCkts9lqR0hVFMdLbWXdKON1Di3j/N7wGy3TczojBA7G@AtkT39HuIARIRl6OXqxPd/ypFqG6VTVdnIX4ft5Y@ZnOUYt6mk3If5u5VZwKs@0g6/cAm1A3114UujsHyzwM13Wu8duJts7xdt77qvwSD@GeLKec1fltPVTjscRJFnFw9le1ZFP2j3EMeCAkaCjH3/v39uJdByEDH8 "Python 3 – Try It Online")
] |
[Question]
[
# Cops' thread
In this thread, your task is to make a recursion-based program/function to generate any integer series. Robbers will try and find a shorter non-recursive solution over in the **[Robbers' thread](https://codegolf.stackexchange.com/questions/157398/this-challenge-is-about-recursion-robbers-thread)**.
# Challenge synopsis
In many languages, recursive functions can significantly simplify a programming task. However, the syntax overhead for a proper recursion may limits its usability in code-golf.
The **cops** will create a program or function taking a single integer `n`, which will generate the first `n` entries of an integer series, **using only recursion**1. They should also make sure there is a shorter nonrecursive way to generate the sequence in order to mark their entry as safe.
The **robbers** will try to find a **shorter** program or function in the same language, generating the same integer series, **using no recursion**2.
If the cops' submission is not cracked within ten days (240 hours), the cop will prove it was in fact possible to have a shorter non-recursive approach by revealing their own solution. They may then mark their submission as **safe**.
**The winner of the cops challenge will be the shortest (according to [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")) recursion-based submission marked safe.**
The winner of the robbers challenge will be the robber who cracked the most solutions.
1: It only needs to be recursive in syntax; you don't need to worry about for example tail call optimization.
2: Again, non-recursive in syntax; so you can't post a recursive solution and claim its compiled to a loop thanks to tail call optimization.
# Submission requirements
Each submission will take a single integer `n` (zero- or one-based). The submission will then output or return the first `n` entries of an integer series of choice. (note that this integer series must not depend on `n`). The input and output method may differ between the recursive and non-recursive approach. The integer series may be any deterministic series with a length of at least 5. The series should be explained properly.
Your submission does not have to work for arbitrary large `n`, but should work for at least `n=5`. The non-recursive approach must be able to work up to at least the same `n` as the recursive approach, or up to `n=2^15-1`, whichever is smaller.
# Recursion
For the sake of this challenge, recursion is defined as creating the desired sequence using a **function** (or function-like construct) that **calls itself** (or calls a sequence of functions that ends up calling itself; this includes constructs like the Y combinator). The recursion depth should go to infinity as `n` goes to infinity. The non-recursive approach is anything that is **not** recursive.
[Answer]
# [Python 3](https://docs.python.org/3/), 65 bytes (Safe)
```
f=lambda n,a=3,b=0,c=6,d=6:n*[1]and[a+b]+f(n-1,c,d,2*c+d,2*a+3*b)
```
[Try it online!](https://tio.run/##FcQ7CoAwDADQ3VNk7CeCWnAQchJxSFurBY1SXDx9xTe8@332S1ytiQ4@fWQQZHLoqcNAI0YaJzFzv7DEma1fbFLS9hgw4mCC/WfrjNc1XQUyZIHCsq1q6PTUwF2yPCqprHX9AA "Python 3 – Try It Online")
Another try in Python.
The sequence is "the number of ways to fill a 2-by-n board with dominoes in three colors, so that no two same-colored dominoes touch each other". Not on OEIS.
---
Let's say `n=6`. The board looks like:
```
######
######
```
and these are valid domino tilings in three colors (`1-3` represent a color each):
```
123123 122331 212332 212121 113311
123123 133221 212112 212121 331133
```
but these are not (two same-colored dominoes are touching each other):
```
112323 332333 211113
112323 112311 233223
```
The sequence counts all possible domino tilings that satisfy the rules for each `n`.
---
# Intended solution, 58 bytes
```
n=int(input());a=3;b=12
for _ in[0]*n:print(a);a,b=b,a*4+b
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P882M69EIzOvoLREQ1PTOtHW2DrJ1tCIKy2/SCFeITMv2iBWK8@qoAikKhEor5Nkm6STqGWinfT/v6EBAA "Python 3 – Try It Online")
Unfortunately it looks like no one bothered to simplify the recurrence relation, which was clearly shown in the recursive code. Making a program with the given double recurrence as-is doesn't work since it's Python 3.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 47 bytes, [cracked by l4m2](https://codegolf.stackexchange.com/a/157419/76323)
```
@(n)(f=@(r,m){@()[r(r,m-1),m],[]}{~m+1}())(f,n)
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI09TI83WQaNIJ1ez2kFDM7oIxNQ11NTJjdWJjq2trsvVNqzV0ASq0snT/J@mYWig@R8A "Octave – Try It Online")
As an example, here is an Octave entry which generates the first `n` positive integers, <https://oeis.org/A000027>.
[Answer]
# [Python 3](https://docs.python.org/3/), 75 bytes, [cracked by xnor](https://codegolf.stackexchange.com/a/157495/78410)
```
f=lambda n,a=[1]:a*n and[a[0]]+f(n-1,sorted({*a[1:],a[0]*2,a[0]*3,a[0]*5}))
```
[Try it online!](https://tio.run/##JcoxDoQgEEDR3lNMOSAmorEh8SSEYjbISqKDYWk2xrPjbqxe8f/xLWvisdYwb7S/PAErmq12hiQDsbdke@fagNxp9Um5LB5PSVYbp/5JDg/jw3QJUUPKECEyZOL3gkMvTANHjlwwYPwNNw "Python 3 – Try It Online")
The famous Hamming numbers, a.k.a. 5-smooth numbers ([A051037](https://oeis.org/A051037)).
### Cracked solution, 51 bytes
```
lambda n:[k for k in range(1,2**n)if 60**k%k<1][:n]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjpbIS2/SCFbITNPoSgxLz1Vw1DHSEsrTzMzTcHMQEsrWzXbxjA22iov9j9IXSaSOgNNKy6FgqLMvBKNNI1MTc3/AA "Python 3 – Try It Online")
### Intended solution, 74 bytes
```
lambda n:sorted(2**(i%n)*3**(i//n%n)*5**(i//n**2)for i in range(n**3))[:n]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqji/qCQ1RcNIS0sjUzVPU8sYxNDXzwOxTaFsLS0jzbT8IoVMhcw8haLEvPRUDaCYsaZmtFVe7H80GSMDTSsuhYKizLwSjTSNTE3N/wA "Python 3 – Try It Online")
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 39 bytes, [cracked by NieDzejkob](https://codegolf.stackexchange.com/a/157453/55934)
```
: | dup 1 > if dup 1 - recurse then . ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WynUKKSUFigYKtgpZKZBmboKRanJpUXFqQolGal5CnoK1v9NFWr@AwA "Forth (gforth) – Try It Online")
[Answer]
# [Röda](https://github.com/fergusq/roda), 40 bytes
```
f x,a=1,b=2{[a];f x-1,a=b,b=a+b if[x>1]}
```
[Try it online!](https://tio.run/##K8pPSfz/P02hQifR1lAnydaoOjox1hrI1zUEiiQBRRK1kxQy06Ir7Axja//nJmbmKVRzKSikKRgZKNQoFBRl5pUoxHPV/gcA "Röda – Try It Online")
This function gives the following finite sequence (the 90 first Fibonacci numbers):
```
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578
5702887
9227465
14930352
24157817
39088169
63245986
102334155
165580141
267914296
433494437
701408733
1134903170
1836311903
2971215073
4807526976
7778742049
12586269025
20365011074
32951280099
53316291173
86267571272
139583862445
225851433717
365435296162
591286729879
956722026041
1548008755920
2504730781961
4052739537881
6557470319842
10610209857723
17167680177565
27777890035288
44945570212853
72723460248141
117669030460994
190392490709135
308061521170129
498454011879264
806515533049393
1304969544928657
2111485077978050
3416454622906707
5527939700884757
8944394323791464
14472334024676221
23416728348467685
37889062373143906
61305790721611591
99194853094755497
160500643816367088
259695496911122585
420196140727489673
679891637638612258
1100087778366101931
1779979416004714189
2880067194370816120
4660046610375530309
```
I know it can generate more Fibonacci numbers, but for purposes of this challenge it is enough to produce these numbers.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes, [Cracked by l4m2](https://codegolf.stackexchange.com/a/157423/76323)
```
f=x=>[w=~-x&&(g=(n,y=2)=>~-n&&(n<y?1:n%y?g(n,y+1):1+g(n/y,y)))(x)+f(x-1),console.log(w)][0]
```
[Try it online!](https://tio.run/##FclBDoIwEEDR00hm0lYYl@jAQQgLgrTRkCkRI50NVy@4@3n/PfyGdfy8lq@T@Jxy9py46TbeXSoKCAxilW/Ize7kBHloS7VctA3/YwhrMmeWahURIaHxkByhHaOscZ6ucwywYd9Vfb57oArzAQ "JavaScript (Node.js) – Try It Online")
Prints the first n terms of the OEIS sequence [A022559](http://oeis.org/A022559) (starting from i=1).
**l4m2 fit 3 for loops into ~~74~~ 72 bytes and cracked my cop post:**
```
n=>{for(i=s=0;j=i++<n;console.log(s))for(x=i;j++<i;)for(;x%j<1;x/=j)s++}
```
**However, my intended answer actually has only 2 for loops:**
```
n=>{for(i=c=0;i++<n;console.log(c))for(p=2,z=i;p<=z;z%p?p++:(z/=p,c++));}
```
[Try it online!](https://tio.run/##FclRCoMwDADQ0wwaorPz0xg9i2TtqEgTdOyjw7NXfL9vXX7LIXuyb5v1HWrkmnn6R91dYmFPCXHMJJoP3cJz048TgLuN@6ZwIhu5UHnYbIiDKx1bI4gAdFaK7uW9h3oB "JavaScript (Node.js) – Try It Online")
[Answer]
# x86 .COM function, 12 bytes, Cracked by [NieDzejkob](https://codegolf.stackexchange.com/a/157447/76323)
```
0000 52 push dx
0001 4A dec dx
0002 7403 je 0007
0004 E8F9FF call 0000
0007 58 pop ax
0008 F7E0 mul ax
000A AB stosw
000B C3 ret
```
Input DX, Output [DI] ~ [DI+2\*DX-1]
Cracker's solution:
```
0: 31 C0 xor ax, ax
2: BF 01 00 mov di, 1
5: 01 F8 add ax, di
7: AB stosw
8: E2 FB loop 5
A: C3 ret
```
Intended solution:
```
xor bx,bx
c:inc bx
mov ax,bx
mul ax
stosw
loop c
ret
```
[Answer]
# [Python 3](https://docs.python.org/3/), 62 bytes, [Cracked](https://codegolf.stackexchange.com/a/157776/65489) by mwchase
```
def f(x):
if(x<1):return[1]
return f(x-1)+[sum(f(x-1)[-2:])]
```
[Try it online!](https://tio.run/##Tc1NCoAgFATgvadw2SOC7D/pJuKuohZZmEKd3owIZjUfw8Act1t2U4YwTjOfk4sk42vMQZC0k/PWKKEZ//gOMkGpOv2WfFZZITXpcNjVuNjlROy3ABfgElyBa3ADbsEduMeveBwe "Python 3 – Try It Online")
I feel like this one is going to be too easy...
The sequence is the Fibonacci sequence `f(n) = f(n-1) + f(n-2)` with `f(0) = f(1) = 1`
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 15 bytes, [cracked](https://codegolf.stackexchange.com/a/157942/76162) by mbomb007
```
I1AZZ;
M:K:?ZNB
```
[Try it online!](https://tio.run/##S8/PScsszvj/39PQMSrKmsvXytvKPsrP6f9/IyMA "Gol><> – Try It Online")
The series is `0,1,2,3,4,5` but each element is followed by that many 0s.
For example, the first few values are:
```
1: 0 First element, followed by 0 zeroes
2: 1 Followed by 1 zero
3: 0
4: 2 Followed by 2 zeroes
5: 0
6: 0
7: 3 Followed by 3 zeroes
8: 0
9: 0
10: 0
etc.
```
[Answer]
# JavaScript, 63 bytes, [Cracked](https://codegolf.stackexchange.com/a/157824/76323)
```
f=x=>(x?[f(x-1)[0]&&1?3*f(x-1)[0]+1:f(x-1)[0]/2,...f(x-1)]:[7])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zbbC1k6jwj46TaNC11Az2iBWzdDeWAvO0za0grP1jXT09PQg3FiraPNYzf9p@UUambYG1pk2ptaZ2tqayfl5xfk5qXo5@ekaaRqZmpr/AQ "JavaScript (Node.js) – Try It Online")
Returns the first n elements in a reversed array
[Answer]
# Windows .BAT, 80 Bytes
```
@set /a n=%1-1
@echo 8%3
@if 0 neq %n% @call %0 %n% 2%3 6%2%3
```
Usage:
```
CD <PATH>
<FILENAME> <N_1>
<FILENAME> <N_2>
<FILENAME> <N_3>
```
The loop version can assume in the current dictionary, but have to init or reset
[Answer]
# Python, 82 bytes; [cracked](https://codegolf.stackexchange.com/a/158082/76323)
This is a recursive Python implementation of [OEIS sequence A004001](https://oeis.org/A004001) in 82 bytes. More background on this series can be found on [Wolfram's Mathworld](http://mathworld.wolfram.com/Hofstadter-Conway10000-DollarSequence.html).
```
def A(n):
if n in[1,2]:return[1]*n
S=A(n-1);return S+[S[S[n-2]-1]+S[n-S[n-2]-1]]
```
The first 30 numbers in this sequence are:
```
1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7, 8, 8, 8, 8, 9, 10, 11, 12, 12, 13, 14, 14, 15, 15, 15, 16, 16, 16
```
] |
[Question]
[
You might already be familiar with the game: [Basketball FRVR](https://www.facebook.com/basketballfrvrgame/) in facebook. There are two types of score you can make:
* **A virgin-shot:**(we call it so in our country :D) When the ball enters the basket without touching the rim or
* **A stale shot:** When the ball enters the basket, but after touching the rim.
The game is over once you miss a shot. Stale shot always scores 2 points.The first in a run of consecutive virgin-shots scores 3 points, the second scores 6 points, and subsequent ones score 9 points each.
For example,
```
Hits Total score
S-V-V-V 2+3+6+9 = 20
S-V-V-V-V 2+3+6+9+9 = 29 (see how added score for consecutive virgin-
shots
saturates at the 5th hit)
S-V-S-V-V-S-V 2+3+2+3+6+2+3= 21
```
Using simple mathematics, it can easily [be](http://www.nepposts.com/weird-score-calculation-in-basketball-frvr/) proven that any score greater than 1 `n>1` can be scored in the game
# The Challenge
For any given number `1<n<100`, output all the possible ways to score `n`.
# Rules:
* You can either write a complete program or function(s), snippets however are not acceptable.
* Hard-coding the output or loading from memory/other programs/website is strictly prohibited, you must compute the output in real-time.
* The output must be a well-separated collection of string of `S`s and `V`s. For eg: `['SVS','SSV','VSS']` or `{'SVS','SSV','VSS'}`.
* It is encouraged to, but the collection need not be sorted or contain only unique elements. Brownie points if you output sorted and unique collection of strings.
# Winning condition:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
# Input/Output (Test-cases)
```
2: {'S'}
3: {'V'}
4: {'SS'}
12: {'SSSSSS', 'VSSVS', 'VSVSS', 'VSSSV', 'SSVSV', 'SVSVS', 'SVSSV'}
16: {'SSSVSVS', 'SSSVSSV', 'VSSSSSV', 'SSVSSVS', 'SVVSV', 'VSSSSVS', 'SVSVV', 'SVSSSSV', 'VVSSV', 'VSVVS', 'SVSVSSS', 'SVSSSVS', 'VSSVSSS', 'SSVSSSV', 'SSSSSSSS', 'VVSVS', 'VSSSVSS', 'SVSSVSS', 'VSVSSSS', 'SSSSVSV', 'SSVSVSS', 'VSSVV'}
```
Thanks to [Peter Taylor](https://codegolf.meta.stackexchange.com/users/194/peter-taylor) for improving this question
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
o2,5ṁo8‘
Hṗ@€⁾VSẎðOḂŒgÇ€FS=ðÐf
```
A monadic link returning a list of the strings (lists of characters).
**[Try it online!](https://tio.run/##AUIAvf9qZWxsef//bzIsNeG5gW844oCYCkjhuZdA4oKs4oG@VlPhuo7DsE/huILFkmfDh@KCrEZTPcOww5Bm/8OHWf//MTI "Jelly – Try It Online")** - The footer calls the link and separates the entries by newlines since a full program's implicit output would smash them together.
### How?
```
o2,5ṁo8‘ - Link 1, helper to form shot scores: list of shots grouped by type (S=1 and V=0)
- e.g. [[1,1],[0,0,0,0,0],[1,1],[0],[1,1]]
2,5 - 2 paired with 5 = [2,5]
o - logical or (vectorises) [[1,1],[2,5,0,0,0],[1,1],[2,5],[1,1]]
ṁ - mould like the input [[1,1],[2,5,0,0,0],[1,1],[2],[1,1]]
o8 - logical or with 8 [[1,1],[2,5,8,8,8],[1,1],[2],[1,1]]
‘ - increment [[2,2],[3,6,9,9,9],[2,2],[3],[2,2]]
Hṗ@€⁾VSẎðOḂŒgÇ€FS=ðÐf - Link: number, total score, n
H - halve n
‚ÅæVS - literal ['V','S']
ṗ@€ - Cartesian power with swapped @rguments for €ach
- ...i.e. for each in [1,2,...,floor(half n)]
- yielding all strings of Vs and Ss from length 1 to floor(half n)
Ẏ - tighten (from a list of lists of lists to a list of lists)
ð ðÐf - filter keep those entries for which this yields a truthy value:
O - cast to ordinals (S->83, V->86)
Ḃ - modulo 2 (S->1, V->0)
Œg - group equal runs (e.g. [0,0,1,1,0] -> [[0,0],[1,1],[0]])
Ç€ - call the last link (1) as a monad for €ach (transform to scores)
F - flatten (make one list of scores)
S - sum (calculate the total score of the string)
= - equals right argument (n)?
```
The resulting order is actually lexicographical in reverse, to have it forward sorted just reverse it by appending `·πö`.
[Answer]
## JavaScript (ES6), ~~73~~ 72 bytes
Prints all unique, lexically sorted combinations.
```
f=(n,p=0,s='')=>n?n>1&&f(n-2,0,s+'S')&f(n-(p-9?p+=3:9),p,s+'V'):alert(s)
```
### Test cases
In this snippet, `alert()` has been replaced by `console.log()` for user-friendliness.
```
f=(n,p=0,s='')=>n?n>1&&f(n-2,0,s+'S')&f(n-(p-9?p+=3:9),p,s+'V'):console.log(s)
;[2, 3, 4, 12, 16]
.forEach(n => { console.log('[' + n + ']'); f(n); })
```
[Answer]
# PHP>=7.1, 158 bytes
```
function b($s="",$g=0){global$r,$i;$g-$i?$g>$i?:b($s."2",$g+2)&b($s.($n=$s[-1]>2?min(9,$s[-1]+3):3),$g+$n):$r[]=strtr($s,2369,SVVV);}$i=$argn;b();print_r($r);
```
[PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/9e5b55f78e8bd6fc7b2f3a266acc0251a22b2484)
Expanded
```
function b($s="",$g=0){
global$r,$i;
$g-$i
?$g>$i
?
:b($s."2",$g+2) # recursive call add a S
&b($s.($n=$s[-1]>2?min(9,$s[-1]+3):3),$g+$n) # recursive call add a V
:$r[]=strtr($s,2369,SVVV); # add to result array if reach score replace integers with S and V
}
$i=$argn; #short input variable
b(); #call the function
print_r($r); #print results
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~96~~ ~~95~~ ~~85~~ ~~77~~ 73 bytes
*-1 byte thanks to @notjagan*
*-4 bytes thanks to @xnor*
```
f=lambda x,s='',i=3:f(x-2,s+'S')+f(x-i,s+'V',3*(i<9)+i)if x>0 else[s]*-~x
```
[Try it online!](https://tio.run/##FcexCsIwEADQ3a@47XLNFdpEBIvxJwou4lCxhwc1LU2HuPjrkb7tLd/tPUdfioRp@DxfA2ROAZE1@E5Mrh0niz2S3aN7bsi@Mno5k1VSgXxtYJzSeE@Pqv7lIvMKChrBsecjt47bU3cAWFaNm1EWo0TlDw "Python 3 – Try It Online")
[Answer]
# Mathematica, 95 ~~102~~ ~~105~~ ~~112~~ bytes
```
If[#4==#2,Echo@#,If[#4>#2,#0[#<>"S",#2+2,0,#4];#0[#<>"V",#2+Min[3#3+3,9],#3+1,#4]]]&["",0,0,#]&
```
There should be a lot of golfing potential.
Bascially it is a recursive function that perform a DFS over all possible combinations.
[Answer]
# Haskell, 75 bytes
```
n#v|n<1=[[]|n==0]|n>0=(('S':)<$>(n-2)#3)++(('V':)<$>(n-v)#min(v+3)9)
f=(#3)
```
Call `f` with the total score value. Uses a fairly straightforward depth-first search to find all the solutions. Sadly, Haskell's precedence rules seem to be out to get me today, so there are lots of parentheses here.
] |
[Question]
[
### You know those Windows boxes where you can only do one thing?
[](https://i.stack.imgur.com/a5L4U.jpg)
### Let's take this to the next level!
# Challenge
Make a dialog box with a button that follows your cursor everywhere!
# Specs
No input may be taken. There may be output to either STDOUT or STDERR. You must open a window with one button (no text is necessary, but text may be contained in either the window title, the dialog box, or the button). The button must be clickable, and it must always follow under your cursor so that you can only click it. Upon clicking, it can do anything you want, but please do not make it crash a computer because I will be testing this... The dialog box must stay open for as long as the button is not pressed, but it does not need to close when the button is closed.
# Assumptions that you can make
* You may assume that the cursor will stay within the drawing canvas.
* You may assume that the window will stay in focus, but you must not put the window out of focus as long as the button is not pressed.
# Example Pseudocode
Here's some example pseudocode:
```
Open Dialog Box
Add Button to Dialog Box at position X, Y
WHILE True:
SET Dialog Box to CursorX - X, CursorY - Y
```
# Test Cases cannot be provided for this challenge
This is a code-golf challenge, so the shortest valid submission by March 14th (Pi Day) wins!
[Answer]
# MATLAB, ~~86~~ 63 bytes
```
set(warndlg,'WindowButtonM',@(s,e)movegui(get(0,'Po')-[99,20]))
```
This solution takes advantage of MATLAB's (typically annoying) ability to use partial property names as long as the part that is provided is unique to only the property of interest.
This solution uses the builtin [`warndlg`](https://www.mathworks.com/help/matlab/ref/warndlg.html) to create a warning dialog with an "OK" button. This function returns a `figure` handle which we can then use to set the [`WindowButtonMotionFcn`](https://www.mathworks.com/help/matlab/ref/figure-properties.html#property_WindowButtonMotionFcn) callback (using the short name `'WindowButtonM'`).
The callback that is evaluated any time the cursor is moved within the window gets the current position of the cursor (using the [`PointerLocation`](https://www.mathworks.com/help/matlab/ref/root-properties.html#property_PointerLocation) property of the [root graphics object](https://www.mathworks.com/help/matlab/ref/groot.html), using it's short name `'Po'`). We then update the [`Position`](https://www.mathworks.com/help/matlab/ref/figure-properties.html#property_Position) of the figure using [`movegui`](https://www.mathworks.com/help/matlab/ref/movegui.html) and specifying the new location of the figure after applying an offset of `[99, 20]` so that the cursor is placed on the button.
When the button is finally clicked, the figure is deleted and all callbacks are automatically released.
[](https://i.stack.imgur.com/lfh55.gif)
[Answer]
## C# (Windows Form Application), 200 114 bytes
```
void F(){var p=Cursor.Position;MouseMove+=(r,t)=>{Controls.Add(new Button());Location=new Point(p.X-30,p.Y-40);};}
```
### Un-Golfed
```
void F()
{
Controls.Add(new Button());
MouseMove += (r, t) =>
{
var p = Cursor.Position;
Location = new Point(p.X - 30, p.Y - 40);
};
}
```
Old 200-byte solution:
```
public void F(){var t=this;var b=new Button();b.Click+=delegate{t.Close();};t.Controls.Add(b);t.Show();for(;;){Application.DoEvents();t.Location=new Point(Cursor.Position.X-30,Cursor.Position.Y-40);}}
```
### Un-Golfed
```
public void F()
{
var t = this;
var b = new Button();
b.Click += delegate
{
t.Close();
};
t.Controls.Add(b);
t.Show();
for (;;)
{
Application.DoEvents();
t.Location = new Point(Cursor.Position.X - 30, Cursor.Position.Y - 40);
}
}
```
[](https://i.stack.imgur.com/FN2Ei.gif)
[Answer]
## AutoHotkey, ~~122~~ 115 bytes
```
MsgBox
WinWait,%A_ScriptName%
Loop{
MouseGetPos,x,y
WinGetPos,a,b
ControlGetPos,c,d,,,Button1
WinMove,x+a-c,y+b-d
}
```
[](https://i.stack.imgur.com/C7G48.gif)
[Answer]
# Java 7, ~~294~~ ~~289~~ ~~286~~ ~~264~~ 220 bytes
```
import java.awt.*;public class B extends java.applet.Applet{Button b;public B(){add(b=new Button());}public void paint(Graphics g){Point p=MouseInfo.getPointerInfo().getLocation();b.setLocation(p.x-9,p.y-65);repaint();}}
```
-22 bytes thanks to MouseInfo (stolen from [Zavada](https://codegolf.stackexchange.com/a/111232/51785)) I don't like the awt libraries >.>
I shaved off 44 bytes by removing the main method here. The main method isn't needed if this is launched as an applet. This can be achieved via eclipse's "Run As Java Applet" or by disabling the security manager and using [appletviewer](http://docs.oracle.com/javase/7/docs/technotes/tools/windows/appletviewer.html), which comes with the JDK (unless you're still able to view applets in web browsers. I don't think chrome allows this).
[](https://i.stack.imgur.com/4Z9hN.gif)
[Answer]
# Java, ~~172~~ ~~199~~ 235 Bytes
Golfed:
```
import java.awt.*;interface D{static void main(String[]z){new javax.swing.JDialog(){{setSize(9,99);setVisible(1>0);add(new Button());a();}void a(){for(Point p;;p=MouseInfo.getPointerInfo().getLocation(),setLocation(p.x-9,p.y-70));}};}}
```
Ungolfed:
```
import java.awt.*;
interface D{
static void main(String[]z){
new javax.swing.JDialog(){
{
setSize(9,99);
setVisible(1>0);
add(new Button());
a();
}
void a(){
for(;;) {
Point p = MouseInfo.getPointerInfo().getLocation();
setLocation(p.x-9,p.y-70);
}
}
};
}
}
```
Explanation: I use double brace initialization on my declaration of a new JDialog. This saved bytes by excluding the extension of JDialog (allowing me to save bytes excluding `public` from `main`). Inside JDialog's anonymous subclass I make it visible (using `1>0` instead of `true`) and call `a()`, which is necessary because the initalizer has a compile-time error if the loop were sat in it normally. I opted to use MouseInfo rather than all the excess code associated with adding a mouse listener.
Edit: Had to increase count by 27 to add `add(new java.awt.Button());`. I thought JDialogs had an implied button by technicality, but I seem to be wrong.
Edit 2: Had to add `setSize` and offset mouse location to make the button clickable.
[](https://i.stack.imgur.com/FHrbZ.gif)
[Answer]
# Modified Processing Js ~~102~~ 108 bytes
```
draw=function(){background(0);rect(mouseX,mouseY,9,9);rect(mouseX,mouseY,4,4);if(mouseIsPressed){fill(9);}};
```
[Try it online!](https://www.khanacademy.org/computer-programming/new-program/4630911026528256) Just updated my link!
It just draws a rectangle that follows your mouse and a smaller rectangle inside of it that you click and it turns red. It works but is not amazing. This version if very strict on braces and all of that :(
[Answer]
# Clojure, 525 bytes
```
(ns d(:require[quil.core :as q][quil.middleware :as m]))(def w 500)(def h 200)(def t 30)(def n 200)(def m 100)(q/defsketch d :size[999 999]:setup(fn[](q/stroke 0 0 0)(q/text-font(q/create-font""(* t 1.3))){:x 0 :y 0}):draw(fn[{x :x y :y}](let[r q/rect f q/fill o(- x(/ w 2))p(- y (/ h 2))](q/background 99 99 99)(f 0 0 255)(r o p w h)(f 200 200 200)(r o(+ p t)w(- h t))(f 255 0 0)(r(-(+ o w)t)p t t)(f 255 255 255)(q/text"X"(- (+ o w) t)(+ p t))(r(- x(/ n 2))(- y (/ m 2))n m))):mouse-moved(fn[_ e]e):middleware[m/fun-mode])
```
Does **not** create a genuine Windows dialog. Instead, it builds a fake one, and creates a dummy (non-functioning) button in the middle.
This was allowed by the OP in the comments.
Uses the [Quil](http://quil.info) library.
```
(ns bits.golf.following-dialog
(:require [quil.core :as q]
[quil.middleware :as m]))
(def width 500)
(def height 200)
(def top-bar-height 30)
(def b-width 200)
(def b-height 100)
(defn -main []
(q/defsketch d
:size [999 999]
:setup (fn []
; Set the border color
(q/stroke 0 0 0)
; Set the font size
(q/text-font (q/create-font "" (* top-bar-height 1.3)))
; The initial state
{:x 0 :y 0})
:draw (fn [{x :x y :y}]
(let [r q/rect ; Shortcut functions for brevity
f q/fill
; The top-left coordinates of the window
window-x (- x (/ width 2))
window-y (- y (/ height 2))]
; Wipe the previous screen
(q/background 99 99 99)
; Blue top bar
(f 0 0 255)
(r window-x
window-y
width height)
; Grey window background
(f 200 200 200)
(r window-x
(+ window-y top-bar-height)
width (- height top-bar-height))
; Red top right "button"
(f 255 0 0)
(r (- (+ window-x width)
top-bar-height)
window-y
top-bar-height top-bar-height)
; The X
(f 255 255 255)
(q/text "X" (- (+ window-x width) top-bar-height)
(+ window-y top-bar-height))
; The main "button"
(r (- x (/ b-width 2))
(- y (/ b-height 2))
b-width
b-height)))
; When the mouse is moved, set the current state to the event object, which
; conveniently has :x and :y properties
:mouse-moved (fn [_ e] e)
; Needed for ease of state management. May try to factor out.
:middleware [m/fun-mode]))
```
[](https://i.stack.imgur.com/BeGrR.gif)
[Answer]
# Javascript (ES6) + HTML + CSS, 139 bytes
HTML:
```
<d id=d><button>X
```
CSS:
```
d{background:red;padding:9px;position:absolute
```
Javascript:
```
onmousemove=e=>{with(d.style){top=e.clientY-20+'px';left=e.clientX-20+'px'}}
```
Since you can't position alert dialogs, I made my custom super fancy dialog in HTML. The javascript registers an event handler on the window object and sets the position to the coordinates of the event.
Try it online: <https://jsfiddle.net/1yohswje/>
[Answer]
## Pug/Slim + CSS/SCSS/LESS/Stylus + ES6 Javascript (98 Bytes)
[Try it online!](//codepen.io/zsty/pen/peJePr)
### Pug (10 UTF-8 Bytes)
```
button#a X
```
### Stylus (18 UTF-8 Bytes)
```
#a{position:fixed}
```
### JS (70 UTF-8 Bytes)
```
onmousemove=e=>{with(a.style){top=e.clientY+'px';left=e.clientX+'px'}}
```
## Decompiled, Ungolfed and explained Snippet:
```
document.addEventListener('mousemove', function(e) {
// Get element with an id of "id"
var el = document.getElementById("id");
// Set the vertical position
el.style.top = e.clientY + 'px';
// Set the horizontal position
el.style.left = e.clientX + 'px';
})
```
```
/* Get element with an id of "id" */
#id {
/* Position it relative to the viewport*/
position: fixed;
}
```
```
<!-- A basic HTML button with an ID of "id" -->
<button id='id'>
X
</button>
```
[Answer]
## Mathematica 226 Bytes
The mouse position relative to the screen is tracked by the front end and the window position of the dialog notebook is moved whenever the mouse moves. Pretty simple, but the commands are very lengthy in terms of letters, as often the case with Mathematica. Clicking OK will close the dialog.
```
{s,d,w}={SetOptions,Dynamic,WindowMargins->m};With[{p=d@MousePosition["ScreenAbsolute"]},
m=d@{{p[[1]]-50,0},{0,p[[2]]-35}}];s[$FrontEndSession,FrontEndEventActions->{"MouseMoved":>s[a,w]}];a=CreateDialog[{DefaultButton[]},w];
```
P.S. When you're done testing, run this to remove the front end option.
```
SetOptions[$FrontEndSession,FrontEndEventActions->None]
```
[](https://i.stack.imgur.com/58I2j.gif)
] |
[Question]
[
[Golomb rulers](https://en.wikipedia.org/wiki/Golomb_ruler) are sets of non-negative integers such that no two pairs of integers in the set are the same distance apart.
For example, `[0, 1, 4, 6]` is a Golomb ruler because all distances between two integers in this set are unique:
```
0, 1 -> distance 1
0, 4 -> distance 4
0, 6 -> distance 6
1, 4 -> distance 3
1, 6 -> distance 5
4, 6 -> distance 2
```
For the sake of simplicity in this challenge (and since translation is trivial), we **impose** that a Golomb ruler **always contains the number `0`** (which the previous example does).
Since this set is of length `4`, we say that this is a Golomb ruler of *order* `4`. The biggest distance in this set (or element, since `0` is always in the set) is `6`, therefore we say that this is a Golomb Ruler of *length* `6`.
## Your task
Find Golomb rulers of *order* `50` to `100` (inclusive) that have as small *lengths* as you can find. The rulers you find need not be optimal (see below).
### Optimality
A Golomb ruler of order `N`, is said to be optimal if there is no other Golomb ruler of order `N` which has a smaller length.
[Optimal Golomb rulers are known for orders less than 28](https://en.wikipedia.org/wiki/Golomb_ruler#Known_optimal_Golomb_rulers), though finding and proving optimality is harder and harder as the order increases.
Therefore, it is not expected that you find the optimal Golomb ruler for any of the orders between `50` and `100` (and even less expected that you can prove they are optimal).
There are no time limits in the execution of your program.
### Baseline
The list below is the list of lengths of Golomb rulers from `50` to `100` (in order) evaluated with a naïve search strategy (Thanks to @PeterTaylor for this list):
```
[4850 5122 5242 5297 5750 5997 6373 6800 6924 7459 7546 7788 8219 8502 8729 8941 9881 10199 10586 10897 11288 11613 11875 12033 12930 13393 14046 14533 14900 15165 15687 15971 16618 17354 17931 18844 19070 19630 19669 20721 21947 22525 23290 23563 23880 24595 24767 25630 26036 26254 27218]
```
The sum of all those lengths is **`734078`**.
### Scoring
Your score will be the sum of the lengths of all your Golomb rulers between `50` and `100`, divided by the sum of the lengths of Golomb rulers between `50` and `100` in the baseline: `734078`.
In case you did not find a Golomb ruler for a specific order, you shall compute your score the same way, using the double of the length in the baseline for that specific order.
The answer with the lowest score wins.
In case of a tie, the lengths of the biggest order where the two answers differ are compared, and the shortest one wins. In case both answers have the same lengths for all orders, then the answer that was posted first wins.
[Answer]
## C#, 259421/734078 ~= 0.3534
### Methods
I finally found a more-or-less readable explanation of the projective field method (Singer's method) in [*Constructions of Generalised Sidon Sets*](https://arxiv.org/abs/math/0408081), although I still think it can be improved slightly. It turns out to be more similar to the affine field method (Bose's method) than the other papers I read had communicated.
This assumes knowledge of [finite fields](//en.wikipedia.org/wiki/Finite_field). Consider \$q = p^a\$ is a prime power, and let \$F(q)\$ be our base field.
The affine field method works over \$F(q^2)\$. Take a generator \$g\_2\$ of \$F(q^2)\$ and a non-zero element \$k\$ of \$F(q)\$ and consider the set $$\{a : g\_2{}^a - k g\_2 \in F\_q\}$$ Those values form a modular Golomb ruler mod \$q^2 - 1\$. Further rulers can be obtained by multiplying modulo \$q^2 - 1\$ by any number which is coprime with the modulus.
The projective field method works over \$F(q^3)\$. Take a generator \$g\_3\$ of \$F(q^3)\$ and a non-zero element \$k\$ of \$F(q)\$ and consider the set $$\{0\} \cup \{a : g\_3{}^a - k g\_3 \in F\_q\}$$ Those values form a modular Golomb ruler mod \$q^2 + q + 1\$. Further rulers can be obtained by modular multiplication in the same way as for the affine field method.
Note that these methods between them give the [best known values](http://www.research.ibm.com/people/s/shearer/grtab.html) for every length greater than 16. Tomas Rokicki and Gil Dogon are [offering a $250 reward](http://www.gathering4gardner.org/g4g12gift/largergolomb.pdf) for anyone who beats them for lengths 36 to 40000. Therefore anyone who beats this answer is in for a monetary prize.
### Code
The C# isn't very idiomatic, but I need it to compile with an old version of Mono. Also, despite the argument checking, this is not production quality code. I'm not happy with the types, but I don't think there's a really good solution to that in C#. Maybe in F# or C++ with insane templating.
```
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sandbox {
class Program {
static void Main(string[] args) {
var winners = ComputeRulerRange(50, 100);
int total = 0;
for (int i = 50; i <= 100; i++) {
Console.WriteLine("{0}:\t{1}", i, winners[i][i - 1]);
total += winners[i][i - 1];
}
Console.WriteLine("\t{0}", total);
}
static IDictionary<int, int[]> ComputeRulerRange(int min, int max) {
var best = new Dictionary<int, int[]>();
var naive = Naive(max);
for (int i = min; i <= max; i++) best[i] = naive.Take(i).ToArray();
var finiteFields = FiniteFields(max * 11 / 10).OrderBy(x => x.Size).ToArray();
// The projective plane method generates rulers of length p^a + 1 for prime powers p^a.
// We can then look at subrulers for a reasonable range, say down to two prime powers below.
for (int ppi = 0; ppi < finiteFields.Length; ppi++) {
// Range under consideration
var field = finiteFields[ppi];
int q = field.Size;
int subFrom = Math.Max(min, ppi >= 2 ? finiteFields[ppi - 2].Size : 1);
int subTo = Math.Min(max, q + 1);
if (subTo < subFrom) continue;
int m = q * q + q + 1;
foreach (var ruler in ProjectiveRulers(field)) {
for (int sub = subFrom; sub <= subTo; sub++) {
var subruler = BestSubruler(ruler, sub, m);
if (subruler[sub - 1] < best[sub][sub - 1]) best[sub] = subruler;
}
}
}
// Similarly for the affine plane method, which generates rulers of length p^a for prime powers p^a
for (int ppi = 0; ppi < finiteFields.Length; ppi++) {
// Range under consideration
var field = finiteFields[ppi];
int q = field.Size;
int subFrom = Math.Max(min, ppi >= 2 ? finiteFields[ppi - 2].Size : 1);
int subTo = Math.Min(max, q);
if (subTo < subFrom) continue;
int m = q * q - 1;
foreach (var ruler in AffineRulers(field)) {
for (int sub = subFrom; sub <= subTo; sub++) {
var subruler = BestSubruler(ruler, sub, m);
if (subruler[sub - 1] < best[sub][sub - 1]) best[sub] = subruler;
}
}
}
return best;
}
static int[] BestSubruler(int[] ruler, int sub, int m) {
int[] expand = new int[ruler.Length + sub - 1];
for (int i = 0; i < ruler.Length; i++) expand[i] = ruler[i];
for (int i = 0; i < sub - 1; i++) expand[ruler.Length + i] = ruler[i] + m;
int best = m, bestIdx = -1;
for (int i = 0; i < ruler.Length; i++) {
if (expand[i + sub - 1] - expand[i] < best) {
best = expand[i + sub - 1] - expand[i];
bestIdx = i;
}
}
return expand.Skip(bestIdx).Take(sub).Select(x => x - ruler[bestIdx]).ToArray();
}
static IEnumerable<int[]> ProjectiveRulers(FiniteField field) {
var q = field.Size;
var fq3 = PowerField.Create(field, 3);
var m = q * q + q + 1;
var g = fq3.Generators.First();
// Define the set T<k> = {0} \union {a \in [q^3-1] : g^a - kg \in F(q)} for 0 != k \in F(q)
// This could alternatively be T<k> = {0} \union {log_g(b - kg) : b in F(q)} for 0 != k \in F(q)
// Then T<k> % (q^2 + q + 1) gives a Golomb ruler.
// For a given generator we seem to get the same ruler for every k.
var t_k = new HashSet<int>();
t_k.Add(0);
var ga = fq3.One;
for (int a = 1; a < fq3.Size; a++) {
ga = ga * g;
if (fq3.Convert(ga + g) < q) t_k.Add(a % m);
}
// TODO: optimise by detecting duplicates
for (int s = 1; s < m; s++) {
if (Gcd(s, m) == 1) yield return t_k.Select(x => x * s % m).OrderBy(x => x).ToArray();
}
}
static IEnumerable<int[]> AffineRulers(FiniteField field) {
var q = field.Size;
var fq2 = PowerField.Create(field, 2);
var m = q * q - 1;
var g = fq2.Generators.First();
// Define the set T<k> = {0} \union {a \in [q^2-1] : g^a - kg \in F(q)} for 0 != k \in F(q)
// Then T<k> % (q^2 - 1) gives a Golomb ruler.
var t_k = new HashSet<int>();
var ga = fq2.One;
for (int a = 1; a < fq2.Size; a++) {
ga = ga * g;
if (fq2.Convert(ga + g) < q) t_k.Add(a % m);
}
// TODO: optimise by detecting duplicates
for (int s = 1; s < m; s++) {
if (Gcd(s, m) == 1) yield return t_k.Select(x => x * s % m).OrderBy(x => x).ToArray();
}
}
static int Gcd(int a, int b) {
while (a != 0) {
var t = b % a;
b = a;
a = t;
}
return b;
}
static int[] Naive(int size) {
if (size == 0) return new int[0];
if (size == 1) return new int[] { 0 };
int[] ruler = new int[size];
var diffs = new HashSet<int>();
int i = 1, c = 1;
while (true) {
bool valid = true;
for (int j = 0; j < i; j++) {
if (diffs.Contains(c - ruler[j])) { valid = false; break; }
}
if (valid) {
for (int j = 0; j < i; j++) diffs.Add(c - ruler[j]);
ruler[i++] = c;
if (i == size) return ruler;
}
c++;
}
}
static IEnumerable<FiniteField> FiniteFields(int max) {
bool[] isComposite = new bool[max + 1];
for (int p = 2; p < isComposite.Length; p++) {
if (!isComposite[p]) {
FiniteField baseField = new PrimeField(p); yield return baseField;
for (int pp = p * p, pow = 2; pp < max; pp *= p, pow++) yield return PowerField.Create(baseField, pow);
for (int pq = p * p; pq <= max; pq += p) isComposite[pq] = true;
}
}
}
}
public abstract class FiniteField {
private Lazy<FiniteFieldElement> _Zero;
private Lazy<FiniteFieldElement> _One;
public FiniteFieldElement Zero { get { return _Zero.Value; } }
public FiniteFieldElement One { get { return _One.Value; } }
public IEnumerable<FiniteFieldElement> Generators {
get {
for (int _g = 1; _g < Size; _g++) {
int pow = 0;
FiniteFieldElement g = Convert(_g), gpow = One;
while (true) {
pow++;
gpow = gpow * g;
if (gpow == One) break;
if (pow > Size) {
throw new Exception("Is this really a field? " + this);
}
}
if (pow == Size - 1) yield return g;
}
}
}
public abstract int Size { get; }
internal abstract FiniteFieldElement Convert(int i);
internal abstract int Convert(FiniteFieldElement f);
internal abstract bool Eq(FiniteFieldElement a, FiniteFieldElement b);
internal abstract FiniteFieldElement Negate(FiniteFieldElement a);
internal abstract FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b);
internal abstract FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b);
protected FiniteField() {
_Zero = new Lazy<FiniteFieldElement>(() => Convert(0));
_One = new Lazy<FiniteFieldElement>(() => Convert(1));
}
}
public abstract class FiniteFieldElement {
internal abstract FiniteField Field { get; }
public static FiniteFieldElement operator -(FiniteFieldElement a) {
return a.Field.Negate(a);
}
public static FiniteFieldElement operator +(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
return a.Field.Add(a, b);
}
public static FiniteFieldElement operator *(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
return a.Field.Mul(a, b);
}
public static bool operator ==(FiniteFieldElement a, FiniteFieldElement b) {
if (Equals(a, null)) return Equals(b, null);
else if (Equals(b, null)) return false;
if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
return a.Field.Eq(a, b);
}
public static bool operator !=(FiniteFieldElement a, FiniteFieldElement b) { return !(a == b); }
public override bool Equals(object obj) {
return (obj is FiniteFieldElement) && (obj as FiniteFieldElement).Field == Field && this == (obj as FiniteFieldElement);
}
public override int GetHashCode() { return Field.Convert(this).GetHashCode(); }
public override string ToString() { return Field.Convert(this).ToString(); }
}
public class PrimeField : FiniteField {
private readonly int _Prime;
private readonly PrimeFieldElement[] _Featherweight;
internal int Prime { get { return _Prime; } }
public override int Size { get { return _Prime; } }
public PrimeField(int prime) {
if (prime < 2) throw new ArgumentOutOfRangeException("prime");
// TODO A primality test would be nice...
_Prime = prime;
_Featherweight = new PrimeFieldElement[Math.Min(prime, 256)];
}
internal override FiniteFieldElement Convert(int i) {
if (i < 0 || i >= _Prime) throw new ArgumentOutOfRangeException("i");
if (i >= _Featherweight.Length) return new PrimeFieldElement(this, i);
if (Equals(_Featherweight[i], null)) _Featherweight[i] = new PrimeFieldElement(this, i);
return _Featherweight[i];
}
internal override int Convert(FiniteFieldElement f) {
if (f == null) throw new ArgumentNullException("f");
if (f.Field != this) throw new ArgumentOutOfRangeException("f");
return (f as PrimeFieldElement).Value;
}
internal override bool Eq(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
if (b.Field != this) throw new ArgumentOutOfRangeException("b");
return (a as PrimeFieldElement).Value == (b as PrimeFieldElement).Value;
}
internal override FiniteFieldElement Negate(FiniteFieldElement a) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
var fa = a as PrimeFieldElement;
return fa.Value == 0 ? fa : Convert(_Prime - fa.Value);
}
internal override FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
if (b.Field != this) throw new ArgumentOutOfRangeException("b");
return Convert(((a as PrimeFieldElement).Value + (b as PrimeFieldElement).Value) % _Prime);
}
internal override FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
if (b.Field != this) throw new ArgumentOutOfRangeException("b");
return Convert(((a as PrimeFieldElement).Value * (b as PrimeFieldElement).Value) % _Prime);
}
public override string ToString() { return string.Format("F({0})", _Prime); }
}
internal class PrimeFieldElement : FiniteFieldElement {
private readonly PrimeField _Field;
private readonly int _Value;
internal override FiniteField Field { get { return _Field; } }
internal int Value { get { return _Value; } }
internal PrimeFieldElement(PrimeField field, int val) {
if (field == null) throw new ArgumentNullException("field");
if (val < 0 || val >= field.Prime) throw new ArgumentOutOfRangeException("val");
_Field = field;
_Value = val;
}
}
public class PowerField : FiniteField {
private readonly FiniteField _BaseField;
private readonly FiniteFieldElement[] _Polynomial;
internal FiniteField BaseField { get { return _BaseField; } }
internal int Power { get { return _Polynomial.Length; } }
public override int Size { get { return (int)Math.Pow(_BaseField.Size, Power); } }
public PowerField(FiniteField baseField, FiniteFieldElement[] polynomial) {
if (baseField == null) throw new ArgumentNullException("baseField");
if (polynomial == null) throw new ArgumentNullException("polynomial");
if (polynomial.Length < 2) throw new ArgumentOutOfRangeException("polynomial");
for (int i = 0; i < polynomial.Length; i++) if (polynomial[i].Field != baseField) throw new ArgumentOutOfRangeException("polynomial[" + i + "]");
// TODO Check that the polynomial is irreducible over the base field.
_BaseField = baseField;
_Polynomial = polynomial.ToArray();
}
internal override FiniteFieldElement Convert(int i) {
if (i < 0 || i >= Size) throw new ArgumentOutOfRangeException("i");
var vec = new FiniteFieldElement[Power];
for (int j = 0; j < vec.Length; j++) {
vec[j] = BaseField.Convert(i % BaseField.Size);
i /= BaseField.Size;
}
return new PowerFieldElement(this, vec);
}
internal override int Convert(FiniteFieldElement f) {
if (f == null) throw new ArgumentNullException("f");
if (f.Field != this) throw new ArgumentOutOfRangeException("f");
var pf = f as PowerFieldElement;
int i = 0;
for (int j = Power - 1; j >= 0; j--) i = i * BaseField.Size + BaseField.Convert(pf.Value[j]);
return i;
}
internal override bool Eq(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
if (b.Field != this) throw new ArgumentOutOfRangeException("b");
var fa = a as PowerFieldElement;
var fb = b as PowerFieldElement;
for (int i = 0; i < Power; i++) if (fa.Value[i] != fb.Value[i]) return false;
return true;
}
internal override FiniteFieldElement Negate(FiniteFieldElement a) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
return new PowerFieldElement(this, (a as PowerFieldElement).Value.Select(x => -x).ToArray());
}
internal override FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
if (b.Field != this) throw new ArgumentOutOfRangeException("b");
var fa = a as PowerFieldElement;
var fb = b as PowerFieldElement;
var vec = new FiniteFieldElement[Power];
for (int i = 0; i < Power; i++) vec[i] = fa.Value[i] + fb.Value[i];
return new PowerFieldElement(this, vec);
}
internal override FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b) {
if (a.Field != this) throw new ArgumentOutOfRangeException("a");
if (b.Field != this) throw new ArgumentOutOfRangeException("b");
var fa = a as PowerFieldElement;
var fb = b as PowerFieldElement;
// We consider fa and fb as polynomials of a variable x and multiply modulo (x^Power - _Polynomial).
// But to keep things simple we want to manage the cascading modulo.
var vec = Enumerable.Repeat(BaseField.Zero, Power).ToArray();
var fa_xi = fa.Value.ToArray();
for (int i = 0; i < Power; i++) {
for (int j = 0; j < Power; j++) vec[j] += fb.Value[i] * fa_xi[j];
if (i < Power - 1) ShiftLeft(fa_xi);
}
return new PowerFieldElement(this, vec);
}
private void ShiftLeft(FiniteFieldElement[] vec) {
FiniteFieldElement head = vec[vec.Length - 1];
for (int i = vec.Length - 1; i > 0; i--) vec[i] = vec[i - 1] + head * _Polynomial[i];
vec[0] = head * _Polynomial[0];
}
public static FiniteField Create(FiniteField baseField, int power) {
if (baseField == null) throw new ArgumentNullException("baseField");
if (power < 2) throw new ArgumentOutOfRangeException("power");
// Since the field is cyclic, there is only one finite field of a given prime power order (up to isomorphism).
// For most practical purposes that means that we can pick any arbitrary monic irreducible polynomial.
// We can abuse PowerField to do polynomial multiplication in the base field.
var fakeField = new PowerField(baseField, Enumerable.Repeat(baseField.Zero, power).ToArray());
var excluded = new HashSet<FiniteFieldElement>();
for (int lpow = 1; lpow <= power / 2; lpow++) {
int upow = power - lpow;
// Consider all products of a monic polynomial of order lpow with a monic polynomial of order upow.
int xl = (int)Math.Pow(baseField.Size, lpow);
int xu = (int)Math.Pow(baseField.Size, upow);
for (int i = xl; i < 2 * xl; i++) {
var pi = fakeField.Convert(i);
for (int j = xu; j < 2 * xu; j++) {
var pj = fakeField.Convert(j);
excluded.Add(-(pi * pj));
}
}
}
for (int p = baseField.Size; true; p++) {
var pp = fakeField.Convert(p) as PowerFieldElement;
if (!excluded.Contains(pp)) return new PowerField(baseField, pp.Value.ToArray());
}
}
public override string ToString() {
var sb = new System.Text.StringBuilder();
sb.AppendFormat("GF({0}) with primitive polynomial x^{1} ", Size, Power);
for (int i = Power - 1; i >= 0; i--) sb.AppendFormat("+ {0}x^{1}", _Polynomial[i], i);
sb.AppendFormat(" over base field ");
sb.Append(_BaseField);
return sb.ToString();
}
}
internal class PowerFieldElement : FiniteFieldElement {
private readonly PowerField _Field;
private readonly FiniteFieldElement[] _Vector; // The version of Mono I have doesn't include IReadOnlyList<T>
internal override FiniteField Field { get { return _Field; } }
internal FiniteFieldElement[] Value { get { return _Vector; } }
internal PowerFieldElement(PowerField field, params FiniteFieldElement[] vector) {
if (field == null) throw new ArgumentNullException("field");
if (vector == null) throw new ArgumentNullException("vector");
if (vector.Length != field.Power) throw new ArgumentOutOfRangeException("vector");
for (int i = 0; i < vector.Length; i++) if (vector[i].Field != field.BaseField) throw new ArgumentOutOfRangeException("vector[" + i + "]");
_Field = field;
_Vector = vector.ToArray();
}
}
}
```
### Results
Unfortunately adding the rulers would take me about 15k characters past the post size limit, so they're [on pastebin](http://pastebin.com/raw/UZJCiaRW).
[Answer]
# Python 3, score 603001 / 734078 = 0.82144
Naive search combined with Erdős–Turan construction:
$$2pk + (k^2\bmod p),\, k \in [0, p-1]$$
For odd primes *p* this gives an asymptotically optimal golomb ruler.
```
def isprime(n):
if n < 2: return False
if n % 2 == 0: return n == 2
k = 3
while k*k <= n:
if n % k == 0: return False
k += 2
return True
rulers = []
ruler = []
d = set()
n = 0
while len(ruler) <= 100:
order = len(ruler) + 1
if order > 2 and isprime(order):
ruler = [2*order*k + k*k%order for k in range(order)]
d = {a-b for a in ruler for b in ruler if a > b}
n = max(ruler) + 1
rulers.append(tuple(ruler))
continue
nd = set(n-e for e in ruler)
if not d & nd:
ruler.append(n)
d |= nd
rulers.append(tuple(ruler))
n += 1
isuniq = lambda l: len(l) == len(set(l))
isruler = lambda l: isuniq([a-b for a in l for b in l if a > b])
assert all(isruler(r) for r in rulers)
rulers = list(sorted([r for r in rulers if 50 <= len(r) <= 100], key=len))
print(sum(max(r) for r in rulers))
```
[Answer]
# Mathematica, score 276235/734078 < 0.376302
```
ruzsa[p_, i_] := Module[{g = PrimitiveRoot[p]},
Table[ChineseRemainder[{t, i PowerMod[g, t, p]}, {p - 1, p}], {t, 1, p - 1}] ]
reducedResidues[m_] := Select[Range@m, CoprimeQ[m, #] &]
rotate[set_, m_] := Mod[set - #, m] & /@ set
scaledRuzsa[p_] := Union @@ Table[ Sort@Mod[a b, p (p - 1)],
{a, reducedResidues[p (p - 1)]}, {b, rotate[ruzsa[p, 1], p (p - 1)]}]
manyRuzsaSets = Join @@ Table[scaledRuzsa[Prime[n]], {n, 32}];
tryGolomb[set_, k_] := If[Length[set] < k, Nothing, Take[set, k]]
Table[First@MinimalBy[tryGolomb[#, k] & /@ manyRuzsaSets, Max], {k, 50, 100}]
```
The function `ruzsa` implements a construction of a Golobm ruler (also called a Sidon set) found in *Imre Z. Ruzsa. Solving a linear equation in a set of integers. I. Acta Arith., 65(3):259–282, 1993*. Given any prime `p`, this construction yields a Golomb ruler with `p-1` elements contained in the integers modulo `p(p-1)` (that's an even stronger condition than being a Golomb ruler in the integers themselves).
Another advantage of working in the integers modulo `m` is that any Golomb ruler can be rotated (the same constant added to all elements modulo `m`), and scaled (all elements multiplied by the same constant, as long as that constant is relatively prime to `m`), and the result is still a Golomb ruler; sometimes the largest integer is decreased significantly by doing so. So the function `scaledRuzsa` tries all of these scalings and records the results. `manyRuzsaSets` contains the results of doing this construction and scaling for all of the first 32 primes (chosen a bit arbitrarily, but the 32nd prime, 131, is well larger than 100); there are nearly 57,000 Golomb rulers in this set, which takes a good several minutes to compute.
Of course, the first `k` elements of a Golomb ruler themselves form a Golomb ruler. So the function `tryGolomb` looks at such a ruler made from any of the sets computed above. The last line `Table...` selects the best Golomb ruler it can, of every order from `50` to `100`, from all the Golomb rulers found in this way.
The lengths found were:
```
{2241, 2325, 2399, 2578, 2640, 2762, 2833, 2961, 3071, 3151, 3194, 3480, 3533, 3612, 3775, 3917, 4038, 4150, 4237, 4368, 4481, 4563, 4729, 4974, 5111, 5155, 5297, 5504, 5583, 5707, 5839, 6077, 6229, 6480, 6611, 6672, 6913, 6946, 7025, 7694, 7757, 7812, 7969, 8139, 8346, 8407, 8678, 8693, 9028, 9215, 9336}
```
I was originally going to combine this with two other constructions, those of Singer and of Bose; but it seems that [Peter Taylor's answer](https://codegolf.stackexchange.com/a/108174/56178) has already implemented this, so presumably I would simply recover those lengths.
] |
[Question]
[
## Scenario
I often cook lasagne, but I also have a few mistakes. Since I repeat these faults so often, I thought I maybe could do a program that checks if I did everything right.
## Valid lasagne
A valid lasagne is
* At least 5 columns wide
* At least 4 layers high
+ Excluding extra cheese
* The top layer is cheese (represented by `,`)
* The second layer is sauce (represented by either `@` or `#`)
* After that the layers alternate (1 layer sauce, 1 layer noodles (represented by either `~` or `-`))
* Each column can have either one or two layers of cheese
## The program
Should
* take a lasagne string as input
+ multiline string
+ string array
+ the string only contains the chars `,@#~-`
+ Rectangular
+ Padded with spaces if necessary
* Output whether it's a valid lasagne
+ Any thing that's thruthy in your language if valid
+ Nothing or anything that's falsy in your language
* be either
+ a full program
+ a function
+ that only uses functionality that was implemented before the 14.12.2016
## Test cases
```
,, ,
,,,,,,
@@@###
~~~~~-
@##@@#
--> truthy
@@@#
----
@@##
----
@###
--> falsy (cause of cheese and width (You don't have to print the stuff in the brackets))
,,,,,
-----
@####
-----
@@@@@
--> falsy (have the sauce as last layer)
```
## Winning criteria
The
* shortest
+ in bytes
+ [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
* functional
submission wins.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~38~~ 34 bytes
*Thanks to Grimy for saving 4 bytes.*
Have a regex with your lasagne.
Byte count assumes ISO 8859-1 encoding.
```
^([, ]+¶)?,{5,}(¶[@#]+¶[-~]*){2,}$
```
Assumes that the input ends with a trailing linefeed. Prints `1` (match) for valid lasagnes and `0` (no match) for invalid ones.
[Try it online!](https://tio.run/nexus/retina#lVAxDoMwDNzvFZZMpVCcpVKnDM0fGCOq/oPCs/KAfCyNCVkL3OK709mynSIcxo9zuJlSvl1@myA0DSn2L5mfspgUg2c1gl2nez8/ZOlyFiEhgmyA956ZsSosCi@6qTOZXV2ItuEahS2A9uxMm@uszagON64ASEriKHRin79XXn9ILT8 "Retina – TIO Nexus")
### Explanation
This is just a standard .NET regex matched against the input, except that Retina provides the alias `¶` for linefeeds or `\n`.
Since the input is guaranteed to be rectangular, we only need to check the width of the lasagne on one of the rows.
```
^ # Anchor the regex to the beginning of the input.
([, ]+¶)? # Match an optional first line of only commas an spaces.
,{5,} # Match at least 5 commas.
( # Match this at least twice to ensure at least two layers of sauce.
¶[@#]+ # Match a line of sauce.
¶[-~]* # Match a line of pasta. This line may be empty (which would
# indicate the end of the input.
){2,}
$ # Make sure we've indeed reached the end. Note that `$` can
# match either at the very end of the input, or in front of
# the trailing linefeed.
```
[Answer]
## [Grime](https://github.com/iatorm/grime), 43 bytes
```
e`[ \,]+/?/(\,/[#@]^/[\-~]/+/[#@]/?)+{5-,4-
```
[Try it online!](https://tio.run/nexus/grime#HcexDYBACEDRnilIaDRAaLQ@9gCMjVOYuDp6vur/vs7AlGIbtqRYkNdhkfqU8X82Vr53lU27EUUQZAJ3Iged4EuiFw "Grime – TIO Nexus")
Prints `1` for match and `0` for no match.
## Explanation
Grime is designed for matching two-dimensional patterns, which are constructed piece by piece from smaller patterns.
I define the optional top layer first, then the other layers by repeating a vertical stripe.
```
e` Match entire input against pattern:
/? Optionally
[ \,]+ a row of spaces and commas,
/ below that
( ) this pattern
+ repeated horizontally
{5-,4- having size at least 5x4.
The brace is closed implicitly.
"This pattern" is a vertical stripe containing
\, a comma,
/ below that
[#@]^/[\-~] a sauce character on top of a noodle character
(the ^/ is like / but with higher precedence)
/+ repeated vertically,
/ below that
/? optionally
[#@] a sauce character.
```
] |
[Question]
[
# Introduction to Numerical Mathematics
This is the "Hello, World!" of PDEs (Partial Differential Equations). The Laplace or Diffusion Equation appears often in Physics, for example Heat Equation, Deforming, Fluid Dynamics, etc... As real life is 3D but we want to say "Hello, World!" and not sing "99 bottles of beer,..." this task is given in 1D. You may interpret this as a rubber robe tied to a wall on both ends with some force applied to it.
On a \$[0,1]\$ domain, find a function \$u\$ for given source function \$f\$ and boundary values \$u\_L\$ and \$u\_R\$ such that:
* \$-u'' = f\$
* \$u(0) = u\_L\$
* \$u(1) = u\_R\$
\$u''\$ denotes the second derivative of \$u\$
This can be solved purely theoretically but your task is it to solve it numerically on a discretized domain \$x\$ for \$N\$ points:
* \$x = \{\frac i {N-1} : 0 \le i \le N-1\}\$ or 1-based: \$\{\frac {i-1} {N-1} : 0 \le i \le N-1\}\$
* \$h = \frac 1 {N-1}\$ is the spacing
### Input
* \$f\$ as a function, expression or string
* \$u\_L\$, \$u\_R\$ as floating point values
* \$N \ge 2\$ as an integer
### Output
* Array, List, some sort of separated string of \$u\$ such that \$u\_i = u(x\_i)\$
### Examples
#### Example 1
Input: \$f = -2\$, \$u\_L = u\_R = 0\$, \$N = 10\$ (Don't take \$f=-2\$ wrong, it is not a value but a constant function that returns \$-2\$ for all \$x\$. It is like a constant gravity force on our rope.)
Output: `[-0.0, -0.09876543209876543, -0.1728395061728395, -0.22222222222222224, -0.24691358024691357, -0.24691358024691357, -0.22222222222222224, -0.1728395061728395, -0.09876543209876547, -0.0]`
There exists an easy exact solution: \$u = -x(1-x)\$

#### Example 2
Input: \$f = 10x\$, \$u\_L = 0\$, \$u\_R = 1\$, \$N = 15\$ (Here there is a lot of upwind on the right side)
Output: `[ 0., 0.1898688, 0.37609329, 0.55502915, 0.72303207, 0.87645773, 1.01166181, 1.125, 1.21282799, 1.27150146, 1.29737609, 1.28680758, 1.2361516, 1.14176385, 1.]`
The exact solution for this states: \$u = \frac 1 3(8x-5x^3)\$

**Example 3**
Input: \$f = \sin(2\pi x)\$, \$u\_L = u\_R = 1\$, \$N = 20\$ (Someone broke gravity or there is a sort of up- and downwind)
Output: `[ 1., 1.0083001, 1.01570075, 1.02139999, 1.0247802, 1.0254751, 1.02340937, 1.01880687, 1.01216636, 1.00420743, 0.99579257, 0.98783364, 0.98119313, 0.97659063, 0.9745249, 0.9752198, 0.97860001, 0.98429925, 0.9916999, 1.]`
Here the exact solution is \$u = \frac {\sin(2πx)} {4π^2}+1\$

[Answer]
# Matlab, ~~84, 81.2~~ 79.1 bytes = 113 - 30%
```
function u=l(f,N,a,b);A=toeplitz([2,-1,(3:N)*0]);A([1,2,end-[1,0]])=eye(2);u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;plot(u)
```
Note that in this example the I use row vectors, this means that the matrix `A` is transposed. `f` is taken as a function handle, `a,b` are the left/right side Dirichlet contraints.
```
function u=l(f,N,a,b);
A=toeplitz([2,-1,(3:N)*0]); % use the "toeplitz" builtin to generate the matrix
A([1,2,end-[1,0]])=eye(2); % adjust first and last column of matrix
u=[a,f((1:N-2)/N)*(N-1)^2,b]/A; % build right hand side (as row vector) and right mu
plot(u) % plot the solution
```
For the example `f = 10*x, u_L = 0 u_R = 1, N = 15` this results in:

[Answer]
# Mathematica, 52.5 bytes (= 75 \* (1 - 30%))
+0.7 bytes per @flawr 's comment.
```
ListPlot[{#,u@#}&/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]]&
```
This plots the output.
e.g.
```
ListPlot[ ... ]&[10 x, 0, 1, 15]
```
[](https://i.stack.imgur.com/tutqp.png)
# Explanation
```
NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]
```
Solve for the function `u`.
```
Subdivide@#4
```
`Subdivide` the interval [0,1] into N (4th input) parts.
```
{#,u@#}&/@ ...
```
Map `u` to the output of `Subdivide`.
```
ListPlot[ ... ]
```
Plot the final result.
# Non-graphing solution: 58 bytes
```
u/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]&
```
[Answer]
## R, 123.2 102.9 98.7 bytes (141-30%)
Edit: Saved a handful of bytes thanks to @Angs!
If someone wants to edit the pictures feel free to do so. This is basically an R adaptation of both the matlab and python versions posted.
```
function(f,a,b,N){n=N-1;x=1:N/n;A=toeplitz(c(2,-1,rep(0,N-2)));A[1,1:2]=1:0;A[N,n:N]=0:1;y=n^-2*sapply(x,f);y[1]=a;y[N]=b;plot(x,solve(A,y))}
```
**Ungolfed & explained:**
```
u=function(f,a,b,N){
n=N-1; # Alias for N-1
x=0:n/n; # Generate the x-axis
A=toeplitz(c(2,-1,rep(0,N-2))); # Generate the A-matrix
A[1,1:2]=1:0; # Replace first row--
A[N,n:N]=0:1; # Replace last row
y=n^-2*sapply(x,f) # Generate h^2*f(x)
y[1]=a;y[N]=b; # Replace first and last elements with uL(a) and uR(b)
plot(x,solve(A,y)) # Solve the matrix system A*x=y for x and plot against x
}
```
**Example & test cases:**
The named and ungolfed function can be called using:
```
u(function(x)-2,0,0,10)
u(function(x)x*10,0,1,15)
u(function(x)sin(2*pi*x),1,1,20)
u(function(x)x^2,0,0,30)
```
Note that the `f` argument is an R-function.
To run the golfed version simply use `(function(...){...})(args)`
## [enter image description here](https://i.stack.imgur.com/fYmXN.png) [enter image description here](https://i.stack.imgur.com/Hmk9K.png) [enter image description here](https://i.stack.imgur.com/KKjQu.png) [enter image description here](https://i.stack.imgur.com/QlJlK.png)
[Answer]
# Haskell, ~~195~~ 168 bytes
```
import Numeric.LinearAlgebra
p f s e n|m<-[0..]!!n=((n><n)(([1,0]:([3..n]>>[[-1,2,-1]])++[[0,1]])>>=(++(0<$[3..n]))))<\>(col$s:map((/(m-1)^2).f.(/(m-1)))[1..m-2]++[e])
```
The readability took quite a hit. Ungolfed:
```
laplace f start end _N = linearSolveLS _M y
where
n = fromIntegral _N
_M = (_N><_N) --construct n×n matrix from list
( ( [1,0] --make a list of [1,0]
: ([3.._N]>>[[-1,2,-1]]) -- (n-2)×[-1,2,-1]
++ [[0,1]]) -- [0,1]
>>= (++(0<$[3.._N])) --append (n-2) zeroes and concat
) --(m><n) discards the extra zeroes at the end
h = 1/(n-1) :: Double
y = asColumn . fromList $ start : map ((*h^2).f.(*h)) [1..n-2] ++ [end]
```
TODO: Printing in ~~83~~ 71 bytes.
Lemme see:
```
import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo
```
D'oh!
[Answer]
# Axiom, ~~579~~ 460 bytes
```
l(w,y)==(r:=0;for i in 1..y|index?(i,w)repeat r:=i;r)
g(z:EQ EXPR INT,y:BasicOperator,a0:Float,a1:Float,a2:Float):Float==(r:=digits();digits(r+30);q:=seriesSolve(z,y,x=0,[a,b])::UTS(EXPR INT,x,0);w:=eval(q,0);s:=l(w,r+30);o:=solve([w.s=a0,eval(q,1).s=a1]::List(EQ POLY Float),[a,b]);v:=eval(eval(eval(q,a2).s,o.1.1),o.1.2);digits(r);v)
m(z:EXPR INT,a0:Float,a1:Float,n:INT):List Float==(n:=n-1;y:=operator 'y;r:=[g(D(y x,x,2)=-z,y,a0,a1,i/n)for i in 0..n];r)
```
ungolf it and test
```
Len(w,y)==(r:=0;for i in 1..y|index?(i,w)repeat r:=i;r)
-- g(z,a0,a1,a2)
-- Numeric solve z as f(y''(x),y'(x),y(x))=g(x) with ini conditions y(0)=a0 y(1)=a1 in x=a2
NSolve2order(z:EQ EXPR INT,y:BasicOperator,a0:Float,a1:Float,a2:Float):Float==
r:=digits();digits(r+30)
q:=seriesSolve(z,y,x=0,[a,b])::UTS(EXPR INT,x,0)
w:=eval(q,0);s:=Len(w,r+30)
o:=solve([w.s=a0,eval(q,1).s=a1]::List(EQ POLY Float),[a,b])
v:=eval(eval(eval(q,a2).s,o.1.1),o.1.2);digits(r)
v
InNpoints(z:EXPR INT,a0:Float,a1:Float,n:INT):List Float==(n:=n-1;y:=operator 'y;r:=[NSolve2order(D(y x,x,2)=-z,y,a0,a1,i/n)for i in 0..n];r)
```
the function for the question is m(,,,)
the above code is put in the file "file.input"
and load in Axiom. The result depends from the digits() function.
if some one think it is not golfed => he or she can show how to do it...
thanks
PS
it seems the 6 numbers afther the . for e^(x^2) are not ok here or in the examples
but here i increase the digits but numbers not change... for me it means that
numbers in example are wrong. Why all other has not showed their numbers?
for sin(2\*%pi\*x) there are problems too
"Here the exact solution is u = (sin(2\*π\*x))/(4\*π^2)+1"
i copyed the exact solution for x=1/19:
```
(sin(2*π/19))/(4*π^2)+1
```
in WolframAlpha
<https://www.wolframalpha.com/input/?i=(sin(2>*%CF%80%2F19))%2F(4*%CF%80%5E2)%2B1
it result
```
1.008224733636964333380661957738992274267070440829381577926...
1.0083001
1234
1.00822473
```
1.0083001 proposed as result
is different in the 4th digit from the real result 1.00822473...
(and not 6th)
```
-- in interactive mode
(?) -> )read file
(10) -> digits(9)
(10) 10
Type: PositiveInteger
(11) -> m(-2,0,0,10)
(11)
[0.0, - 0.0987654321, - 0.172839506, - 0.222222222, - 0.24691358,
- 0.24691358, - 0.222222222, - 0.172839506, - 0.098765432, 0.0]
Type: List Float
(12) -> m(10*x,0,1,15)
(12)
[0.0, 0.189868805, 0.376093294, 0.555029155, 0.72303207, 0.876457726,
1.01166181, 1.125, 1.21282799, 1.27150146, 1.29737609, 1.28680758,
1.2361516, 1.14176385, 1.0]
Type: List Float
(13) -> m(sin(2*%pi*x),1,1,20)
(13)
[1.0, 1.00822473, 1.01555819, 1.02120567, 1.0245552, 1.02524378, 1.02319681,
1.0186361, 1.01205589, 1.00416923, 0.99583077, 0.987944112, 0.981363896,
0.976803191, 0.97475622, 0.975444804, 0.978794326, 0.98444181, 0.991775266,
1.0]
Type: List Float
(14) -> m(exp(x^2),0,0,30)
(14)
[0.0, 0.0202160702, 0.0392414284, 0.0570718181, 0.0737001105, 0.0891162547,
0.103307204, 0.116256821, 0.127945761, 0.138351328, 0.147447305,
0.155203757, 0.161586801, 0.166558343, 0.170075777, 0.172091643,
0.172553238, 0.171402177, 0.168573899, 0.163997099, 0.157593103,
0.149275146, 0.13894757, 0.126504908, 0.111830857, 0.0947971117,
0.0752620441, 0.0530692118, 0.0280456602, - 0.293873588 E -38]
Type: List Float
```
] |
[Question]
[
*.i xu .e'o lo zunsnagri cu drani loka jboge'a*
---
Given an input of a string consisting of two characters, output whether it is a
valid consonant cluster in Lojban.
Here is a quote from [CLL 3.6](https://lojban.github.io/cll/3/6/) detailing the
rules for a valid consonant cluster pair (or rather, an *invalid* one):
```
1) It is forbidden for both consonants to be the same, as this would
violate the rule against double consonants.
2) It is forbidden for one consonant to be voiced and the other unvoiced.
The consonants “l”, “m”, “n”, and “r” are exempt from this restriction.
As a result, “bf” is forbidden, and so is “sd”, but both “fl” and “vl”,
and both “ls” and “lz”, are permitted.
3) It is forbidden for both consonants to be drawn from the set “c”, “j”,
“s”, “z”.
4) The specific pairs “cx”, “kx”, “xc”, “xk”, and “mz” are forbidden.
```
The quote references "voiced" and "unvoiced" consonants. Here is a table of the
unvoiced consonants and their voiced counterparts (also from CLL 3.6):
```
UNVOICED VOICED
p b
t d
k g
f v
c j
s z
x -
```
Note that {x} has no voiced counterpart. For completeness, the remaining
consonants that are not on this list (which can be either voiced or unvoiced
for the purposes of the quote) are `lmnr`. (`y` is a vowel, and the letters
`hqw` are not used.)
The input must be a single string, but you may assume that it will always
consist of exactly two consonants, with optional trailing newline if you wish.
The output may be any [truthy or falsy
value](https://codegolf.meta.stackexchange.com/q/2190/3808).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
Test cases (these are all possible input strings placed in the proper
categories):
```
Valid consonant clusters:
bd bg bj bl bm bn br bv bz cf ck cl cm cn cp cr ct db dg dj dl dm dn dr dv
dz fc fk fl fm fn fp fr fs ft fx gb gd gj gl gm gn gr gv gz jb jd jg jl jm
jn jr jv kc kf kl km kn kp kr ks kt lb lc ld lf lg lj lk lm ln lp lr ls lt
lv lx lz mb mc md mf mg mj mk ml mn mp mr ms mt mv mx nb nc nd nf ng nj nk
nl nm np nr ns nt nv nx nz pc pf pk pl pm pn pr ps pt px rb rc rd rf rg rj
rk rl rm rn rp rs rt rv rx rz sf sk sl sm sn sp sr st sx tc tf tk tl tm tn
tp tr ts tx vb vd vg vj vl vm vn vr vz xf xl xm xn xp xr xs xt zb zd zg zl
zm zn zr zv
Invalid consonant clusters:
bb bc bf bk bp bs bt bx cb cc cd cg cj cs cv cx cz dc dd df dk dp ds dt dx
fb fd ff fg fj fv fz gc gf gg gk gp gs gt gx jc jf jj jk jp js jt jx jz kb
kd kg kj kk kv kx kz ll mm mz nn pb pd pg pj pp pv pz rr sb sc sd sg sj ss
sv sz tb td tg tj tt tv tz vc vf vk vp vs vt vv vx xb xc xd xg xj xk xv xx
xz zc zf zj zk zp zs zt zx zz
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), ~~59~~ ~~57~~ ~~54~~ ~~53~~ 52 bytes
```
(.)\1|[cjsz]{2}|mz
T`fb-jz`svkv
kx|xk|^v?[kpstx]v?
```
The trailing linefeed is significant. For valid clusters, this outputs a non-empty string; for invalid ones the output is empty.
[Try it online!](http://retina.tryitonline.net/#code=KC4pXDF8W2Nqc3pdezJ9fG16CgpUYGZiLWp6YHN2a3YKa3h8eGt8XGJ2P1trcHN0eF12Pwo&input=VmFsaWQgY29uc29uYW50IGNsdXN0ZXJzOgogYmQgYmcgYmogYmwgYm0gYm4gYnIgYnYgYnogY2YgY2sgY2wgY20gY24gY3AgY3IgY3QgZGIgZGcgZGogZGwgZG0gZG4gZHIgZHYKIGR6IGZjIGZrIGZsIGZtIGZuIGZwIGZyIGZzIGZ0IGZ4IGdiIGdkIGdqIGdsIGdtIGduIGdyIGd2IGd6IGpiIGpkIGpnIGpsIGptCiBqbiBqciBqdiBrYyBrZiBrbCBrbSBrbiBrcCBrciBrcyBrdCBsYiBsYyBsZCBsZiBsZyBsaiBsayBsbSBsbiBscCBsciBscyBsdAogbHYgbHggbHogbWIgbWMgbWQgbWYgbWcgbWogbWsgbWwgbW4gbXAgbXIgbXMgbXQgbXYgbXggbmIgbmMgbmQgbmYgbmcgbmogbmsKIG5sIG5tIG5wIG5yIG5zIG50IG52IG54IG56IHBjIHBmIHBrIHBsIHBtIHBuIHByIHBzIHB0IHB4IHJiIHJjIHJkIHJmIHJnIHJqCiByayBybCBybSBybiBycCBycyBydCBydiByeCByeiBzZiBzayBzbCBzbSBzbiBzcCBzciBzdCBzeCB0YyB0ZiB0ayB0bCB0bSB0bgogdHAgdHIgdHMgdHggdmIgdmQgdmcgdmogdmwgdm0gdm4gdnIgdnogeGYgeGwgeG0geG4geHAgeHIgeHMgeHQgemIgemQgemcgemwKIHptIHpuIHpyIHp2CgpJbnZhbGlkIGNvbnNvbmFudCBjbHVzdGVyczoKIGJiIGJjIGJmIGJrIGJwIGJzIGJ0IGJ4IGNiIGNjIGNkIGNnIGNqIGNzIGN2IGN4IGN6IGRjIGRkIGRmIGRrIGRwIGRzIGR0IGR4CiBmYiBmZCBmZiBmZyBmaiBmdiBmeiBnYyBnZiBnZyBnayBncCBncyBndCBneCBqYyBqZiBqaiBqayBqcCBqcyBqdCBqeCBqeiBrYgoga2Qga2cga2oga2sga3Yga3gga3ogbGwgbW0gbXogbm4gcGIgcGQgcGcgcGogcHAgcHYgcHogcnIgc2Igc2Mgc2Qgc2cgc2ogc3MKIHN2IHN6IHRiIHRkIHRnIHRqIHR0IHR2IHR6IHZjIHZmIHZrIHZwIHZzIHZ0IHZ2IHZ4IHhiIHhjIHhkIHhnIHhqIHhrIHh2IHh4CiB4eiB6YyB6ZiB6aiB6ayB6cCB6cyB6dCB6eCB6eg) This tests all clusters at once (removing all the invalid ones and leaving all the valid ones intact). To make that possible I've had to replace the `^` anchor with a `\b` word boundary.
Another solution for the same byte count:
```
(.)\1|[cjsz]{2}|mz
T`fk-dbz`scv
cx|xc|^v?[cpstx]v?
```
### Explanation
The goal is to remove all invalid pairs completely. We can do with the valid pairs whatever we want as long as at least one character remains.
```
(.)\1|[cjsz]{2}|mz
```
This takes care of three rules: `(.)\1` matches any pair violating rule 1. `[cjsz]{2}` matches any pair violating 3. `mz` matches the specifically disallowed pair from rule 4.
That leaves only rule two and the other specific pairs `xk`, `kx`, `xc` and `cx`. We can save a bunch of bytes by doing some preprocessing so we have to handle fewer cases:
```
T`fb-jz`svkv
```
The idea is to collapse all voiced consonants into one, as well `k` and `c`. I'm also turning `f` into `s` out of necessity. This is a transliteration stage which will substitute individual characters for other characters. To see the actual mapping we need to expand the range and remember that the last character of the target list is repeated indefinitely:
```
fbcdefghijz
svkvvvvvvvv
```
The initial `f => s` is necessary, because it overrides the later `f => v` which would turn `f` into a voiced consonant. We also see that `c` is turned into `k`. And all the voiced consontants `bdgjz` are turned into `v`. That leaves `ehi`... luckily these are either vowels or unused in Lojban. The same could also have been achieved with
```
T`fcb-jz`skv
```
Alternatively, check out the other solution I posted above that uses a very different transliteration (with a reverse range, and it also turns `k` into `c` instead).
Now the remaining invalid combinations can be checked much more easily:
```
kx|xk|^v?[kpstx]v?
```
`cx` and `cx` have become `kx` and `xk` so we only need to check two cases now. For rule 2, we try to match the entire pair, starting from the beginning with an optional voiced consonant (reduced to `v`), a mandatory unvoiced consonant (where we don't need to check for `f` and `c` separately) and another optional voiced consonant. If the pair is a mix of voiced and unvoiced one of the two optional `v`s will match and the entire pair is removed. Otherwise, this can only match if the pair starts with a voiced consonant (and has anything else second) - in that case only the first character will be removed, and the other one will remain, still giving a truthy result.
[Answer]
## Pyth, ~~53~~ ~~48~~ 47 bytes
```
!}z+"mz"s.pMs[+VGGc"xcxkcsjz"2*"ptkfcsx""bdgvjz
```
This generates a list of all invalid pairs based on the rules above, then checks if the input is one of them.
```
! } A not in B
z input
+
"mz" "mz"
s flattened
.pM permutations of each:
s [ flatten the three-element array:
+V Alphabet vectorized concat with itself.
G That is, duplicate letters
G
c"xcxkcsjz"2 That string chopped every 2
* outer product of
"ptkfcsx" voiced letters
"bdgvjz and unvoiced letters
```
Try it [here](https://pyth.herokuapp.com/?code=%21%7Dz%2B%22mz%22s.pMs%5B%2BVGGc%22xcxkcsjz%222%2a%22ptkfcsx%22%22bdgvjz&input=ct&debug=0).
[Answer]
## TypeScript Compiler, ~~427~~ 417 bytes
```
type U="p"|"t"|"k"|"f"|"c"|"s"|"x"
type V="b"|"d"|"g"|"v"|"j"|"z"
type S="c"|"s"|"j"|"z"
type G<T,W>=T extends W?0:T extends"l"|"r"|"m"|"n"?1:T extends U?W extends V?0:1:W extends U?0:1
type H<T,W>=T extends"x"?W extends"k"|"c"?0:G<T,W>:T extends"k"|"c"?W extends"x"?0:G<T,W>:T extends"m"?W extends"z"?0:G<T,W>:G<T,W>
type L<T>=T extends`${infer A}${infer B}`?A extends S?B extends S?0:H<A,B>:H<A,B>:0
let y:L<"bd">=1
```
[Playground link](https://www.typescriptlang.org/play?#code/C4TwDgpgBAqgvAIjAgPg4qEGtMDNMDGmAzpgB4ICwAUKJFAGqIBGmAJpgOaYBumAVpgBeVWuGgBlRETSk0gtCJp1oAcQA8AFQA0AdQB8cTVAhlgEAHZtiUXQH4ADAC5jp81dIAbTACdMAW0wLBDsARhcTM0trWDtdSPcYhkcncPi3aJsYFNDlcSgACS09Q1cojwQKOITM7EIQ5w0dAwiMipw0Imq260qGpyaS1vLewO6R0hEUwZaZ-Tz6ABktUpqPAAMAEgBvAEsLXAgfKABBAF8d-cPjgCEz9bsTtZiJOxvnm1fnIpPtG-0nD8-gCHDRPBBgFAQE5lghmBxDKEgA)
If you replace the `bd` on the last line with an illegal pair of consonants, the code will not compile. I may well have missed some optimizations, but I'm just content with the fact that the ``${infer A}${infer B}`` works as intended. Interestingly, any single character is considered valid.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 49 bytes
```
$Qa|`[ptkfcsx][bdgvjz]|[ck]x`NPZa|a~=`[cjsz]+|mz`
```
Outputs with the [truthy and falsey values switched](https://codegolf.meta.stackexchange.com/a/19205/16766) (i.e. truthy if the consonant cluster is *not* valid, falsey if it is valid). If that's not considered acceptable for this challenge because it predates the linked consensus, then tack `!:` on the front for +2 bytes.
Verify all test cases: [Try it online!](https://tio.run/##DZJLjh03EAT3fYrAQDtDuoGOIMHeajDSDIsgYf5QYBE0UX721Z96m8hNRob@rc9fX@zLv89Pf3083l911SR23l5DzLv42@NV6tt5//7nj4/Hx/9f31@lmL/98ej@/vyPb9fjwctFiIRMKIRG6IRBmIRNcCQhFWlIRwaiyEQWMRAzsRAbsRMHcRL3RXSSkCqpkTppkJQ0SUZapEMO5Egu5Ebu5EGe5E12SqBESqY0Sr8ogzIpmyrURG3UTh1UpU6qURct0IQWaYmWaYVWaZ02aEqbNKOti7Zph@b0QBd6pCd6phd6pTf6oCt90o2@6Jt@GIEhjMhIjMwojHoxGqMzlDEZxliMzbjbjgqa0Io2tKMDnaihCz3MwBRmZCZmZpaLWZmN2ZmDqUxjLuZm3m3HElaxhnVsYIpNbGGHJazEqqzG6qxxsZQ1WcY67MCO7Mwu7Mbu7MGebOckTuN0zuAoZ3KMs/CARzzj7cI7PvCJ7@s2JBCEkAiVoAQjLMJBAiJIRDJSEEM2cudOFGIkJmIlKtGItzbnIgVSJCVSJhXSJjlZyImcyZWsZCMv8qEIJVEKpVKUYpRFuXOnhosaqZlaqJV6e3KoTrvP7HRn3PQDGtGMFlTRjTrzZhgwwSKWsYLZhW3MWYEVWZlVWIu1Wc4WdmJXtrKNvdibfTiBI5zIyZzCqZzNuTcexwVPeMErrrjhN@KD@/XCT/55Pj@33w "Pip – Try It Online")
### Explanation
The input `a` is an invalid cluster if...
```
$Qa |
```
... its two characters are string-equal; or...
```
`[ptkfcsx][bdgvjz]|[ck]x` N PZa |
```
... the input `P`alindromi`Z`ed (e.g. `xc` -> `xcx`) contains an unvoiced consonant `[ptkfcsx]` followed by a voiced consonant `[bdgvjz]` or one of `[ck]` followed by `x`; or...
```
a~=`[cjsz]+|mz`
```
... the input consists entirely of one or more (in this case, two) characters from the set `[cjsz]`, or consists entirely of the sequence `mz`.
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), 128 bytes
```
Class U {p,t,k,f,c,s,x}
Class V {b,d,g,v,j,z}
Class J {c,j,s,z}
R:
{{@U,@V,l,m,n,r}$1 $1,@V @U,@U @V,@J @J,{cx,kx,xc,xk,mz}}=>*
```
Replaces invalid clusters with an empty string.
## Ungolfed
```
Class U {p,t,k,f,c,s,x}
Class V {b,d,g,v,j,z}
Class C {@U,@V,l,m,n,r}
Class J {c,j,s,z}
replace:
@C$1 $1 => * # no dups
@V @U => * # no UV/VU pairs
@U @V => *
@J @J => * # no both cjsz
{cx,kx,xc,xk,mz} => * # specific pairs
```
] |
[Question]
[
Back in 1965, The Beatles released their hit song ['Eight Days a Week'](https://youtu.be/kle2xHhRHg4).
In this [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge we are going to reimagine dates of the 21st century as if there really were eight days a week.
### Input
A Gregorian calendar date between 1 January 2001 and 31 December 2100 inclusive. You may take input in any convenient format (including built-in date objects).
### Output
The *weekday number*, *week number*, and *week-numbering year* (all defined below) corresponding to the input date. You may use any format (to be specified in your answer) in which all three numbers are unambiguously identifiable.
### Week date system
The week date system, based on the [ISO week date system](https://en.wikipedia.org/wiki/ISO_week_date) but modified for eight-day weeks, works like this:
* Reckoning of dates begins on 1 January 2001 (Gregorian), which is weekday number 1 of week number 1 of week-numbering year 2001.
* Weeks begin on weekday number 1 and end on weekday number 8. (So 9 January 2001 is weekday number 1 of week number 2 of week-numbering year 2001.)
* Week number 1 of a week-numbering year is the week that contains 4 January.
* Week-numbering years contain exactly 45 or 46 weeks. Thus a week-numbering year begins on weekday number 1 of week number 1 and ends on weekday number 8 of week number 45 or 46.
Given that the number of days in a Gregorian calendar year is never a multiple of 8, the above rules have two important consequences:
* Week number 1 of a week-numbering year may begin in the last four days of December of the previous Gregorian year.
* Week number 46 (if there is one) of a week-numbering year may end in the first three days of January of the next Gregorian year.
### Test cases
Input (Gregorian yyyy-mm-dd) -> Output (week-numbering year, week number, weekday number)
```
2001-01-01 -> 2001, 1,1
2001-01-08 -> 2001, 1,8
2001-01-09 -> 2001, 2,1
2001-12-31 -> 2001,46,5
2002-01-01 -> 2001,46,6
2002-01-04 -> 2002, 1,1
2002-12-29 -> 2002,45,8
2002-12-30 -> 2003, 1,1
2020-02-29 -> 2020, 8,7
2037-09-13 -> 2037,32,5
2061-04-23 -> 2061,15,4
2100-12-31 -> 2101, 1,4
```
---
[Related](https://codegolf.stackexchange.com/q/22268/92901), but that challenge involves standard 7-day weeks, has finicky I/O requirements, and bans date/time libraries and built-ins.
[Answer]
# JavaScript (ES6), ~~129 ... 107~~ 105 bytes
Expects a Date object. Returns `[year, week, weekday]`.
```
d=>(g=n=>(w=/an 0[^9]/.test(x=new Date(99,24,n))?++y/y:w+1,q=(d-x)/864e5)>3?g(n+8):[y,w,5+q])(-3,w=y=2e3)
```
[Try it online!](https://tio.run/##XY9fb5swFMXf8ynum21hg7GBQConmtRWmjZtD3lsM4kFh1IlJgF3FFX77JlJ0hBN/JHuT@eec@5r/idv1021t8zUhT5u1LFQc1wq4/6dCnID/OlXtgp8q1uL35XRHdznVuMsoyKihpCF5/VBP@u8kB4ULtg7CdIk0jGZy0WJjZeS2VNPOxp7hxXBTNJO9UpoSY6NPrxVjcZo0yLiNzovHqutXvZmjTnxbb20TWVKTPx2v60sRs/GyTZ185CvX3ALag4fEwBnDjsKBYWeU@jcV/AVKGj9XW6dMHguvKAkbtrjH2@737ohd26t0c4BNvh60GADDEK3T06KdW3aeqv9bV1ipz4ZmCHV3Hbb58XS5o3FkhD/ta4MRoiAB8g9HgyLw4BAKdf0puAC0M9vCGaAHr98/f5wj4bQv@QoOA/Z6QU2h2GirlM4ufL0lqcjz0YuPvWhYHL0iRIaD1z85@94MvLowsU1Vww@IrvyKD7nnrjkFy4/9YIzPuqFuzelU8fl1JVkoTxzOaVSnPokQygTF544k5hGExFyftM/PN8b/QM "JavaScript (Node.js) – Try It Online")
### How?
We start a few days before January 1, 2001 and progressively advance in the future, adding 8 days at each iteration. We increment the year and reset the week number each time we reach the 4th of January. We stop as soon as the target date is passed.
The most important part in the code is:
```
/an 0[^9]/.test(x = new Date(99, 24, n))
```
When the year argument is less than 100, the `Date()` constructor interprets it as 19xx. So, `new Date(99, 24, n)` means *24 months and n-1 days after January 1, 1999*, or *n-1 days after January 1, 2001*.
When passed to the `.test()` method, the date is implicitly turned into a string. For instance, `new Date(99, 24, 5)` is converted to:
```
"Fri Jan 05 2001 00:00:00 GMT+0000 (Coordinated Universal Time)"
```
January is the only month whose 3-letter abbreviation ends in `-an`. So `/an 0[^9]/` is used to test if the date is between January 1 and January 8 (both included).
What we really want to know is whether we are between January 4 and January 11, but the corresponding regular expression would be significantly longer. It's shorter to do it that way and use an offset of -3 days instead. This is why **n** is initialized to -3.
### Commented
```
d => ( // d = input date
g = n => // g is a recursive function taking a number of days n
( //
w = // update w:
/an 0[^9]/ // if the following date x is between January 1 and
.test( // January 8 (meaning that x + 3 days is within the
x = // week including the 4th of January)
new Date( // where x is defined as ...
99, 24, n // ... n-1 days after January 1, 2001
) // (24 months and n-1 days after January 1, 1999)
) ? // then:
++y / y // increment the year y and set w to 1
: // else:
w + 1, // increment w
q = (d - x) // if x + 3 days is less than the target date d
/ 864e5 // i.e. the difference in days q between d and x
) > 3 ? // is greater than 3:
g(n + 8) // do a recursive call with n + 8,
// i.e. one '8-day week' later
: // else:
[ // return the result array:
y, // year
w, // week number
5 + q // weekday: 8 + (q - 3)
] // end of array
)(-3, w = y = 2e3) // initial call to g with n = -3 and y = 2000
```
[Answer]
# T-SQL, ~~83~~ ~~80~~ 76 bytes
Saved 2 bytes by 0-indexing weekday.
Solved without looping
```
SELECT
year(z|7^1),(datepart(y,z|7^1)+7)/8,z%8FROM(SELECT
datediff(d,2,@)z)t
```
**[Try it online](https://data.stackexchange.com/stackoverflow/query/1266373/eight-days-a-week)**
In order to show this method provides the correct results, I have included a link to compare **[all test cases](https://data.stackexchange.com/stackoverflow/query/1266372/eight-days-a-week)** from the question. This link is not 0 indexed to allow easy comparison
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 166 bytes
```
d=>{w=(d-978336e6)/r+.5&7
for(D=0,e=new Date(d.getTime()+(7-w)*r);e.getMonth()!=0||e.getDate()!=4;D++)e.setTime(e.getTime()-r)
return[e.getYear(),8+D>>3,w+1]}
r=864e5
```
Takes input as a Javascript date object. Outputs as a 3-element list `[week-year, week number, weekday number]`. The week-numbering year is expressed as a 2-digit year (year minus 1900). If this is not acceptable, change `e.getYear()` to `e.getFullYear()` for +4 bytes.
[Try it online!](https://tio.run/##XZHLboMwEEX3/orpprLLIzYQHoqcFdvuuqkQCxSGlCoxlaGlUpJvp4agJEWyLd/jmauZ8WfxU7Q7XX91jmpKHCo5lHJ76iUtnSSKfT/EkK205a6fI1I1mqaS2ygV9pAWHdLS3WP3Vh@RMotGTs9eNNvgCF8b1X1Q9iT5@TyBKd7oYJNaFkO3nRPxbuFoRjR231plE33HQlNmx1a63fp2b4n8QrSMwwDXw65RbQelMW1BQkYg8zgXNpgFIrf/6Xihk0ft2eDfEryFwayDR222lyyAz2fgcfNqMm4RfmRDMlr6MwiNYTBGzEBwfquC5GScMtADXnuDprr2yOBEYLUCR0Bbqx3CcZxvC4VG4E6tSvzFksA4leaA7qHZ04rev8kcmSlx8spE7oj56uWMMXIZ/gA "JavaScript (Node.js) – Try It Online")
**Huh?**
```
r=864e5 // milliseconds in a day
d=>{ // Take d as a date object
w= // w is 1 less than the week number
(d-978336e6) // milliseconds since Jan 1, 2001
/r+ // Divide to get days
.5&7 // Round (up or down) to nearest integer, and take mod 8.
// This rounding smooths over DST and related variations
// Variations over 12 hours do not occur, as far as I know
for(
D=0, // D will be the number of days since the last Jan 4
e=new Date(d.getTime()+(7-w)*r); // Initialize e to be the end of this week
e.getMonth()!=0||e.getDate()!=4; // While e is not Jan 4 of any year:
D++ // Increment D
) e.setTime(e.getTime()-r) // Set e to the day before
return [
e.getYear(), // The week-numbering year of d is the same as the Gregorian year of the preceding Jan 4
8+D>>3, // Convert days elapsed into weeks since Jan 4
w+1 // the week number
]
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), 181 bytes
```
def c(t):
y,w,d=2001,1,1;D=type(t);O=D.toordinal
for o in range(730487,O(t)+1):
y,w,d=(y,w,d+1)if d<8 else(y,w+1,1)if O(D(y+1,1,4))not in range(o,o+8)else(y+1,1,1)
return y,w,d
```
[Try it online!](https://tio.run/##fZLbbqMwEIbv8xQjrrDirTg1oWnZq9znESwLhtZSsBF2tI2iPHt2bEiTKgcQMjPz8XvG/P3efRmdn04NtlDHjq1msOf/eFNlSZJyut/Xldv3SKX3TbV@ccYMjdJyO4PWDGBAaRik/sR4mSdFueQbIuep15mE4rBQSrXQfJSAW4s@Nydxn9vE63jvA14wpo27KBpu5iUb@QCkbAYDut2gR@0TfS6Elh0KAVUFkRCdVFqIyG8P0A6mg0Y6dKpDUF1vBhdikBbWtAbKoXWilhYtVHAIKX/5ehxOASA8bAVXccr4Q7T8jZZP0LcrNHuomlIpv2qgWHB4vYNmt716dPEELSY0ezxWNjaQvV3Q4vX@WBOaJxOaP1TNknHis2qISw7LWzRf@oMilXxEfZxnd09gEUYi1Qn1cUq9FjdomiS/zjU9/5IzepyNHiKXK91zwO/eW/PilhflsLMxW/0o94PSLj7THCz2VQR//kLEfhizc2Sz2lOXpLQWyZp@C7IxIRzaiCKsHTZwoLejL8ja7eQWDgQco9N/ "Python 3 – Try It Online")
My approach counts years, weeks and days for every proleptic Gregorian ordinal between `2001-01-01` and the date.
`c` expects a `datetime.date` instance of a date on or after `2001-01-01`.
Every day the day counter is incremented unless a week has passed.
Every week the day counter is reset and the week counter is incremented, unless january 4th of the next year is in the next week.
Every year the week counter is reset and the year counter is incremented.
The magic number `730487` is the ordinal of `2001-01-02`:
`730487 == datetime.date(2001, 1, 2).toordinal()`
c returns a tuple of integers containing the year, week number and day of the week in that order.
week number and day of the week are `>=1`.
] |
[Question]
[
# API Easter egg hunt!
There's an API at <http://easter_egg_hunt.andrewfaraday.com> which will provide a special Easter egg hunt, just for you...
You can see the API docs at the above address, or try it from here.
## The API:
All calls to this API are GET requests, which will return a JSON string.
These examples are in a 5x5 garden, for illustration only.
The API will actually operate on a 100x100 garden (from indexes 1 to 100)
```
/new_game
```
Internally, the API produces a garden, and hides an egg in it.
In this example the egg is at 4, 4
```
+----------+
| |
| |
| |
| |
| E |
| |
| |
| |
| |
| |
+----------+
```
Call
```
/new_game
```
Returns
```
{game_id: 'abcde'}
```
---
```
/guess/:game_id/:x/:y
```
The API looks in the garden and tells you how close you are.
If you guess 2 across and 8 down, the garden looks like this
```
+----------+
| |
| |
| |
| |
| E |
| |
| |
| g |
| |
| |
+----------+
```
Call
```
/guess/abcde/2/8
```
Returns
```
{x: 'higher', y: 'lower'}
```
This means:
\* Your x is too low (the egg position is higher)
\* Your y is too high (The egg position is lower)
Correct call:
```
/guess/abcde/4/4
```
Returns
```
{x: 'right', y: 'right', turns: 10}
```
---
## The Rules
Write a program to find the Easter egg with an API.
* Use any language.
* Try to write concise, but readable code.
* Your program **MUST** call '/new\_game' every time, and use the game\_id returned in all 'guess' calls. No peeking at the garden!
* Try to consistently finish the game with the smallest number of calls possible.
* This is not code golf.
---
## Competetive answer?
To be in with a chance of winning here's what we need to know:
* What code are you using (In your answer, or a github link if it's bigger than you like to put in an answer).
* Run your code 10 times, and record the game\_id and score each time.
**-game\_id-**: -score-
e.g.
**abbbbbbb**: 10
**abbbbbdd**: 5
(Note: The game\_ids are required to verify a result)
The score will be calculated thus:
* The highest and lowest two results will be ignored.
* The remaining 6 scores will be added together.
* This is your score.
* Lowest score wins.
---
## Addendum
Tl,dr: The app is a little shoddy.
The API was written in the space of about 90 minutes, and is deployed on a Raspberry Pi 2. Please be gentle with my API server. If you DDOS this poor thing you could spoil it for everyone.
Also, it's implemented with NOIP to simulate a static IP address, but sometimes this will drop out for a little while. That's what I get for using for zero-budget web hosting.
Just for giggles, here's a simple statistical analysis of games played... <http://easter_egg_hunt.andrewfaraday.com/stats>
[Answer]
# APL+WIN
Works by starting in the centre and converges on the location by setting the upper or lower limit to the last value and adding or subtracting half the difference to the appropriate limit to the last guess on each iteration.
```
API
id←¯20↑¯2↓GetUrl 'http://easter_egg_hunt.andrewfaraday.com/new_game'
xh←yh←100 ⋄ xl←yl←0 ⋄ x←50 ⋄ y←50 ⋄ c←0
:repeat
xy←GetUrl 'http://easter_egg_hunt.andrewfaraday.com/guess/',id,'/',(⍕x),'/',⍕y
xy←(('higher'⍷xy)+(¯1×'lower'⍷xy)+2×'right'⍷xy)~0
:if xy[1]=1 ⋄ xl←x ⋄ x←x+⌈(xh-x)÷2 ⋄ :endif
:if xy[1]=¯1 ⋄ xh←x ⋄ x←x-⌈(x-xl)÷2 ⋄ :endif
:if xy[2]=1 ⋄ yl←y ⋄ y←y+⌈(yh-y)÷2 ⋄ :endif
:if xy[2]=¯1 ⋄ yh←y ⋄ y←y-⌈(y-yl)÷2 ⋄ :endif
c←c+1
:until 4=+/2↑xy
'id:',id,' x:',(⍕x),' y:',(⍕y),' count:',⍕c
```
This function uses the following function to do the API calls:
```
r←GetUrl url
⎕wself←'HTTP' ⎕wi 'Create' 'MSXML2.ServerXMLHTTP'
⎕wi 'XOpen' 'GET' url 0
⎕wi 'XSend'
r←⎕wi 'xresponseText'
```
The results for 10 trys were:
```
id:rbgprkxrqzzhwdfsbszn x:36 y:52 count:7
id:nmpcxdqsdzhgrbtlcpbp x:35 y:49 count:6
id:qqnsbpwnlbptxxblywnz x:99 y:22 count:6
id:nsytnvcgnsyrgzvjcysc x:45 y:28 count:6
id:yfkpfhphjpqxtqnwpmhv x:95 y:40 count:7
id:kxhszzrhxqlnvwvwjgnm x:49 y:6 count:6
id:rwnwfgdpzcjpzzfmgcfn x:93 y:34 count:7
id:tcvhtpqlfrwngybsyzqh x:95 y:94 count:6
id:pmlmqnprwcjggjfhttmy x:20 y:41 count:6
id:kpsmmhfhxxrrlvbbgzkv x:9 y:28 count:5
```
[Answer]
# Ruby (+JSON, HTTParty) - Score: 40 (6+7+7+7+7+6)
This was a fun challenge. I used binary search to find the egg and got these results:
```
[{:x=>34, :y=>17, :game_id=>"mgpbmdqbnklcqrdjpyrr", :count=>7},
{:x=>99, :y=>17, :game_id=>"mhrsqfzmrrlcqxtcfgnw", :count=>7},
{:x=>23, :y=>86, :game_id=>"zgmsrjpqvdtmqmmglstn", :count=>6},
{:x=>24, :y=>55, :game_id=>"vkpjffyyltplztwhdsft", :count=>7},
{:x=>12, :y=>94, :game_id=>"pxrzjvqfjrjsptvtvnfw", :count=>4},
{:x=>83, :y=>59, :game_id=>"bdxljxkcnqmsqgnvggql", :count=>7},
{:x=>45, :y=>40, :game_id=>"mqrsbrhbldcqwgbnmymc", :count=>7},
{:x=>13, :y=> 9, :game_id=>"bphxkdgfcyyrvwxnfvkx", :count=>6},
{:x=> 8, :y=>80, :game_id=>"qzdstksdwnwrhxqrczpc", :count=>7},
{:x=>56, :y=>92, :game_id=>"ypqkfvmvwrcvvmjccvxg", :count=>6}]
```
Here's [the code](https://gist.github.com/clupasq/c5e2dd46818bb6b8d2c9514be0069250):
```
require 'rspec/autorun'
require 'json'
require 'httparty'
require 'pp'
GuessResult = Struct.new :x, :y, :count
class FakeGame
def initialize(x=random_num, y=random_num)
@x = x
@y = y
@count = 0
end
@@results = [:right, :higher, :lower]
def guess(x, y)
@count += 1
GuessResult.new(@@results[@x <=> x], @@results[@y <=> y], @count)
end
def id
:fake
end
def random_num
rand(100) + 1
end
end
class RealGame
def initialize
response = HTTParty.get('http://easter_egg_hunt.andrewfaraday.com/new_game')
j = JSON.parse(response.body)
@id = j['game_id']
end
def guess(x, y)
response = HTTParty.get("http://easter_egg_hunt.andrewfaraday.com/guess/#{id}/#{x}/#{y}")
j = JSON.parse(response.body)
x_result = j['x'].to_sym
y_result = j['y'].to_sym
count = (j['turns']||0).to_i
GuessResult.new(x_result, y_result, count)
end
def id
@id
end
end
class BinarySearch
def initialize(min, max)
@min = min
@max = max
@guessed = false
update_next_guess
end
attr_reader :next_guess, :guessed
def go(result)
return if @guessed
case result
when :right
@guessed = true
when :lower
@max = @next_guess - 1
update_next_guess
when :higher
@min = @next_guess + 1
update_next_guess
end
end
private
def update_next_guess
@next_guess = (@max + @min) / 2
end
end
def play(game)
x_search = BinarySearch.new(1, 100)
y_search = BinarySearch.new(1, 100)
until x_search.guessed && y_search.guessed
puts ?.
result = game.guess(x_search.next_guess, y_search.next_guess)
x_search.go(result.x)
y_search.go(result.y)
end
{
x: x_search.next_guess,
y: y_search.next_guess,
game_id: game.id,
count: result.count
}
end
def game_controller(game_constructor, game_count)
(1..game_count).map do |i|
game = game_constructor.call
puts "Starting game #{game.id}..."
play(game)
end
end
def main
# pp game_controller(->{ FakeGame.new }, 10)
pp game_controller(->{ RealGame.new }, 10)
end
main
# tests
describe :FakeGame do
it "returns right results" do
game = FakeGame.new 4, 4
result = game.guess(2, 5)
expect(result.x).to eql :higher
expect(result.y).to eql :lower
expect(result.count).to eql 1
result = game.guess(5, 3)
expect(result.x).to eql :lower
expect(result.y).to eql :higher
expect(result.count).to eql 2
result = game.guess(4, 4)
expect(result.x).to eql :right
expect(result.y).to eql :right
expect(result.count).to eql 3
end
end
describe :binary_search do
let(:search) { BinarySearch.new 1, 100 }
it "makes optimal guesses" do
# aiming for 34
expect(search.next_guess).to eql 50
expect(search.guessed).to be_falsey
search.go(:lower)
expect(search.next_guess).to eql 25
search.go(:higher)
expect(search.next_guess).to eql 37
search.go(:lower)
expect(search.next_guess).to eql 31
search.go(:higher)
expect(search.next_guess).to eql 34
search.go(:right)
expect(search.next_guess).to eql 34
expect(search.guessed).to be_truthy
end
end
describe :fake_game do
it "correctly responds to guesses" do
game = FakeGame.new(34, 77)
result = play(game)
expect(result.y).to eql :lower
expect(result.count).to eql 1
result = game.guess(5, 3)
expect(result.x).to eql :lower
expect(result.y).to eql :higher
expect(result.count).to eql 2
result = game.guess(4, 4)
expect(result.x).to eql :right
expect(result.y).to eql :right
expect(result.count).to eql 3
end
end
describe '#play' do
it "guesses correctly" do
game = FakeGame.new(34, 77)
result = play(game)
expect(result[:x]).to eql 34
expect(result[:y]).to eql 77
expect(result[:count]).to eql 7
expect(result[:game_id]).to eql :fake
end
end
```
[Answer]
# Python 3 (+requests), 39 points
```
http://easter_egg_hunt.andrewfaraday.com/guess/dbxqfgldhryxymljthkx/13/82
{"turns": 7, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/kfmgrdqlyxfknbgycfwm/6/52
{"turns": 7, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/gnykwddprlfwwkrybkmc/34/91
{"turns": 6, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/xhwrqdgtdyrwrvdqqcpk/92/54
{"turns": 7, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/hmbgrnxjfgqcxhbfkztm/44/48
{"turns": 7, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/mhbchhbkppqqyxzqvrnb/62/38
{"turns": 7, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/pbrkghynqybmkmctncmr/73/25
{"turns": 6, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/sspxcsfblrnmhflgtggn/89/73
{"turns": 6, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/rlvdstmpsthktzkqbynn/4/71
{"turns": 6, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
http://easter_egg_hunt.andrewfaraday.com/guess/wknwwcrdrmjsqxnqbvhm/50/67
{"turns": 6, "url": "http://easter_egg_hunt.andrewfaraday.com/surprise", "x": "right", "y": "right"}
```
Score 39 (7+7+7+6+6+6 - 7-7-6-6)
Source:
```
import requests
import json
url='http://easter_egg_hunt.andrewfaraday.com/guess/{id}/{x}/{y}'
start='http://easter_egg_hunt.andrewfaraday.com/new_game'
gid = requests.get(start).json()['game_id']
x=y=50
step=25
lx=lr=''
def get_new(old,value):
if value == 'higher':
return old+step
elif value == 'lower':
return old-step
else:#right
return old
while True:
res = requests.get(url.format(id=gid,x=x,y=y)).json()
if res['x'] == 'right' and res['y'] == 'right':
print(url.format(id=gid,x=x,y=y))
print(json.dumps(res, sort_keys=True))
break
x=get_new(x,res['x'])
y=get_new(y,res['y'])
step=step // 2 or 1
```
[Answer]
# PHP
```
<?php
error_reporting(E_ALL);
$url = 'http://easter_egg_hunt.andrewfaraday.com';
extract(json_decode(file_get_contents("$url/new_game"), true));
$i = $j = 51;
$step = 50;
$right = false;
while(!$right) {
extract(json_decode(file_get_contents(sprintf("$url/guess/$game_id/%d/%d", $i, $j)), true));
$lower = -$higher = $step /= 2;
$i += $$x;
$j += $$y;
$right = !($$x || $$y);
}
printf('{game_id: %s; x: %2d; y: %2d; turns: %d}', $game_id, $i, $j, $turns);
```
Using [file\_get\_contents](http://php.net/manual/en/function.file-get-contents.php) and [json\_decode](http://php.net/manual/en/function.json-decode.php).
[As far as I can tell](https://tio.run/##XVDBCsIwDL33KyL00FHFTvBiN3YSPAjuLjJKmbSiOLaJivrtM2nFwy7ty3vJeyGNa4YhKxrXMMYN5LA/aHa8toI/sEg14J8hUIqglAm8GAD3KC5TTbAjqAK0YQTR3flzLYR6c5/AJMfJOBfa5zksdCw8yJzejGIKElcw491PtVIS@pC1wcWw1Wr2wUV7DFJhz9pYJ1A1HVAWhYzY0z@6p7SLeQjup8RHc/SrrbtGwSRTKDdltd5tdaRN25pn1d0uJMKcLjFuQePA442G4Qs "PHP – Try It Online"), an optimal strategy needs at most 7 moves, with an average of 5.8 moves on one axis, and an average of 6.4786 moves on two axes.
---
**Sample of 10**
```
{game_id: pfmyldcsltlbtmcfjtqr; x: 76; y: 51; turns: 6}
{game_id: jnmshsfvstcmksdcdrnj; x: 40; y: 5; turns: 7}
{game_id: wsrptrymycxjfxwvdvlh; x: 55; y: 35; turns: 7}
{game_id: fxpxtqwnxstwcxbsqtwc; x: 73; y: 93; turns: 6}
{game_id: zppntvjxnjpnlmpfzcfj; x: 71; y: 76; turns: 6}
{game_id: fzvlxqgrxcvtbbydgrpj; x: 48; y: 51; turns: 6}
{game_id: hqytpzjxkfhqhhwwfryd; x: 23; y: 87; turns: 6}
{game_id: ldsbfgcqbqpxgdhtkxsm; x: 90; y: 81; turns: 5}
{game_id: shypwsmjljyqdvwcwnxv; x: 19; y: 57; turns: 7}
{game_id: bsfrhhrvmpqfvyhjxcwh; x: 82; y: 85; turns: 6}
```
**Score:** 6 + 6 + 6 + 6 + 6 + 7 = **37**
---
**Golfed, 245 bytes**
```
<?$e="extract(json_decode(file_get_contents('http://easter_egg_hunt.andrewfaraday.com";eval("$e/new_game".$f="'),1));");
for($i=$j=$h=50;!$url;$l=-$h/=2)eval("$e/guess/$game_id/".-~($i+=$$x[0]).'/'.-~($j+=$$y[0]).$f);
echo$game_id,~$i,~$j,-$turns;
```
Sample Output
```
$ php egg-hunt.php
hgzqmqyrznglsdwfwcft-9-86-7
```
[Answer]
# Haskell, Total Score ~~66~~ 40
(Edit: Missed the part about dropping highest and lowest results in scoring)
I'm just using binary search. Not sure if there's a way to get better than 6.5 per try on average without cheating (I suppose I could just keep running sets of 10 until I get a better score, but where's the fun in that?).
Ah, by the way very fun challenge. The idea is simple enough to be inclusive of everyone, and I don't usually deal with web APIs in my day job and I was just itching for an excuse to try out `servant`, so thanks for that :) Probably not so great if you're hoping for competition, but I think challenges like this could be used to gather code samples for beginners and things like that.
Executable script (runs one game and reports the gameId and score):
```
#!/usr/bin/env stack
{- stack
--resolver lts-11.2
script
--package servant
--package servant-client
--package http-client
--package aeson
--package text
-}
-- the above comments allow this to be run as a script if haskell-stack is installed.
-- Actual source starts here.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main where
import Data.Aeson
import Servant.API
import Servant.Client
import qualified Network.HTTP.Client as HttpClient
import Data.Proxy
import Data.Text(Text)
import Text.Printf
import System.IO(stderr)
newtype GameID = GameID Text deriving (PrintfArg, ToHttpApiData)
instance FromJSON GameID where
parseJSON = withObject "GameID" $ \o ->
fmap GameID (o .: "game_id")
data Accuracy = Lower | Higher | Correct
readAccuracy :: Text -> Accuracy
readAccuracy t
| t == "lower" = Lower
| t == "higher" = Higher
| t == "right" = Correct
| otherwise = error $ printf "Unexpected accuracy text: \"%s\"" t
data GuessResult = GuessResult { xAccuracy :: Accuracy, yAccuracy :: Accuracy, turnCount :: Maybe Int }
instance FromJSON GuessResult where
parseJSON = withObject "GuessResult" $ \o ->
GuessResult
<$> fmap readAccuracy (o .: "x")
<*> fmap readAccuracy (o .: "y")
<*> o .:? "turns"
type EggAPI = "new_game" :> Get '[JSON] GameID
:<|> "guess"
:> Capture "game_id" GameID
:> Capture "x" Int
:> Capture "y" Int
:> Get '[JSON] GuessResult
getNewGame :: ClientM GameID
makeGuess :: GameID -> Int -> Int -> ClientM GuessResult
getNewGame :<|> makeGuess = client (Proxy :: Proxy EggAPI)
data CoordinateRange = CoordinateRange { lowerBound :: Int, higherBound :: Int }
middleOfRange :: CoordinateRange -> Int
middleOfRange rng = lowerBound rng + (higherBound rng - lowerBound rng) `div` 2
adjustCoordinateRange :: Accuracy -> CoordinateRange -> CoordinateRange
adjustCoordinateRange Lower rng = CoordinateRange (lowerBound rng) (middleOfRange rng)
adjustCoordinateRange Higher rng = CoordinateRange (middleOfRange rng) (higherBound rng)
adjustCoordinateRange Correct rng = rng
searchForEggs :: ClientM (GameID, Int)
searchForEggs = do
game <- getNewGame
let initialRange = CoordinateRange 1 100
score <- loop game initialRange initialRange
return (game, score) where
loop gId xRange yRange = do
guessResult <- makeGuess gId (middleOfRange xRange) (middleOfRange yRange)
let newXRange = adjustCoordinateRange (xAccuracy guessResult) xRange
newYRange = adjustCoordinateRange (yAccuracy guessResult) yRange
maybe (loop gId newXRange newYRange) return $ turnCount guessResult
main :: IO ()
main = do
manager' <- HttpClient.newManager HttpClient.defaultManagerSettings
let clientEnv = mkClientEnv manager' (BaseUrl Http "easter_egg_hunt.andrewfaraday.com" 80 "")
result <- runClientM searchForEggs clientEnv
case result of
Left err -> hPrintf stderr "Error: %s\n" (show err)
Right (game, score) -> printf "GameID: %s | Score: %d\n" game score
```
# Results
```
GameID | Score
---------------------+-------
fdcbwwxkvhkfskqlpgnh | 7
cdgjnksfnrhgjjsdbnhd | 7
lbjjqgkvfzzprnrxcpsx | 6
rtbngkdlwdfmhdyggnjd | 6
rcphvxzzgblfnzxdqlyh | 6
gyfjbjmplkrfnqjptygl | 7
bkdnbqhsbhwwvgtcfhjb | 6
knjdxdmvttwgltjdpvtv | 7
zqpstnhjgsykkwxnxcbv | 7
rccpmsbfxqvsmzxckhcs | 7
```
[Answer]
# JavaScript, 35 points
Posting ungolfed code does *not* sit well with me! :D
```
(async _=>{
url=`https://crossorigin.me/http://easter_egg_hunt.andrewfaraday.com/`
promise=await fetch(url+`new_game`)
json=await promise.json()
id=json.game_id
max={x:100,y:100}
min={x:0,y:0}
(guess=async (x,y)=>{
promise=await fetch(url+`guess/${id}/${x|=0}/${y|=0}`)
json=await promise.json()
turns=json.turns
if(turns)
console.log(`{game:"${id}",turns:${turns},x:${x},y:${y}}`)
else{
switch(json.x){
case`higher`:
min.x=x
x+=max.x
x/=2
break
case`lower`:
max.x=x
x+=min.x
x/=2
}
switch(json.y){
case`higher`:
min.y=y
y+=max.y
y/=2
break
case`lower`:
max.y=y
y+=min.y
y/=2
}
guess(x,y)
}
})(50,50)
})()
```
---
## Scoring: 5+6+6+6+6+6=35
Got very lucky, pulling that score of 3 on my last test before posting!
```
{game:"bjzkjzxwmksmbsbxtdzp",turns:3,x:75,y:12}
{game:"bvmhssnmzhlnykgxdkww",turns:5,x:93,y:71}
{game:"mcydbttxhcxwqymksgbg",turns:5,x:71,y:37}
{game:"xdynxrkxgsyltsfrqzll",turns:6,x:54,y:88}
{game:"wjdkclsqksnvdnwbspxq",turns:6,x:90,y:13}
{game:"mgvlssfgjcgtylwqpvhq",turns:6,x:26,y:68}
{game:"rgjvbkrlzqvpdfphqxtq",turns:6,x:19,y:81}
{game:"hgrscvfzgrkzzjvkjjwb",turns:6,x:41,y:19}
{game:"lrfrblmmkggghntshnkj",turns:7,x:86,y:32}
{game:"ldsndvjsbvgvbhbtfckp",turns:7,x:24,y:7}
```
---
## Try it
Using a *somewhat* golfed version of the code above!
```
(async url=>(
json=await(await fetch(url+`new_game`)).json(),
id=json.game_id,
max={x:100,y:100},
min={x:0,y:0},
(g=async x=>(
json=await(await fetch(url+`guess/${id}/${x|=0}/${y|=0}`)).json(),
x+=json.x==`higher`?(min.x=x,max.x):json.x==`lower`?(max.x=x,min.x):x,x/=2,
y+=json.y==`higher`?(min.y=y,max.y):json.y==`lower`?(max.y=y,min.y):y,y/=2,
json.turns?console.log(`{game:"${id}",turns:${json.turns},x:${x},y:${y}}`):g(x)
))(y=50)
))`https://crossorigin.me/http://easter_egg_hunt.andrewfaraday.com/`
```
[Answer]
# Rust
As it happens, Rust has a really nice deserialization library called `serde` which helped a lot with this program. The algorithm itself is a rather straightforward binary search, except ran twice - once for `x` and once for `y`.
The URL macro has a specific case for no format strings because it can be done for pretty much free, and when not formatting the string would be stored in static storage.
## Cargo.toml
```
[package]
name = "easter-egg-hunt"
version = "0.1.0"
authors = ["Konrad Borowski"]
[dependencies]
reqwest = "0.8.5"
serde = "1.0.36"
serde_derive = "1.0.36"
```
## main.rs
```
extern crate reqwest;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use reqwest::Client;
#[derive(Deserialize)]
struct NewGame {
game_id: String,
}
#[derive(Deserialize)]
struct Guess {
x: GuessStatus,
y: GuessStatus,
turns: Option<u32>,
}
#[derive(Deserialize)]
#[serde(rename_all = "lowercase")]
enum GuessStatus {
Lower,
Right,
Higher,
}
macro_rules! url {
($path:expr) => {
concat!("http://easter_egg_hunt.andrewfaraday.com", $path)
};
($path:expr $(, $part:expr)*) => {
&format!(url!($path) $(, $part)*)
};
}
struct BinarySearch {
low: u8,
high: u8,
}
impl BinarySearch {
fn new() -> Self {
BinarySearch { low: 1, high: 100 }
}
fn current_guess(&self) -> u8 {
(self.low + self.high) / 2
}
fn update(&mut self, guess_status: GuessStatus) {
let current_guess = self.current_guess();
match guess_status {
GuessStatus::Lower => self.high = current_guess - 1,
GuessStatus::Higher => self.low = current_guess + 1,
GuessStatus::Right => {
self.high = current_guess;
self.low = current_guess;
}
}
}
}
fn run_game(client: &Client) -> reqwest::Result<()> {
let NewGame { game_id } = client.get(url!("/new_game")).send()?.json()?;
let mut x_search = BinarySearch::new();
let mut y_search = BinarySearch::new();
loop {
let x_guess = x_search.current_guess();
let y_guess = y_search.current_guess();
let response = client
.get(url!("/guess/{}/{}/{}", game_id, x_guess, y_guess))
.send()?
.json()?;
match response {
Guess { x, y, turns: None } => {
x_search.update(x);
y_search.update(y);
}
Guess {
turns: Some(turns), ..
} => {
println!("id:{} x:{} y:{} count:{}", game_id, x_guess, y_guess, turns);
return Ok(());
}
}
}
}
fn main() {
let client = Client::new();
for _ in 0..10 {
run_game(&client).unwrap();
}
}
```
## Summary
```
id:tlxjnjtslnsnbdxyzlvn x:97 y:22 count:7
id:bbzpyhhflrdjzylwxtbr x:21 y:6 count:5
id:kcjdkfvddgxckmprxwtw x:81 y:99 count:6
id:tnzryxpkblqrqbqrqkby x:30 y:25 count:7
id:pbzkdrmjrvwmkgmlvwcb x:79 y:20 count:7
id:qxvcbcslkdmjxnffsxfb x:36 y:94 count:7
id:hqfgpdmktyfwqtbrvvly x:94 y:71 count:5
id:ytgsnssvlpnhzqzgvygw x:1 y:83 count:7
id:gjhglmkbhvswqwgrynft x:65 y:94 count:5
id:rzghpypysxtwkclgpbkx x:55 y:96 count:7
```
5 + 6 + 7 + 7 + 7 + 7 = 39
[Answer]
# Python 2
**Golfed vesrion - 276 bytes**
```
from requests import*
u='http://easter_egg_hunt.andrewfaraday.com'
i=get('%s/new_game'%u).json()['game_id']
x=y=50;s=25;o={}
while not'turns'in o:o=get('%s/guess/%s/%d/%d'%(u,i,x,y)).json();exec("%s+=s*'rh'.rfind(o['%s'][0]);"*2)%tuple('xxyy');s=s%2+s/2
print i,x,y,o['turns']
```
**More readable version + comments**
```
from requests import*
u='http://easter_egg_hunt.andrewfaraday.com'
i=get('%s/new_game'%u).json()['game_id'] # get game id
x=y=50 # initial central position
s=25 # step of binary search
o={} # initialize o to further store returns
while not'turns'in o: # cycle until 'turns' occurs in return
o=get('%s/guess/%s/%d/%d'%(u,i,x,y)).json()
exec("%s+=s*'rh'.rfind(o['%s'][0]);"*2)%tuple('xxyy');s=s%2+s/2
# this exec is used to shorten two similar lines for x and y:
# x += s * (... o['x'] ...);
# s*'rh'.rfind(o['%s'][0]) - look at first letter of return and use its position in string 'rh' to map multipliers for step:
# -1 for lower, +1 for higher and 0 for right
# rfind() will return -1 for not finding l
s=s%2+s/2 # divide step in two, rounding up
print i,x,y,o['turns']
```
# Results
```
vjwqvbydwmbvbrhwrxqz 19 95 4
svkdvszghjzfbvqxsprt 5 12 4
dvbpnxjdgrydwffcndnt 81 67 6
qqwgsctqhdcrbywwrcxf 21 49 6
zrgqqtzjjrrsqbgvkbsm 37 12 6
trzjngljbwbwxycxpcbk 91 2 7
kysjwfzsrdjsybrchnzg 76 45 7
kcjtxqfmcgszrwkyhlkm 68 48 7
wykbjvthqmcyzscxnsxt 68 41 7
kldrfccjdphzqnqcmdgz 88 14 7
```
# Summary
Somewhat expected :D
6+6+6+7+7+7 = 39
] |
[Question]
[
Simple challenge: given a series of positive integer numbers, find the number that contains among its digits the longest run of consecutive digits. The trick? It's allowed for the digits in the runs to wrap around the possible values (`0123456789`) and to run backwards. So both `2345`, `89012` and `5432109` are valid runs of consecutive digits (but not `3456765` nor `321090123` as the run must be always in the same direction, although `3456765` can be considered as two runs: `34567` and `765`). In the case of ties, return the first one.
**Test cases:**
```
Input: [3274569283, 387652323, 23987654323648, 2345687913624]
Output: 23987654323648
(The run is 98765432; run length: 8)
Input: [123012363672023, 098761766325432, 15890123456765]
Output: 15890123456765
(The run is 8901234567; run length: 10)
Input: [43, 19, 456]
Output: 456
Input: [5, 9, 0]
Output: 5
Input: [71232107, 7012347]
Output: 7012347
Input: [1234, 32109876]
Output: 32109876
Input: [9090, 123]
Output: 123
```
**Notes:**
* There will be at least one number in the input.
* Input numbers can contain leading zeroes.
* Input and output can be in [any reasonable format](https://codegolf.meta.stackexchange.com/q/2447/70347). So input numbers can be taken as strings, lists of digits/characters...
* Output can contain trailing and/or leading whitespaces and newlines as long as the number is printed.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program/function for each language win!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
I9,-;N¤yŒgỊS€ṀµÐṀḢ
```
[Try it online!](https://tio.run/##y0rNyan8/9/TUkfX2u/Qksqjk9If7u4KftS05uHOhkNbD08AUg93LPr//390tKGOgpGOgrGOgoGOApxtBiPNwSIGEPFYHYVoINNSR8ECLGMG1gFhQHQAVZnqKJhA2CDlhmABC7AmZAtMwOJmMN2msbEA "Jelly – Try It Online")
Takes and returns as list of digits so as to preserve leading zeroes.
[Answer]
## JavaScript (ES6), ~~104~~ ~~102~~ 98 bytes
Takes input as a list of lists of digits. Returns the best one.
```
a=>a.map(s=>s.map(n=>(i=(d=(x-(x=n)+11)%10)&&d-2?0:d-p?(p=d,1):i+1)>j&&(r=s,j=i),p=x=-10),j=-1)&&r
```
### Test cases
```
let f =
a=>a.map(s=>s.map(n=>(i=(d=(x-(x=n)+11)%10)&&d-2?0:d-p?(p=d,1):i+1)>j&&(r=s,j=i),p=x=-10),j=-1)&&r
console.log(JSON.stringify(f([[3,2,7,4,5,6,9,2,8,3], [3,8,7,6,5,2,3,2,3], [2,3,9,8,7,6,5,4,3,2,3,6,4,8], [2,3,4,5,6,8,7,9,1,3,6,2,4]])))
console.log(JSON.stringify(f([[1,2,3,0,1,2,3,6,3,6,7,2,0,2,3], [0,9,8,7,6,1,7,6,6,3,2,5,4,3,2], [1,5,8,9,0,1,2,3,4,5,6,7,6,5]])))
console.log(JSON.stringify(f([[4,3], [1,9], [4,5,6]])))
console.log(JSON.stringify(f([[5], [9], [0]])))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18 16~~ 15 [bytes](https://github.com/DennisMitchell/jelly)
```
I%⁵Œg%8ċ€1ṀµÐṀḢ
```
A monadic link taking a list of lists of digits, and returning the leftmost one containing a maximal run as described.
**[Try it online!](https://tio.run/##y0rNyan8/99T9VHj1qOT0lUtjnQ/alpj@HBnw6GthycAqYc7Fv3//z862lDHSMdYxyRWJ9oYyDLUMdCx1LHQMdcxA7KNYmMB "Jelly – Try It Online")** or see a [test suite](https://tio.run/##PY6/asMwEMb3PoUQeHNBupN10tK9LxAoxmMIBL9AN7tLhiwhc7t06JQ10ELJEMcPEr@IeidBQf@@n77v7rbrvn9N6blaxvN83FThtl/eTvb@M1zP04Gv@/dnWjHiNe0e5t9px6@teK5fgsdLrUQuw7t6fFLL8PGSUttqBHKNjxBQ10pjIN8AQhaAUaRj6V0ohL2BokUPTne1arUFNLw9egJTckZilrxHkLAg24QoNo5zxZJ02WyjnMwLbERlZAogToE1JIhyCfpv7PLI/CsNC40mmlyWR@m6Pw "Jelly – Try It Online") (with processing to make I/O look like it is in the question).
### How?
```
I%⁵Œg%8ċ€1ṀµÐṀḢ - Link: list of lists of integers (digits) from [0-9]
µÐṀ - keep elements for which the link to the left is maximal:
I - incremental differences (i.e. [a2-a1, a3-a2, ...])
⁵ - literal 10
% - modulo by (i.e. [(a2-a1)%10, (a3-a2)%10, ...])
- this equates deltas of -9 and -1 with 1 and 9 respectively
Œg - group runs of equal elements
%8 - modulo by 8; vectorised (9s become 1s, others unaffected)
ċ€1 - count number of 1s in €ach group
Ṁ - maximum
Ḣ - head (get the first one of those that were maximal)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 118 bytes
Takes a list of lists of digits `a`; returns one of its lists.
```
lambda a:max(a,key=lambda l:len(max(re.findall('1+|9*',`[(x-y)%10for x,y in zip(l,l[1:])]`[1::3]),key=len)))
import re
```
[Try it online!](https://tio.run/##ZU9db4QgEHy/X8FLA7R7F/Hr1Mb@EUsi7WFLimiITbTpf7eAni99YJmdmZ2FcZk@BxOvXf26atG/3QQSVS9mIuBLLvVO6UpLQzxt5aVT5ia0Jpg9/ZaPGNqGzOeFPrCoGyyaYUHKoB81Eg26YRWnvHVXlXC6RUpDKT2pfhzshKxc/ZTyM1aYD0kyWiFRKzN@T4Q@o9EqM6FWtBcrRy3eJcEIA8YUED6/YEBtRwT9p65Nk0AMV0ghgxxKhwtIOCBHF47OHR2DtwTSw/IQ0k1wOIXiLm9B3lICC2IMKeenpmHBHAHbh/y5Ohzd06Mjm4Wah/x9jzcw1xTOdM/YdoXHhA3plsOg9FdQA5/5NnBReOaBkgOlYfBo9@KH/Tp3OGwf4PwP "Python 2 – Try It Online")
[Answer]
## [Husk](https://github.com/barbuz/Husk), 20 bytes
```
←Ö¤>(→Of€1†%8gẊo%10-
```
Takes and returns a list of lists of digits.
[Try it online!](https://tio.run/##TVAhDgIxEPS8AkOCWJK217u2hi/wgOYskBBCwgUPJ06gCAKNQJLgEMjD8A36kbLdlsuJtrMzs7ObLnfVyg/Xn0fl6sO2fXrXnN6X9jYdu@Y8m7v6zt3@OtKL7@u4GXE28d5bm4EABRJyKMAg1pCVgKxGtkBWQHAELiDT8TLyiCXopMaU4DDASRMgy3JgLScvA556wlGIWcpmXTKnu6D0NAV1jlij558QJ9EmlC8phYPBmzRic6wCw6hSqVfgy0Ahr3p5qrenpB@IvrQXqYZqRpPC3uUP "Husk – Try It Online")
## Explanation
```
←Ö¤>(→Of€1†%8gẊo%10- Implicit input.
← Return first element of
Ö the input sorted in a stable manner
> in descending order
¤ ( with respect to the following function:
Argument is list of digits, say [5,2,1,0,9,1,0].
- Differences
o%10 mod 10
Ẋ of all adjacent pairs: [7,9,9,9,2,1]
g Group adjacent equal elements: [[7],[9,9,9],[2],[1]]
†%8 Vectorized mod 8: [[7],[1,1,1],[2],[1]]
f€1 Keep those runs where 1 occurs: [[1,1,1],[1]]
O Sort in ascending order: [[1],[1,1,1]]
→ Take last element (gives [] on empty list): [1,1,1]
This is a list of 1s with length one less than
the longest run of consecutive digits.
```
[Answer]
# MATLAB, 130 bytes
Take input to array, array of column differences [X(2)-X(1),...,X(n)-X(n-1)], check the most frequent value in the array (1 ascending order -1 otherwise), get the index for either the most frequent value or -9 multiplied by the most frequent value (-9 occurs in ascending order, 9 otherwise), find the consecutive indices (i.e. whose difference is equal to 1) and sum it please, because it's late.
Output the largest.
```
a=input('')
t=[]
for i=1:numel(a)
b=diff(num2str(a(i))-'0')
c=mode(b)
t=[t sum(diff(find(b==c|b==-9*c))==1)]
end
[t,I]=max(t),a(I)
```
[Try it online!](https://tio.run/##HYtLCoMwEED3OYW7zBQFtSsLcwDPIFmM@UCgSYqO0kXvnoqbBw/eK1b49LUyxfw5BLRGJbQYFcrWRBpe@Uj@DYxqJRdDgMvHXTZgiIid7q/eUirOw3qf0uxHgjsNMTtYiezvQjc9LCLRgEb57NQi7Wwo8RcEW4YZa12mfurbZhifpv4B "Octave – Try It Online")
] |
[Question]
[
The [Discordian calendar](https://en.wikipedia.org/wiki/Discordian_calendar) is an alternative calendar used by Discordians.
1. The discordian year has 5 seasons, each lasting 73 days: Chaos, Discord, Confusion, Bureaucracy, and The Aftermath.
2. The discordian week has 5 days: Sweetmorn, Boomtime, Pungenday, Prickle-Prickle, and Setting Orange. Every year begins with Sweetmorn (and in Chaos).
3. Every **f**ourth year (which happe**n**s to align with Greg**o**rian leap yea**r**s), an extra **d**ay is inserted between Chaos 59 and Chaos 60 called *St. Tib's Day*. It is outside of the Discordian week, meaning the day after St. Tib's Day will be Setting Orange, the day before Prickle-Prickle.
4. The Gregorian and Discordian calendars line up; both start on the same day, which is called January 1st in the Gregorian calendar, and Chaos 1 in the Discordian one.
5. The first Year of Our Lady of Discord (YOLD 1) was 1166 BC in the Gregorian calendar, meaning this year (2017 AD) is YOLD 3183.
6. The Discordian calendar also has holidays, but they are not important for this challenge and you should not output them or anything about them.
Write a program or function that outputs or returns today's date (at the time of execution):
```
Today is Boomtime, the 16th day of Confusion in the YOLD 3183
```
The format is `"Today is $day_of_the_week, the $ordinal day of $season in the YOLD $year"`, where $day\_of\_the\_week is the capitalized (title-case) day of the week, $ordinal is the day of the season as an ordinal (1st, 2nd, 3rd, 4th, ...), $season is the capitalized (title-case) season, and $year is the year.
If your program or function is executed on St. Tib's Day, it should instead output or return `"Today is St. Tib's Day in the YOLD $year"`.
### Rules:
* Standard loopholes apply.
* If your language of choice has no way of getting the current date, it may also take the current Gregorian date in any reasonable format as input.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code (per language) wins.
* Trailing whitespace is okay.
* Capitalization matters.
* Calling `ddate` in any way is banned
* Your program should be guaranteed to work from 3067 to 3265 YOLD (1901 to 2099 AD), outside that range it can give incorrect values
## See also:
* Malaclypse The Younger. *"Principia Discordia, Or How I Found Goddess And What I Did To Her When I Found Her"*. [p. 00034](https://principiadiscordia.com/book/41.php)
* ddate(1)
* [Sandbox post for those who can see it](https://codegolf.meta.stackexchange.com/a/12301/21173)
[Answer]
## Mathematica, ~~403~~ 401 bytes
Version to count number of bytes: (removed spaces and newlines - unfortunately this part is quite hard)
```
"Setting Orange"["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle"][[#~Mod~5]]<>", the "<>SpokenString@p[[Mod[#,73,1]]]~StringExtract~2<>" day of "<>{"Chaos","Discord","Confusion","Bureaucracy","The Aftermath"}[[⌈#/73⌉]]&;
Row@{"Today is ",#2," in the YOLD ",1166+#}&[#,If[4∣#,If[#2>60,%[#2-1],If[#2<60,%@#2,"St.Tib's Day"]],%@#2]]&@@FromDigits/@DateString@"ISOOrdinalDate"~StringSplit~"-"
```
Version to read:
```
"Setting Orange"["Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle"][[#~Mod~5]] <>
", the " <>
SpokenString@p[[Mod[#, 73, 1]]]~StringExtract~2 <>
" day of " <>
{"Chaos", "Discord", "Confusion", "Bureaucracy",
"The Aftermath"}[[Ceiling[#/73]]] &;
Row@{
"Today is ",
#2,
" in the YOLD ",
1166 + #
} &[#,
If[4 ∣ #,
If[#2 > 60, %[#2 - 1],
If[#2 < 60, %@#2, "St.Tib's Day"]
], %@#2
]] & @@ FromDigits /@ DateString@"ISOOrdinalDate"~StringSplit~"-"
```
The answer can be tested with arbitrary date by replacing `DateString@"ISOOrdinalDate"` by `DateString[{year,month,day},"ISOOrdinalDate"]` for `year`, `month` and `day` replaced by numbers.
[Answer]
## Python 2, 423 Bytes
Short version:
```
import time
y,d=time.gmtime()[0::7]
t="Today is "
o=" in the YOLD "+`y+1166`
if y%4<1 and d>59:
if d==60:print"%sSt. Tib's Day%s%d"%(t,o);quit()
d-=1
s,e=divmod(d-1,73)
print t+["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"][(d-1)%5]+", the %d%s day of %s"%(e+1,'tsnrthtddh'[min(e*(e/10-1 and 1)%10,4)::5],["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"][s]+o)
```
Longer, more readable form:
```
import time
# now = time.strptime("2017.06.11", "%Y.%m.%d") # for testing
now = time.gmtime()
year, day_of_year = now[0::7]
leapyear = year % 4 < 1
today = "Today is "
yold = " in the YOLD " + `y+1166`
if leapyear and day_of_year>59:
if day_of_year==60:
print "%sSt. Tib's Day%s%d"% (today, yold)
quit() # dirty, but ... hey.
day_of_year -= 1
season, day = divmod(day_of_year-1,73)
print today + \
["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"][(day_of_year-1)%5] + \
", the %d%s day of %s" % (
day+1,
'tsnrthtddh'[min(day*(day/10-1 and 1)%10,4)::5],
["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"][season] + yold
)
```
**Update:** Fixed with help of the great @Neil and @EriktheOutgolfer. But @Jonathans answer is way shorter.
[Answer]
# [Python 2](https://docs.python.org/2/), 346 bytes
*Note:* This is a golf (and fix) of [jammon's answer](https://codegolf.stackexchange.com/a/125847/53748) - I originally thought I'd submit a comment, but I changed quite a bit in the end (plus the day-suffixes have been fixed).
```
import time
y,d=time.gmtime()[::7]
t="Today is %s in the YOLD "+`y+1166`
r=y%4<1<59<d
d-=r+1
e=d%73
print t%[["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"][d%5]+", the %d%s day of "%(e+1,'snrttddh'[min(e%10+3*(e/9==1),3)::4])+["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"][d/73],"St. Tib's Day"][(r*d)==58]
```
**[Try it online!](https://tio.run/##LY5fa8IwFEff@ylCINiaqsvqn1nMw6aPAwf6MkLArok2bE3kJmX003ep7Ol3uFw4596HxtnnYTDt3UFAwbQ66XPFR5jf2nHSTJTlRiaB47NTVY@MR8QjY1FoNPo8vh8QppeeMrZeXxLgPVnu2G613alEzThQlmiuyKZI7mBsVBAh8OlX69A6sDjHb849PBE/OnvTNjpGBlN//@jZ/8bLSYdg7A0doYpvWApFVpLi/NFBVGwa69wVYZJqyvKJtxCCUs1EtMammrAnWkxTvdhyzrK8yMpyKTMq8L6pnI@Cg/G1AxVp7@y188Y9@jrQVVdDVY9Z5@h6vQYNbRWasWGxKWRsC3N0Nl8Tjw6xXooUpirjfPUih@EP "Python 2 – Try It Online")** or see some [hard-coded test dates](https://tio.run/##TZBBa@MwEIXP9q8YBMJWLbeRnTSNiQ67NexlSxeaSzCGeiMlFl1LQVZY/OtT2W3TIIHeEzPzPuk4uNbo7HxW3dFYB051MtwbC1v6REtQGuI4m7ElZZQRCl86u@iMZg8Xk18VeT2/Novv9ozmn3XZ7GrAh1ldzDiNFGEwUMFHrttDNx7xpLu3SccTJ519L0JIVRTLOgyOVmkH0S8rD8aqRsM2fUpL4IBFOu0iwh/9JAwcRxsjmgFUD7gfH@5aCdvn3yWg5HVIGLu/fw0Dywc8X7P1YrUWYSBSbhMWBpILvMy/Eh2uKvTyX0rXGasRRT@Nmci9/HPSB6l9zqit2r39k@nn6W9epHNKH@DZNr4M1ZXAizpBdGLBwnONhGYPCMcyYTTqtXVOiDaqOqVjidksyW9iebfi3P9wTopiXpOkQo9tY3ofUKp@Z6zw6tHo/alXZuI7WdmcdrbZjVgbn/Vj76TtGteODHfLvPZs7hY26m/UQ@np6yq2N4Jwvnioz@d3).
[Answer]
## JavaScript (ES6), ~~387~~ 380 bytes
```
f=(d=new Date(),a=d.getDate()-1,y=d.getFullYear()+1166)=>d.getMonth()?f(d,a+d.getDate(d.setDate(0))):`Today is ${y%4-2|a<59||59-a--?`Sweetmorn,Boomtime,Pungenday,Prickle-Prickle,Setting Orange`.split`,`[a%5]+`, the ${d=a%73+1}${[,`st`,`nd`,`rd`][d-10-(d%=10)&&d]||`th`} day of `+`Chaos,Discord,Confusion,Bureaucracy,The Aftermath`.split`,`[a/73|0]:`St. Tib's Day`} in the YOLD `+y
```
Takes an optional date parameter. Ungolfed:
```
function discordian(date) {
var a = date.getDate();
while (date.getMonth()) {
date.setDate(0);
a += date.getDate();
}
if (date.getYear() % 4 == 0) {
if (a == 60) return "Today is St. Tib's day in the YOLD " + (date.getYear() + 1166);
if (a > 60) a--;
}
var weekday = ['Setting Orange', 'Sweetmorn', 'Boomtime', 'Pungenday', 'Prickle-Prickle'][a % 5];
var seasonday = (a - 1) % 73 + 1;
var ordinal = seasonday % 10 == 1 && seasonday != 11 ? 'st' : seasonday % 10 == 2 && seasonday != '12' : 'nd' : seasonday % 10 == 3 && seasonday != '13' ? 'rd' : 'th';
var season = ['Chaos', 'Discord', 'Confusion', 'Bureaucracy', 'The Aftermath'][Math.floor((a - 1) / 73)];
return "Today is " + weekday + ", the " + seasonday + ordinal + " day of " + season + " in the YOLD " + (date.getYear() + 1166);
}
```
[Answer]
# C#, 392 bytes
```
using System;s=>{var t=DateTime.Now;int d=t.DayOfYear,y=t.Year,m=d%73;return"Today is "+(DateTime.IsLeapYear(y)&d==60?"St. Tib's Day":"Sweetmorn|Boomtime|Pungenday|Prickle-Prickle|Setting Orange".Split('|')[d%5-1]+", the "+ m+(m<2|m==21|m>30?"st":m==2|m==22?"nd":m==3|m==23?"rd":"th")+" day of "+"Chaos|Discord|Confusion|Bureaucracy|The Aftermath".Split('|')[d/73])+" in the YOLD "+(y+1166);}
```
Full/Formatted version:
```
using System;
class P
{
static void Main()
{
Func<string, string> f = s =>
{
var t = DateTime.Now;
int d = t.DayOfYear, y = t.Year, m = d % 73;
return "Today is " + (DateTime.IsLeapYear(y) & d == 60
? "St. Tib's Day"
: "Sweetmorn|Boomtime|Pungenday|Prickle-Prickle|Setting Orange".Split('|')[d % 5 - 1] +
", the " +
m +
(m < 2 | m == 21 | m > 30 ? "st" : m == 2 | m == 22 ? "nd" : m == 3 | m == 23 ? "rd" : "th") +
" day of " +
"Chaos|Discord|Confusion|Bureaucracy|The Aftermath".Split('|')[d / 73])
+ " in the YOLD " + (y + 1166);
};
Console.WriteLine(f(null));
Console.ReadLine();
}
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 295 bytes
```
J.d2A<J2Kt+s<+,31 28*2t*3,30 31tH@J2=Y&&!%G4<58K!qH3=N%K73%"Today is %s in the YOLD %d",@,++@c"SweetmornZBoomtimeZPungendayZPrickle-PrickleZSetting Orange"\Z%K5%", the %d%s day of ",+N1@c"stndrdth"2h.mb,3+%NT*3q1/N9@c." yNlSFk.»&ô?Z#u!%ô6'mç
M«_ôvëû¹)+¬<"\Z/K73"St. Tib's Day"q*YK59+G1166
```
Note: contains binary, may not be safe to copy-paste from here. Copy-pasting from TIO should work.
[Try it online!](https://tio.run/##LY9BTsJAGIUv4Alw8zNmIHbGYjuCkJRYDRFCtZCUDY2JATrSBttKO2i69wLGtWsXuGRj2E0PVqtx9TbvfV/eUyb8ohiqnn5pDHVLkNQglGmgtxVdKIyyU2CaGJhDvTut1aq4f2Y021Z1PWBdG1vnDKNJ7M0yCFLAKQQRCJ/DdHTTA@whalJCzAVyXjgXYZxE7lUchyIIuTveREselUt3nASL1SM/@U/X4UIE0RJGyaysoDsXW02M6B8Ye6XkVxc/AKLE1kp4KiIv8YSPdF8N55QRbE8UttYadsdcqAiyQ/vRuV7JD1Xua/nuwpVvR5sqznct@VoP88@DW7m9z3fP@TbfV@S3fD8m8qtilOJG@Q85QoVJMK@n0JtlaK1MrWaH9DWt1SqKHw "Pyth – Try It Online")
You can test arbitrary dates by replacing `.d2` at the start with a 3-tuple of (year, month, day) like this: `(2020 2 29)`.
This one was a bit annoying since Pyth doesn't have any way to get "day of year" so I had to compute it myself.
] |
[Question]
[
# What's the Binary Time?
Everybody knows what the normal time is. It's up there in the top-right (or wherever you put it) of your screen. But a question people rarely seem to ask themselves is this: What's the *binary* time?
## Binary Time
Binary Time (True Binary Time) works by first reading the most significant bit (MSB) of the number. If that number is `0`, the time expressed is before noon. If that number is `1`, the time expressed is after noon. The next bit splits the half of the day the first bit expressed into two more equal halves, this time of 6 hours. The following bit splits into 3 hours, the next 90 minutes, and so on. Times like `12:00:00`, where it seems it should be neither, become `1`.
I can only understand this strange system of timing, so I need a program to convert to that for me. But as binary numbers are Base-2, and 2 is a small number, your program must be as short as possible.
## Requirements
* Your program should take a time (as 24-hour-time) as input and output the corresponding binary time number.
* The output number should have 16-bit precision (the number should be 16 digits long).
* You cannot use a builtin that does all of that conversion for you.
* You should floor if it needs to be rounded.
## Rules
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* Your program should not write anything to `STDERR`.
## Test Cases
`00:00:00` ==> `0000000000000000`
`12:00:00` ==> `1000000000000000`
`01:30:00` ==> `0001000000000000`
`10:33:06` ==> `0111000010001101`
`09:57:30` ==> `0110101000111000`
`06:00:00` ==> `0100000000000000`
`18:00:00` ==> `1100000000000000`
## Scoring
To win, as I mentioned earlier, you must have the least bytes.
## Submissions
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
```
/* Configuration */
var QUESTION_ID = 81057; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
if (/<a/.test(lang)) lang = jQuery(lang).text();
languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang > b.lang) return 1;
if (a.lang < b.lang) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<div id="language-list">
<h2>Winners by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
## CJam, 20 bytes
```
l':/60b9m<675/2bG0e[
```
[Test suite.](http://cjam.aditsu.net/#code=qN%2F%7BS%2F0%3D%3AL%3B%0A%0AL'%3A%2F60b9m%3C675%2F2bG0e%5B%0A%0A%5DoNo%7D%2F&input=00%3A00%3A00%20%3D%3D%3E%200000000000000000%0A12%3A00%3A00%20%3D%3D%3E%201000000000000000%0A01%3A30%3A00%20%3D%3D%3E%200001000000000000%0A10%3A33%3A06%20%3D%3D%3E%200111000010001101%0A09%3A57%3A30%20%3D%3D%3E%200110101000111000%0A06%3A00%3A00%20%3D%3D%3E%200100000000000000%0A18%3A00%3A00%20%3D%3D%3E%201100000000000000)
### Explanation
Makes use of the fact that 65536 (216) over 86400 (the number of seconds in a day) simplifies to 512 over 675.
```
l e# Read input.
':/ e# Split around ':', so we get ["hh" "mm" "ss"].
60b e# Interpret as base-60 digits, which computes hh*60^2 + mm*60 + ss,
e# i.e. it computes the total number of seconds. Note that this implicitly
e# converts all three strings to integers.
9m< e# Bitwise left-shift by 9 positions, which is the same as multiplying by
e# 2^9 = 512.
675/ e# Divide by 675, flooring the result.
2b e# Convert to binary.
G0e[ e# Left-pad with zeros to 16 digits.
```
[Answer]
# Pyth, ~~31~~ 27 bytes
```
.[\016.Bs*512cisMcQ\:60 675
```
[Test suite.](http://pyth.herokuapp.com/?code=.[%5C016.Bs*512cisMcQ%5C%3A60+675&test_suite=1&test_suite_input=%2200%3A00%3A00%22%0A%2211%3A00%3A00%22%0A%2212%3A00%3A00%22%0A%2201%3A30%3A00%22%0A%2210%3A33%3A06%22%0A%2209%3A57%3A30%22%0A%2206%3A00%3A00%22%0A%2218%3A00%3A00%22%0A%2223%3A59%3A59%22&debug=0)
Converts the input into number of seconds passed, multiply by a factor of `2^16 / 24*60*60`, and then floor and convert to 16-bit binary.
Saved 4 bytes by simplifying `65536/86400` into `512/675` (stupid me).
## Input/output
```
00:00:00 0000000000000000
11:00:00 0111010101010101
12:00:00 1000000000000000
01:30:00 0001000000000000
10:33:06 0111000010001101
09:57:30 0110101000111000
06:00:00 0100000000000000
18:00:00 1100000000000000
23:59:59 1111111111111111
```
[Answer]
# TSQL(sqlserver 2012), 103 bytes
```
DECLARE @d datetime = '10:33:06'
DECLARE @ char(16)='',@x INT=cast(@d as real)*131072WHILE
len(@)<16SELECT @x/=2,@=concat(@x%2,@)PRINT @
```
[Try it online](https://data.stackexchange.com/stackoverflow/query/493477)
Ungolfed
```
DECLARE @d datetime = '10:33:06'
DECLARE @ char(16)='',
@x INT=cast(@d as real)*131072
WHILE len(@)<16
SELECT @x/=2,@=concat(@x%2,@)
PRINT @
```
# TSQL(sqlserver 2012), ~~119~~ 106 bytes
Also included a different version without the variable @x, however it was a few bytes longer. Including the ungolfed version for those interested:
```
DECLARE @d datetime = '23:59:59'
DECLARE @ varchar(16) =''
WHILE LEN(@)<16
SET @+=LEFT(CAST(@d as decimal(9,9))*2*POWER(2,LEN(@))%2,1)
PRINT @
```
[Answer]
# JavaScript (ES6), 72 ~~76~~ bytes
**Edit** 4 bytes save thx @Neil
~~Still unclear about the rounding.~~ This one truncates and that's ok.
```
t=>(t.split`:`.map(v=>t=+v+60*~~t),t*512/675|65536).toString(2).slice(1)
```
**Test**
```
f=t=>(t.split`:`.map(v=>t=+v+60*~~t),t*512/675|65536).toString(2).slice(1)
function test() {
var v=I.value
R.textContent=f(v)
}
test()
;`00:00:00 ==> 0000000000000000
12:00:00 ==> 1000000000000000
01:30:00 ==> 0001000000000000
10:33:06 ==> 0111000010001101
09:57:30 ==> 0110101000111000
06:00:00 ==> 0100000000000000
18:00:00 ==> 1100000000000000`
.split('\n').forEach(t=>{
[i,k]=t.split(' ==> ')
r=f(i)
ok=r==k
O.textContent += (ok ? 'OK ':'KO ')+ i + ' -> ' + r + (ok? '\n' : ' Expected '+k+'\n')
})
```
```
<input id=I value='12:34:56' oninput=test()>
<span id=R></span>
<pre id=O></pre>
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
YOtk-KWW*k16&YB
```
Uses a builtin for converting a string representing time to a serial date/time number, which is allowed by the challenge.
[**Try it online!**](http://matl.tryitonline.net/#code=WU90ay1LV1cqazE2JllC&input=JzA5OjU3OjMwJw)
### Explanation
```
YO % Input time string. Convert to serial date/time. Time is fractional part
tk- % Duplicate, round down, subtract. This keeps fractional part only
KWW % 34, 2 raised to, 2 raised to (`16W` would require an extra space)
* % Multiply
k % Round down
16&YB % Convert to binary string with 16 digits. Display
```
[Answer]
# [APL (Dyalog)](https://dyalog.com), ~~24~~ 21 bytes
The rules have now been clarified.
Prompts for time as 3-element list.
```
(16/2)⊤⌊512×675÷⍨60⊥⎕
```
Edit: Updated (`⌈` → `⌊`) to match new result for 10:33:06.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPdKTMvsagyJDM39b@GoZm@keajriWPerpMDY0OTzczNz28/VHvCjODR11LH/VNBan/rwAGCG1cBgYKEAQFXBgqDI0IqTAwVDAmYIaBgrGxgoEZHjMsFUzNQcbgVmFG0KUWqCoA "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt for input
`60⊥` evaluate in base-60
`675÷⍨` divide by 675
`512×` multiply by 512
`⌊` floor
`(`…`)⊤` convert to (mnemonic: upside-down base is anti-base) the following number system:
`16/2` replicate 2 sixteen times (i.e. 16-bit binary)
[Answer]
## Q, 32 Bytes
```
48_0b\:_(512%675)*60/:"I"$":"\:
```
**Test**
```
t "00:00:00"
0000000000000000b
t "12:00:00"
1000000000000000b
t "01:30:00"
0001000000000000b
t "10:33:06"
0111000010001101b
t "09:57:30"
0110101000111000b
t "06:00:00"
0100000000000000b
t "18:00:00"
1100000000000000b
```
* In order to reduce display cluttering, i assume a slight modification
to the original expression, that gives name `t` to the lambda
* b suffix indicates binary
**Explanation**
NOTE.- read left to right, evaluates right to left
Reads as: 48 drop from binary representation of floor of 512 divideb by 675 and multiplied by 60 scalarFromVector over integer cast from splits at ":" original string
Evaluation:
`":"\:x` splits string x (implicit arg of the lambda) at ":" character (Q uses "" to denote char)
`"I"$x` cast string(s) x to int(s) -> hours, minutes, seconds
`60/:x` uses base 60 to calculate a single value from a sequence of ints -> seconds total
`(512%675)*x` calculates ratio `512%675` (% is divide) and multiplies seconds. 512%675 is the simplified form of the fraction (totalSecondsPerDay%64K)
`_ x` indicates floor of float x
`0b\:x` calculates binary representation of x (64 bits)
`48_ x` drop first 48 bits, so we have our 16 bits representation
Example (x="01:30:00"). NOTE.- "/" indicates comment to end of line
`":"\:"01:30:00" /-> ("01";"30";"00")
"I"$ /-> 1 30 0
60/: /-> 5400
(512%675)* /-> 4096.0
_ /-> 4096
0b\: /-> 0000000000000000000000000000000000000000000000000001000000000000b
48_ /-> 0001000000000000b`
[Answer]
# Ruby, 75 bytes
```
h,m,s=t.split(':').map &:to_i;((h*3600+m*60+s<<9)/675).to_s(2).rjust 16,'0'
```
I feel like there must be a shorter method of converting the time to seconds, but this is all I could think of.
[Answer]
# Python, 45 bytes
```
lambda h,m,s:bin((s+m*60+h*3600)*512/675)[2:]
```
Came up with the `512/675` factor myself, then saw others did it the same.
[Answer]
# C, 91 bytes
```
f(h,m,s,n,i){i=0;n=(s+m*60+h*3600)*512/675;while(i<16)printf((n&32768)?"1":"0"),n<<=1,i++;}
```
[Answer]
# PHP, ~~47~~ ~~46~~ 43 bytes
Uses IBM-850 encoding.
```
printf(~┌Ø,strtotime($argn.UTC,0)*512/675);
```
Run like this:
```
echo "18:00:00" | php -nR 'printf(~┌Ø,strtotime($argn.UTC,0)*512/675);';echo
```
# Tweaks
* Saved a byte by using IBM-850 encoding.
* Saved 3 bytes by using `$argn`
] |
[Question]
[
Calculate a product or ratio of SI units.
For example, `kg m / s s` (kilogram-meter per second squared) should return `N` (newton).
The input will always be either:
* A list of symbols for SI units, space-separated (representing a product) or
* The above, `/`, and the above (representing a ratio).
The input will never contain any other characters (such as numeric literals or other punctuation).
You may assume that this will always equal a single SI unit.
Use the following symbols:
```
Base quantities:
s # second
m # meter
kg # kilogram
A # ampere
Derived quantities:
N = kg m / s s # newton
J = N m # joule
W = J / s # watt
Hz = W / J # hertz
Pa = N / m m # pascal
C = s A # coulomb
V = J / C # volt
F = C / V # farad
Ω = V / A # ohm (you may use the O symbol instead, for a penalty of +3 bytes)
S = A / V # siemens
Wb = J / A # weber
T = Wb / m m # tesla
H = Wb / A # henry
```
Examples:
```
m => m
N m => J
J / W => s
A J / W => C
T m m => Wb
N / A m => T
V s / A => H
J S / F A => V
s / s s => Hz
Hz kg m Hz => N
Hz s / Ω => S
Wb / H => A
V Pa S s / C => Pa
N s / m Hz => kg
V A => W
s / Ω => F
J / A s A => Ω
```
Shortest code (in bytes) wins.
[Answer]
# CJam, ~~184~~ ~~105~~ ~~98~~ 96 bytes
```
00000000: 22 73 20 6d 20 6b 67 41 20 4e 20 4a 20 57 20 48 "s m kgA N J W H
00000010: 7a 50 61 43 20 56 20 46 20 ce a9 53 20 57 62 54 zPaC V F ..S WbT
00000020: 20 48 22 32 2f 53 66 2d 22 d6 9c 64 c6 a1 24 a4 H"2/Sf-"..d..$.
00000030: 4b f9 1c 4a 57 f4 61 79 31 ed 82 34 22 33 31 38 K..JW.ay1..4"318
00000040: 62 35 62 32 66 6d 34 2f 6c 53 25 32 24 32 24 65 b5b2fm4/lS%2$2$e
00000050: 72 22 2f 22 61 2f 3a 3a 2e 2b 3a 2e 2d 61 23 3d r"/"a/::.+:.-a#=
```
The above is a hexdump; it can be reversed with `xxd -r`.
Verify all test cases at once in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F%7B%0A%20%20%20%20%22s%20m%20kgA%20N%20J%20W%20HzPaC%20V%20F%20%C3%8E%C2%A9S%20WbT%20H%222%2FSf-%22%C3%96%C2%9Cd%C3%86%C2%A1%24%C2%A4K%C3%B9%1CJW%C3%B4ay1%C3%AD%C2%824%22318b5b2fm4%2FLS%252%242%24er%22%2F%22a%2F%3A%3A.%2B%3A.-a%23%3D%0AN%7DfL&input=m%0AN%20m%0AJ%20%2F%20W%0AA%20J%20%2F%20W%0AT%20m%20m%0AN%20%2F%20A%20m%0AV%20s%20%2F%20A%0AJ%20S%20%2F%20F%20A%0As%20%2F%20s%20s%0AHz%20kg%20m%20Hz%0AHz%20s%20%2F%20%C3%8E%C2%A9%0AWb%20%2F%20H%0AV%20Pa%20S%20s%20%2F%20C%0AN%20s%20%2F%20m%20Hz%0AV%20A%0As%20%2F%20%C3%8E%C2%A9%0AJ%20%2F%20A%20s%20A). 1
### Test run
```
$ LANG=en_US
$ cjam si.cjam <<< 'Hz s / Ω'; echo
S
$ cjam si.cjam <<< 'J / A s A'; echo
Ω
```
### Idea
We can encode each unit **u = sa mb kgc Ad** as the vector **tu = (a + c - d, b, c, d)**. 2
This way, for the input **u1 … un / v1 … vm**, we only have to calculate **(tu1 + … + tun) - (tv1 + … + tvm)** and check which unit it corresponds to.
### Code
```
"s m kgA N J W HzPaC V F ΩS WbT H"
2/ e# Split the string into chunks of length 2.
Sf- e# Remove all spaces (if any) from each chunk.
"ÖdÆ¡$¤KùJWôay1í4"
318b e# Convert from base 318 to integer.
5b e# Convert from integer to base 5.
2fm e# Subtract 2 from each base-5 digit.
4/ e# Split into chunks of length 4.
lS% e# Read one line of input sand split it at spaces.
2$2$ e# Copy the unit names and the vector table.
er e# Perform transliteration.
"/"a/ e# Split at "/".
::.+ e# Add the vectors of numerator and denominator (if any).
:.- e# Subtract the resulting sums (or leave a single sum untouched).
a# e# Find the index of the resulting vector in the vector table.
= e# Retrieve the corresponding unit.
```
---
1 Note that, due to limitations of the online interpreter, I cannot use a different encoding for source code and I/O. Therefore, the symbol Ω shows up as its UTF-8 encoding (Ω). The official Java interpreter does not share this limitation.
2 This saves a few bytes over the straightforward mapping to **(a, b, c, d)**, since it shortens the range of the first coordinate.
[Answer]
# GNU sed, 1118
Way too long but gets the job done.
Score includes +1 for `-r` option to sed. As if it matters here. Score excludes comments.
```
### convert 2-letter units to 1-letter substitutes
s/kg/k/g
s/Hz/z/g
s/Pa/P/g
s/Wb/b/g
### remove spaces
s/ //g
### start label for main loop to render all in terms of base units
:
### convert N in denominator to s s / kg m
s|/(.*)N|ss/\1km|;t
### convert N in numerator to kg m / ss
s|N(.*)/|\1km/ss|;t
### convert N in non-rational to kg m / ss
s|N(.*)|\1km/ss|;t
### ... etc for all other derived units
s|/(.*)J|ss/\1kmm|;t
s|J(.*)/|\1kmm/ss|;t
s|J(.*)|\1kmm/ss|;t
s|/(.*)W|sss/\1kmm|;t
s|W(.*)/|\1kmm/sss|;t
s|W(.*)|\1kmm/sss|;t
s|/(.*)z|s/\1|;t
s|z(.*)/|\1/s|;t
s|z(.*)|\1/s|;t
s|/(.*)P|mss/\1k|;t
s|P(.*)/|\1k/mss|;t
s|P(.*)|\1k/mss|;t
s|C|sA|;t
s|/(.*)V|sssA/\1kmm|;t
s|V(.*)/|\1kmm/sssA|;t
s|V(.*)|\1kmm/sssA|;t
s|/(.*)F|kmm/\1ssssAA|;t
s|F(.*)/|\1ssssAA/kmm|;t
s|F(.*)|\1ssssAA/kmm|;t
s|/(.*)Ω|sssAA/\1kmm|;t
s|Ω(.*)/|\1kmm/sssAA|;t
s|Ω(.*)|\1kmm/sssAA|;t
s|/(.*)S|kmm/\1sssAA|;t
s|S(.*)/|\1sssAA/kmm|;t
s|S(.*)|\1sssAA/kmm|;t
s|/(.*)b|ssA/\1kmm|;t
s|b(.*)/|\1kmm/ssA|;t
s|b(.*)|\1kmm/ssA|;t
s|/(.*)T|ssA/\1k|;t
s|T(.*)/|\1k/ssA|;t
s|T(.*)|\1k/ssA|;t
s|/(.*)H|ssAA/\1kmm|;t
s|H(.*)/|\1kmm/ssAA|;t
s|H(.*)|\1kmm/ssAA|;t
### cancel out any units appearing in both numerator and denominator
s|(.)(.*/.*)\1|\2|;t
### remove trailing slash when rational cancels down to non-rational
s|/$||
### sort numerator and denominator kg > m > s > A
:A;s|([^/A])A|A\1|;tA
:s;s|([^/s])s|s\1|;ts
:m;s|([^/m])m|m\1|;tm
:k;s|([^/k])k|k\1|;tk
### Final replacements back to derived units
s|kmm/sssAA|Ω|
s|kmm/sssA|V|
s|kmm/sss|W|
s|kmm/ssAA|H|
s|kmm/ssA|Wb|
s|kmm/ss|J|
s|km/ss|N|
s|k/mss|Pa|
s|k/ssA|T|
s|/s|Hz|
s|ssssAA/kmm|F|
s|sssAA/kmm|S|
s|sA|C|
s/k/kg/
```
[Answer]
# Javascript ES6, 479 bytes
```
f=(s,b="s, m, gk, A, gkm,ss gkmm,ss gkmm,sss gkmm,AAss gk,mss As, gkmm,Asss AAssss,gkmm gkmm,AAsss AAsss,gkmm gkmm,Ass gk,Ass ,s".split` `,d="s m kgA N J W H PaC V F Ω S WbT Hz",p=s.split` / `.map(i=>i.split` `.map(i=>b[d.indexOf(i)/2].split`,`).reduce((p,c)=>(p[0]+=c[0],p[1]+=c[1],p),[[],[]])))=>(p[1]&&(p[0][0]+=p[1][1],p[0][1]+=p[1][0]),[x,y]=p[0].map(i=>[...i].sort().join``),d.match(/../g)[b.indexOf([...x].reduce((p,c)=>(y==(n=y.replace(c,""))&&(p+=c),y=n,p),"")+","+y)])
```
Ungolfed:
```
f=(s, // define function, accept string to calculate
// vvv derived quantities reduced to base quantities in the form of <numerator>,<denominator>
b="s, m, gk, A, gkm,ss gkmm,ss gkmm,sss gkmm,AAss gk,mss As, gkmm,Asss AAssss,gkmm gkmm,AAsss AAsss,gkmm gkmm,Ass gk,Ass ,s".split` `,
d="s m kgA N J W H PaC V F Ω S WbT Hz", // symbols list
p=s.split` / ` // split input into [numerator,denominator]
.map(i=>i.split` ` // split numerator and denominator strings into list of symbols
.map(i=>b[d.indexOf(i)/2].split`,`) // convert symbols to their base quantities
.reduce((p,c)=>(p[0]+=c[0],p[1]+=c[1],p),[[],[]])) // consolidate base quantities
)=>(
p[1]&&(p[0][0]+=p[1][1],p[0][1]+=p[1][0]), // if input was in form of numerator / denominator, reduce to numerator / 1
[x,y]=p[0].map(i=>[...i].sort().join``), // sort base quantities in numerator and denominator strings
d.match(/../g)[b.indexOf( // derive symbol from base quantities
[...x].reduce((p,c)=>(y==(n=y.replace(c,""))&&(p+=c),y=n,p),"")+","+y // remove duplicate symbols from numerator and denominator
)])
```
Test Runs:
```
>> ["m","N m","J / W","A J / W","T m m","N / A m","V s / A",
"J S / F A","s / s s","Hz kg m Hz","Hz s / Ω","Wb / H",
"V Pa S s / C","N s / m Hz","V A","s / Ω","J / A s A"]
.forEach(i=>console.log((i+" ".repeat(12)).slice(0,12)+" -> "+f(i)))
<< m -> m
N m -> J
J / W -> s
A J / W -> C
T m m -> Wb
N / A m -> T
V s / A -> H
J S / F A -> V
s / s s -> Hz
Hz kg m Hz -> N
Hz s / Ω -> S
Wb / H -> A
V Pa S s / C -> Pa
N s / m Hz -> kg
V A -> W
s / Ω -> F
J / A s A -> Ω
```
] |
[Question]
[
There are two pieces of wood. Both consist of a straight body and some extra blocks below the body. An example piece with extra blocks at (0-indexed) positions 0,4,7,9,10:
```
XXXXXXXXXXX
X X X XX
```
The piece can be represented as a `01` binary sequence with the `i`th character showing if there is a block at the `i`th position. The upper example can be represented as `10001001011`.
We can put together two pieces by vertically flipping the second one (and maybe flipping it horizontally too). After the flip(s) we can find an alignment where the two pieces can be put together to have a height of 3.
```
Two example pieces:
XXXXXXXXXXX XXXXXXXX
X X X XX XXX
Second piece flipped vertically and horizontally:
XXXXXXXXXXX
X X X XX
XXX
XXXXXXXX
Pieces put together:
XXXXXXXXXXX
XXXXX X XX
XXXXXXXX
```
The example resulted in a total width of 12 blocks.
You should write a program or function which receives two string as input representing the two pieces and outputs an integer the **minimal achievable width** with a height of 3.
## Input
* Two strings consisting of the characters `0` and `1`.
* Both strings contain at least one character.
* You may choose to receive the two strings as one joined by a single space.
## Output
* A single positive integer, the minimal total width achievable.
## Examples
```
0 0 => 1
1 0 => 1
1 1 => 2
11 111 => 5
010 0110 => 5
0010 111 => 5
00010 11011 => 6
01010 10101 => 5
1001 100001 => 6
1110001100001 1100100101 => 14
001101010000101 100010110000 => 16
0010110111100 001011010101001000000 => 21
0010110111100 001011010101001001100 => 28
100010100100111101 11100101100010100100000001 => 27
0010 10111 => 5
0100 10111 => 5
0010 11101 => 5
0100 11101 => 5
10111 0010 => 5
10111 0100 => 5
11101 0010 => 5
11101 0100 => 5
```
This is code golf so the shortest entry wins.
[Answer]
# Pyth, ~~37~~ ~~35~~ ~~34~~ ~~32~~ 31 bytes
```
eSX0lM.zff-\1@VhY>eYT*Fm,d_d.z0
```
Takes input newline separated.
[Demonstration](https://pyth.herokuapp.com/?code=eSX0lM.zff-%5C1%40VhY%3EeYT*Fm%2Cd_d.z0&input=0010110111100%0A001011010101001001100&debug=0), [Test Harness](https://pyth.herokuapp.com/?code=FN.zIN%3DZ%3CcNd2ZeSX0lMZff-%5C1%40VhY%3EeYT*Fm%2Cd_dZ0&input=0+0++%3D%3E++%0A%0A1+0++%3D%3E++%0A%0A1+1++%3D%3E++%0A%0A11+111++%3D%3E++%0A%0A010+0110++%3D%3E++%0A%0A0010+111++%3D%3E++%0A%0A0010+10111++%3D%3E++%0A%0A00010+11011++%3D%3E++%0A%0A01010+10101++%3D%3E++%0A%0A1001+100001++%3D%3E++%0A%0A1110001100001+1100100101++%3D%3E++%0A%0A001101010000101+100010110000++%3D%3E++%0A%0A0010110111100+001011010101001000000++%3D%3E%0A%0A0010110111100+001011010101001001100++%3D%3E++%0A%0A100010100100111101+11100101100010100100000001++%3D%3E++&debug=0).
Explanation:
At the high level, for each combination of normal and reversed strings, we shift the second string to the left by a given number of positions, and check for overlaps with the first string. This is repeated until a shift amount with no overlaps is found. That shift amount is added to the first string length, and the result is compared with the second string length. The higher value is printed.
```
eSX0lM.zff-\1@VhY>eYT*Fm,d_d.z0
.z The list of the two input strings.
m Map to
,d_d The pair of each string and its reverse.
*F Take the cartesisan product of those lists.
f Filter those pairs of a first string and a
second string, possibly reversed,
-\1 On the absence of the string "1" in
@V The vectorized intersection (intersection
of 0th position, 1st position, etc.) of
hY the first string and
>eYT the second string without the first T elements.
f 0 Starting at 0 and counting upwards, find the
lowest T where the result is truthy.
(where anything passes the inner filter)
lM.z Map the input strings to their lengths.
X0 Add the above result to the first entry.
eS Take the maximum of the two values and print.
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), ~~72~~ ~~70~~ 48 bytes
```
Fp[aRVa]CP[bRVb]L#a+1{I2NI$+plAE:#$+^pp@1.:0}MNl
```
Takes the two strings as command-line arguments. Formatted, with comments:
```
a, b initialized from cmdline args; l is [] (implicit)
F p [aRVa]CP[bRVb] For each possible pair p of a/reverse(a) with b/reverse(b):
L #a+1 { Loop for each potential offset of bottom piece:
I 2 NI $+p If no 2's in the sum of p:
l AE: # $+ ^p Append the max width of elements of p to l (see below for explanation)
p@1 .: 0 Append a 0 to bottom piece
}
MNl The answer is min(l); print it (implicit)
```
We're only calculating the overlaps where the bottom piece sticks out to the left, so we need to try it with both top and bottom pieces reversed. Each time through the inner loop, if there are no 2's in the sum, it is a fit; we then tack another zero onto the the end of the bottom piece and try again.
```
0010
111
0121
0010
111_
1120
0010
111__
11110
0010
111___
111010
0010
111____
1110010
```
To find the total width, we split the elements of `p` into lists of characters and sum. Item-wise operations on uneven-length lists preserve the length of the longer one, so the length of this sum is exactly what we need. (Splitting is necessary because simply summing as numbers will eliminate leading zeros: `$+[0101 10] = 111`, but `$+^[0101 10] = [0 1 1 1]`.)
```
C:\> pip.py woodPacking.pip 0010 111
5
```
[Answer]
# Ruby 127 ~~130~~
This turned out to be *so* long... :(
```
->m,n{[[m,n],[m,n.reverse],[n,m],[n,m.reverse]].map{|u,d|[(0..l=u.size).find{|i|(d.to_i(2)<<i)&u.to_i(2)<1}+d.size,l].max}.min}
```
Tests: <http://ideone.com/te8XWk>
Readable Ruby:
```
def pack_length piece1, piece2
min_possible_packed_length = [
min_packed_length(piece1, piece2),
min_packed_length(piece1, piece2.reverse),
min_packed_length(piece2, piece1),
min_packed_length(piece2, piece1.reverse)
].min
min_possible_packed_length
end
def min_packed_length up_piece, down_piece
x = up_piece.to_i 2
y = down_piece.to_i 2
# find the smallest shift for the piece placed down
# so that they fit together
min_packed_shift = (0..up_piece.size).find{|i| (y<<i)&x<1 }
# min pack length cannot be smaller than any of the
# two pieces
[min_packed_shift + down_piece.size, up_piece.size].max
end
```
[Answer]
# JavaScript (*ES6*) 160
Couldn't make shorter ...
```
F=(a,b,c=[...b].reverse(),
K=(a,b,t=a.length)=>{
for(e=i=-1;e&&i++<t;)for(e=j=0;u=b[j];j++)e|=u&a[j+i];
return t<i+j?i+j:t
})=>Math.min(K(a,b),K(a,c),K(b,a),K(c,a))
// test
out=x=>O.innerHTML += x+'\n'
test=[
['0', '0', 1],['1', '0', 1],['1', '1', 2],['11', '111', 5]
,['010', '0110', 5],['0010', '111', 5],['0010', '10111', 5]
,['00010', '11011', 6],['01010', '10101', 5],['1001', '100001', 6]
,['1110001100001', '1100100101', 14]
,['001101010000101', '100010110000', 16]
,['0010110111100', '001011010101001000000', 21]
,['0010110111100', '001011010101001001100', 28]
,['100010100100111101', '11100101100010100100000001', 27]
,['0010','10111', 5],['0100','10111', 5]
,['0010','11101', 5],['0100','11101', 5]
,['10111','0010', 5],['10111','0100', 5]
,['11101','0010', 5],['11101','0100', 5]
]
test.forEach(t=>{
r = F(t[0],t[1]),
out(
(r==t[2]?'Ok':'Fail')
+ ' A: '+t[0]+', B: '+t[1]
+ ', Result: '+r + ', Check: '+t[2])
})
```
```
pre { font-size: 10px }
```
```
<pre id=O></pre>
```
] |
[Question]
[
**Description**
Given a source path and a destination path, output the relative path to the destination with respect to the source.
**Rules**
1. The input can come from stdin or as arguments to the program/function.
2. Both Windows and Unix style paths must be supported.
3. The output path can use `/` and/or `\` for the path separator (your choice and combination of both is OK).
4. You can assume a relative path is possible.
5. The use of external programs, built-in or library functions made for computing relative paths is prohibited (e.g. Python's `os.path.relpath`)
6. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
*Edit:* New rule from comments.
7. The relative path must be the shortest relative path possible.
8. Assume the destination path is different from the source path.
**Example 1**
```
# In
/usr/share/geany/colorschemes
/usr/share/vim/vim73/ftplugin
# Out
../../vim/vim73/ftplugin
```
**Example 2**
```
# In
C:\Windows\System32\drivers
C:\Windows\System32\WindowsPowerShell\v1.0
# Out
..\WindowsPowerShell\v1.0
```
[Answer]
# CJam, 46 bytes
```
ll]{'\/'/f/:~}/W{)__3$=4$@==}g@,1$-"../"*o>'/*
```
[Try it online.](http://cjam.aditsu.net/)
### Examples
```
$ echo '/usr/share/geany/colorschemes
> /usr/share/vim/vim73/ftplugin' | cjam path.cjam; echo
../../vim/vim73/ftplugin
$ echo 'C:\Windows\System32\drivers
> C:\Windows\System32\WindowsPowerShell\v1.0' | cjam path.cjam; echo
../WindowsPowerShell/v1.0
```
### How it works
```
ll] " Read two lines from STDIN and wrap them in an array. ";
{ " For each line: ";
'\/ " Split by “\”. ";
'/f/ " Split each chunk by “/”. ";
:~ " Flatten the array of chunks. ";
}/ " ";
W " Push -1 (accumulator). ";
{ " ";
)__ " Increment and duplicate twice. ";
3$= " Extract the corresponding chunk from the first line. ";
4$@= " Extract the corresponding chunk from the second line. ";
= " If the are equal, ";
}g " repeat the loop. ";
@, " Rotate the array of chunks of the first line on top and get its length. ";
1$- " Subtract the value of the accumulator. ";
"../"*o " Print the string “../” repeated that many times. ";
> " Remove all chunks with index less than the accumulator of the second line. ";
'/* " Join the chunks with “/”. ";
```
[Answer]
# Bash + coreutils, 116
Here's a shell script to get the ball rolling. Pretty sure there'll be shorter answers:
```
n=`cmp <(echo $1) <(echo $2)|grep -Po "\d+(?=,)"`
printf -vs %`grep -o /<<<${1:n-1}|wc -l`s
echo ${s// /../}${2:n-1}
```
Output:
```
$ ./rel.sh /usr/share/geany/colorschemes /usr/share/vim/vim73/ftplugin
../vim/vim73/ftplugin
$ ./rel.sh /usr/share/geany/colorschemes/ /usr/share/vim/vim73/ftplugin/
../../vim/vim73/ftplugin/
$ ./rel.sh /usr/share/vim/vim73/ftplugin /usr/share/geany/colorschemes
../../geany/colorschemes
$
```
Note there is no way for the script to tell if the string `ftplugin` is a file or a directory. You may explicitly provide a directory by appending it with an `/` as in the example above.
Won't handle paths containing whitespace or other funny characters. Not sure if that is a requirement or not. Just a few extra quotes would be needed.
[Answer]
# Javascript (E6) 104
*Edit* Added alert for output
```
R=(s,d)=>alert(s.split(x=/\/|\\/).map(a=>a==d[0]?d.shift()&&'':'../',d=d.split(x)).join('')+d.join('/'))
```
**Ungolfed**
```
R (s,d) => // a single espression is returned, no {} or () needed
s.split(x=/\/|\\/) // split string at / or \, save regexp in X for later
.map( // create a new array from s
a => a == d[0] // check if current of s and d equals
? d.shift() && '' // map to '' and cut 1 element of d
: '../', // else map to '../'
d=d.split(x)) // second param of map is useless, so split d here
.join('')+d.join('/') // join map and concat to rest of d adding separators
```
**Test**
```
R('C:\\Windows\\System32\\drivers','C:\\Windows\\System32\\WindowsPowerShell\\v1.0')
```
>
> ../WindowsPowerShell/v1.0
>
>
>
```
R('/usr/share/geany/colorschemes','/usr/share/vim/vim73/ftplugin')
```
>
> ../../vim/vim73/ftplugin
>
>
>
[Answer]
## Ruby >= 1.9, 89 ~~94~~ characters
```
$;=/\\|\//
a,b=$*.map &:split
puts"../"*(a.size-r=a.index{a[$.+=1]!=b[$.]}+1)+b[r..-1]*?/
```
Input via command line arguments. Works for both UNIX- and Windows-style paths, including paths with repeated folder names:
```
$ ruby relpath.rb /usr/share/geany/colorschemes /usr/share/vim/vim73/ftplugin
../../vim/vim73/ftplugin
$ ruby relpath.rb 'C:\Windows\System32\drivers' 'C:\Windows\System32\WindowsPowerShell\v1.0'
../WindowsPowerShell/v1.0
$ ruby relpath.rb /foo/bar/foo/bar /foo/qux/foo/bar
../../../qux/foo/bar
```
[Answer]
# J - 63 char
A function taking the old path on the left and the new path on the right.
```
}.@;@(c=.c&}.`(,~(<'/..')"0)@.(~:&{.))&('/'<;.1@,'\/'&charsub)~
```
This solution comes in three parts, looking like `post@loop&pre~`. Explained by explosion:
```
post @ loop & pre ~ NB. the full golf
~ NB. swap the arguments: new on left, old on right
& pre NB. apply pre to each argument
loop NB. run the recursive loop on both
post @ NB. apply post to the final result
'/'<;.1@,'\/'&charsub NB. pre
'\/'&charsub NB. replace every \ char with /
'/' , NB. prepend a / char
<;.1@ NB. split string on the first char (/)
c=.c&}.`(,~(<'/..')"0)@.(~:&{.) NB. loop
@.(~:&{.) NB. if the top folders match:
&}. NB. chop off the top folders
c NB. recurse
` NB. else:
(<'/..')"0 NB. change remaining old folders to /..
,~ NB. append to front of remaining new folders
c=. NB. call this loop c to recurse later
}.@; NB. post
; NB. turn the list of folders into a string
}.@ NB. chop off the / in the front
```
Note that we add a leading `/` to each path before splitting, so that we handle Windows-style paths by making `C:` into a "folder". This results in an empty folder at the start of Unix-style paths, but that always gets removed by the loop.
See it in action:
```
NB. you can use it without a name if you want, we will for brevity
relpath =. }.@;@(c=.c&}.`(,~(<'/..')"0)@.(~:&{.))&('/'<;.1@,'\/'&charsub)~
'/usr/share/geany/colorschemes' relpath '/usr/share/vim/vim73/ftplugin'
../../vim/vim73/ftplugin
'C:\Windows\System32\drivers' relpath 'C:\Windows\System32\WindowsPowerShell\v1.0'
../WindowsPowerShell/v1.0
```
You can also try it yourself at [tryj.tk](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%27%2Ffoo%2Fbar%2Ffoo%2Fbar%27%20%28relpath%20%3D%3A%20%7D.%40%3B%40%28c%3D.c%26%7D.%60%28%2C~%28%3C%27%2F..%27%29%220%29%40.%28~%3A%26%7B.%29%29%26%28%27%2F%27%3C%3B.1%40%2C%27%5C%2F%27%26charsub%29~%29%20%27%2Ffoo%2Fqux%2Ffoo%2Fbar%27).
[Answer]
# Bash, 69 66
I didn't post this one because I thought someone must be able to do it much better. But apparently it is not that easy.
```
sed -r 'N;s/(.*[/\])(.*)\n\1/\2\n/'|sed '1s/[^/\]*/../g;N;s!\n!/!'
```
`N` makes `sed` match two lines together. The first expression removes the common prefix ending with `/` or `\`. The second expression replaces directory names with `..` in the first line. Finally it concatenates the two lines with the separator.
Thanks to Hasturkun for 3 characters.
[Answer]
# C, 119 106
```
void p(char*s,char* d){while(*s==*d){s++;d++;}s--;while(*s){if(*s==47||*s==92)printf("../");s++;}puts(d);}
```
[Answer]
## Python 3, 120
```
a,b=(i.split('\\/'['/'in i])for i in map(input,' '))
while[]<a[:1]==b[:1]:del a[0],b[0]
print('../'*len(a)+'/'.join(b))
```
Example:
```
$ python3 path.py
/usr/share/geany/colorschemes
/usr/share/vim/vim73/ftplugin
../../vim/vim73/ftplugin
```
[Answer]
# Ruby - 89
```
r=/\/|\\/
s = ARGV[0].split r
d = ARGV[1].split r
puts ("../"*(s-d).size)+((d-s).join"/")
```
Usage:
```
ruby relative.rb working/directory destination/directory
```
[Answer]
# JavaScript - 155
```
function p(s,d){s=s.split(/\\|\//g);d=d.split(/\\|\//g);o=[];for(i=0;s[i]==d[i];i++);for(j=s.length-i;j--;)o[j]="..";return o.concat(d.slice(i)).join("/")}
```
Parses either path format but outputs with `/` separator.
```
console.log(p("/usr/share/geany/colorschemes","/usr/share/vim/vim73/ftplugin"));
../../vim/vim73/ftplugin
console.log(p("/usr/share/geany/colorschemes/test/this","/usr/share/vim/vim73/ftplugin/this/is/a/test"));
../../../../vim/vim73/ftplugin/this/is/a/test
console.log(p("c:\\windows\\system32\\drivers\\etc\\host","c:\\windows\\system\\drivers\\etc\host"));
../../../../system/drivers/etchost
```
[Answer]
# PHP, 158 151
```
function r($a,$b){$a=explode('/',$a);$b=explode('/',$b);foreach($a as $k=>$v){if($v==$b[$k])$b[$k]='..';else break;}unset($b[0]);echo implode('/',$b);}
```
Ungolfed:
```
function r($a,$b){
$a=explode('/',$a);
$b=explode('/',$b);
foreach($a as $k=>$v){
if($v==$b[$k])$b[$k]='..';
else break;
}
unset($b[0]);
echo implode('/',$b);
}
// these lines are not included in count:
r('/test/test2/abc','/test/test3/abcd'); // ../test3/abcd
r('/test/test2/abc','/test/test2/abcd'); // ../../abcd
```
[Answer]
## Groovy - 144 chars
One solution:
```
x=args[0][1]!=':'?'/':'\\'
f={args[it].tokenize x}
s=f 0
d=f 1
n=0
while(s[n]==d[n++]);
u="..$x"*(s.size-(--n))
println "$u${d.drop(n).join x}"
```
example output:
```
bash$ groovy P.groovy C:\\Windows\\System32\\drivers C:\\Windows\\System32\\WindowsPowerShell\\v1.0
..\WindowsPowerShell\v1.0
bash$ groovy P.groovy /usr/share/geany/colorschemes /usr/share/vim/vim73/ftplugin
../../vim/vim73/ftplugin
bash$ groovy P.groovy /foo/bar/foo/bar /foo/qux/foo/bar
../../../qux/foo/bar
```
ungolfed:
```
// fs = file seperator, / or \
fs = args[0][1]!=':'?'/':'\\'
s = args[0].tokenize fs
d = args[1].tokenize fs
// n = # of matching dirs from root + 1
n = 0
while (s[n] == d[n++]) ;
// up = the up-prefix. e.g. "../../..", for instance
n--
up = "..${fs}" * (s.size-n)
println "$up${d.drop(n).join fs}"
```
] |
[Question]
[
The goal of this code-golf is to create a program that takes a string as input, and you have to output the [SHA-1](http://en.wikipedia.org/wiki/SHA-1) hash value as a hexadecimal number. You can find the pseudocode for SHA-1 [here](http://en.wikipedia.org/wiki/SHA-1#SHA-1_pseudocode)
Other rules:
1. No network access
2. You're not allowed to run external programs
3. You're not allowed to use built-in methods to hash the input
4. The shortest code wins
5. It's only necessary to handle ASCII input
6. Output can be either lowercase or uppercase
7. The input can be provided using:
1. Prompting for input
2. Using command-line arguments
3. Using STDIN
Test cases:
```
Input: The quick brown fox jumps over the lazy dog
Output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12
----------------------------------------------------------
Input: The quick brown fox jumps right over the lazy dog
Output: 1c3aff41d97ada6a25ae62f9522e4abd358d741f
------------------------------------------------------------
Input: This is a code golf challenge
Output: f52ff9edd95d98e707bd16a7dead459cb8db8693
```
[Answer]
### GolfScript, 374 322 characters
```
[128]+.,.~55+64%1,*\(8*2
32?:?.*+256{base}:B~1>++"!Vi9y BRQ+@phoKD5Vj=]30z0"{96@32-*+}*?B\64/{4/{256B}%{0'=820'{64-
2$=^}/2*.?/+?%+}64*1$'&4$?(^3$&|1518500249{++[]@+@+@?*4/.?/+?%+2$+\@32*.?/++@(@+?%@-1%+}:Y~
^2$^1859775393Y
&4$3$&|3$3$&|2400959708Y
^2$^3395469782Y'n/{'~3$3$'\+20*~}/+]zip{~+?%}%}/{?+16B{.9>7*+48+}%1>}%''+
```
This is based on an exact implementation of the pseudo-code in GolfScript plus some minor encodings to shorten the code (try it [online](http://golfscript.apphb.com/?c=OyJUaGUgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nIgoKWzEyOF0rLiwufjU1KzY0JTEsKlwoOCoyCjMyPzo%2FLiorMjU2e2Jhc2V9OkJ%2BMT4rKyIhVmk5eSBCUlErQHBob0tENVZqPV0zMHowIns5NkAzMi0qK30qP0JcNjQvezQvezI1NkJ9JXswJz04MjAnezY0LQoyJD1efS8yKi4%2FLys%2FJSt9NjQqMSQnJjQkPyheMyQmfDE1MTg1MDAyNDl7KytbXUArQCtAPyo0Ly4%2FLys%2FJSsyJCtcQDMyKi4%2FLysrQChAKz8lQC0xJSt9Oll%2BCl4yJF4xODU5Nzc1MzkzWQomNCQzJCZ8MyQzJCZ8MjQwMDk1OTcwOFkKXjIkXjMzOTU0Njk3ODJZJ24veyd%2BMyQzJCdcKzIwKn59Lytdemlwe34rPyV9JX0vez8rMTZCey45PjcqKzQ4K30lMT59JScnKwo%3D&run=true)). Input will be read from STDIN.
[Answer]
## Python 3 - 645 chars
```
h=0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0
L=lambda v,s:(v<<s|v>>B-s)%2**B
B=32
R=range
m=input().encode()
l=len(m)
m+=b'\x80'+bytes((55-l)%64)+m.fromhex(hex(2**64+l*8)[3:])
for C in [m[i:i+64]for i in R(0,len(m),64)]:
w=[sum(C[i+j]<<8*(3-j)for j in R(4))for i in R(0,64,4)];a,b,c,d,e=h
for i in R(16,80):w+=[L(w[i-3]^w[i-8]^w[i-14]^w[i-16],1)]
for i in R(80):f=[b&c|~b&d,b^c^d,b&c|b&d|c&d,b^c^d][i//20];k=[0x5A827999,0x6ED9EBA1,0x8F1BBCDC,0xCA62C1D6][i//20];t=L(a,5)+f+e+k+w[i];e=d;d=c;c=L(b,30);b=a;a=t%2**32
g=a,b,c,d,e;h=[(h[i]+g[i])%2**32for i in R(5)]
B=160
print('%x'%(L(h[0],128)|L(h[1],96)|L(h[2],64)|L(h[3],32)|h[4]))
```
Just a golfed version of the pseudocode.
[Answer]
# D (759 chars)
Online executable version: <http://dpaste.dzfl.pl/f0c8508f>
```
import std.range,std.algorithm,std.bitmanip,std.stdio:g=writef;
void main(char[][]x){
auto m=cast(ubyte[])x[1];
uint a=0x67452301,b=0xEFCDAB89,i,t,f,k;
uint[5]h=[a,b,~a,~b,0xC3D2E1F0],s;
uint[80]w;
auto r=(uint u,uint b)=>u<<b|u>>32-b;
auto u=(uint i)=>[r(s[0],5)+f+s[4]+k+w[i],s[0],r(s[1],30),s[2],s[3]];
ubyte[64]p;
p[0]=128;
m~=p[0..64-(m.length+8)%64]~nativeToBigEndian(8*m.length);
foreach(ch;m.chunks(64)){
16.iota.map!(i=>w[i]=ch[i*4..$][0..4].bigEndianToNative!uint).array;
iota(16,80).map!(i=>w[i]=r(w[i-3]^w[i-8]^w[i-14]^w[i-16],1)).array;
s=h;
80.iota.map!(i=>(i<20?f=s[3]^s[1]&(s[2]^s[3]),k=0x5A827999:i<40?f=s[1]^s[2]^s[3],k=0x6ED9EBA1:i<60?f=s[1]&s[2]|s[3]&(s[1]|s[2]),k=0x8F1BBCDC:(f=s[1]^s[2]^s[3],k=0xCA62C1D6),s[]=u(i)[])).array;
h[]+=s[];
}
g("%(%08x%)",h);
}
```
[Answer]
## C, 546 characters
The program calculates the SHA-1 of the contents of its standard input.
```
unsigned b[16],k[]={1732584193,0xEFCDAB89,0,271733878,0xC3D2E1F0},i,j,n,p,t,u,v,w,x;
char*d=b;a(c){for(d[p++^3]=c,c=0,t=*k,u=k[1],v=k[2],w=k[3],x=k[4];
c>79?*k+=t,k[1]+=u,k[2]+=v,k[3]+=w,k[4]+=x,p=0:p>63;x=w,w=v,v=u<<30|u/4,u=t,t=i)
i=b[c-3&15]^b[c+8&15]^b[c+2&15]^b[j=c&15],c++>15?b[j]=i*2|i>>31:0,i=u^v^w,
i=(t<<5|t>>27)+x+b[j]+(c<21?(w^u&(v^w))+1518500249:c<41?i+1859775393:
c<61?(u&v|w&(u|v))-1894007588:i-899497514);}
main(){for(k[2]=~*k;i=~getchar();++n)a(~i);for(a(128);p-56;a(0));
for(;p<20?printf("%02x",(d=k)[p^3]&255):p>55;a(n*8L>>504-p*8));}
```
A couple of notes:
1. This program assumes that `int` is exactly 32 bits. For platforms where this is not the case, the `unsigned` declaration at the very beginning should be replaced by the platform's unsigned 32-bit type. (`uint32_t` would be the obvious choice, if it didn't require `#include <stdint.h>`.)
2. This program assumes a little-endian platform. For a big-endian platform, simply remove the two occurrences of `^3` in the program, and replace the initialization of `k[]` with the following block: `{19088743,0x89ABCDEF,0,1985229328,0xF0E1D2C3}`, for a size of 541 characters.
3. For implementations where `char` is unsigned by default, one can delete the `&255` that appears on the final line to save four more characters.
[Answer]
My python code is a little longer but it is fully working.
```
data="hello world"
bytes = ""
h0,h1,h2,h3,h4=0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0
for n in range(len(data)):bytes+='{0:08b}'.format(ord(data[n]))
bits=bytes+"1"
pBits=bits
while len(pBits)%512!=448:pBits+="0"
pBits+='{0:064b}'.format(len(bits)-1)
def chunks(l,n):return[l[i:i+n]for i in range(0,len(l),n)]
def rol(n,b):return((n<<b)|(n>>(32-b)))&0xffffffff
for c in chunks(pBits,4512):
words=chunks(c,32)
w=[0]*80
for n in range(0,16):w[n]=int(words[n],2)
for i in range(16,80):w[i]=rol((w[i-3]^w[i-8]^w[i-14]^w[i-16]),1)
a,b,c,d,e=h0,h1,h2,h3,h4
for i in range(0,80):
if 0<=i<=19:f=(b&c)|((~b)&d);k=0x5A827999
elif 20<=i<=39:f=b^c^d;k=0x6ED9EBA1
elif 40<=i<=59:f=(b&c)|(b&d)|(c&d);k=0x8F1BBCDC
elif 60<=i<=79:f=b^c^d;k=0xCA62C1D6
temp=rol(a,5)+f+e+k+w[i]&0xffffffff
e,d,c,b,a=d,c,rol(b,30),a,temp
h0+=a
h1+=b
h2+=c
h3+=d
h4+=e
print '%08x%08x%08x%08x%08x'%(h0,h1,h2,h3,h4)
```
] |
[Question]
[
[@BeastlyGerbil](https://codegolf.stackexchange.com/users/70004/beastly-gerbil) presents, the world's very first **MOBIUS SUDOKU**:
>
> [](https://i.stack.imgur.com/0So5Z.png)
>
>
>
---
[](https://i.stack.imgur.com/kKE9v.png)
[Google Sheets version](https://docs.google.com/spreadsheets/d/1ZAQKFn0pnUyejh7S44mqpeSgYC_YTtOkIcJcciJfbjM/edit?usp=sharing)
(The left most square backs onto the right most square, and the middle squares back onto each other. The ends are then attached as indicated.)
**RULES**:
* Normal sudoku rules apply for rows and boxes - boxes are split into groups of 3 indicated by the thicker lines.
+ This means that each row must contain the numbers 1 - 9 without repetition.
* Columns ‘wrap around’ over the edge of the mobius strip – 6 cells per column as a result, normal sudoku rules apply on these 6 cells.
* No number will ever be orthogonally adjacent to itself, including across the thicker borders separating the sets of 3 boxes.
* There are 18 total boxes, and as a result 18 total middle cells. There are 2 of each number, 1-9, in the middle cells.
***Note**: If you need additional information or references for "normal" sudoku, [here](https://www.sudokuonline.io/tips/sudoku-rules) is a great resource.*
---
#### üëÇ Input
Your input will be a collection of integers in \$[1,9]\$, representing each side of a completed strip respectively. Here, *collection* means whatever type of collection works to meet your needs, so long as you accept a value for every square (front and back). You can use comma delimited lists, arrays, arrays of arrays, n-dimensional arrays, lists, etc. For example in C# using a comma delimited list:
>
> 4,6,1,8,5,3,7,9,2,4,8,1,3,9,7,6,5,2,6,4,2,8,1,9,5,3,7,2,7,8,4,9,1,6,5,3,6,7,5,1,4,2,9,3,8,3,8,9,7,2,5,6,1,4,9,5,3,6,2,7,4,1,8,2,9,3,5,8,6,7,1,4,5,7,1,4,6,3,9,8,2,1,9,4,2,8,5,6,3,7,1,9,2,5,7,4,6,3,8,5,7,2,9,8,1,4,3,6,5,6,2,7,3,9,8,1,4,7,6,8,3,2,9,4,5,1,6,8,1,5,4,3,2,9,7,3,7,8,1,4,6,5,9,2,3,4,5,1,6,8,9,2,7,4,3,9,6,7,2,5,8,1
>
>
>
***Note**: You must tell us how to input the data.*
#### üì¢ Output
Your output should represent whether or not the provided input is a valid solution using your languages truthy/falsy, with respect to [this answer](https://codegolf.meta.stackexchange.com/a/2194/81972):
>
>
> ```
> if (x) {
> print "x is truthy";
> }
> else {
> print "x is falsy";
> }
>
> ```
>
> If it results in a runtime or a compile-time error then x is neither truthy nor falsy.
>
>
>
For example in C#, when provided the above input, the expected output is:
>
> true
>
>
>
#### ✔️ Test Cases
Your test inputs will represent both valid and invalid solutions to include the original puzzle's solution:
>
> **Test Case 1**: 0
>
> **Test Case 2**: 4,6,1,8,5,3,7,9,2,4,8,1,3,9,7,6,5,2,6,4,2,8,1,9,5,3,7,2,7,8,4,9,1,6,5,3,6,7,5,1,4,2,9,3,8,3,8,9,7,2,5,6,1,4,9,5,3,6,2,7,4,1,8,2,9,3,5,8,6,7,1,4,5,7,1,4,6,3,9,8,2,1,9,4,2,8,5,6,3,7,1,9,2,5,7,4,6,3,8,5,7,2,9,8,1,4,3,6,5,6,2,7,3,9,8,1,4,7,6,8,3,2,9,4,5,1,6,8,1,5,4,3,2,9,7,3,7,8,1,4,6,5,9,2,3,4,5,1,6,8,9,2,7,4,3,9,6,7,2,5,8,1
>
> **Test Case 3**: 8,8,8,8,8,8,7,9,2,4,8,1,3,9,7,6,5,2,6,4,2,8,1,9,5,3,7,2,7,8,4,9,1,6,5,3,6,7,5,1,4,2,9,3,8,3,8,9,7,2,5,6,1,4,9,5,3,6,2,7,4,1,8,2,9,3,5,8,6,7,1,4,5,7,1,4,6,3,9,8,2,1,9,4,2,8,5,6,3,7,1,9,2,5,7,4,6,3,8,5,7,2,9,8,1,4,3,6,5,6,2,7,3,9,8,1,4,7,6,8,3,2,9,4,5,1,6,8,1,5,4,3,2,9,7,3,7,8,1,4,6,5,9,2,3,4,5,1,6,8,9,2,7,4,3,9,6,7,2,5,8,1
>
>
>
Your outputs should be (again, in C# for example):
>
> **Test Case 1**: false
>
> **Test Case 2**: true
>
> **Test Case 3**: false
>
>
>
Here's a screenshot of the solved grid for reference:
[](https://i.stack.imgur.com/DI1QC.png)
#### üèÖ Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so smallest solution in bytes wins.
#### üìù Final Note
This challenge is inspired by [this puzzle](https://puzzling.stackexchange.com/questions/111725/sudoku-on-a-mobius-strip) crafted by [@BeastlyGerbil](https://codegolf.stackexchange.com/users/70004/beastly-gerbil). If you like this challenge, go show some love for the original puzzle too!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~54~~ 47 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3δôø˜©‚˜9ôI2ä`í«ø«D€ÙQIÂí‚øε˜Ć}D€ÔQ®9ô€Ås9L¢<PP
```
Takes the input as a 6x27 matrix, kinda like the reference screenshot of the grid.
Outputs `1` for truthy, or another integer (usually `0`) as falsey.
[Try it online](https://tio.run/##TU@xSgQxEP2haS7J5DZgaXNgcVcvCypYWFlcLciBfoGNspXYyHlWK2ydsVu4j7gfWd9MglgkmXl5b96bu@3V9e3NPPvjIIOMU58/Tg@vU59kWDl5v5RD3suY9@en3ae8bFaykwMIMh6/p/7n6d7w503@gkDLx226yG9n6/U8t22gSAtqiMnTkhI5CugW6BL6CNzhDrgVTYXXUevw2wBPQKOhEQijU25C39jRKQ64ugToUuWqPphzYTMqnaB6rm@0FGBAp94lBRu@tDTOuIXZWO1MoWq4QMfVy//hupVmczaRLb/@sGkU1f287VdSsDn5f@xU8@vUWDcEu@t@AQ) or [verify all test cases](https://tio.run/##7VKxSsRAEP2VcPUUd5vs3i4I11xpcVcvARUsrCwOhBSCHHgfIDZKKrGR86wipM7aBe4j8iPxzWxQCyttjyWbmbfvzZtZ9nJ1enZx3l8Vs1HSbe6S0ayY9@m@ClWo27J56W4e29KFqlDh@STsmm2om@28W7@Gh2UR1mEHQqj37235sbkW/H7ZvEHA4e3KHTdPR4tFT733fpznlHifkaEJWdKU0pQcKcqQTZA55Aa4wp5hZ9RFXk5e4dQCd0CNoAaIRsZch9zKx1UUcHbJoHMDl/WZOEe2RsQVWK@Hv5EuwICOvWMXWvCpdKOEG5lWYiUKVsMFOj14pV84T8W9KamopX8@0aJhlOdLZb7YhRan9AfbDf1zVTNMCHa80jH9YcHyoPtNJ1dq6XsdXum/X2n@CQ).
**Explanation:**
Step 1: Transform the input-matrix to a (flattened) list of blocks:
```
δ # Map over each row of the (implicit) input-matrix
3 ô # Split the inner list into parts of size 3
√∏ # Zip/transpose this matrix; swapping rows/columns
Àú # Flatten it
© # Store this list in variable `®` (without popping)
```
Step 2: Pair it with the flattened input and split both the 'rows' and blocks into parts of size 9:
```
‚Äö # Pair it together with the (implicit) input-matrix
Àú # Flatten it to a list of integers
9ô # Split it into parts of size 9
```
Step 3: Get all Mobius columns, and merge those to the same list:
```
I # Push the input-matrix again
2√§ # Split it into 2 equal-sized parts
` # Pop and push both separated to the stack
í # Reverse each inner list of the second matrix
¬´ # Merge the two lists back together again
√∏ # Zip/transpose this matrix; swapping rows/columns
¬´ # Merge it to the earlier list of nonets
# (We now have a list of all 'rows'; all blocks; and all Mobius columns)
```
Step 4: Check for each 'row', block, and Mobius column that they only contain unique digits:
```
D # Duplicate the list of lists
€Ù # Uniquify each inner list
Q # Check that it's still equal to the list of lists
```
Step 5: Connect the Mobius rows as shown by the colors in the challenge description, including wrap-around:
```
I # Push the input-matrix again
 # Bifurcate it, short for Duplicate & Reverse copy
í # Reverse each inner row of this reversed copy as well
‚Äö # Pair it with the input-matrix
√∏ # Zip/transpose; creating pairs of the rows of the two matrices
ε # Map over the pair of lists:
Àú # Flatten it to a single connected row
Ć # Enclose it, appending its own first item
} # Close the map
```
Step 6: Check that these connected Mobius rows doesn't contain any adjacent pair of digits that are the same:
```
D # Duplicate it
€Ô # Connected-uniquify each inner list in this duplicate
Q # Check if both matrices are still the same
```
Step 7: Check if the center cells of each block all combined contain each positive digit twice:
```
® # Push the list of variable `®`
9ô # Split it into parts of size 9 to get a list of blocks
ہs # Only leave the center cell value for each block-list
9L¢ # Count for each value in [1,2,3,4,5,6,7,8,9] how many time it occurs in
# this list of block center cells
< # Decrease each by 1
P # Take the product of this list (1 if all counts were 2;
# another integer (0, negative, or positive) if a count wasn't 2)
```
Step 8: Check if everything combined is truthy, and output the result:
```
P # Check if the three are truthy by taking the product on the stack
# (after which the result is output implicitly)
```
[See this for a step-by-step of the input to the output.](https://tio.run/##bVRNb9NAEL3zK1a9tJXcQ5zYxAjUQytQJaoWceAQRcrG2SRLN950d90QTqgS/AJOqCcEB9SPU4V6jo@V@BH9I2Fm1k6atlLiZMdvZt57M7a2vCvFfL62l41z94Ktbb@a/d1@tvZGOOaGgnWVTo8s0306SQRtKWkd2@gr7pzIRG@TbTGurGbWaSMAJy0A2Qk3kneVYJ3ZVQcL1/9dF9fFze3Z7I/vccilYRL66EfF8bxu9MSub7JFIyxy9@XH7ZlPfz9WkIyfDCqMuXHE08rPgiWITYrrVTH7uitzy1Kt8lH2SBSp3wuLX53icnZe3PjcfWEG4h5LwY2SwjDiyS2bCKUwcXbu8TtDkR6xvjaATIfggsqxBeOsVQuS9pbh2UD0fPpkKKAkerBOlnk2WVndkoa34NrvFcGodjkWkluPA@RnCfC0UsLFrG/0iC3dZTzrPSxG3t2dfqvc84qkN8vmI0JypVabsBRhlnFYgRgrdA7id2UBI7gTlJ5qkJc6MKBMRhargxhxZ@QnmkVxWlzCwIubu9OLauo7iwp5Jo9z2Z8@ZdsuZBTfH/Anm62TQF0c51ytLB7bsHQC@hO8ZJrx3keeisyVaBqlXY52qQVEbGLXUu9hbocru0IG@80m/1ceDcYHXGYBTcKurDRPHfZdjiepOGB/WrqrxY4fZGrKlOAn3uiR7PWgQQrbiZlEeEnDT/ii@GorU3OQOdQTNuIZGCpHZZNqNGNtpZNQuycHEp@zNM2N38/ZT19jV6QwZysqc7Bid8pqiHrpIR8MH9PmlLui/cpbx2FATg/Kp4G0wy5mA1BQ0d30JV77lwF45B1Lq@GKE2Gm8O7JBgzeP87kbjgN4AmTQAYCOjfMCJsrKnZ7dhjM561WI4iDWtAMoqAePA@SIAwacKrBKYFzDPEQrg24YjTxuHbQCuFuE@IJRGOKxhCJ4ITYBM5N@mKVEOLYpQF5SYnF/AZ19ugI/mEFzI/K35hYAALysLdnEVH8ObEJCeuRTfofUgZmQxfIi8pe9UUcVSG3kCpGxB/vRJSDUdRXJ32eRUSd6vfQSckfq8alQkC32/8B)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 44 [bytes](https://github.com/DennisMitchell/jelly)
```
s€3;"3/Ẏ;;ZFs9ƲQ€ƑȧZṙ3;"Ɗ;"`IƲȦȧḊm3FƊ⁺ĠƊṁ€Ƒ2
```
A monadic Link that accepts a list of twenty-seven length six lists of integers that yields `1` if valid or `0` if not.
The input is a list of the twenty-seven columns starting with one adjacent to a bold border and reading around the strip, where each column reads in the same order as every other such that it starts at one edge of the Mobius-strip then reads one side followed by the other with wrapping (at the other edge of the Mobius-strip).
**[Try it online!](https://tio.run/##TZEtbgMxEIWvYgVbqvy3trU8UmFpViuVlEQpCipM4IJIhWVFDQkKSoIra6@xuYhjz4zXYfY3fvOeZ9Yfm81XjNv7/qTahXqZboe2XS23PpzfEgvf43E1XX9SLQzt4v01nMe/8Thdhk@1DMN9d/v/DcN03cFbGWPsOs2Z5MxzJjiznDU9Z10DR8OZg4rKTMBNAU4CnVkCSd4ASBWRmQGJhA6p6DJTc3eQ@8zwpou1zMxDWUCz1NtmJssNnUxms6mF146y2GJtamYDco/ymmX@myZfDYC6Uj4JAOMYmot/Go2k/2JLDOUpMwZWGJG0dXjkgaa2zECR1j9FbOrfyICyiJIPbVyd3zztkg9Vru4NX7iykrIPXRaZl9D3Dw "Jelly – Try It Online")**
### How?
It's a long chain so I'll break it down...
```
s€3;"3/Ẏ;;ZFs9ƲQ€Ƒ - are all nonets, columns, and rows distinct sets?: columns
s€3 - split each column into threes
3/ - three-wise reduce by:
;" - zipped concatenation
Ẏ - tighten -> the eighteen nonets
; - concatenate with the twenty-seven columns
∆≤ - last four links as a monad, f(columns):
Z - transpose
F - flatten
9 - nine
s - split (flatten result) into slices of lenth (9)
-> the eighteen rows
; - (nonets & columns) concatenate (rows)
Q€Ƒ - is invariant under deduplicate-each?
-> 1 if all nonets, columns, and rows are distinct sets
else 0
ȧZṙ3;"Ɗ;"`IƲȦ - ...and there are no adjacent cells which are equal?
(note that the distinct sets check performed earlier automatically
checked rows & columns. Rows get checked again here as it is golfier)
∆≤ - last four links as a monad, f(columns):
Z - transpose -> the six half-Mobius-strip-rows on the "front" and "back"
Ɗ - last three links as a monad, f(half-Mobius-strip-rows):
3 - three
·πô - rotate (half-Mobius-strip-rows) left by (3)
;" - zipped concatenation -> full-Mobius-strip-rows
;"` - zipped concatenation with itself (to cater for row-wise wrapping)
I - incremental differences ([b-a, c-b, ...] for each)
ȧ - (current check result) logial AND (that)
»¶ - non-empty and contains no 0 when flattened?
-> 1 if all nonets, columns, and rows are distinct sets
AND no adjacent cells are equal
else 0
ȧḊm3FƊ⁺ĠƊ - ...if so get the middles of all nonets grouped by values, otherwise 0
Ɗ - last three links as a monad, f(columns):
Ɗ - last three links as a monad, g(columns):
Ḋ - dequeue
m3 - modulo-3 slice
F - flatten
⁺ - repeat -> g(that result) -> middles of all nonets
Ġ - group indices by value
ȧ - (current check result) logial AND (that)
-> those groups if all nonets, columns, and rows are distinct sets
AND no adjacent cells are equal
else 0
ṁ€Ƒ2 - ...and the groups (or the 0 we have instead) are all length 2?
Ƒ - is invariant under:
ṁ€ 2 - mould each like [1,2]
-> 1 if a valid fill of an empty Mobius-strip-Sudoku
else 0
```
] |
[Question]
[
[Carcassonne](https://en.wikipedia.org/wiki/Carcassonne) is a tile-based game, where the objective is to construct Roads, Cities and Monasteries, in order to score points. The game works by players taking turns to draw and place tiles to construct a landscape, then claiming roads, cities and monasteries. An example landscape is:
[](https://i.stack.imgur.com/jcVxG.jpg)
There are \$19\$ distinct tiles (ignoring rotations), each of which contains at least one feature (Road, City or Monastery):
[](https://i.stack.imgur.com/QMtF8.jpg)
Also, notice that the landscape must be consistent. This means that roads must connect to other roads, city edges must connect to other city edges and fields must connect to fields. Therefore, these tiles are inconsistent:
[](https://i.stack.imgur.com/e2Vt3.jpg)
In a normal game of Carcassonne, each feature in the landscape is claimed by a player, and contributes to their final score. However, in this version, we will change the rules slightly (primarily for people who already know the standard Carcassonne rules):
* There will only be \$1\$ player
* The player will automatically own every feature in the landscape
* There will be no "badge" score for cities
+ Notice that in some of the tiles in the pictures have badge symbols on them. In this challenge, we're ignoring them.
In a landscape, each feature is either complete or incomplete:
* A complete monastery is one where it's tile is surrounded by \$8\$ tiles. [This](https://i.stack.imgur.com/HUyIh.jpg) landscape contains one complete monastery (in the center) and one incomplete monastery (Top center).
* A complete city is one fully enclosed by walls. [This](https://i.stack.imgur.com/VSmr9.jpg) landscape has \$2\$ complete cities and \$2\$ incomplete cities.
* A complete road is one where both ends terminate at either a city, village or by forming a loop. [This](https://i.stack.imgur.com/a6cV1.jpg) landscape has \$2\$ complete roads and \$2\$ incomplete roads.
A landscape is scored as follows:
* For every complete city, the player scores \$2\$ points for every tile containing that city. Therefore [this](https://i.stack.imgur.com/GCJHv.jpg) city scores \$4\$ points, and [this](https://i.stack.imgur.com/lqoh9.jpg) city scores \$18\$ points.
* For every complete road, the player scores \$1\$ point for every tile containing that road. Therefore [this](https://i.stack.imgur.com/28lhx.jpg) road scores \$6\$ points, and [this](https://i.stack.imgur.com/tC3fE.jpg) road scores \$2\$.
* For every complete monastery, the player scores \$9\$ points, such as [this](https://i.stack.imgur.com/EGc8Q.jpg) monastery.
* For every incomplete city, the player scores \$1\$ point for every tile containing that city. [This](https://i.stack.imgur.com/qTclH.jpg) landscape contains two incomplete cities, one scoring \$2\$ and the other \$5\$.
* For every incomplete road, the player scores \$1\$ point for each tile containing that road. [This](https://i.stack.imgur.com/kmLGw.jpg) landscape contains three incomplete roads, scoring \$1\$, \$2\$ and \$3\$ points.
* For every incomplete monastery, the player scores \$1\$ point for each tile that neighbours the monastery, plus \$1\$ for the monastery itself. [This](https://i.stack.imgur.com/8cT8l.jpg) landscape contains \$3\$ monasteries, scoring \$2\$, \$5\$ and \$7\$.
Take this landscape:
[](https://i.stack.imgur.com/4PrC1.jpg)
This landscape contains \$1\$ complete city, \$2\$ incomplete cities, \$4\$ complete roads, \$2\$ incomplete roads and \$1\$ incomplete monastery which scores \$4 + (3+3) + (3+2+6+2) + (4+2) + 4 = 33\$ points.
---
To avoid this challenge being about image processing, we can translate each tile into a list containing \$5\$ values, according to this legend:
```
[North edge, East edge, South edge, West Edge, # of cities]
0: Field
1: Road
2: City
```
For instance, [this](https://i.stack.imgur.com/ygJCI.jpg) tile can be described as `[2, 0, 1, 1, 1]`. Using this legend, we can describe each tile uniquely, and it's rotations are rotations of the first four elements. The entire grid can be described as a rectangular matrix, with a \$20^\text{th}\$ distinct value for an empty square. Translating the first landscape into this format, we get:
```
[
[ [], [], [1, 1, 0, 0, 0], [1, 1, 2, 1, 1], [0, 1, 0, 1, 0], [], []],
[[1, 0, 1, 0, 0], [], [0, 0, 0, 0, 0], [2, 0, 2, 0, 2], [], [0, 2, 2, 2, 1], [0, 0, 0, 2, 1]],
[[1, 1, 0, 1, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 2, 1], [2, 0, 0, 2, 1], []]
]
```
using `[]` to represent an empty square. The complete list of tiles (ignoring rotations) in the same grid as the second image is
```
[1, 0, 1, 0, 0] [0, 0, 1, 1, 0] [2, 1, 1, 1, 1] [0, 1, 1, 1, 0] [2, 0, 0, 0, 1]
[2, 2, 0, 2, 1] [0, 0, 0, 0, 0] [2, 2, 2, 2, 1] [2, 2, 0, 0, 1] [2, 1, 1, 2, 1]
[2, 2, 0, 0, 2] [0, 0, 1, 0, 0] [2, 0, 1, 1, 1] [2, 1, 1, 0, 1] [0, 2, 0, 2, 1]
[1, 1, 1, 1, 0] [2, 1, 0, 1, 1] [2, 2, 1, 2, 1] [2, 0, 2, 0, 2]
```
Note that the only way to distinguish tiles with monasteries and villages is by the number of roads/cities on the tile, and that there is no specific indicator that a tile has a monastery/village aside from the roads.
---
Your task is to take a matrix of lists in the above format representing a landscape and to output the score the player would have if they claimed all the features, complete or incomplete, in the landscape. You may take input in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), may choose any three consistent values to represent Field, City and Road edges and may use any value to represent the empty squares that isn't already a tile. Output must be an integer represented in your language's most natural format. If you aren't sure about an I/O format, just ask.
In addition, the inputs will always have consistent landscapes, and will always have at least 1 tile. Finally, the tiles will not be constrained by the tile availability (like in the real game).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in bytes wins.
## Test cases
Each test case has the matrix followed by the score, with the score breakdown underneath with abbreviations.
```
[[[], [], [1, 1, 0, 0, 0], [1, 1, 2, 1, 1], [0, 1, 0, 1, 0], [], []], [[1, 0, 1, 0, 0], [], [0, 0, 0, 0, 0], [2, 0, 2, 0, 2], [], [0, 2, 2, 2, 1], [0, 0, 0, 2, 1]], [[1, 1, 0, 1, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0], [2, 2, 0, 0, 1], [2, 2, 0, 2, 1], [2, 0, 0, 2, 1], []]] -> 32
1 c. city (4), 1 i. city (6), 6 i. roads (10), 2 i. monasteries (12)
[[[0, 2, 2, 2, 1], [1, 0, 1, 2, 1], [0, 1, 1, 0, 0], [2, 2, 2, 1, 1]], [[2, 1, 1, 2, 1], [1, 0, 0, 1, 0], [1, 1, 1, 0, 0], [2, 2, 2, 1, 1]], [[1, 1, 1, 0, 0], [0, 2, 1, 1, 1], [1, 0, 1, 2, 1], [2, 1, 1, 0, 1]], [[1, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 0, 0, 1, 0], [1, 0, 1, 0, 0]]] -> 33
1 c. city (4), 2 i. cities (6), 4 c. roads (13), 2 i. roads (6), 1 i. monastery (4)
[[[0, 1, 1, 0, 0], [2, 1, 0, 1, 1], [1, 2, 1, 1, 1], [0, 2, 0, 2, 1], [0, 1, 1, 2, 1]], [[], [], [1, 0, 2, 1, 1], [0, 1, 1, 0, 0], [1, 2, 1, 1, 1]], [[2, 1, 0, 1, 1], [1, 2, 1, 1, 0], [2, 1, 1, 2, 1], [], [1, 1, 0, 1, 0]], [[], [1, 0, 0, 1, 1], [1, 0, 1, 0, 0], [2, 2, 0, 0, 2], [0, 1, 1, 2, 1]]] -> 39
2 c. cities (12), 4 i. cities (5), 1 c. road (2), 12 i. roads (20)
[[[2, 1, 1, 0, 1]]] -> 2
1 i. city (1), 1 i. road (1)
[[[1, 2, 1, 1, 1], [0, 0, 0, 2, 1], [], [1, 1, 0, 1, 0], [2, 2, 2, 1, 1]], [[1, 0, 1, 0, 0], [], [2, 0, 2, 0, 2], [0, 0, 0, 0, 0], []], [[1, 1, 2, 2, 1], [0, 1, 0, 1, 0], [2, 0, 1, 1, 1], [], []], [[], [], [2, 2, 1, 2, 1], [], []]] -> 29
2 c. cities (8), 4 i. cities (4), 2 c. roads (8), 4 i. roads (4), 1 i. monastery (5)
[[[], [0, 0, 2, 0, 1], [], [], [0, 0, 2, 0, 1], [], [], []], [[], [2, 1, 1, 0, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [2, 0, 1, 1, 1], [], [], []], [[], [1, 0, 1, 0, 0], [0, 2, 2, 0, 1], [0, 2, 2, 2, 1], [1, 1, 2, 2, 1], [0, 0, 1, 1, 0], [], []], [[0, 1, 1, 0, 0], [1, 2, 2, 1, 1], [2, 0, 2, 2, 1], [2, 0, 2, 0, 1], [2, 2, 0, 0, 2], [1, 1, 2, 2, 1], [0, 1, 2, 1, 1], [0, 0, 1, 1, 0]], [[1, 1, 1, 0, 0], [2, 2, 2, 1, 1], [2, 2, 2, 2, 1], [2, 1, 2, 2, 1], [0, 0, 0, 1, 0], [2, 2, 0, 0, 1], [2, 1, 2, 2, 1], [1, 0, 1, 1, 0]], [[1, 0, 1, 0, 0], [2, 2, 0, 0, 1], [2, 0, 2, 2, 1], [2, 0, 2, 0, 1], [0, 0, 0, 0, 0], [0, 2, 2, 0, 1], [2, 1, 1, 2, 1], [1, 0, 0, 1, 0]], [[1, 1, 0, 0, 0], [0, 0, 1, 1, 0], [2, 2, 0, 0, 1], [2, 2, 0, 2, 1], [0, 2, 0, 2, 1], [2, 1, 1, 2, 1], [1, 0, 0, 1, 0], []], [[], [1, 1, 0, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0], [1, 0, 0, 1, 0], [], []]] -> 106
3 c. cities (54), 5 c. roads (34), 2 c. monasteries (18)
```
Note that in the largest city in the [final example](https://i.stack.imgur.com/L2vHc.jpg), the tile `[2, 2, 0, 0, 2]` has two sections of the city, but is only a single tile. Therefore, it only counts for 2 points, not 4.
If you have a copy of Carcassonne, I'd highly recommend building the test cases, if only to help visualise them
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~306~~ 246 bytes
```
Eθ⭆ι⎇λ⊟λψ≔ΣEθΣEι∨⁼²№λ¹№λ¹ζFLθFL§θι«Jκι¿›²Σ∨§§θικ²≧⁺⊕LΦKM℅λζ»FLθFL§θι«Jκι¿⁼²ΣKK«≔⌕§§θικ²δ≔δεM✳⁻χ⊗ε¿ΣKK«W∨⁻ⅉι⁻ⅈκ«≧⁻ΣKKεW∨›²§§§θⅉⅈε¬Σ§KVε≦⊕εM✳⁻χ⊗ε»¿¬⁼﹪⁺²ε⁴δ1»»»Wφ«≔⁰φFLθFL§θκ«Jλκ≔ΣKKδ≔§§θκλη≔∧δΦ⌕A粬℅§KVμε¿ε«≔¹φ¿‹Lεδ«§≔η⊟ε⁰≔¹δ1»ψ≧⁺δζ»»»≧⁺⊗ΣEKAΣιζ⎚Iζ
```
[Try it online!](https://tio.run/##rVTJbtswED3LX0HkRAEsYAm95RRkKVLEqdEERQLDB9UaW4Rp0taSNiny7e4MFy2x2@ZQwSZMet68eW@GWhRZuTCZ2u@npdQ1n2RbvhPsrsbdijZSsHsodVY@cyXY1Gy5igV7jvE5HZ1VlVxpftdsWqD/ibAvJb/cNZmqeCrYuWkwO2ZI4ni4o0ewF8y2NCXjN6BXdcF3ccz6@7P6WufwkygkAtivUfS52WzvDV/TyekokkvGP5WQ1VASIRWCFQTcAC/YGr8pMTMs1qn4KldFzaeqqQS71osSNqBryEMBV1JR5inAemJMCTwmhbnUmUJHWg2v/0FF5xqJIEYe@@jIO34ldf53bYLllC8AcsHA7ifmCfiFLGFRS6P5ROqm4slYsAvTfFeoF1xrI1tKvwDLH/0opAJG1jroIxlBtG77wG0FITp6Y68NGugKdfUz99r4VmNP66NFP/gcuNya2hYcYojhm9G30GwyrbkLG/Sc9xrdFfJ@i6JXWsgo4vZ9m5i8UcZOEikA5P1o24HM7pKdJCcWjuhXnBgvfGk984Uh25Ji3jlNreN@nBQd9do/MHwwGEeMpQGiS14M4nDg0CN/DWj@zpTihRs1Uh8uw5/d3/i7Du14gR8Tz5F40e7PG6iqIBWcgX6oXHggKtxriULGvoNdvtyfDI13fQNVge/Iszs@@jLI3c1u23U0KIxGeP@RejIodsMuuzfEuYKs5PjDMZ9nVc1fcJz2@9lsxGas/8zmgs1wFFCIX@mg3dmDuTiGOkyThDTjFjUbDzI5ru5zeOBQGJwGVOKDUhuBa9qhUhfXoVol46MVpoeoo0FpoEs61PifqFZGckg@H83n@w9P6jc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Eθ⭆ι⎇λ⊟λψ
```
Start by printing the number of cities on each tile so that the tiles can be walked using canvas operations rather than array indexing. Just getting the number of cities via `AtIndex(AtIndex(AtIndex(q, i), k), 4)` normally takes 7 bytes, whereas it can be read from the canvas in only 6 via `JumpTo(k, i);` and then `Sum(Peek())` (although obviously we can only do that as a separate statement). We can also directly inspect adjacent cells using `PeekMoore()` and `PeekVonNeumann()` to see whether they are empty tiles (empty tiles will be a null byte or an empty string for out-of-range tiles, but both have an ordinal of 0). Furthermore, removing the city count data from the input array makes the code to deal with the features cleaner (i.e. shorter).
```
≔ΣEθΣEEι№λ¹∨⁼²λλζ
```
Start off by counting the roads. Complete and incomplete roads both score their length, so the only special case here is that a tile with two roads only scores 1.
```
FLθFL§θι«Jκι¿›²Σ∨§§θικ²≧⁺⊕LΦKM℅λζ»
```
Next, find the monasteries, whose tiles have with no features apart from an optional road. For each monastery, simply count one more than the number of adjacent tiles, since complete monasteries count 9 anyway.
```
FLθFL§θι«
```
We need to check whether tiles with two cities are connected. Loop over all of the tiles.
```
Jκι¿⁼²ΣKK«
```
Is this a tile of two cities?
```
≔⌕§§θικ²δ≔δεM✳⁻χ⊗ε
```
Pick one of the city directions and move one step.
```
¿ΣKK«
```
Is there city here?
```
W∨⁻ⅉι⁻ⅈκ«
```
Repeat until we get back to the original tile.
```
≧⁻ΣKKε
```
If this is a different tile of two cities, then immediately U-turn, otherwise turn left. This allows us to perform a left-following maze traversal.
```
W∨›²§§§θⅉⅈε¬Σ§KVε≦⊕ε
```
Turn right until there is a connected city.
```
M✳⁻χ⊗ε
```
Move to the next city.
```
»¿¬⁼﹪⁺²ε⁴δ1»»»
```
If we did not arrive in the opposite direction to which we left, then the two cities on this tile are actually connected, so count them as a single city.
```
Wφ«≔⁰φ
```
Next, we need to find tiles with incomplete cities. Use a variable with a predefined non-zero value as a loop variable, but immediately set it to zero inside the loop.
```
FLθFL§θκ«
```
Loop over each tile.
```
Jλκ≔ΣKKδ≔§§θκλη≔∧δΦ⌕A粬℅§KVμε
```
Check for adjacent tiles in the appropriate directions. We can assume that these tiles will be city tiles if they exist, but if they don't exist then this tile is part of an incomplete city.
```
¿ε«≔¹φ
```
If so, then note that we had an incomplete city for later.
```
¿‹Lεδ«
```
If this tile has two cities, but only one was found to be incomplete, then...
```
§≔η⊟ε⁰
```
... mark that direction as a field, and...
```
≔¹δ
```
... reduce the score for this tile to 1, and...
```
1
```
... reduce the number of remaining cities to 1.
```
»ψ
```
Otherwise delete the tile completely. This will cause any adjacent city tiles to be (re)evaluated for incompleteness.
```
≧⁺δζ»»»
```
Score the number of cities deleted.
```
≧⁺⊗ΣEKAΣιζ
```
Score two for any remaining cities on the remaining tiles, as these must now be complete cities.
```
⎚Iζ
```
Clear the canvas and output the final score.
] |
[Question]
[
# Help PPCG Claus Deliver his Presents
# Overview
PPCG Claus is running hella late delivering his gifts because nowadays we have so many odd little kiddos out there. This makes it much harder for PPCG Claus to get all the presents to the correct place. Your challenge is to help him delvier his presents correctly.
# The Complexity
Given a list of capitalized first names representing the kids he's supposed to deliver to and a list of presents represented by numbers, you must figure out how to distribute the presents among said children. Of course there's a catch though....
Nowadays kids are getting picky, if the kiddo is an odd fellow (first initial is ASCII-code odd) he wants an odd gift! If he's an even fellow (first initial is ASCII-code even) he obviously must be given an even one! Any child divisible by 3, however, is a naughty, naughty lad, so PPCG Claus must completely ignore them to make them behave next year. To consider his route a success he must deliver all presents to all children who deserve them and must not give any one child too many presents. If any child gets 3+ more presents than his or her peers, he risks becoming a naughty child next year, and that's just not right! Also, if any ***good*** child were to receive a present when another ***good*** child didn't, that also would turn that child evil.
# Example
The kids are as follows:
`Kids = ["Amy", "Betty", "Clyde", "Dave", "Francine"] = [A,B,C,D,F] = [65,66,67,68,70]`
* Betty is the bane of humanity, clearly in cahoots with the number 3.
* Amy and Clyde have been weirdos since birth and would hate to receive
even presents.
* Dave and Francine are normal, even, kids; they should only receive even presents!
The presents are as follows:
`Presents = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]`
One possible output would be:
```
[
['Amy',[1,3,5]],
['Betty',[]],
['Clyde',[7,9,11,13]],
['Dave',[2,4,6,8]],
['Francine',[10,12,14]]
]
```
# Exception Scenarios
However, just because PPCG Claus is ready and willing, doesn't mean PPCG Claus can. Here's a list of exception scenarios where you must break the bad news to PPCG Claus with a message of:
`PPCGmas is cancelled!`
The following scenarios will result in Christmas being cancelled:
* There are no children.
+ `[],[1,2,3]` - Wellp, they ded.
* There are no good children.
+ `["Betty"],[1,2,3]` - Seriously, screw Betty.
* There are no presents, or less presents than good children.
+ `["Amy","Charles"],[]` - One or more would receive no presents.
+ `["Amy","Charles"],[1]` - One or more would receive no presents.
* There are not odd/even presents to satisfy all good children.
+ `["Amy","Dave"],[2,4,6]` - Amy is screwed over.
Here's a list of scenarios that shouldn't affect PPCGmas:
* Leftover Presents (All children should receive the maximal amount of presents).
+ `["Amy","Dave"],[2,4,6,8,10,12,14,7,9] = [["Amy",[7,9]],["Dave",[2,4,6,8]]]`
# Main Rules Reiterated
1. Good children are either even or odd, based on their first initial.
2. Bad children have a first initial wholly divisible by 3.
3. All good children must receive at least one present.
4. No good child is to receive greater than 2 presents more than any other good child.
5. If there are to be leftover presents you must maximally distribute them, without violating 4.
6. Bad children must receive no presents at all.
7. **If ANY of these is violated, you must output** `PPCGmas is cancelled!`**, exactly.**
# I/O Format Requirements
* The 1st input must be an array/list/comma-delimited string of full names, not just the first initial.
* The 2nd input must be a array/list/comma-delimited string of positive integers.
* The output may be any denotation of how you distributed the presents that makes sense; or `PPCGmas is Cancelled!`.
# Winning Criterion: [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
TL;DR: Betty is a jerk, don't compete.
[Answer]
# APL, 171 bytes
```
{D←{⍵=1:⊂⍺⋄0~⍨¨↓⍵↑⍉↑⍺⊂⍨1=⍵|⍳⍴⍺}⋄e←⍺~o←⍺/⍨2|⍺⋄(0=≢G)∨0∊≢¨P←P↑⍨¨(2+⌊/R)⌊R←≢¨P←(o D≢O),e D≢E←G~O←G/⍨2|⎕A⍳⊃¨G←⍵/⍨×3|⊃∘⎕UCS¨⍵:'PPCGmas is cancelled!'⋄(O,E,B),[⍟4]P,(≢B←⍵~G)↑⊂⍬}
```
This takes the presents as the left argument, the children as the right argument, and returns a matrix where the first column contains the names of the children and the second column contains the presents they get.
Testcases:
```
P←{D←{⍵=1:⊂⍺⋄0~⍨¨↓⍵↑⍉↑⍺⊂⍨1=⍵|⍳⍴⍺}⋄e←⍺~o←⍺/⍨2|⍺⋄(0=≢G)∨0∊≢¨P←P↑⍨¨(2+⌊/R)⌊R←≢¨P←(o D≢O),e D≢E←G~O←G/⍨2|⎕A⍳⊃¨G←⍵/⍨×3|⊃∘⎕UCS¨⍵:'PPCGmas is cancelled!'⋄(O,E,B),[⍟4]P,(≢B←⍵~G)↑⊂⍬}
(⍳14) P 'Amy' 'Betty' 'Clyde' 'Dave' 'Francine'
┌────────┬─────────┐
│Amy │1 5 9 13 │
├────────┼─────────┤
│Clyde │3 7 11 │
├────────┼─────────┤
│Dave │2 6 10 14│
├────────┼─────────┤
│Francine│4 8 12 │
├────────┼─────────┤
│Betty │ │
└────────┴─────────┘
1 2 3 P ⍬
PPCGmas is cancelled!
1 2 3 P ⊂'Betty'
PPCGmas is cancelled!
⍬ P 'Amy' 'Charles'
PPCGmas is cancelled!
(,1) P 'Amy' 'Charles'
PPCGmas is cancelled!
2 4 6 P 'Amy' 'Dave'
PPCGmas is cancelled!
2 4 6 8 10 12 14 7 9 P 'Amy' 'Dave'
┌────┬───────┐
│Amy │7 9 │
├────┼───────┤
│Dave│2 4 6 8│
└────┴───────┘
```
[Ungolfed version here.](https://bitbucket.org/snippets/marinuso/nBor6)
[Answer]
## JavaScript (ES6), ~~525~~ ~~492~~ ~~454~~ 453 bytes
-71 bytes thanks to [@Guedes](https://codegolf.stackexchange.com/users/52956/guedes)
-1 bit thanks to [@Jake Cobb](https://codegolf.stackexchange.com/users/34283/jake-cobb)
```
P=(K,p)=>{y='charCodeAt';n=(C)=>C[y](0)%3>0;N=(C)=>C[y](0)%3<1;E=(C)=>C[y](0)%2>0;O=(C)=>C[y](0)%2<1;f=(U)=>U%2<1;F=(U)=>U%2;M=(U,C)=>C%s==S;s=S=0;a=new Array();G='filter';e=p[G](f);o=p[G](F);J=K[G](n);r=J[G](O);L='length';i=J[G](E);s=r[L];for(S=0;S<r[L];S++){a.push([r[S],e[G](M)]);}s=i[L];for(S=0;S<i[L];S++){a.push([i[S],o[G](M)]);}K=K[G](N);for(S=0;S<K[L];S++){a.push(K[S],[]);}return(e[L]<r[L]||o[L]<i[L]||(r[L]+i[L])<1)?"PPCGmas is Cancelled!":a;}
```
[Try it online !](https://repl.it/EtKn/10)
[Non-golfed version](https://repl.it/EtKn)
Can be more golfed I think. I just did a litteral translation of the non-golfed version.
This is now shorter than the sum of the CharCode composing "santa" (115 + 97 + 110 + 116 + 97 = 535). Yeay
[Answer]
## Python 2, ~~334~~ ~~355~~ 354 bytes
```
k,p=input()
z=zip
l=len
e=[];o=[];g=[];b=[];q=[];r=[]
for x in k:[g,b][ord(x[0])%3<1]+=x,
for x in g:[e,o][ord(x[0])&1]+=x,
for x in p:[q,r][x&1]+=x,
v=l(e)
w=l(o)
t=v and l(q)/v
u=w and l(r)/w
if u:t=min(t,u+2)
if t:u=min(u,t+2)
if l(g)*(t or v<1)*(u or w<1)<1:exit('PPCGmas is cancelled!')
print z(e,z(*[iter(q)]*t))+z(o,z(*[iter(r)]*u))+z(b,[()]*l(b))
```
Lost 21 bytes to handle case of only-even or only-odd children.
Saved 1 byte thanks to @TuukkaX.
[Answer]
# Javascript (ES6), ~~218~~ 216 Bytes
```
(a,b)=>{c={};a.forEach(d=>c[d]=[]);e=f=0;while(!e){e=g=1;a.forEach(h=>(j=h.charCodeAt())%3?(k=b.findIndex(l=>l%2==j%2))<0?g=0:c[h][f+1]?0:e=0&c[h].push(b.splice(k,1)[0]):0);f+=!e&g}return f?c:"PPCGmas is cancelled!"}
```
The output (if it's not the error string) is an object whose keys are the children's names; the value is the array of presents that child receives.
Saved two bytes when I realized I had a pair of redundant parentheses.
Ungolfed version:
```
(names, gifts) => {
// Initialize result. Set every child's gift array to empty
var result = {};
names.forEach(name =>
result[name] = [];
);
// Initialize external loop values
var done = false;
var leastNumberOfPresentsAmongGoodChildren = 0;
// Give the gifts
while (!done) {
// Initialize internal loop values
done = true;
var everyGoodChildGotGift = true;
// Try to give at most one gift to every good child
names.forEach(name => {
var nameCode = name.charCodeAt(0);
// Ignore bad children
if ((nameCode % 3) != 0) {
// Try to find an appropriate gift
var giftIndex = gifts.findIndex(gift => (gift % 2) == (nameCode % 2));
// If there is no gift, set the flag
if (giftIndex < 0)
everyGoodChildGotGift = false;
// Make sure we don't give too many gifts
else if (result[name].length < leastNumberOfPresentsAmongGoodChildren + 2) {
// Remove the gift from the gifts array (we can't give it again)
var giftToGive = gifts.splice(giftIndex, 1)[0];
// Give the gift to the child
result[name].push(giftToGive);
// If at least one child got a gift, try to give more gifts
done = false;
}
}
}); // end forEach
// If we're done, that means we couldn't give a gift to any good child
if (done)
everyGoodChildGotGift = false;
// If every good child got a gift, then increase the count
if (everyGoodChildGotGift)
leastNumberOfPresentsAmongGoodChildren++;
} // end while
// If every good child gets at least one gift, return who gets what
if (leastNumberOfPresentsAmongGoodChildren != 0)
return result;
else
return "PPCGMas is cancelled!"; // IT'S ALL YOUR FAULT, BETTY. YOU'VE RUINED PPCGMAS.
}
```
] |
[Question]
[
A difference pyramid is a pyramid where each new diagonal is the absolute value of the differences between the elements of the last diagonal. For example, if we start with the array
```
2 5 4 9 3 4
```
Now, we arrange these in a diagonal column:
```
2
5
4
9
3
4
```
Now, we fill in the next diagonal. The absolute differences between the consecutive elements of this array are:
```
3 1 5 6 1
```
So that is our next diagonal.
```
2
3 5
1 4
5 9
6 3
1 4
```
Repeat until the pyramid is filled in:
```
2
3 5
2 1 4
2 4 5 9
1 3 1 6 3
0 1 4 5 1 4
```
# The Challenge
Given a list of positive integers in the range `[0, 9]`, generate this ASCII-art representation of the difference pyramid for that particular array. The input is guaranteed to contain at least two elements. You may take these numbers in any reasonable format. (Array/list/whatever you call it, a string, command line arguments, etc.) Trailing spaces on each line and up to one trailing newline are allowed.
# Test IO
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1
1 2
0 1 3
0 0 1 4
0 0 0 1 5
0 0 0 0 1 6
0 0 0 0 0 1 7
0 0 0 0 0 0 1 8
0 0 0 0 0 0 0 1 9
[4, 7]
4
3 7
[3, 3, 3]
3
0 3
0 0 3
[1, 3, 6, 3, 4, 9]
1
2 3
1 3 6
1 0 3 3
1 2 2 1 4
1 0 2 4 5 9
[8, 7, 3, 2, 4, 5, 9, 1, 6]
8
1 7
3 4 3
0 3 1 2
2 2 1 2 4
0 2 0 1 1 5
0 0 2 2 3 4 9
1 1 1 1 1 4 8 1
0 1 0 1 0 1 3 5 6
```
As usual, this is code-golf, so standard loopholes apply, and shortest answer in bytes wins!
---
*Inspired by [this OEIS](https://oeis.org/A254967) and [this conjecture](https://en.wikipedia.org/wiki/Gilbreath%27s_conjecture).*
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
IA$ṖпUṚz”@ṚGḟ”@
```
[Try it online!](http://jelly.tryitonline.net/#code=SUEk4bmWw5DCv1XhuZp64oCdQOG5mkfhuJ_igJ1A&input=&args=WzgsIDcsIDMsIDIsIDQsIDUsIDksIDEsIDZd)
### Background
Generating the differences is quite straightforward. For input
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```
`IA$Ṗп` (absolute value of increments while there is more than one element) yields the following ragged 2D array.
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 1, 1, 1, 1, 1, 1, 1]
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0]
[0, 0]
[0]
```
`U` reverses the order of the columns and `Ṛ` the order of the rows, yielding the following.
```
[0]
[0, 0]
[0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 1, 1, 1, 1, 1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
```
Now, we transpose rows and columns with `z”@`, which pads all rows to the same length before transposing. The result is the following.
```
[0, 0, 0, 0, 0, 0, 0, 1, 9]
[@, 0, 0, 0, 0, 0, 0, 1, 8]
[@, @, 0, 0, 0, 0, 0, 1, 7]
[@, @, @, 0, 0, 0, 0, 1, 6]
[@, @, @, @, 0, 0, 0, 1, 5]
[@, @, @, @, @, 0, 0, 1, 4]
[@, @, @, @, @, @, 0, 1, 3]
[@, @, @, @, @, @, @, 1, 2]
[@, @, @, @, @, @, @, @, 1]
```
Reversing the rows gives
```
[@, @, @, @, @, @, @, @, 1]
[@, @, @, @, @, @, @, 1, 2]
[@, @, @, @, @, @, 0, 1, 3]
[@, @, @, @, @, 0, 0, 1, 4]
[@, @, @, @, 0, 0, 0, 1, 5]
[@, @, @, 0, 0, 0, 0, 1, 6]
[@, @, 0, 0, 0, 0, 0, 1, 7]
[@, 0, 0, 0, 0, 0, 0, 1, 8]
[0, 0, 0, 0, 0, 0, 0, 1, 9]
```
To turn the 2D array into a whitespace-separated string, we use the built-in grid atom (`G`). It joins columns by spaces and rows by linefeeds, yielding the following result.
```
@ @ @ @ @ @ @ @ 1
@ @ @ @ @ @ @ 1 2
@ @ @ @ @ @ 0 1 3
@ @ @ @ @ 0 0 1 4
@ @ @ @ 0 0 0 1 5
@ @ @ 0 0 0 0 1 6
@ @ 0 0 0 0 0 1 7
@ 0 0 0 0 0 0 1 8
0 0 0 0 0 0 0 1 9
```
All that's left to do is removing the padding character with `ḟ”@`, yielding
```
1
1 2
0 1 3
0 0 1 4
0 0 0 1 5
0 0 0 0 1 6
0 0 0 0 0 1 7
0 0 0 0 0 0 1 8
0 0 0 0 0 0 0 1 9
```
which is the desired output.
[Answer]
## CJam, 29 bytes
```
q~{_2ew::-:z}h]W%zzeeSff*W%N*
```
[Try it online!](http://cjam.tryitonline.net/#code=cU4vezpROwoKUX57XzJldzo6LTp6fWhdVyV6emVlU2ZmKlclTioKCl1uTG59Lw&input=WzIgNSA0IDkgMyA0XQpbMSAyIDMgNCA1IDYgNyA4IDldCls0IDddClszIDMgM10KWzEgMyA2IDMgNCA5XQpbOCA3IDMgMiA0IDUgOSAxIDZd) (The first and last line enable a linefeed-separated test suite.)
This uses the triangle-rotation and layouting code [from this answer](https://codegolf.stackexchange.com/a/69473/8478) and the triangle itself is generated with the same principle as in [this answer](https://codegolf.stackexchange.com/a/82705/8478).
[Answer]
# J, ~~46~~ ~~42~~ ~~39~~ 36 bytes
```
(#\-#)|."_1#{.[:":@|./.<@#2&(|@-/\)]
```
A straight-forward implementation. Generates a table of successive differences between each pair and repeats it a number of times equal to the length of the input array. Then traverses each diagonal of that table to form the rows of the triangle. The rest is formatting the rows into a pyramid.
## Usage
```
f =: (#\-#)|."_1#{.[:":@|./.<@#2&(|@-/\)]
f 2 5 4 9 3 4
2
3 5
2 1 4
2 4 5 9
1 3 1 6 3
0 1 4 5 1 4
f 4 7
4
3 7
f 8 7 3 2 4 5 9 1 6
8
1 7
3 4 3
0 3 1 2
2 2 1 2 4
0 2 0 1 1 5
0 0 2 2 3 4 9
1 1 1 1 1 4 8 1
0 1 0 1 0 1 3 5 6
```
## Explanation
```
(#\-#)|."_1#{.[:":@|./.<@#2&(|@-/\)] Input: list A
# Get len(A)
<@ Box it
] Get A
2&( ) Repeat len(A) times on A initially
2 \ Get each iverlapping sublist of size 2
/ Reduce it using
|@- The absolute value of the difference
This will form a table where each row contains the
successive differences
[: /. Operate on the diagonals of that table
|. Reverse each diagonal
":@ Format each into a string
# Get len(A)
{. Take that many from the strings of diagonals
#\ Get the length of each prefix of A
Makes the range [1, 2, ..., len(A)]
# Get len(A)
- Subtract the len(A) from each in the prefix range
Makes [-len(A)+1, ..., -1, 0]
|."_1 Rotate each string left using each value
A negative rotate left = rotate right
Output the pyramid
```
[Answer]
# Pyth, 22 bytes
```
jmX-jN_Pd;N;_.t_M.uaVt
```
[Try it online!](http://pyth.herokuapp.com/?code=jmX-jN_Pd%3BN%3B_.t_M.uaVt&input=%5B1%2C2%2C4%2C3%2C5%5D&debug=0)
[Answer]
# Python 3, 144 bytes
```
def f(x):
y=[x]
for i in range(len(x)-1):y+=[['']*-~i+[abs(y[i][j]-y[i][j+1])for j in range(i,len(y[i])-1)]]
for i in zip(*y):print(*i[::-1])
```
A function that takes input of a list `x` via argument and prints the result to STDOUT.
**How it works**
The program takes input of a list `x`, and initialises a nested list `y` such that `y[0] = x`. The absolute differences for the last list in `y` (initially `x`) are then generated and appended as a list to `y` until a list of length `1` is reached; at each stage, the list is pre-padded with spaces such that all lists in `y` have the same length as `x`. Next, `y` is transposed, leaving it containing a tuple for each output line, but reversed. Each tuple in the transpose is unpacked, reversed and printed, leaving the difference pyramid on STDOUT.
[Try it on Ideone](https://ideone.com/Yx4peJ)
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.