text
stringlengths 180
608k
|
---|
[Question]
[
>
> ...Ordinal numbers (or ordinal numerals) are words representing position or rank in a sequential order.
>
>
>
[](https://i.stack.imgur.com/YOUmZ.png)
*From [Wikipedia](https://en.wikipedia.org/wiki/Ordinal_number_(linguistics)).*
Your task is, using 2 separate programs (of which can be made from 2 different languages), to output the ordinal sequence from first to `nth`. You will be outputting the full word `second` as opposed to `2nd`.
The challenge of ordinal numbers has been brought up before, particularly in [this entry](https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd). In this challenge, ordinals are merely a vehicle to facilitate the unique conditions detailed below.
---
## Part 1
You must make a program that, when given the input of `n` must output *anything*.
`n` will always be a positive, non-zero integer no larger than 999.
Valid output includes but **is not limited to**:
* Any output to `stdout` / `stderr` / etc
* Creation of files / folders / etc
* A graphical interface or images of any kind
***Anything goes.***
---
## Part 2
You must make a program that uses the output of part 1's program to output a sequence of ordinal numbers, starting from 1 (first), up to whatever `n` was parsed in part 1.
### General Conditions:
* The total bytes for part 2 must not exceed the total bytes for part 1 (less than or equal to).
### Output conditions:
* Not case sensitive.
* Output must contain only the ordinal sequence (only characters a-Z) and whitespace (newlines allowed).
* Can be output to any source, so long as it is visible either during or after execution.
* Program does not need to terminate so long as its output is correct.
* Output is not required to have any grammar, but may optionally include it (hyphens, commas, "ands", etc). `nine hundred ninety ninth` is just as acceptable as `nine hundred and ninety-ninth`.
### Sample Output
*Where `n` is 8*
```
FIRST SECOND THIRD FOURTH FIFTH SIXTH SEVENTH EIGHTH
```
---
## Scoring
The hierarchy of win conditions is:
>
> 1. The lowest number of bytes in part 1
> 2. The lowest number of bytes in part 2
>
>
>
```
Entry #1 | Part 1 = 32 bytes, Part 2 = 22 bytes
Entry #2 | Part 1 = 31 bytes, part 2 = 30 bytes
Entry #2 wins - Part 1 contains 31 bytes vs 32 bytes
---
Entry #1 | Part 1 = 21 bytes, Part 2 = 33 bytes
Entry #2 | Part 1 = 80 bytes, Part 2 = 70 bytes
Entry #2 wins - Entry #1 disqualified (Part 2 contains more bytes than Part 1)
---
Entry #1 | Part 1 = 50 bytes, Part 2 = 49 bytes
Entry #2 | Part 1 = 50 bytes, Part 2 = 50 bytes
Entry #1 wins - Part 1 is equal, Part 2 contains 49 bytes vs 50 bytes
```
[Answer]
# [Sledgehammer 0.5.1](https://github.com/tkwa/Sledgehammer/commit/9e4f8257aae28f8aa0660948d2141e2745c15100) / Sledgehammer 0.5.1, 10 bytes
### Program 1 (10 bytes):
```
⣘⢷⠾⣃⢖⣎⢅⡨⠱⢳
```
Decompresses into this Wolfram Language function:
```
{Range[#1], "Ordinal"} &
```
### Program 2 (7 bytes):
```
⡾⡁⢚⣷⣬⠤⣾
```
Decompresses into this Wolfram Language function:
```
StringRiffle[IntegerName @@ #1, " "] &
```
[Try it online!](https://tio.run/##DYy7DoMgFIZ3n@IPJk4uuDE0Ye1SjY6E4cQeKIkwkLOZPjsyf5dM8uNMkk5qLWi8cO9UIrtR@1mt9ZsKXeo/tbB0dkhNJe4phIvduwhHrh/KDGsx6hkKymMahq1r4npi0Z8WxhjfHg "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [R](https://www.r-project.org/) (with `english` package), 16 bytes / 16 bytes
### Part 1, 16 bytes
```
f=function(n)1:n
```
### Part 2, 16 bytes
```
english::ordinal
```
Requires the `english` package (which is not installed on TIO, unfortunately).
`english::ordinal(f(22))` outputs `first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth thirteenth fourteenth fifteenth sixteenth seventeenth eighteenth nineteenth twentieth twenty first twenty second`.
Of course, part 1 could be made much shorter (3 bytes: `seq`), but that would go against the constraint that part 2 has to be no longer than part 1.
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/) (both parts), 18 bytes / 15 bytes
-5/-1 thanks to [lirtosiast](https://codegolf.stackexchange.com/questions/188363/output-ordinal-numbers-up-to-n/188367?noredirect=1#comment451280_188367)
### Part 1, 18 bytes
```
Range@#|"Ordinal"&
```
### Part 2, 15 bytes
```
IntegerName@@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PygxLz3VQblGyb8oJTMvMUdJ7X@6LZdnXklqemqRX2JuqoODshpXQFFmXkl0ukOag0UsEsfQyDj2PwA "Wolfram Language (Mathematica) – Try It Online")
Two functions which output via return value.
[Answer]
## Python 3(part 1 & part 2)
Unfortunately Nodebox is very wordy... there is not much room for golfing.
### Part 1 76 bytes
```
for i in range ( 1 , int ( input ( ) ) + 1 ) : print ( i ,end=" ")
```
### Part 2 (Uses the [NodeBox](https://www.nodebox.net/code/index.php/Linguistics) library) 76 bytes
```
import en.number as n
for i in input().split():print(n.ordinal(n.spoken(i)))
```
[Answer]
# JavaScript (Node.js), 47 bytes / 47 bytes
Two functions in the same Node.js environment, invoked like `g(f(n))`. Uses the npm package [number-to-words](https://www.npmjs.com/package/number-to-words).
### Part 1, 47 bytes (40 bytes + 7 spaces)
```
n=>H=>{for(i=0;i<n;)console.log(H(++i))}
```
### Part 2, 47 bytes
```
F=>F(require("number-to-words").toWordsOrdinal)
```
[Try it on Runkit!](https://runkit.com/5d2e1bc6298e33001a1b8926/5d2e1bc68e898b001a939f05)
---
# JavaScript (Node.js), 48 bytes / 43 bytes
### Part 1, 48 bytes
```
n=>[n,require("number-to-words").toWordsOrdinal]
```
### Part 2, 43 bytes
```
([n,F])=>{for(i=0;i<n;)console.log(F(++i))}
```
[Try it on Runkit!](https://runkit.com/5d2e1bc6298e33001a1b8926/5d2e1ea4298e33001a1b8e13)
[Answer]
# Perl 5.10 / Common Lisp, 34 / 26 bytes
So, Common Lisp `format` has this as a built-in, because of course it does.
## Program 1 (34 bytes)
```
say"(format t\"~:r \"$_)"for 1..<>
```
Perl does all the iterating. The equivalent Common Lisp code (`(dotimes(i(read)) ...)`) is longer than the much golfier Perl `... for 1..<>`. Perl outputs a bunch of Common Lisp code.
## Program 2 (26 bytes)
```
(loop(eval(read nil nil)))
```
It's a REPL, minus the P. It reads standard input and, well, executes it. Doesn't terminate, but the rules explicitly say that's fine.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 2/2 bytes
```
ɾ, # print range (1,n+1)
```
```
∆o # nth ordinal of each
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCLJvixcbuKIhm8iLCIiLCI2Il0=)
] |
[Question]
[
Your task is to find two missing characters in a Columbo episode title.
## Input
One of the 69 Columbo episode titles (as listed below), with exactly two characters replaced with `*`.
**Example**:
```
"Ran*om for a *ead Man"
```
## Output
You may either return the full episode title, or just the two missing characters in any reasonable format, provided that the order of the characters is unambiguous.
**Some valid outputs**:
```
"Ransom for a Dead Man"
"sD"
["s", "D"]
```
## Episodes
Please [follow this link](https://pastebin.com/Z8nd50H1) to get the unformatted list.
```
Prescription: Murder Swan Song Murder, Smoke and Shadows
Ransom for a Dead Man A Friend in Deed Sex and the Married Detective
Murder by the Book An Exercise in Fatality Grand Deceptions
Death Lends a Hand Negative Reaction Murder: A Self Portrait
Dead Weight By Dawn's Early Light Columbo Cries Wolf
Suitable for Framing Troubled Waters Agenda for Murder
Lady in Waiting Playback Rest in Peace, Mrs. Columbo
Short Fuse A Deadly State of Mind Uneasy Lies the Crown
Blueprint for Murder Forgotten Lady Murder in Malibu
Etude in Black A Case of Immunity Columbo Goes to College
The Greenhouse Jungle Identity Crisis Caution: Murder Can Be Hazardous to Your Health
The Most Crucial Game A Matter of Honor Columbo and the Murder of a Rock Star
Dagger of the Mind Now You See Him... Death Hits the Jackpot
Requiem for a Falling Star Last Salute to the Commodore No Time to Die
A Stitch in Crime Fade in to Murder A Bird in the Hand...
The Most Dangerous Match Old Fashioned Murder It's All in the Game
Double Shock The Bye-Bye Sky High IQ Murder Case Butterfly in Shades of Grey
Lovely But Lethal Try and Catch Me Undercover
Any Old Port in a Storm Murder Under Glass Strange Bedfellows
Candidate for Crime Make Me a Perfect Murder A Trace of Murder
Double Exposure How to Dial a Murder Ashes to Ashes
Publish or Perish The Conspirators Murder With Too Many Notes
Mind Over Mayhem Columbo Goes to the Guillotine Columbo Likes the Nightlife
```
## Clarifications and rules
* *Storing the list of episodes (or storing enough information to guess the missing characters) is part of the challenge.* In other words, you don't get the list 'for free'. If using external files, their lengths must be added to your byte count.
* Your program/function must support the titles exactly as listed above:
+ The case of each letter must match exactly.
+ The punctuation must also match exactly.
+ Etc...
* All characters in the title may be replaced with `*`, not just letters. They might be contiguous.
* You may expect another 'blank' character instead of `*`, as long as it does not appear anywhere in any title. (If so, please mention it in your answer.)
*Ah, there's just one more thing. I almost forgot...*
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins!
## Test set
[Here is a link](https://pastebin.com/JQnDGzsR) to all 14252 possible inputs.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 294 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ê(·▲[*▬è0↑u■<pá{∞♫┼¢]$Fò╦7τ}αzoN≡ù÷♥R♪♪éé#Ä↑♂¼y>Φp←E├Tì·æ≈ßÿOÄ╩%▼Åp}∞½É÷_~ï♦♪s○╨5╓ok½♪◄}§3vimεå╩p"G4ƒs┬]K╡àbá•Ä◄E°µte\τ╚¥∞LH¥êoc▐I/♥∞íJ{σ↓⌠╢§♥]8<µ6ε∩╠ån¥←A↨⌡↨▼♠áiåcTε╛ëJv⌡♂'┬û▒╟_E2↑☺│╚ê£-vç╘▬╒ì)#Φ¼∟æ∟q⌐▀☻7w_ì~Δc'Ω∙j≡┼Γó2"äV√n◘j≤╦╓ΘiL.,▲♂▌▼∞ccñó╘î←iaΩï)NCøAP┼b_ε☺Cam╥~αDM↕Aä<₧¿é■N/╞τQ╠Γù>b^S>◘á↑
```
[Run and debug it](https://staxlang.xyz/#p=8828fa1e5b2a168a301875fe3c70a07bec0ec59b5d244695cb37e77de07a6f4ef097f603520d0d8282238e180bac793ee8701b45c3548dfa91f7e1984f8eca251f8f707decab90f65f7e8b040d7309d035d66f6bab0d117d153376696dee86ca702247349f73c25d4bb58562a0078e1145f8e674655ce7c89dec4c489d886f63de492f03eca14a7be519f4b615035d383ce636eeefcc866e9d1b4117f5171f06a069866354eebe894a76f50b27c296b1c75f45321801b3c8889c2d7687d416d58d2923e8ac1c911c71a9df0237775f8d7eff6327eaf96af0c5e2a232228456fb6e086af3cbd6e9694c2e2c1e0bdd1fec6363a4a2d48c1b6961ea8b294e43004150c5625fee0143616dd27ee0444d1241843c9ea882fe4e2fc6e751cce2973e625e533e08a018&i=Ran*om+for+a+*ead+Man%0A**Deadly+State+of+Mind%0ACaution*+Murder+Can+Be+Hazardous+to+Your+Healt*&a=1&m=2)
Here's the approach:
* Consider each possible substitution of characters for asterisks. I'm using upper and lower-case letters, plus the handful of punctuation marks.
* Interpret each candidate as a base-91 integer. Why 91? It covers the span of possible characters in the input, it's prime, and it's 2 digits. It just seems good. I don't know if it's optimal.
* Modulus by a carefully chosen denominator. (359473561) Then check for a the existence of the result in the embedded hash array. If there's a match, that's the correct substitution.
In order to verify that no incorrect result would be produced, I used a C# program to verify the output for all possible inputs. It's not very portable, and it's quite long running. I've been letting it search for more than 24 hours for candidate denominators so far, so it's not really suitable for TIO. I'm running it in LINQPad.
```
const string AllChars = " ',-.:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const int Base = 91;
const int InputCount = 14252;
void Main() {
string filename = Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath), "titles.txt");
var titles = File.ReadAllLines(filename);
Console.WriteLine("Original titles: {0}", titles.Length);
Console.WriteLine("All characters: {0}", AllChars.Length);
var originalHashes = titles.Select(Hash).ToArray().Dump("Original hashes");
BigInteger candidateMod = 359473561; //BigInteger.One * InputCount * AllChars.Length * AllChars.Length * titles.Length;
BigInteger? bestMod = null;
BigInteger failJump = 1;
var candidateContainer = new DumpContainer(candidateMod).Dump("Candidate");
var bestContainer = new DumpContainer(bestMod).Dump("Best");
var rateContainer = new DumpContainer().Dump("Candidates / s");
int tested = 0;
var sw = Stopwatch.StartNew();
while (true) {
bool success = TestCandidateMod(candidateMod, titles, originalHashes);
if (success) {
bestContainer.Content = bestMod = BigInteger.Min(bestMod ?? candidateMod, candidateMod);
candidateMod = candidateMod * 99 / 100; // reduce by 1%;
}
rateContainer.Content = ++tested * 1e3 / sw.ElapsedMilliseconds;
candidateContainer.Content = --candidateMod;
}
}
bool TestCandidateMod(BigInteger candidateMod, string[] titles, BigInteger[] originalHashes) {
var moddedHashes = new HashSet<BigInteger>(originalHashes.Select(h => h % candidateMod));
bool TitleIsOk(string title) {
BigInteger originalHash = Hash(title);
for (int i1 = 0; i1 < title.Length - 1; i1++) {
BigInteger placeValue1 = BigInteger.Pow(Base, title.Length - i1 - 1);
foreach (var c1 in AllChars) {
int offset1 = c1 - title[i1];
BigInteger hash1 = originalHash + placeValue1 * offset1;
for (int i2 = i1 + 1; i2 < title.Length; i2++) {
BigInteger placeValue2 = BigInteger.Pow(Base, title.Length - i2 - 1);
foreach (var c2 in AllChars) {
int offset2 = c2 - title[i2];
if (offset1 == 0 && offset2 == 0) continue;
BigInteger hash2 = hash1 + placeValue2 * offset2;
if (moddedHashes.Contains(hash2 % candidateMod)) {
return false;
}
}
}
}
}
return true;
}
return titles.AsParallel().AsUnordered().All(TitleIsOk);
}
BigInteger Hash(string title) => title.Aggregate(BigInteger.Zero, (a, b) => a * Base + b);
```
Another note about the storage of the embedded hash values in the program. The hashes are sorted prior to embedding in the array. I'm using a stax feature called "crammed integer arrays" which is a way of efficiently representing integer arrays. This representation is able to store differences between elements if that's more efficient, so pre-sorting the values saves some bytes.
Here's the unpacked representation with some minimal comments.
```
Vl" ',-.:"+:2 all pairs of replacement characters
f filter
;'*/s\$1T do replacement
91|E base-91 digits
359473561% mod by denominator
">m\zR^ehBT}/!P*Nv:0N?s}FGN\:M.RT0r2VVm560$k;!yP<I*&R0_&q6wEcg8)&DsZ_!}&}Y&:Ngv&B::n!g6y &&eej...Z-&J..7!Rso36>y89:*iA*eNHGBmZ5!kiZ5*D(};*Xgkvwqn^(g?!kJib&g$ep!aDaA!Xw$_!w,2E.6NFG6DPat&(u4?28BIRu<bBL\S!ugPf!Ry;&T0\/^y\S{gu;!\0spo!^3!}X0l!i$L5&Z8@|!X4}p.LyU:X2M&PR6Y!k*,[F(&v&(ZJ5Jo0d!RN!hsDFvV.kI*{u@_!a<oGoqsG2}XhJ:2,"!
# count occurrences in crammed array
```
[Answer]
# Python 2, 862 bytes
```
00000000: 2363 6f64 696e 673a 3433 370a 696d 706f #coding:437.impo
00000010: 7274 2072 652c 7a6c 6962 0a6c 616d 6264 rt re,zlib.lambd
00000020: 6120 733a 7265 2e66 696e 6461 6c6c 2873 a s:re.findall(s
00000030: 2e72 6570 6c61 6365 282a 222a 2e22 292c .replace(*"*."),
00000040: 7a6c 6962 2e64 6563 6f6d 7072 6573 7328 zlib.decompress(
00000050: 2222 2278 da65 54cb 96da 3810 fd95 da65 """x.eT...8....e
00000060: 93e9 0fc8 ce40 80ce 810e c13d a74f 9605 .....@.....=.O..
00000070: 2eb0 4ecb 2a46 8f10 cfd7 e796 0c9d d702 ..N.*F..........
00000080: b08d 54f7 2937 a997 4459 a9a9 179f 7d47 ..T.)7..DY....}G
00000090: 4b4e bdd3 201d 6d4b ec24 d2ce f378 e0e3 KN.. .mK.$...x..
000000a0: 2b3d f742 730d e9e2 2267 8de9 bee0 df60 +=.Bs..."g.....`
000000b0: df2b cf29 d15e 5226 1768 277c 94f7 b48d .+.).^R&.h'|....
000000c0: e901 7b7c 190e 4a6b bd1a d4c2 b127 be6f ..{|..Jk.....'.o
000000d0: 5ef0 f98c 1f3d 51c6 f8ad 0b60 a0f1 ac39 ^....=Q....`...9
000000e0: 4ba0 0d77 23cd 7c91 4b74 21d3 49e3 7d9b K..w#.|.Kt!.I.}.
000000f0: 71d9 2ab0 e6b1 1c6d e08a 073c e157 7c09 q.*....m...<.W|.
00000100: a6ef 249e e498 df96 472d 070f 4d2f 9c05 ..$.....G-..M/..
00000110: cc1b 9a73 1243 7d1c 8612 5c5c 1ee9 b193 ...s.C}...\\....
00000120: 90ed 621e 5d72 893e e6d2 8949 9979 13bf ..b.]r.>...I.y..
00000130: e4e9 0e02 7ea1 301b e51f 7ca8 7d1d 69ed ....~.0...|.}.i.
00000140: ce3d 3d7e b9ff 5d01 7651 d231 ba4b 86a3 .==~..].vQ.1.K..
00000150: 1f7e f3eb a8df eaa5 701a 69e3 2c05 b337 .~......p.i.,..7
00000160: ea35 5013 e8e3 772c 71a9 422e 39b3 3766 .5P...w,q.B.9.7f
00000170: 0db5 6078 eced 2158 42f0 a2ca c2ea 8ba6 ..`x..!XB.......
00000180: 12e5 cdea 8d7b bd4d 7c02 abec dd09 6b85 .....{.M|.....k.
00000190: 730f 9679 fae3 1354 5d34 4302 32b8 8677 s..y...T]4C.2..w
000001a0: 50cc d11b 176c f8e9 ef82 03f2 d182 b4d9 P....l..........
000001b0: a077 5c30 74a9 2744 018f ed6a 9abb 91d0 .w\0t.'D...j....
000001c0: 2518 bf66 2488 47b0 5aea a406 e6a3 0be6 %..f$.G.Z.......
000001d0: f54d 7f0d f9b3 c9df f2d8 cb40 ad7c 27db .M.........@.|'.
000001e0: 561b c031 3ab1 1119 f9b9 6f82 0140 ce53 V..1:[[email protected]](/cdn-cgi/l/email-protection)
000001f0: 47d6 1ad4 ac2d bf19 3a67 a424 80fe 9f63 G....-..:g.$...c
00000200: 6754 11d2 572d 91d6 c21e dc56 7122 7594 gT..W-.....Vq"u.
00000210: 1a44 7ab3 e90d 749a 035c 30a6 bd22 ed36 .Dz...t..\0..".6
00000220: 73a4 27a5 6733 b976 f6a7 b72b 9d8e 0cee s.'.g3.v...+....
00000230: bd9c 851e 33bc 6bbc afed c0b0 dac4 0de2 ....3.k.........
00000240: 8599 b392 e14c ee51 d01b c68b 03a1 6745 .....L.Q......gE
00000250: 8b38 8c80 c818 f684 8301 bef0 0122 dcf0 .8..........."..
00000260: f0f0 40cd 197e f29f 8d5f 4591 d043 21e2 ..@..~..._E..C!.
00000270: 2be1 8ce4 dbe2 325b 056c e532 f2e0 c219 +.....2[.l.2....
00000280: eca3 a506 4fba 9378 af57 2bfc ccc5 ee4e ....O..x.W+....N
00000290: d142 3294 0d23 e196 7dc9 5565 6da0 0e83 .B2..#..}.Uem...
000002a0: 76fa 4b97 d034 707c 517f 4292 63f5 6c5e v.K..4p|Q.B.c.l^
000002b0: ab80 8356 0f28 86be b0cb 86dc d4e8 211c ...V.(........!.
000002c0: 06e6 2973 0bfb 56d3 b637 6f6f 7ab0 6b8b ..)s..V..7ooz.k.
000002d0: 5a1f ca5f c656 138b 0371 cc14 f310 e99f Z.._.V...q......
000002e0: 7c05 6a7b 9cc3 6483 e1c5 789f 7518 eba6 |.j{..d...x.u...
000002f0: 99ea 7dfc 073b 2c02 ca3b 8d70 c365 da73 ..}..;,..;.p.e.s
00000300: 483a 549f 782a 2812 304a 31d3 d21c 6daf H:T.x*(.0J1...m.
00000310: 76af 50b1 97ff 8a93 fbda 257b 3fb9 6a9d v.P.......%{?.j.
00000320: 9033 d756 eef1 82b3 3259 f93a d799 5a5b .3.V....2Y.:..Z[
00000330: 3e1d cb06 d1da bbd4 c08d 3563 b3c6 e1c6 >.........5c....
00000340: ed3d b583 e245 654e 9a9e 299f 256c 0e35 .=...EeN..).%l.5
00000350: a185 48f7 0304 28f2 1d22 2222 2929 ..H...(.."""))
```
[Here](https://tio.run/##bVXJbiTHEb3zKwocA1wskpGZkZsE@6KzAEM@emwgthwSILuJ7h5oRtC/j19TBCQDLh7YlRnri/eiVI6P37592H48hJxiOz3G9nrYfzrIy/3F9UXY4367@mB7f9p9@p5Lv3o/enp53R9O2yG@@/X5Sd9P73bb1bO8qMt2/P4Q9@tp5/L8fH28P8Trs1hc317e3l/evPnce9j@5fUQx@P15eXle4g@XKpXNu05CSvZ8lTDNfNcRsnnSjhMeXYaw3qeITmo5tKaipuXnJfTmLPDs3gIpaI2R87CTTx6mdyrhI6q2fGnKXdpzccUZ@7i5KNNi5TbsBLOgxdLXi0m2eQVQ7StmCPVEqswj66kbQ5BzbaIc@5cuwVbGpWihvgk0tT66HVqrylXkeCAkbLmpeyE2JGjZ0egGHX2SIw4ZdUGGBZ5oMU6Z0owVg5cimTrLeVhKWpKo@FCZlulch8pAYxVJ451lqLDfZqUIohCsThlrUJWYd8WyZq15u6@aKZ1TtW8FRUuWTXIqEuVpj1o9JE7IO4pc2VOApzD2oQdJ7Yo3rwQT84RWhUANz1PZq1evVUAKdQo0ARNw6gLcF@9C8@EwciAcZ@9uQDFTGth3K0JcxuBsSieAnoh9bQeA1OaTj1QY1LGYOqgZCCQeKl6DoYxoF2woMNlzFh1jSItYRLLlDBOt1KasaJesSlztDKM0eqiUTQAvhSqk8s0a2UFa0pTtS7zStzIWga9Vi3dem2sJbN46gbyViXqaVgLsG/I4BoEJueVa@dBrUQMPY@FFANYBgIIwlgeC2TsKWnpvYDFPTognBh7c@N5htFHbSuvQatMFOd5KrhIVAKEtNabgTNSZzRy56ncIRwMCORAkx1UljPAzcFhG4s6lZbBBoGi@uLWqXWxdEa2n9mAwJQFOK0xKYBkLjM3cwKgbaJ8K7kbmc@i2pIPG4LBpiiDMrMUOGtJqhOEM0ML1GbUMvXsAUNZSNIM6bMpPDNIDGqQ5pEdnOAKeaoOEdTsKzdeBlUniynSAekargZcVnGItQJPPB3ETmZMXZFpVWyVEWqlWrVUK0HtKMZEJ1CEOVqCqoY55HpOE5bVGsr3M@OwOIBMoDWUCRr1EUaTgfDKoiBoU0oJ4OYFvCEKr1UASQayCOFgoIAB1ogSL1AuMLkSBfNkLokJO0@TmqOxGJ6hOqwsgsSgMfdUUFnGYJfODOxwxHl0TlWtgr3ONCAQ7CwGg5kKsulgx44AIpAbzRraDC55YPsU7g1jALJgzIReG2XtAqV60VqURcY0lahL0K5PxfZo3h1vNUaCMqBvGJ//o4KGQ8zHFH0zxmogAmSMt@IkFRzuCYrmoXgBPkAEasfiWOACwzAAA7b8QpW2cvLtt@3LF9/uDtvd6x@fGHwtbm6uLm62v2@2f/78ovv7168XFx@2fxyedqft6XR/YXL6893Z9Wzwz8f9L7g/bs@x@3R6vP/94hfb7uxP5sh6DN@ujg8fr/9Fd/PfH//68eb@9gEJvp4e97stf7d9TJt@PcXx4eqPxLI9xhf//PL6Hvdc@v@L@p@HDc/ZE64/f969Vfzm8WZQjg@/f0Qf1t/ef/yAs788/PD6lmZdX/4su9v9y7b2ByS9xQdm@0l2lzcPV/@b7/Wt3Lzdffv2Xw) is a bash script that assembles this program and demonstrates its execution.
# Explanation
This is a fairly simple solution: I looked for the most compressable permutation of the titles as joined by spaces. This program simply replaces `*` in the input by `.`, and looks for a match of that a regular expression inside the string.
The string decompresses to:
```
How to Dial a Murder Forgotten Lady No Time to Die Old Fashioned Murder Suitable for Framing Fade in to Murder Agenda for Murder The Conspirators Requiem for a Falling Star A Case of Immunity Candidate for Crime Any Old Port in a Storm Troubled Waters Rest in Peace, Mrs. Columbo Short Fuse Try and Catch Me Death Lends a Hand Double Exposure Strange Bedfellows Lady in Waiting Now You See Him... Prescription: Murder Grand Deceptions Columbo and the Murder of a Rock Star Etude in Black Dagger of the Mind Undercover A Friend in Deed Caution: Murder Can Be Hazardous to Your Health The Greenhouse Jungle Blueprint for Murder The Bye-Bye Sky High IQ Murder Case Columbo Goes to College Ransom for a Dead Man Publish or Perish Lovely But Lethal Playback Ashes to Ashes A Trace of Murder By Dawn's Early Light A Deadly State of Mind Sex and the Married Detective Murder Under Glass Columbo Likes the Nightlife Uneasy Lies the Crown Death Hits the Jackpot Mind Over Mayhem Columbo Goes to the Guillotine Murder by the Book A Bird in the Hand... It's All in the Game Negative Reaction Double Shock Make Me a Perfect Murder The Most Crucial Game Butterfly in Shades of Grey An Exercise in Fatality Last Salute to the Commodore A Stitch in Crime Swan Song Murder in Malibu Murder, Smoke and Shadows Murder With Too Many Notes A Matter of Honor The Most Dangerous Match Dead Weight Identity Crisis Columbo Cries Wolf Murder: A Self Portrait
```
[Answer]
# JavaScript (ES6), 634 bytes
*This submission **[was meant to remain hidden](https://codegolf.stackexchange.com/revisions/160500/1)** until an answer of less than 500 bytes was published. **[Which has now been done](https://codegolf.stackexchange.com/a/160499/58563)**.*
```
s=>[..." ',-.:ABCDEFGHIJLMNOPQRSTUWYabcdefghiklmnopqrstuvwxyz"].some((x,_,a)=>!a.every(y=>'kmpyjzlu83giljc0o4nvjfsic25kyom2obemwt8b1434qdrd9tuyqjk6lqyhbwi8rpv6aiw91v5s50psxbs7fb5zx3j8e09lscyct7assemgy9rqg15jqv3ulcg76mhtd57dlcoalt99155ot34at8towx1stbymusf5l0lqubd75ri8edrftn1dfkvfwxmc1akftcluh9z58vo8apk79wr6f1lwbvi4nebpuy0n8ducjbzg9osmujjn3rvvkoqw6jp4zn2tcaawx8r0johdvm650uk0ju97rvl806y7bfaf8m0i8h4jk3xetxe2m0r4slgwuoabjmvvoq81koc00m0bd7q32qlwpne04odf6uxaw9nvo3i8x18904y5d56r98j39rc18vkqfkhe4z5gjzht0lgj8y'.indexOf((1e5+[...S=s.replace(/\*/g,_=>i++?y:x,i=0)].reduce((h,c)=>(h*123+c.charCodeAt())>>>0,0).toString(36)).slice(-6))%6))&&S
```
[Try it online!](https://tio.run/##fVZdb9vGEn3vr9gGaC1NHJWyPkwFsC9sKbYTWI5rOTCK3qJYkkNyqSVX2g9S1J9Ph3LSh2KVBwGSONyZOXPOmS14zU2sxca@q1SCX9OLr@bi8s/BYPCGnZy@G7y/up4vPtzc3n38dL98@Pz4@9Pq@cvLHzyKE0yzXKxlWanNVhvr6mbX7t/8NTCqxF5vd/r3Ke9fXP7MB1ijbnvtxeXJuty0xV66cJQJWcSBGld1kRoRn03WrSrPVIRlY8NoOB6Nt4lOZta122I9lds2jxoR6k095aKZDeuJmQQbs4vMeRpN9rtREWIwkyZuY3vOjcEya2d6mw0nxbYeORln59Myt8nkPJGx4tLOZsPJRNnRmNvQqmY3NDZqS2fSiQzk1kXJ@USLEBOd2mqYpOs6bXZlPOTr1MbS5bP9JKxVyDfr81mjp@lQNlEtxhVGG9cGVZi4uIj22UyZ0hVFNdJ1vVbbZlpsxvvqzMacN7tQB4XKk7qcTgK3Dgo3O9e1DINpex6lPA3LQIT5uFiPdmh3eFYGemxk1jjFo6Ksa7UNh2sVB0EZULXb0dlWNpsKg7FK0qnb8WZW1Wokwt0wnAXjdpJMpnoWFqOZjodhvd6m6xzH@0lW7HMbyKwI25OBqBLcfU57vSFO3nYkWF2YgcaN5DH2fvs//Jad/n1xKd6@/V/7fncqLoL@X/SYmqWB56cxjbuXw/Bs9DYexDnXc2LUle31@5eXl8Fp0B9YtbJaVFlvNO33B0YKevEdff2FPr/@uvoaq8ooiQOpsl7ae/Oo4ZWbQlXv2dJBgvpNv//Tf8KeOBDnWKo0cLZAnrAlrzxxS9B0AItaZnNk1wrWniBAbnO4xyoxjLM7XiWeIEoC7AVFBtbzdOWE5RFgVxG70byEKvOE3fMEmKjYCwcrvBGrXGnLAAz6CpUONwSmPaRZOuoNPGEfrINDmmsaoq/hZyr0ViNWuXIG2CdXZdKX75kwW4KxbK5dDFyyW1764hY8AwSm0gPKS@EF8Am3DvAwM0L5hoMkBNjKct98r9gKhI1zoC7mWpRHq1NgYcGrDDW1QiSgd3wFgosk0pnKi8c91CBbdu0su0ebc@mrqGrZZ5mwR6Jchy2HlVW69ETOiUCQcPtKhrkGP2bqUNKHHShw2hfx6CIQJmd0yCNo@ubjt4CEfSazpdbb3MuGVcMr6rwCL8w3IIj3HcwLxMTbN9WIOhYGu7ZvuKXBWd9hD5jRwxrZE3b0Vj49XrdsAQ2cGPaBa4L8XmS5T0@gD/AkpBSL2pftUUIbgXecV9A5ArQduWgKRMsjlLxROlPWQsXuObRefObcHE6AsnTESF/QR4DK0qOOqEYY7zFLQoSGBCm7U5XyMf5BNQyUYytEdieg28Y@/yAxrjg4asuqg9pAlaVKlJdBNzw5DM3CcbPoOH3DTU7zIipBF6aPWMZ1i@/ow1brlkrMcvbx9@5coMY6mHxv6ZaRGtgcSJdkJT4GU0bQ7AutIQ23kha5jw58TVpH8o1H1CnGlr0auyf0jnAkaBadXfHjYUDQzemvjdBAOvYlnSvpIFLsVqH5jvatAykVeTcebeWUrUpF5QL1vcp5ohrf4SvcHZA5GCbXWpB/LtBSa6L2wXSrO1dZYIzdagTjT0@jeM/IO1GmnVFZTZQ90llJnRFh0cALyNRH2oyMgcO3TQP@NYzERyLYI/IYTtlSmwH7Bpsn@kuFnNbNPXR4dvhr1fxgadO5JBsRuR908H029BswA68bu8NdAl7vEsRU2oskMb7nOul2Br39h3Ka3SHdEfMf5Pp3XK@MJS1z9kQL5dgOO1wrSCjWsI5tn2gXb5T1Sp89ixI6mS4Eev3jWrxunS7/HYfEbw8f7QnAlZTfI4@sa7IPMqOU7FdU0FGUMCSLoxtB650awRaTr/vQBUu87KwBkxRJGY3f/kATPw5GfMxfrgyxgpTIrkyOR9jdje9FEKbPSjGgvOxBWTwm3RIUrZf1N649AC0aKdIOj6//AA "JavaScript (Node.js) – Try It Online") (one random test case per episode)
### How?
We define **chr**, the list of characters used in the episode titles.
```
chr = " ',-.:ABCDEFGHIJLMNOPQRSTUWYabcdefghiklmnopqrstuvwxyz"
```
We define **hash**, a string containing the hashes of all unobfuscated titles. Each hash consists of a 6-digit number in base-36.
```
hash =
'kmpyjzlu83giljc0o4nvjfsic25kyom2obemwt8b1434qdrd9tuyqjk6lqyhbwi8rpv6a' +
'iw91v5s50psxbs7fb5zx3j8e09lscyct7assemgy9rqg15jqv3ulcg76mhtd57dlcoalt' +
'99155ot34at8towx1stbymusf5l0lqubd75ri8edrftn1dfkvfwxmc1akftcluh9z58vo' +
'8apk79wr6f1lwbvi4nebpuy0n8ducjbzg9osmujjn3rvvkoqw6jp4zn2tcaawx8r0johd' +
'vm650uk0ju97rvl806y7bfaf8m0i8h4jk3xetxe2m0r4slgwuoabjmvvoq81koc00m0bd' +
'7q32qlwpne04odf6uxaw9nvo3i8x18904y5d56r98j39rc18vkqfkhe4z5gjzht0lgj8y'
```
We define **H()**, a simple hash function.
```
H = s => ( // given s
1e5 + // prepend '100000' to make sure we have enough leading 0's
[...s].reduce((h, c) => // for each character c in s:
(h * 123 + c.charCodeAt()) // update h to h * 123 + ASCII code of c
>>> 0, // force an unsigned 32-bit integer
0 // start with h = 0
).toString(36) // encode the result in base-36
).slice(-6) // and keep only the last 6 digits
```
This gives **log2(366) ~= 31 bits** of entropy. By rounding this to 4 bytes and adding the size of **chr**, the total size of the payload data is: **4 \* 69 + 53 = 329 bytes**.
The main function now reads as:
```
s => // given an obfuscated title s
[...chr].some((x, _, a) => // for each character x in chr:
!a.every(y => // for each character y in chr:
hash.indexOf( // look for the position in the hash string
H(S = s.replace( // of the hash value of the string S
/\*/g, // obtained by replacing in s the two '*'
_ => i++ ? y : x, // with x and y
i = 0 // i = counter
)) // end of call to H()
) % 6 // apply modulo 6 -> forces every() to fail when it's 0
) // end of every() -> forces some() to succeed when it fails
) && S // end of some(); return S
```
(This was exhaustively tested against [all possible inputs](https://pastebin.com/JQnDGzsR).)
[Answer]
# Wolfram Language ~~1383~~ 1226 bytes
*EditDistance* finds the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between strings.
```
f@i_:=Sort[{i~EditDistance~#,#}&/@StringSplit[Uncompress@"1:eJxtVU1vGzcQzam/Y3rqJTHaHnPThyU5kBxFq8Ao0MtIO9olzOWoJNfK5tfnkVzZStCDjSU55Lw3783o94PuKvnt3butl3D05hyNuo+06X0t/t8///p7xy5oRyf1xDQXrmnDLh2UEDoMFFuhqepz2kVEbGktrg6IX7Grx92ansQ0bUzLqjeRD1byqwvPnXFN2l9zPZBx9MQmjltVqz7Sog+SVlPby9kbF/PNN5D3sa8l3ZxaPmYce2BaehHXKu7Sp941Vq4HGw2RZr4/Gra05C4fzLlpwEdPmc/GFOQ7+a83cuW/YGsBjKrIOe8EXyYe25R65k33c4Y5O7yI/CgZgnIS7RNvsCow1/oidqBpH1Gz2LLNr7qBPtuatok6XmZkUd+loxkKamqOpXSvKcdn77+dNfQ+b22xY0JLCNuKx1fWDKzo8wtobnhoJT9ZXdhRpaXcE8hhIF5KOxepCxw8LP5oQi7xgiNbE4d09CgNR/MitBM+JudkkQYwv7g/At2zB7n1Vfa9zzDhBBDwIaO0PBxGySbZXriA6oIghLiKsFDfaIziKDmkxM445JiHruvdCOehFgc9hlSYYEIJRO1j0XWlTrNsj3qhf7SnSoRWpru7uyvug2YV2x7Jo2YXzLTrtNZS0QUXj+HszXlJpwWHFtxB7G0/mWA6yAf8UfU8IE3T0sOXMSKjLyUZCJJinVy0kZvG+urS/6XlkIls+Bm2EpgBcp7kGG+SrcAHqObJzvwLiJm6cDae4aD8zkxt3x2UlirhSnPZG2sVLXeT/z1VnSJlQle1XOslX6/kW97KPcIeZqkhWwQe2CAFLH06nstR8igJby9+JLSL2FP2tUeL38KBYsDzpPaUVWvgQf6lyXcScjts4TV5Txsf7mi8no6/OuGQ3JZ4JeJeL7eDCjc3MO6h/78qYG2lkdJi/e0MhDQYK/AJf2dfp2ZGOMzjaSVsY3v72mthyk1YjmmHTn+dF2U6rkwsED/B+WeNxZK0RzMXGaU4d2p8bsQUmibp6NOHiNaaWHs9ug4wDBEY/WTzCE2SgRogYAoOpT7AdMS8yUgqKIDpBGb1SSD+ZeyWvUdxc++91n0S2lKk/HFT0ScDMnvV9Isw0KNG+clha/M8SvGYJoA1J/kBVHorKg==",{"\n"}]][[1,2]]
```
---
```
f["Ran*om for a *ead Man"]
"Ransom for a Dead Man"
```
[Answer]
# [Python 2](https://docs.python.org/2/), 621 bytes
```
C='6PX2OHRR3M431R8RODFNHWX44MRFXJFPZ3FH5D9920XJ6DQRBGY02VNRZETRUTVB0TH9V3T0C0VKA5NLPVQ6T9IUVNSSHXMDQORLA842O8MJQEM46Y6BKW9IQWXOL02MTRLM5L1APZFUXO1EY880ECSXKW0GO1YJPTW7P56X0B6ZSMJBUDS2FZIQ4XPAS5PHQL6HEICDMJQKQZXGISSQ4F0KBLG0ODLEJXYUVNUP5IS27GIMC5FBZFAK6PU5WOEFBOJZHXBGBJYMB8Z0GQH5VFJW6JQ0BVJAQAW7KJ56R0DF35U5IGBO2U22VQPWMBIP8IAH0Y1TU9VGRWDHR59G4HELD8491GJECIQNH9ERA2IRMOBM2DMYSN87Z1NBLEBMEYI4AV40ZPP2MC4DPQRMOT16IUAACE'
H=[int(C[i::69],36)for i in range(69)]
P="acbedgfihkjmlonqpsrutwvyxz";P+=P.upper()+" '-,.:"
f=lambda s:[t for h,t in[(hash('B'+s.replace('*','%s')%(i,j))%(36**6),i+j)for i in P for j in P]if h in H][0]
```
[Try it online!](https://tio.run/##bVVrb@I4FP08/Aqr0gqYYVCgkIGuulJCyIMSCAnvUmldYojbEDOJM232z89eO7Sd0e6Hlti@vj73nHPtc8EjlrR//hzcVlVv3Z7avn/tdq5bfs@fGubEXq07Hdc31yPT216bdtfo99vKeqQaM1@3Nkp7OfG3w7m/mC91ZW73l9dzZaAs77TuZOwtZ@q87yyWkyCw164xm/pjrddpT3vuaDZ0O@pG1e9WfWe2Wk/HStud@2O3O25p3tZcrKet4abXU4aDYH23UqxpazPy5qtvXlddK7q6DdyRvjCCtrl1Zp21pwVdz56NVXvoDAzIfjfbri0nCGYdU7nTx5YyNcbD0XoDWBZe1wna3yzHHXRNfWtqd6q36K6mQ1Ofjrb2Wrf00cbVe1vFmtndpTlaqaOZoi9H2kxbfbsbdVVfMczr7qLrWPq0vWi3lzNv5eqO13M0W9m05ov@0vJXhu13@1bHHo6NXqffskbDgTOb2P2hr7Ud353qbttwN8Gk923bmujjoe4ON05HW3aUree13UHH8GYQNm@pzkLTBsNqxb69pwmvDe7pzY3af2hcq/UDSxFFNEEpTo6kpvbrDxXv9grvH0l4PNDo@ekUs@T7OUtz/vKjeP3n6k/vy63XzM9nktbqX65Q9WujeXNVOdzG@PQYYpTd3HMk0kYNDonvaxHOolpVr37Jmik5x3hPatXP1Ub1j6xa/6NGG091@LlWP39W6w365ekDkifTPMnPB3pAkfiyH@6Vh8pPejqzlAvUITtVKpzymGS3V15Ksn1Kz5yy5Aa5eRqSdJf4OMnYSWbDyCA4RC5Odkm5jB4LxCOCdMaedwms8giNSRJmEGtDejkXohWhx4jvkiCnHD/GRGYzU3yiyXGXjHFYCHQrTLmcCCIBz8wzskv0OCfnFJiXe95ADXkeErFHB0rg5DlgsFJCkojBLjTKk2NMymmXZRwN0nxPcYwsfIJpAx@PgJ0dJHaXCpw@@Z5T8lanieMYoKCAYzhNg1/K95LCQUpPv2Y2hPQpnAq0QAgkZ7moEGoQwMbsB4kLpOcceOERjiFbUqBpHCJPFAkZMWRn6WmXDIAwGmJe0nM56JJu@HpmWZ7ChAdjmkUIQjySwhdoARWg6Q8oycVFRCBV8IITFDBBpgZEU5BEHGUQEgoAkI6ke5pJCk3McUx5sUsm5Ig5/UGQT/BeuADoL6DCl6SaoSFOoZBxKeQ8lbBAWYCbZoAqxsWjlEKTJoFQ4A5KAZJLgk2WHhnnJEFCbxE3wJlcd06nPJEAnJAkwHQhis9oJoKAVV5qZbOEgRgT9oI2LEcBIcimp2azKRwESgQ4zuFAzqSqA3Y6sZAJxkxcegVW3vwj@DehtaBGKOJtVoiqF@Qr/KHguYD0xwg5s8u6xCtKLxAIBSPhCJe8t8IiEf@tGGcA3MXPYBAC4oJIB7Ln74fYgB@QGMKO@LejByzJzjTF4AbIMGBxfnpkyGIkeyvKymkcM2iS91MbKDgxOEogCiIcshfYGpBXOSHdjVOQPwRROKAAcXeJJRofJvZEtnr2lusGgdFJfJDOTKEZP0CAHoBixeIDaHIEN@Hf2tEnmbSyB74hDeSmWRNdtu6SRUJwJpwj6hBlpuzl4wKBXS7Y7zH/b8UwjsmRiMbIf72TgHpofFAf/4PTULQeBIMlUmQTHPPoI9M7CeU@MBFGPvTlpa/L@8qmvAQ2Av@eGRcWQ3NovlImIlyo01Q2kAgT95p0ncOhLbQ4flsoLxdodTDsIZZXmpAEioGD4XYqBBeAYw93ApwecPlsQCXhgYCsL9Lv8xQolF1z4VbLopIO@fHO24oC9Dlj4jYu0IRx8otnxvT5QvZE9GtMD@SqmZ2hy2vVXVKtVypCPS5FfX@@Wkr9pvJJPgboFsEdw2vlC9HcR4zCw1O@E/V65dMrBPy@VqaISVJG1UVU8Z8omTQj/H/Cv4rp@9cHuVNOwgASwGv3JyrHxWX8AbJabT4x@pak8ql8KOSoUb39q9r4@3BZ@/vnvw "Python 2 – Try It Online")
Note: Dang! Just saw this is essentially the same as Arnauds solution...
Not fully golfed yet...
The basic idea here: create a list of hashes of the titles, modulo 36^6 (this requires 6 bytes per title; plus some overhead).
Now, given a title with two missing characters, brute force substitute the two possible letters, and check to see if the resulting string's hash is in the list.
By preprending 'B' to the titles and using Python's `hash` function, we get a list which never has collisions in that task; so there will always be one and only one possible answer.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 752 bytes
```
“¬pẋEĠṬɓV;_÷¡×KḌƤ0m®Ạ-^jSƁhṙ#4¶µ.zbọẒṂhʋhe]ÇjỴėṖ=½%ẓ>ẆḃḥḞ-€VœØsỊv^ḅṇŒ#ċyṂkḅṄɠmS3HṬ`ØỵṆ(ṆƇṀßI(ċɓẊ^Ʋs#ç⁺&ð⁸³Iṙ}ṃỌ¤zhṡ¥ẉeE/WḌĊEd⁸ġƝẈµ9raẒ[ḳėŒnÞ*ƒṭɓ>>^ƓdeɦlCḥƘ-=Ʋẓ"÷:V}Ṅ⁼ƭbÇḤƁẊ21ẋṄŻėḢ⁴GG⁷ñ,ụƥṭ6ʂ¥ƊsØĖż]ṗŀṙĠ⁷ṀĿt$²ỵÞ(ŻṙS¥pḥƝ|þœ¹fX{bbð*ṾẹḢGẊmʠḲḤFẎṘṣʋ¡f⁺}4Sọ(Ẉḅ¿ọṿỌŒ0mo@ƒ⁻ıƲỊḢ#ẹ⁵ŀạƭėµdƙæṀ|ḷ2¶TḲẈżḣƁ/ṃạHṠVf¿2ỊþfnṪðF:=WẒXȷḂ5ȧẓ®ƥƤḃ0¿ṬỌḥg4Ụ3Ḅ(ⱮƬZƒẈİu<Ð6ImṖƇṁgḊƘBƤṡ⁾ȯ=ƓẆ{œƙYṅb÷ėÞṬSȷƁḌɱyƒþwỊK¬6t=ėṡ⁽Ṡƥġ-ẒḞOṙOṾ.Eḣḋqṣ,¢¬ƒṗ3ṾỌƓ¤þṗñỤṫ#Ḷġ*żėṣĖƈ1)zḄ×l⁻ñ:ẊẎY®ɠ4ƭ⁹ṪqạƬẒẆO_jṃgẓ¶ɓẎṆ⁼Ẹ⁴9%*'ọḌṅṅþḷḄ*Þ9ɓ&ȯ'~æ:⁷ịẒ⁸t)!ẸƙȥṫỴỵṢ ẏxƓ}ɠ+£¡Ṃ¦ṗẏÞæẊA²Ʋ#ẹƊ!£Æụ½:eUỌƒṾịụ&ḋȤ#lṖ*M¤fçȮṫo]ṗXṚ'+8ỊEẋ8{{Sṇ85⁺VɦrF¢c,[£Nȯœ/ʋñṄṬƑỤsṗxṿŒ¿€Ỵ¥ƬƭṂṂỤẋogṠṡḢÆṭzƘȯ:Ẓ¹ḥṃṄạėPȦ4ṗḋĊ⁵Ḣẋṛ⁷oNHAnṃ÷°5ṿ¿Ṗ,%ßĠṠ⁷ṂÐrEʋėỌẊƲXœ>*þƒƲẇÐĠṪṀ$:İƥøs²ṗ)}ṇ5⁻g¦eLʠCı32ṾŻƲƘ¹$²ƘsĿÇḳPṬẒƘẎlṂṫ8ɦɓ4ẸþCẈạOỌẏŻḲⱮʠÑ<ʠĊṣßỌK7Ø5],⁸ƒjḂƥ⁷»Ỵ©=ċ€0i2ị®
```
[Try it online!](https://tio.run/##JVQLUxNHHP8qWEQwgiKvAhWmlkFlrI8pLWIdsVAClvJQsK2CdjxAoDlaMTdDQltjAkkYNTwShezeYZjZvdtJ8i3@@SL0t3Qml5l77H9/zx3xj44@OToqPf9XpB6QbXa6UeKpgtXzxT2ZFTEZukpsWcVrx8Q22dGavpFuZdwnvlbeIPbF3tnpAXL@JDtIfPZ@0bzvvysXR8j56IaIr7aJTxVkW@1kLxCbI5YgFqkpzaZ6PEuGp8gJ/NpH7AXxRS9Y7ppPMOLn4/v5QnSsu/4KYPwgw@TsEV@owqUWiT@Xb7qqXLNgkR3oU5mpcrlZMuxTcrdkMPGhC7ieEZ8jZ1nEp4EyJhJk/@HvPHcLJNxA5yA@c2PqNdlLYq9lsh/A7xD74Ia84LiM@BRobBWs9vY@ZQ36C8nRDoBW4Zo2lQGPz2S2tQfj50vGgdoakIvE4soAkLrz0A3PPQe02XrJ@Hj5csnIynQ1OQmVwMym4qxIqMCUDLur3sFd4iHvObC6UXwGUu7ho5MiA6YyUuU5eNEtEg/01q@fypxnCT7UOzMwIHd9xHNkc@xxGduOFaPEMgBxiey/iIeJbxRNERuCIM8aumFLFWhCUHGoLeL4X/aCtWMTX6pgyXDcNEg5Acwqx8iSsQdEdkxtuSGxN6jWZBK4nhLL1on9b/U29pJ3QGxDGee0wHYM9kR7hsRhHYbI3NA48Xdy91Jr2y1o2pvPEpttzG9CNbGtEioO/2uBg6cAAsSGG8iJ1xObryqlt1XqewhvL7m7v1yQK01dY4iO9toYJhZQ4a@wmsdKRi6/06bg@8KMZ6m128RfDMisG5IRTO3OZ@EEWy6kn6igzP0GTFdFqulRm84h1n4CWJVwYzU6qSxyAxLjyp3tBCNi5kNIVy3WRUoHIFSvVXaWlSXiMod7mQZY4u/Lie27MZ93oIduuKtq6fzpaXCQoVHoKdOt8ARO3BbbhWiD2ioZHJo81KKm9Lb2wo17I9BuWIuyrxMM0xaQJbIZItNS4avUPrFlMMMPWzOoOO@TkZaCdSq/U/m7TLbqvDgmxiHIj06fwFK1lkfC3qNzx01ZLyP75WNlPStEz4gNEUOpBKwM4amMwFQ7cFFkVEZ7rgInxIZcQEbFp1b/d5py8Ji6iUenIEs@Xj4KL3zXRHxIbua3sc2Ezm4v8b8rzzRD5E4Ev3lmphsdbm5E7noKyclLYv3H6jti43p@x7POFU3Ix@fhkXoFGaew/DGy6AXFIU4CoEYvUmoLMPUPOtvmxDDcgm2IJtDxrWkVzu9A3KDg@gxB@jDPjrmhm/lkg6bGTDeAAOP74x7@A5Emrl@5iEjO4QjbbcR@Onur1RXyjT7d/m/drFyZ7CyaMBORtAMq0@tZ7T6ZU0Hd9kW5oj99hxacbHV3VUKyKVSUh07jBFgEV2dYJP1fF6Mdbrq@DrJ5jsqosOAosgpPuYf6ePhwUyfeDqowzB495vi@uZAsWA0wTuY6dD/t2I1jAC9RfJZBHYpR@epCMeoGEDL5Bu@ufi7DjXer4bgKjqBXKgH8wtHavW1zTchY@xNaaIrto6Ojb/rHfRNjZUMTk2X9ZT5//2DZtf7x/wA "Jelly – Try It Online")
Used [this](https://codegolf.stackexchange.com/a/151721/41024) to compress the list.
This assumes that there is no movie which has exactly 2 characters different than another movie, which is proven [here](https://tio.run/##ZVS7khs3EMzxFZM5kc4uh6pywMeRPBV5orlUXTkc7g53YWIBCsAetQ4dOHHmf1Dm0IlLmcr@EPlH6AaWPF2VAj52MZjp6e6Zn8WY/nz@/PGvf/8of/j2n98/ffjv1z@/@14@//3b@Xxeewml18eonX1Fq85X4tWGbXAt7Z0npqlwRSu2ajikXU@xERo7d1A4iw0txVYBkQu2lcrhD6LrJqqi05F3RnKmmedW21otuepJW3pgHdNz0TgfadYFUWPTydFrG/OFC5jb2FWSLowNlwe1Re25F7GNwxV63dnaSH67ciHSxHelZkNzbkVNua6B2O0z4pUGvI2867Rce5uxMcBARWSvRvjRsWxSrYnX7bOsU7ZIhIIgAhFq6rrUFqAD0dI9iulp3EUwERs2amR7emMqWqfOkI2R2flWTUCQrjgOhAw1Lqlu3x9d6LyoNR51aAgBa/H4pxJuevOIRlbcN9Kq4sSWCgfuRmBVg/1UZCpSoTIyiS91yJTNOLLRsVf3UnPUj0Ib4TJprcY9ujrZbwLdsgf8ZVZs6zMcKAiUPqi14X6XaB9lHyAOVAE/KM10zpyvXYxiKcmKqAmHfHrXtp1Nle8qsaC1T@0GHRACCuOgysJZ59W9O9FPrqNChBa6vbm5gUdAesGmQ6nosnoT17aucmBoxoMfcHCxSOJ6xqFBX4B@eZnEG/fyEh8qDj1S1w3d/Xg5zkDRbk/QBA9J95VcPf7Wpu@54RDUig9wgUBE6LGXMl4LLIAbGKbJbvy86sTZcNSeoXlQE2e6dudo7iRce5l32hgH918LvqCidSiTsBQNV@4UVCHv83O2LnvoXEGDCADQUc19OptKKXl0wyXRK4KLxeyz9Twm7Kk@6AeAB2f2alTDMvx8xjYSslHXcIe8oJUPN3S5qN5a4ZD8kfCn7rw7PS0D3FnBYbvuqz7xbKQWeL57vltANSYZQvMv7Ks0UYiF@p4WwiY2T3meWh@uwS1MG4zbMKvD4lnoOGB6DYseXYSVaIuhGmQReG2sfR6OFJTWUzLXXYTpR8Zc3@dVgemFKfcmr6YkAbpATWyaXmU3lJhyrwqQilWADqo9FmvSaURbD9bySAxsjkIzcJD/XKl60EC8dS7t0p7uXZQv5ljqw4Xd@zSGRu/lfw) (output `1`).
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~1185~~ 1165 bytes
```
->s{t="Pr@c2p#:[Trac}of[F2)X>6ed_Ag)d14~_Bluepr`0f^[6(lVSt?}3M`d_F(}>&[C%}3Immun;y_OlXF%hi7ed[M?tK 3H7^_UndKcovK_A9t;c/>C2mZMak}M}1PKfect[BirX`jH]d<Sho8jGuillot`ZHow & Di5 1~=Mos0Cruci5 GamZ~,9mok}]XSh(ow+It's All `jGamZ*W;/Too M]VNot@_C]did?}4C2mZ~: A9elf P^tra;_Su;abl}4Fram`g_*>M5ibu_Sw]97g_*UndK Gl%+L(V>Wa;`g_*byjBook{C2@ Wolf_Playback{]dj*31Rock9tar_Etud}>Bla8 CollegZNow Y$9e}Him<Exposure{Lik@jN!lifZ6?/L)ds 1H]d=Mos0D]gK$s M?ch_DaggK ofjM`d=Bye-By}SkVHig/IQ *C%ZR]som 416aXM]_Sex ]djMar2eX6tectivZAn ExKcis}>F?5;y_Gr]X6cep#+Neg?iv}Reac#_6aXWe!_BVDawn's EarlVL!_Tr$bleXW?K+R@0>Peace, Mrs. Columbo_Sh^0FusZUne%VLi@jCrown_F^gott) L(y=Gre)h$s}JunglZId)t;VC2si+Cau#: *C] B}Hazard$s & Y$r He5th_6?/H;sjJackpot_Requiem 41F5l`g9tar_L%t95ut}&jCommod^ZNo Tim}& DiZButtKflV>Sh(@ 3Grey_LovelVBu0Leth5_TrV]XC?c/MZAnVOlXP^0>a9t^m_Str]g}Bedfellow+Ash@ & Ash@_Publis/^ PKish=C7spir?^+M`XOvK Mayhem"
"!ight|#ti7|$ou|%as|&to|(ad|)en|*~ |+s_|/h |0t |1a |2ri|3of |4f^ |5al|6De|7on|8ck{Go@ to|9 S|;it|<..._Doubl}|=_Th}|>` |?at|@es|Ker|Vy |Xd |Ze_|[ ~_A |]an|^or|`in|j th}|{_Columbo |}e |~Murder".scan(/[^|]+/){|u|t.gsub!u[0],u[1..-1]}
t.split(?_).find{|u|u.match?s.gsub(?*,?.)}}
```
[Try it online!](https://tio.run/##LVNZf9o4EH/vpxA5KEdKOBIgLbcJIQWn2ZA6FK8tBJZtgWyxkpyURc5Xz4r@9kUvo5n5X8OT1f7Db3986YiDbJ888sm6tjv/2p29uZ2bAL5fdCK2TV17FhYz1SdXsMsmsk0XFka1vN1uYg/O8G/gehsT8Rq2mxKvJXldVFb7zYCxLezH4Pb3fE1E2h71Gq09vOOu3Vzj3Xm12StP854ACIxdDz7goEde0yecO4fvX0G/g6kPHh3JUQvqlS/4FA6sIXqLPwtwizi1pn@fHozaBLww6sNZ0kIrmvoOGHEULQP4zOsriu2X3rzaD/IeAr7TnRat9gtq6eojRftVbgufJhK0H3EOXwCTixIwGE2iFYOz0JFglIhFoVmk1kz20itz6cGfMc5aUzLZGDwTwwFN8I4v5XH0yAmYlHkwLe5hpW02yCqBtzLx0vaA6j0FI5te3UdRErf2hzs2OdOLKA4Wz2F6x3E@rIv0exIHdHHv5WXLMmqCVA2UnH8FFcMFg3SM/kXcq4uzX3UOxrghw28GT9akAe5QtCiYPTkHV@Mb56CNqFwh8MTW245EHA5REMwB8zdH@A8Z8KvewemYRKVSCWr9xy2x@Z7b7piET/ifhODLUYMugz@t06zsNBKZXm8MFkXMcxYPDDyTKL0GQ7Lod2RrXW4btWgxKqbt625hQLi93Ggr9exvQzeY1wUwe@sQ/qD2KBuSG2y/w3up7etTCpabI/KhNimdhRot1FIM9vjLYJ/OttaYBOX7vzT57GKQSDn3qbXshMUJuNJy7eGUvWJq6QqYYhk2tNmWaxu9ddlc/Iy9@Zq9znXwLL1YBwi0UUc6EawcS@COZqszyd0gHWDPx5RmqobrEa93zM6RjYm2qZki8Dj3dZS7hWeeS5nf/YP09veOiYQvxpmzodYedfsinJwdH/iYrCgRZUf3EREe2Rg3Ykd4z6lWXlrlZ8aA6VoPTE6gubR/vM6BifYhjo5pANebu4RQyuQSH6ZkO9k8nFLi45NPJxn2pk5JEEp1Bq6BOpfkRmWRUDm0Vnkcq0IfqCLy1GWkU6gvSZVDoCrvQFUFVDVO1BXzgbqWTNVZohqIquYQqxsWq29HjCYTEqgWkaq9BKoDZqoL3qHqIakmWChrD9Qcc7XAUNkeUA7jykWxWpJYbYAMU3WA/58MUCkG6t1MuIf5SUmsUZy7tF3lFC/zB5UoWQpEssokdtm5SOxKqfSl4qSfZEnsKJG5LsyXfBJ7x59JKUJyHXbFn45ct3DRLeXT9GOXSAF8@@QJxQWm6TKu@RYw8rSS8Ynz8R8 "Ruby – Try It Online")
A lambda accepting a string and returning a string. Uses some homebrewed string expansion. There's probably room for golfing both in how the title is chosen from the expanded list, and in how exactly the list is compressed.
-20 bytes: Rearrange the order of the list (by hand) to increase substring repetition
Ungolfed:
```
->s{
t="Pr@c2p#:..." # t will expand to an underscore-delimited list of titles
"!ight|#ti7|$ou|..." # This is a pipe-delimited list of substitutions
.scan(/[^|]+/){|u| # For each substring consisting of non-pipe characters:
t.gsub! u[0], u[1..-1] # Each substitution's first character is the key
}
t.split(?_) # Split t into individual titles
.find{|u| # Find the first title where:
u.match? s.gsub(?*,?.) # Treating the input as a regex yields a match
}
}
```
Here is a snippet of the greedy substitution selection algorithm I used to generate this code. I've omitted some details so it won't work as-is, but it should give the gist.
```
chars = (0..127)
.map(&:chr)
.select{|c| c.inspect.size == 3 && !titles.include?(c)}
substitutions = []
while !chars.empty?
most_valuable_substring = Hash
.new{ |hash,key| hash[key] = 0 }
.tap{ |reps| titles.substrings.each{ |sb| reps[sb] += 1 } }
.select{ |sb,count| count > 1 && sb.size*count > 4 }
.sort_by{ |sb,count| sb.size*count }
.last
.first
c = chars.pop
substitutions << c + most_valuable_substring
titles.gsub! most_valuable_substring, c
end
p titles
p substitions.reverse.join "|"
```
[Answer]
# Java 10, ~~1426~~ ~~1405~~ ~~1381~~ ~~1315~~ ~~1313~~ 1298 bytes
```
s->{var i=new java.util.zip.Inflater(0<1);i.setInput(java.util.Base64.getDecoder().decode("ZVTLjts6DP0VAlp00zsf0F0ek2SKeJo7TjHokrEZW4gs5UpyM75f30Pl0QJdGDBE6vDw8FC7KKmJ9pxt8F+oGmMr0dQX9lQH35nrwWeqh3ASYt9S3XMbLsm8sU9hoGOIxLQUbqlib2a0ilaQZj0OpTW1fJRruRckRARbBLI02f6UGzwdphKfh3AyM0/PHxIbm0RBVpzZ2TyZdVSYpTRSuCaDmrmnLYolMNggal6lY8WlN+FGs24FvtCManFH2oWYI9tsCuF3sV2fzXyiJV/8p0TPHN1E23K6CG4cDoEWoJzoPbijqUeb+eCkNL2KPFgotI9hxBnQOEtMZtaBEZeUm5pbbidt5R2F9cbO8XTg5mTeJGUN7MBWPlMV0xPdypq6B1VajUmgqbIFsTqjBIUjVRbNfvfCSdmCnqq3iOHizdyNco7W5z8ZrELsQs7iSbncVUflCtoeRvOcx7aoPXfKa0YLTqXQyzCMXtW/q7EOWi0oTSedmD0Kr6OI7wOo0tfRd07MSys+45qKl2wyCx7/9BfgUUows/85trioiD/CGGkj7HJfUKsAcRZxbCw7WvOgOlSMJqIS2wQf4oPVw2BXeMSZ3kJzUsWiWXLXXU9Ljmr3Gi5aEKYACzs8PT3d7LSx+armVwhxDhkz+m+0cvf5ip3DCK+4WwbDmt2IoaCBMoMwDKENUVCB9nYogaVV7jUEaXoVGaKgmxVfJUfCbUozmttYNkeh1NDK66HFkj3aULUgQ9Obb64Fn9RDWLjvhvGSYeOZc3eUItyyOBSbC0kK3nySf/BRfZrQcdfTy7+/RwPHzUfV+eiKbXXhMXTIh0FPZht+CgJIwe7lnh02YCoTWCgtqgTOBFKDPPTkJ1KiungKxtAhxOFuwZJJa8cpmRqbiQ5hjPYozukbA5+0tlXTq/xX3SrGQ1ThLcLaxCPekd/y7SP2qOzH9eTW9/PHOaQRM9lg6mUecBQ/rqX+aunyY3a4YlNPqAd8/BXBFnhwzjYyuKc793cLv+xD0HdvoteQcVvNRd/QOA6nXoa/9qbMZLRoD0+BPMJbe7pt8as+Ps4e5Rc="));var b=new byte[1433];i.inflate(b);i.end();for(var t:new String(b).split("#"))if(t.matches(s.replace("*",".")))System.out.print(t);}
```
-66 bytes thanks to *@OlivierGrégoire* by encoding the String.
**Explanation:**
[Try it online.](https://tio.run/##jVddd6rIEn2fX9Er9@Em7RwlGjVO7sxaAb8VRQG/Zs1DAw20Aq3QqDjr/PZzC5Nzz4Q4s@5DWIau7qratWt3sSVH8mXr7L7ZAUkSpBIW/fkTQiwSNHaJTdEk/xehI2cOsu91EbPIQ8kDEn7MTwnqnG26F4xHL2D29Sd4JIIIZqMJitCv6Fvy5bc/jyRG7NeIntAWvJVTwYLyhe3Lg8gNCPi5l/7z@PDCygkVg2ifivsfZjJJaOOp7FHRpjZ3wPah7Fx/3d9tFsZ4K5JGW5MWr8Feki6JK3UluqvqIzrkTWPb57u4s1k@eUnd3Gdqs@7WJC2QZkOn15Y7jWP79NxVmqNROGztz@K5W@K9UI0lZ7ZqBbN@rR7FpyU9@LVXfS1aem2lWuMkfE7Mls9708F5PDOtQ8CsKpFYQGabrTTdG8tHdziP07m9m7/OLXk8kKpuw@xdTs7eH7lwVqZKFa1/HlihNJcX@8umamQbZ6Gv98ZcTxXSDuMwGq95oE48jwSNYP28DCalbi@pPnWPQlFJ1O1X@XI9aIlESbu1ZFF1L6uMDReV571kaP3JY6daGzWU3pPd5p0lH164ZrHtwaRWiSq7ybg60roeF4OWf5aj2bQj1I0gcmdDzbC@tyzmiPq82m3Z1vR5ZXj10KDDnjlpqvJSC9SFdNacbH9oyI8LsjVD72ANuolx2MoDc7uYWxP36Cq6EyrR4VBj0z67ONnE5s1l/fK8iTvjZJY0mW5F9sJ0A0VwOj9O7XOTcG3ljoi0HhuH1Sy7KOpKLCuHZme6ZBI3dOqEbWkUN6aD5mnKJeHOHamp6llSeqofRkH1lCnnZqUlu55pAjErz3WgKmftitLr7bbN/tA1R8mrPd@cLeXUXB6n3jTQ1eFhoFdPM/eJa4tTVV5RVd/UdsOLmSzZcjVerczWeBvGtR6rk85o/apckmfNqDnNsX4ukThcnPxz299dSmFJso9une1rbWVUelqerHYoqgNOFFnl6qk96kzMhSK3ojX3yGLR3JodsuKLHhl54XnhDk1XsUx@CYVYT3bUf5y0R41Gv7vb1og5Nr1Za2pZjadu1Jq3l@Pt0T/29DWdbuwaNQciy6aybinSblSLMt2tyHN3E89sxzWyZqkyP2n9i@kuSpSNrNXKV1fGwJe62sYXJcUbDk60GUS@VF0r3Fgqnjh4xlTujtqaZuyGjyOWRt7oLF7987SbnjbDIXm29@H8YLFZ3d9qa35Jd9ZrvSSJYGUcKudVTY97s0fDH9tjclY0unMqWVPXqofppd@ixrIF9J@S2VxtBV4jNKktzyrxYVUiaZSta@RpHUy0w6vzXJFXcjfyT5ftOktHdrNVs8fH0rkt9Z0jF3RmL46TuVOZTV8b0YqTSutgqZvxnLelkqypQ4s29@KZJCUteaL1uf3r3cPDSy5F1lWKrEzQ3x@farU/QHnYmxLdW7kM0ci5f3hxeXyfW4tfcus33YP1crIPmLi/@xecxtx7UQ6JsH2a3CflmO4DUMz7O3z3810Z1h@AnYKGZZ6K8h72i3vx8PL120uukvvUCkAl38Xyqq4haO@7wP7@B/mssG9C/K7ALBdKg4mAgsreDSaaafxy9/JmUfT6w/bhzSLPDRZAlOv1F8S@fPnth0k5oJEnfEDg80F3KMfwtpO7qWlcg/gbgyC6/8eV65KgCZykxRTbMbsmjZGaxqD73499s5iTCPMwzwMR3KbEgYsr@mjytg3jDHCkSOZ893EddgkfjXHkJHBGn0TOp3WMlpR5WHxc0FMmiIXp1XsXkxDK8dFiTJwM4wgtCROfFrHPY4G6aYI/vpeDlOIcjuu51@gLFlikDoXCIww0K2RjQI44pjTyeQqhDaFnA/rZRMWJQEqc2owEuEfCgkmbeB5gxt0rZiouYjKnOGX0HXeESRDkVNQFKZTnFd4xaAvEMHjD4a1IOETSJpFHMU7zuQPMC8FgaBGKdMyLyY75kQYZwqlAYyp8HBS8RxmaBhhpOdAAF8G64HH40UiBgjOHvJfxRpCYX9138J4naVxY1PLuTXyAHGk0ZrgQusqwg6ZHCnUk2KcF1/oJmIV5kRivqBsz0B4EzMGUOsWkED7T2GYJznPqEkFAh7KPRhPqgZxATnNKbPhRaAk5A8RPEQZNITEAOIbAC@TG8TVtCCIfzJJC1gHJLIx3xbgxNCAcBzwQFHHoWFYkTpfHMG9gGiHoDVzcr8CQl5NuEIY4@pTUwKERhrdQJIZZUtwMzBFQBtjeB7UoEHHCT2jN0xxP1GdhGZeLnQos1EmQQuACX1kPuhJyhxcr3iXQjwC84NAXnwVpGjhQk8SHsgJ4tyxy0ssZxfCH9F0G4Xg@GnyXtysGhQ1xhkh0rQR0Eqa35A24kj97GGb3wnpObRXSyQnqUlvc1NE@4AN5txkOoKFvWeRhKwAsZjGBLkqKTRKkocVRj9MkhyYHsJeyIOAgfPimICM95Dt6zUz3icNPBTOdnq@L0NdQ2xhawkFtLCADdixg0IsJ9Bl8GMD9CMAnt/2BGNHABTXAIgZBLsjAewIgANAWSx64BX6BPjnkTZJvFHUOz7wdNbiw6M9IjXEZvR/50dCMKIHOHbMcpxzSGJ9uX1hwmorhoyItBoo/IA1eMPVoUdTS/M78Bf@PVBGSgfnkQmKH4@tGaIcY9SkJhH8DCszfwaffiYldYMYcNPiGzr/doX0s3pIaYnu350VFwchgIc1dtxktdq/MYicHMN@e38G4XKDDQPwbShgEb0YYfb605FTk36pBlkOXUwoAAjXoYZoVa4BBQPGxWESYqPJ7CFrMcSlQF3/SGAOIdlWoWx3yCgp/Rfb643aXMoDJ4DyfUjI8geE1uUXDnB@7d4JMsOeLgLnvyf71y/o6LF73/XUW/Nt58eY0@M@D4P85A0Zl@8Npfzfyff3p67f/Ag)
[Here is the code for the encoder.](https://tio.run/##tVbbUtxGEH33V3StHiKCWTtlVyrB4WEv5uJiMWFxqFTih0HqXY0ZaTYzI7Cc8reTMzPaG2aBpCpUUYiZvpw@fbqlT@Ja7HzKr25vZTnTxtEnHHSl7n7/5tnqSe2kuvfsi5z580wJa2kkZEV/PyOa1ZdKZmSdcPhzrWVOJe7SsTOymv7xkYSZ2i1yhdE3lt5@znjmpI6@RC9e0FE1q91u@C/6kPQn7fMedU4N28zI4LZLo9rkbJLxjahorKtpEg@e07jUV0yiymlciBzJkjNRWV3SRBsSNGSRA3WV9GjfSIYZChgy58mYPwc3VzAMDC5zXDjOnLzmNjxdNuG@r/VV0qtQB5tMWvZB9oUTSromOTA@zJDbEm2CnK6gYySzQHCI2@SEp8LHpTMWmbdqE@xSj8asJnQK0o2QLgmAL1hOC5f0GxqKm@o7ECiMaug4nA60qstLTQNAtnSh1SQZ19KJS8Wh6H0jSnCYnBuNJqGqC@HY2KQ3BSIRTFo2j0Xe@FIukNh7nCrRXIrsKjlj6/zFKdDycxoZ26U2bTIuvD72a8vg1KMFsDFkwKQnNJIo9kPFwnq0gOfZG0ADVdJXNc/QXLeKYF@bqXaOK/JY5qwj8wjcXtbJW1fnge2@8rh6NBA2JDoqy7ry7M/ZONA@m/YwFU85OUfiA8NcFRpQ6V1dTRUnRzlXDm6ePCttMhD1qr4QHqkYPfsiTA5HH/F3XRs6ZKFcEaKONMgZmDqTQtGBKD0PI4EijAd2qCttFqgWAovhcS/oTGdXnjGTDMV0Gk@DjefuRN/4hBAFUMiy2@22cjqULrL5DkTMtEOP/qolz3W@L5TygxPiHgsgHAtVoykoIPRAl6XOtWFkoHNZhouh9NjHICQrPMkgBdXsi0g5DNou9agvTZgcH8oL2uNacDEUFcrwbIGGrEjeqxx4bAFiob42xpGDjHtKzaME4oZBoZhcUBLi9RvewS@NrxpUPC3o6Ndla6C4fu15nqggWz/waDroQ6Ob5FhfMy5ggtlzhVCYgCZ0YOBh0YihTETKYIeaqoY8UD94PpgAD9qUcwkGSzrwSy/BTvIVQhj5hJXyOwY6yWXuRe/pj7yNBBbRCLsIY2Mm2CNL@s4N5ijMRzxp6377eaZtjZ4couuhH1CUWLjZIko6PCSnfuPagpAP8fEUCBtg4cykEcBu59gvJPRyrrXfew2daAdvLy56j8Jx2BRcfjM3oSe1RHlYBby4PpZX7RSf@OWj5IQ7b@LWbqzjsqtr1w1jraq0E5f6n1Vne2WZb220b28uG8d4YwSXPp4t1v@Kf3fK8TjdeiTzjuJq6opdavMHr248fBDF/KX0tsp0zrsbs@xs@uk8WqRffBzC5x5WzxjRfLCcj@UXRr0/vXy1RsaKqaej4pt4synEx@g95Iny254yXc7wArV4jN7zm/Tn5y9/@aEFtbTqWnaBw3TJ3LdGE1lBeA@VBElD@YuyVnzzCCBdreyBhs4D4UMCYckinu/rQ/m2O5R2ttNNFO3tPeS8td3ZeryLd9rSx0768bUXaFSOSbe60eTeMuO3TXuz@NLx3Yn/PJmbaBYGbS3ao/gfiEbL4VmL2c5PuvWkCfoNq2nSxBp9ebbOMnxtAez/MVRHVSv3nOdK03PBz@/SpdxXrZaCX37qLtuJr7m2nTmvtrOleWUA4j1adneif3j9an2kF5Z3Rvr@CB83pbgzYWs1yVhzuprq38/Y5nzthN2PeG9vs@PTpmutFnyspuuD04a/b3CeWHBsaxyctWj/aXDaaCuDsxbzaYOzKfhAGwP6VDPfF@FLpk3gc6Wrr0h8Cwpl0/WaYuKvz77e3v4D)
```
s->{ // Method with String parameter and no return-type
var i=new java.util.zip.Inflater(0<1);
// Create the decoder
i.setInput(java.util.Base64.getDecoder().decode(
// Put the following encoded String in the decoder
"ZVTLjts6DP0VAlp00zsf0F0ek2SKeJo7TjHokrEZW4gs5UpyM75f30Pl0QJdGDBE6vDw8FC7KKmJ9pxt8F+oGmMr0dQX9lQH35nrwWeqh3ASYt9S3XMbLsm8sU9hoGOIxLQUbqlib2a0ilaQZj0OpTW1fJRruRckRARbBLI02f6UGzwdphKfh3AyM0/PHxIbm0RBVpzZ2TyZdVSYpTRSuCaDmrmnLYolMNggal6lY8WlN+FGs24FvtCManFH2oWYI9tsCuF3sV2fzXyiJV/8p0TPHN1E23K6CG4cDoEWoJzoPbijqUeb+eCkNL2KPFgotI9hxBnQOEtMZtaBEZeUm5pbbidt5R2F9cbO8XTg5mTeJGUN7MBWPlMV0xPdypq6B1VajUmgqbIFsTqjBIUjVRbNfvfCSdmCnqq3iOHizdyNco7W5z8ZrELsQs7iSbncVUflCtoeRvOcx7aoPXfKa0YLTqXQyzCMXtW/q7EOWi0oTSedmD0Kr6OI7wOo0tfRd07MSys+45qKl2wyCx7/9BfgUUows/85trioiD/CGGkj7HJfUKsAcRZxbCw7WvOgOlSMJqIS2wQf4oPVw2BXeMSZ3kJzUsWiWXLXXU9Ljmr3Gi5aEKYACzs8PT3d7LSx+armVwhxDhkz+m+0cvf5ip3DCK+4WwbDmt2IoaCBMoMwDKENUVCB9nYogaVV7jUEaXoVGaKgmxVfJUfCbUozmttYNkeh1NDK66HFkj3aULUgQ9Obb64Fn9RDWLjvhvGSYeOZc3eUItyyOBSbC0kK3nySf/BRfZrQcdfTy7+/RwPHzUfV+eiKbXXhMXTIh0FPZht+CgJIwe7lnh02YCoTWCgtqgTOBFKDPPTkJ1KiungKxtAhxOFuwZJJa8cpmRqbiQ5hjPYozukbA5+0tlXTq/xX3SrGQ1ThLcLaxCPekd/y7SP2qOzH9eTW9/PHOaQRM9lg6mUecBQ/rqX+aunyY3a4YlNPqAd8/BXBFnhwzjYyuKc793cLv+xD0HdvoteQcVvNRd/QOA6nXoa/9qbMZLRoD0+BPMJbe7pt8as+Ps4e5Rc="));
var b=new byte[1433]; // Create a byte-array to contain the decoded bytes
i.inflate(b); // Decode it
i.end(); // Let the decoder know we're done
for(var t:new String(b) // Convert the byte-array with decoded bytes to a decoded String
.split("#")) // And loop over the titles
if(t.matches( // If a title matches
s.replace("*",".")))// the input with all "*" replaced with a regex-wildcard "."
System.out.print(t);} // Print this title
```
] |
[Question]
[
# Background
Yes, bitstring physics is [a real thing](http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=363694&punumber%3D2948%26filter%3DAND%28p_IS_Number%3A8339%29%26pageNumber%3D2).
The idea is to construct a new theory of physics using only strings of bits that evolve under a probabilistic rule... or something.
Despite reading a couple of papers about it, I'm still pretty confused.
However, the bitstring universe makes for a nice little code golf.
# Program Universe
Bitstring physics takes place in a so-called *program universe*.
At each step of the evolution of the universe, there is a finite list `L` of bitstrings of some length `k`, starting with the two-element list `[10,11]` where `k = 2`.
One timestep is processed as follows (in Python-like pseudocode).
```
A := random element of L
B := random element of L
if A == B:
for each C in L:
append a random bit to C
else:
append the bitwise XOR of A and B to L
```
All random choices are uniformly random and independent of each other.
# Example
An example evolution of 4 steps might look like the following.
Start with the initial list `L`:
```
10
11
```
We randomly choose `A := 10` and `B := 10`, which are the same row, which means we need to extend each string in `L` with a random bit:
```
101
110
```
Next, we choose `A := 101` and `B := 110`, and since they are not equal, we add their XOR to `L`:
```
101
110
011
```
Then, we choose `A := 011` and `B := 110`, and again append their XOR:
```
101
110
011
101
```
Finally, we choose `A := 101` (last row) and `B := 101` (first row), which are equal, so we extend with random bits:
```
1010
1100
0111
1010
```
# The Task
Your task is to take a nonnegative integer `t` as input, simulate the program universe for `t` timesteps, and return or print the resulting list `L`.
Note that `t = 0` results in the initial list `[10,11]`.
You can output `L` as a list of lists of integers, list of lists of boolean values or a list of strings; if output goes to STDOUT, you may also print the bitstrings one per line in some reasonable format.
The order of the bitstrings is significant; in particular, the initial list cannot be `[11,10]`, `[01,11]` or anything like that.
Both functions and full programs are acceptable, standard loopholes are disallowed, and the lowest byte count wins.
[Answer]
# CJam, ~~42~~ ~~40~~ ~~38~~ 37 bytes
*1 byte saved by Sp3000.*
```
B2b2/q~{:L_]:mR_~#L@~.^a+L{2mr+}%?}*p
```
## Explanation
Create the initial state as a base-2 number:
```
B2b e# Push the the binary representation of 11: [1 0 1 1]
2/ e# Split into chunks of 2 to get [[1 0] [1 1]]
```
And then perform the main loop and pretty-print the result at the end:
```
q~ e# Read and eval input t.
{ e# Run this block t times.
:L e# Store the current universe in L.
_] e# Copy it and wrap both copies in an array.
:mR e# Pick a random element from each copy.
_~ e# Duplicate those two elements, and unwrap them.
# e# Find the second element in the first. If they are equal, it will be found at
e# index 0, being falsy. If they are unequal, it will not be found, giving
e# -1, which is truthy.
e# We'll now compute both possible universes for the next step and then select
e# the right one based on this index. First, we'll build the one where they were
e# not equal.
L@~ e# Push L, pull up the other copy of the selected elements and unwrap it.
.^ e# Take the bitwise XOR.
a+ e# Append this element to L.
L e# Push L again.
{ e# Map this block onto the elements in L.
2mr+ e# Append 0 or 1 at random.
}%
? e# Select the correct follow-up universe.
}*
p e# Pretty-print the final universe.
```
[Test it here.](http://cjam.aditsu.net/#code=YZ%5DYfbq~%7B%3AL_%5D%3AmR_~%23L%40~.%5Ea%2BL%7B2mr%2B%7D%25%3F%7D*p&input=4)
[Answer]
# Pyth, ~~27~~ 26 bytes
```
u?+RO2GqFKmOG2aGxVFKQ*]1U2
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=u%3F%2BRO2GqFKmOG2aGxVFKQ*%5D1U2&input=0&debug=0)
### Explanation:
```
implicit: Q = input number
*]1U2 the initial list [[1,0], [1,1]]
u Q reduce, apply the following expression Q times to G = ^
mOG2 take two random elements of G
K store in K
qF check if they are equal
? if they are equal:
+RO2G append randomly a 0 or 1 to each element of G
else:
aG append to G
xVFK the xor of the elements in K
```
[Answer]
# Julia, ~~141~~ 129 bytes
```
t->(L=Any[[1,0],[1,1]];for i=1:t r=1:length(L);A=L[rand(r)];B=L[rand(r)];A==B?for j=r L[j]=[L[j],rand(0:1)]end:push!(L,A$B)end;L)
```
Nothing clever. Creates an unnamed function that accepts an integer as input and returns an array of arrays. To call it, give it a name, e.g. `f=t->...`.
Ungolfed + explanation:
```
function f(t)
# Start with L0
L = Any[[1,0], [1,1]]
# Repeat for t steps
for i = 1:t
# Store the range of the indices of L
r = 1:length(L)
# Select 2 random elements
A = L[rand(r)]
B = L[rand(r)]
if A == B
# Append a random bit to each element of L
for j = r
L[j] = [L[j], rand(0:1)]
end
else
# Append the XOR of A and B to L
push!(L, A $ B)
end
end
# Return the updated list
L
end
```
Examples:
```
julia> f(4)
4-element Array{Any,1}:
[1,0,1,0]
[1,1,1,1]
[0,1,1,0]
[0,1,0,0]
julia> f(3)
3-element Array{Any,1}:
[1,0,1,1]
[1,1,1,0]
[0,1,0,1]
```
Saved 12 bytes thanks to M L!
[Answer]
# Python 2, 141
I tried a few different methods, but the best I could get was relatively straightforward. Thanks to @Sp3000 for 15 chars or so (and for teaching me about the existence of `int.__xor__`).
```
from random import*
L=[[1,0],[1,1]];C=choice
exec"A=C(L);B=C(L);L=[L+[map(int.__xor__,A,B)],[x+[C([1,0])]for x in L]][A==B];"*input()
print L
```
[Answer]
# Pyth, 34
```
u?+RO`TGqJOGKOG+Gsm`s!dqVJKQ[`T`11
```
Uses reduce to apply each iteration. I'll explain when I'm done golfing.
[Try it here](https://pyth.herokuapp.com/?code=u%3F%2BRO%60TGqJOGKOG%2BGsm%60s!dqVJKQ%5B%60T%6011&input=4&debug=0)
[Answer]
# K, 46 53 46 bytes
```
{x{:[~/t:2?x;{x,*1?2}'x;x,,,/~=/t]}/(1 0;1 1)}
```
A good chunk of the size (about 7 bytes) of this is do to the fact that K has no `xor` operator, so I had to implement one myself. Originally, I used a list of strings, followed by realizing that was insanely stupid. So now I cut off the 7 bytes again!
Before:
```
{x{:[~/t:2?x;{x,*$1?2}'x;x,,,/$~=/(0$')'t]}/$:'10 11}
```
@JohnE pointed out in the comments that the initial state was supposed to be hardcoded, which cost 7 extra bytes. :/
[Answer]
# JavaScript (*ES6*) 152
A function, using strings (with numbers it should be shorter, but in javascript bit operations are limited to 32 bit integers).
Test in Firefox using the snippet below.
```
F=(t,L=['10','11'],l=2,R=n=>Math.random()*n|0,a=L[R(l)],b=L[R(l)])=>
t--?a==b
?F(t,L.map(x=>x+R(2)),l)
:F(t,L,L.push([...a].map((x,p)=>x^b[p]).join('')))
:L
test=_=>O.innerHTML=F(+I.value).join('\n')
```
```
#I{width:3em}
```
```
<input id=I value=10><button onclick=test()>-></button><pre id=O></pre>
```
[Answer]
# K, ~~45~~ ~~41~~ 38 bytes
```
{x{(x,,~=/t;{x,1?2}'x)@~/t:2?x}/1,'!2}
```
The structure of my answer is quite similar to that of @kirbyfan64sos, but instead of strings I used 1/0 vectors and I avoid the need for a conditional (`:[ ; ; ]`) by instead indexing into a list.
A few runs:
```
{x{(x,,~=/t;{x,1?2}'x)@~/t:2?x}/1,'!2}3
(1 0 0 0
1 1 1 1
0 1 1 1)
{x{(x,,~=/t;{x,1?2}'x)@~/t:2?x}/1,'!2}3
(1 0 0
1 1 0
0 1 0
1 0 0)
{x{(x,,~=/t;{x,1?2}'x)@~/t:2?x}/1,'!2}3
(1 0 0
1 1 0
0 1 0
1 1 0)
```
## Edit:
Saved four bytes with a more compact way to build the initial universe:
```
1,'!2 / new
(1 0;1 1) / old
```
## Edit2:
I forgot that "choose" can take a list as its right argument:
```
2?"abcd"
"dc"
2?"abcd"
"cc"
2?"abcd"
"ca"
```
So I can simplify part of this. Credit where it's due, Kirby got this trick before I did.
```
2?x / new
x@2?#x / old
```
[Answer]
# Javascript, ~~241~~ 233 bytes
That's kind of long.
```
a=[[1,0],[1,1]];for(b=prompt();b--;)if(c=a.length,d=a[c*Math.random()|0],e=a[c*Math.random()|0],d+""==e+"")for(f=0;f<c;f++)a[f].push(2*Math.random()|0);else{g=[];for(h=0;h<d.length;h++)g.push(d[h]^e[h]);a.push(g)}alert(a.join("\n"));
```
[Answer]
# T-SQL (2012+), 1019
I'm really sorry this is nowhere near competitive, but to be honest I didn't think I could get this to work and had to post it once I did. I did try to golf it a bit :)
To handle the binary/integer conversions I had to create a couple of scalar functions (513 of the bytes). `A` goes from integer to a bit string. `B` does the reverse.
```
CREATE FUNCTION A(@ BIGINT)RETURNS VARCHAR(MAX)AS
BEGIN
DECLARE @S VARCHAR(MAX);
WITH R AS(SELECT @/2D,CAST(@%2 AS VARCHAR(MAX))M
UNION ALL
SELECT D/2,CAST(D%2 AS VARCHAR(MAX))+M
FROM R
WHERE D>0)SELECT @S=M FROM R WHERE D=0
RETURN @S
END
CREATE FUNCTION B(@ VARCHAR(MAX))RETURNS BIGINT AS
BEGIN
DECLARE @I BIGINT;
WITH R AS(SELECT CAST(RIGHT(@,1)AS BIGINT)I,1N,LEFT(@,LEN(@)-1)S
UNION ALL
SELECT CAST(RIGHT(S,1)AS BIGINT)*POWER(2,N),N+1,LEFT(S,LEN(S)-1)
FROM R
WHERE S<>''
)SELECT @I=SUM(I)FROM R
RETURN @I
END
```
Then there is the procedure. `@C` is the number of steps
```
DECLARE @C INT=9
DECLARE @ TABLE(S VARCHAR(MAX))
DECLARE @R VARCHAR(MAX)
INSERT @ VALUES('10'),('11')
WHILE(@C>=0)
BEGIN
SET @C-=1
SELECT @R=CASE WHEN MAX(S)=MIN(S)THEN''ELSE RIGHT(REPLICATE('0',99)+dbo.A(dbo.B(MAX(S))^dbo.B(MIN(S))),LEN(MAX(S)))END
FROM(SELECT TOP 2S,ROW_NUMBER()OVER(ORDER BY(SELECT\))N FROM @,(VALUES(1),(1),(1))D(D)ORDER BY RAND(CAST(NEWID()AS VARBINARY(50))))A
IF @R=''UPDATE @ SET S=CONCAT(S,ROUND(RAND(CAST(NEWID() AS VARBINARY(50))),0))
ELSE INSERT @ VALUES(@R)
END
SELECT * FROM @
```
Ten thousand iterations took around 2 minutes and returned 9991 rows
```
1001001100110
1101001001110
0111100100101
1111100001011
1111001010011
0110101001101
...
1110101000100
1111011101100
1100001100010
0110010001001
1110100010100
```
[Answer]
# Pyth - 37 bytes
Obvious, just follows psuedocode. Probably can golf a lot.
```
KPP^,1Z2VQ=K?m+dO1KqFJ,OKOKaKxVhJeJ;K
```
[Try it here online](http://pyth.herokuapp.com/?code=KPP%5E%2C1Z2VQ%3DK%3Fm%2BdO1KqFJ%2COKOKaKxVhJeJ%3BK&input=4&debug=1).
[Answer]
# Mathematica, 106 bytes
```
Nest[If[Equal@@#,Map[#~Append~RandomInteger[]&],Append[BitXor@@#]]&[#~RandomChoice~2]@#&,{{1,0},{1,1}},#]&
```
[Answer]
# Perl, 102
```
#!perl -p
@l=qw(10 11);$_=$l[rand@l]^$l[rand@l],$_|=y//0/cr,@l=/1/?(@l,$_):map{$_.~~rand 2}@l for 1..$_;$_="@l"
```
Try [me](http://ideone.com/KAQAyx).
[Answer]
## R, 186
```
L=list(0:1,c(1,1))
if(t>0)for(t in 1:t){A=sample(L,1)[[1]]
B=sample(L,1)[[1]]
if(all(A==B)){L=lapply(L,append,sample(0:1, 1))}else{L=c(L,list(as.numeric(xor(A,B))))}}
L
```
Nothing magical here. Enter the value for `t` in the R console and run the script. It's hard to "golf" R code but here's a more readable version:
```
L <- list(0:1, c(1, 1))
if(t > 0) {
for(t in 1:t) {
A <- sample(L, 1)[[1]]
B <- sample(L, 1)[[1]]
if (all(A == B)) {
L <- lapply(L, append, sample(0:1, 1))
} else {
L <- c(L,list(as.numeric(xor(A, B))))
}
}
}
L
```
[Answer]
# Ruby, 82
Pretty much straight-forward. Compared with other non-golfing languages, ruby seems to do well with its large standard library.
```
->t{l=[2,3]
t.times{a,b=l.sample 2
a.equal?(b)?l.map!{|x|x*2+rand(2)}:l<<(a^b)}
l}
```
Sample output for t=101010 :
```
[9, 15, 6, 13, 5, 12, 10, 11, 5, 4, 15, 13, 2, 7, 11, 9, 3, 3, 8, 6, 3, 13, 13, 12, 10, 9, 2, 4, 14, 9, 9, 14, 15, 7, 10, 4, 10, 14, 13, 7, 15, 7]
```
] |
[Question]
[
## CLOSED to competing entries
New bots are welcome but are not part of the main competition and probably won't be officially tested.
You stand on a dusty stretch of code, watching the other programs stare at you. Will they shoot? How much ammunition do they have left? All you know is that you want to be the last one standing.
## Before the Game
You will be given 10 points to distribute between HP, Dexterity, Armor, and Speed. You may distribute up to 10 points between these categories (integer amounts only). You may put 0 points into a category.
* Your HP will equal 10 plus the number of points you put in HP.
* Your Dexterity (chance of dodging a hit) is equal to 0.04 times the number of points you put in Dexterity. For example, if you put 8 points in Dex, you would have a .32 chance of dodging a hit.
* Your Armor (chance of taking 1 less damage from a hit) is equal to .1 times the number of points you put into Armor.
* Your Speed is simply equal to the number of points you put in Speed.
* You always start with 2 ammo.
## Gameplay
This game is turn-based. Agents will be ordered based on their speed, with ties being broken at random before the game begins. Each agent will take their turn, choosing one of the three move options and executing it, then the next player will go. Unlike many KoTHs similar to this one, moves are NOT all executed at the same time.
On each agent's turn, there are three possible moves:
* Heal: If not at maximum HP, gain 1 HP.
* Reload: Gain 2 ammo.
* Shoot: Choose another agent. That agent rolls for dexterity (creates a random real, and wins the roll if their dexterity is higher). If they win the roll they dodge and take 0 damage. Otherwise, they roll for armor. If they win, they take a random amount of damage from 0 to 3, while if they lose, they take a random amount of damage from 1 to 4. All damage is integers.
Once an agent's HP is less than 0, it is out and can no longer take actions. Last agent surviving wins the round.
## Scoring
Each round, if there were X agents, your agent receives X points for each agent below it, plus an extra 2 points if they win. Therefore, in a 10 player game, the top agent would get 11 points, the second would get 8, and so on. As long as all the agents run fast, I should be able to run thousands (maybe hundreds of thousands) of tests, so the scores should be well-distributed. All scores are divided by the number of rounds played for ease of use.
## I/O
All players will create a class which extends PlayerClass. As an example, you can look at any of the four (non-competing) bots created in the github. Each bot will have a class constructor which initializes the stats picked earlier and a `makeMove()` function, which determines what action to take and who is the target.
For input, you have access to the following functions:
1. getHP() (gets current HP)
2. getAmmo() (gets ammo amount)
3. getMaxHP() (gets your max HP)
4. getDex() (gets dexterity)
5. getArmor() (gets armor)
6. getSpeed() (gets speed, you MAY call this on other players)
7. getPlayers() (gets list of all players)
8. getShotAt() (gets the PlayerClass object who you shot at most recently)
9. getShotBy() (gets the PlayerClass object who shot at you most recently)
10. getAliveEnemies() (gets a list of all players who have 1 or more HP and are not you)
11. deadQ() (gets whether a player is dead, you MAY call this on other players)
12. compareTo(PlayerClass p) (gets p's speed minus your speed)
13. getWhoShotYou()(gets all bots who shot you (in a random order) since the last time you called the move() action)
The lists of players (getPlayers and getAliveEnemies) should be in turn order, so that allows you to check who will shoot next and/or solve ties in speed.
## Rules for Bounty
If, at the end of the challenge (May 6, 20:00 GMT), the current winning bot is in the lead by at least 1 point AND in no way targets specific bots/acts differently based on the bots it faces, that bot will be given the bounty.
Otherwise, if a bot posted after the bounty satisfied this condition at one point, the most recent bot to do so will receive the bounty.
If no bot ever managed to meet the required conditions, the bounty will be awarded to the winner of the KoTH.
You may NOT delete bots you submitted previously to make your bot perform better. If you will delete a bot, I recommend deleting one of your worst ones.
As an example, Destroyer would currently meet the no-targeting requirement (since it simply shoots the first bot in the turn order), but only is leading by around .6 points, so doesn't meet the point requirement.
## Rules
Submissions in Java only. As long as the submission is simple enough, I might be able to translate from pseudocode/some other language to Java though.
You may only enter 5 bots at any one time, and your bots may not collaborate. Feel free to submit more than 5, but when you submit a new one, set another one as noncompeting.
You MAY design your bots to target specific bots and/or predict what they will do, as long as it doesn't massively help your other bots.
No calling any methods of other entities, except for the ones called out above. The biggest problem here is `takeDamage()`, which has to be public so it can be called when someone is shot.
No redefining any functions/variables of PlayerClass besides `makeMove()`.
The subclass constructor must be of the form `super(x,y,z,a);` and cannot overwrite the requirements in the PlayerClass constructor (for example, allowing yourself to spend more than 10 points).
Feel free to define other methods of your class and/or create variables for memory purposes. Between each game, your bot will be reset, so it will only affect each individual game.
Don't make your code take forever. This KOTH is pretty lightweight, so there shouldn't be a need for complex algorithms.
---
## Leaderboard (FINAL STANDINGS)
```
ChargeBot->0.10870789129210871
SmartBot->1.151028848971151
Tank->3.4236785763214237
RageBot3->3.693295306704693
OneVsOneMeBro->3.7322532677467324
FriendlyAndHealthyBot->5.668694331305669
HpKing->7.525759474240526
FriendlyNotFriendlyBot->7.694217305782694
WinnerBot->8.004405995594004
NormalBot->8.276454723545276
Destroyer->8.732566267433732
StrategicBot->8.91998708001292
Dexter->9.556512443487556
WhatABot->10.622109377890622
FocusFireBot->10.945748054251945
```
---
FocusFireBot takes the victory!
---
The controller and all current agents can be found here:
<https://github.com/romanpwolfram/GunfightKoTH/tree/main>
Challenge name by tjjfvi.
[Answer]
# #1 - FriendlyNotFriendlyBot
```
package standoffKOTH;
import java.util.Random;
public class FriendlyNotFriendlyBot extends PlayerClass
{
Random rand = new Random();
public FriendlyNotFriendlyBot()
{
super(10, 0, 0, 0);
}
@Override
protected int makeMove()
{
if (this.getAmmo() < 1)
return this.move('r', this);
else if (this.getShotBy() != null && !this.getShotBy().deadQ())
return this.move('s', this.getShotBy());
else if (this.getAmmo() < 10)
return this.move('r', this);
else if (this.getHP() < 20)
return this.move('h', this);
else
return this.move('s', this.getAliveEnemies().get(rand.nextInt(this.getAliveEnemies().size())));
}
}
```
This bot tests these conditions, in order:
* If it has no ammo, it refills.
* If it is getting attacked, and the opponent is still alive, it will retaliate.
* If it has less than 10 ammo, it refills.
* If it has less than 20 health, it heals.
* Else, it shoots at random.
**There is a flaw**: if it got attacked twice or more in the same turn, but the last attacker is dead, it will not retaliate because only the last attacker can be viewed.
*Trivia*: There is an interesting [Prisoner's dilemma](https://en.wikipedia.org/wiki/Prisoner%27s_dilemma) with the Speed of the bots. The thing is the most effective strategy is to have the speed to 0, but if someone increases his speed to 1, he will be faster and therefore win. But in this case, others will increase their speed to 2, and progressively to the maximum 10. At this point however, a player can set his speed back to 0 and win easily.
# #2 - FriendlyAndHealthyBot
```
package standoffKOTH;
import java.util.Random;
public class FriendlyAndHealthyBot extends PlayerClass
{
Random rand = new Random();
public FriendlyNotFriendlyBot()
{
super(10, 0, 0, 0);
}
@Override
protected int makeMove()
{
if (this.getAmmo() < 1)
return this.move('r', this);
else if (this.getShotBy() != null && !this.getShotBy().deadQ())
return this.move('s', this.getShotBy());
else if (this.getHP() < 20)
return this.move('h', this);
else
return this.move('s', this.getAliveEnemies().get(rand.nextInt(this.getAliveEnemies().size())));
}
}
```
A slight variation of FNFB.
This bot tests these conditions, in order:
* If it has no ammo, it refills.
* If it is getting attacked, and the opponent is still alive, it will retaliate.
* If it has less than 20 health, it heals.
* Else, it shoots at random.
[Answer]
## Destroyer
```
class Destroyer(PlayerClass):
def __init__(self):
super().__init__(10, 0, 0, 0)
def makeMove(self):
if self.health == 1:
return "h"
if self.ammo < 3:
return "r"
return "s", getAliveEnemies.get(0) # destroy first enemy
```
---
Java version:
```
package standoffKOTH;
public class Destroyer extends PlayerClass {
public Destroyer()
{
super(10,0,0,0);
}
protected int makeMove()
{
if(getHP()<2)
{
return move('h',this);
}
else if(getAmmo()<3)
{
return move('r',this);
}
else
{
return move('s',getAliveEnemies().get(0));}}}
```
```
[Answer]
# Example Bots
These bots will not compete, but will likely be included in the test rounds for the first few bots and have a few useful examples.
## Bot 0: ExampleBot
Literally just heals, no stats.
```
package standoffKOTH;
public class ExamplePlayerClass extends PlayerClass {
public ExamplePlayerClass()
{
super(0,0,0,0);//put stats here
}
protected int makeMove()
{
return this.move('h',this);//It doesn't matter who is target with non-shoot actions, so just self here
}
}
```
## Bot 1: RevengeBot
Shoots whoever shot it last. Is happy to just reload until it is shot. If whoever shot it is now dead, it goes into a rage and picks someone at random to shoot.
```
package standoffKOTH;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Player1Class extends PlayerClass {
public Player1Class()
{
super(0,8,1,1);
}
protected int makeMove()
{
List<PlayerClass> g = new ArrayList<PlayerClass>();g= this.getAliveEnemies();
if((int)getHP()<6)
{return this.move('h', this);}
else {
if (getAmmo()<1)
{return this.move('r',this);}
else {
if(getShotBy()!=null&& g.contains(getShotBy())) {
if(getAmmo()>0){
return this.move('s',(PlayerClass) getShotBy());}
else{
return this.move('r',this);}}
else{
if(getShotBy()!=null&&(getShotBy()).deadQ()&&getAliveEnemies().size()!=0)
{Collections.shuffle(g);return this.move('s',g.get(0));}
else {return this.move('r', this);}}
}}}
}
```
## Bot 2: RandomBot
Will pretty much shoot anyone who's still alive, other than itself, of course. It may be random, but it's no EmoWolf.
```
package standoffKOTH;
import java.util.List;
import java.util.Random;
public class Player2Class extends PlayerClass {
Random rand = new Random();
public Player2Class()
{
super(9,0,0,1);
}
protected int makeMove()
{
List<PlayerClass> z = getAliveEnemies();
if(getAmmo()>0) {return this.move('s',z.get(rand.nextInt(z.size())));}{return this.move('r',this);}
}
}
```
## Bot 3: DedicatedBot
Just like RevengeBot, DedicatedBot won't shoot until shot. However, DedicatedBot will shoot a specific bot until they die, then switch to another random bot. DedicatedBot also won't heal (unless they are already dead, in which case it doesn't matter). It's just that dedicated.
```
package standoffKOTH;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Player3Class extends PlayerClass {
PlayerClass firstShot = null;
public Player3Class()
{
super(5,0,5,0);
}
protected int makeMove()
{
List<PlayerClass> g = new ArrayList<PlayerClass>();g= this.getAliveEnemies();
if(getShotBy()!=null&&firstShot==null) {firstShot = (PlayerClass) getShotBy();}
if(getHP()<1)
{return this.move('h', this);}
else {
if (getAmmo()<2)
{return this.move('r',this);}
else {
if(firstShot!=null&& g.contains(firstShot)) {
if(getAmmo()>0){
return this.move('s',firstShot);}
else{
return this.move('r',this);}}
else{
if(getShotBy()!=null&&((PlayerClass)getShotBy()).deadQ()&&this.getAliveEnemies().size()!=0)
{Collections.shuffle(g);return this.move('s',g.get(0));}
else {return this.move('r', this);}}
}}}
}
```
## Bot 4: PsychopathBot
The sibling of DedicatedBot, PsychopathBot brings its philosophy to the extreme. It picks a bot at the beginning of the game and attempts to kill them. Once they are dead, it checks if it got shot by anyone (which it should have been). If it did, it picks them as its new target and does its best to take them out. Otherwise, it just chooses at random again and starts shooting.
```
package standoffKOTH;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Player4Class extends PlayerClass {
Random random = new Random();
PlayerClass firstShot = null;
public Player4Class()
{
super(10,0,0,0);
}
protected int makeMove()
{
List<PlayerClass> g = new ArrayList<PlayerClass>();g= this.getAliveEnemies();
if (this.getAliveEnemies().contains(firstShot)) {;} else if(getShotBy()!=null) {firstShot = getShotBy();} else {firstShot = this.getAliveEnemies().get(random.nextInt(this.getAliveEnemies().size()));}
if(getHP()<1)
{return this.move('h', this);}
else {
if ((int)getAmmo()<2)
{return this.move('r',this);}
else {
if(firstShot!=null&& g.contains(firstShot)) {
if((int)getAmmo()>0){
return this.move('s',firstShot);}
else{
return this.move('r',this);}}
else{
if(getShotBy()!=null&&getShotBy().deadQ()&&this.getAliveEnemies().size()!=0)
{Collections.shuffle(g);return this.move('s',g.get(0));}
else {return this.move('r', this);}}
}}}
}
```
Generally, RevengeBot, DedicatedBot, and PsychopathBot split on subscore relatively closely, while RandomBot takes last. However, RevengeBot wins 50% of the games, while DedicatedBot wins around 10% (and RandomBot only wins 5%). This means that RevengeBot scores around 18000 points in a 5000 round match, while PsychopathBot scores 17000, DedicatedBot 16000, and RandomBot 3500.
[Answer]
# Tank
```
package standoffKOTH;
import java.util.concurrent.ThreadLocalRandom;
public class Tank extends PlayerClass {
public Tank() {
super(3, 1, 5, 1);
}
@Override
protected int makeMove() {
if (getHP() < 6 && ThreadLocalRandom.current().nextBoolean()) {
return move('h', this);
} else if (getAmmo() == 0) {
return move('r', this);
} else {
PlayerClass lastShot = getShotBy();
if (lastShot == null) {
return move('r', this);
} else {
return move('s', lastShot);
}
}
}
}
```
Simple bot with high armor and health. If its health is below 6, it has a 50% chance of healing itself. If it has an empty holster, it reloads. Otherwise, if nobody fired it it, it also reloads the holster. If someone fired at the bot, it fires back.
[Answer]
## HpKing
```
package standoffKOTH;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
public class HpKing extends PlayerClass{
// Keep a map of the amount of times an enemy (last) shot at us
TreeMap<String, Integer> shotBy = new TreeMap<>();
int previousHp;
public HpKing(){
super(10,0,0,0); // Health ftw!
previousHp = getHP();
}
protected int makeMove() {
// Update the shotBy-map with the latest enemy that shot at us
if(getShotBy() != null && previousHp!=getHP()){
shotBy.merge(getShotBy().getClass().toString(), 1, Integer::sum);
previousHp = getHP();
}
// Remove any enemies from the shotBy-map that are already dead:
shotBy.keySet().removeIf(enemyStr -> getAliveEnemies().stream().noneMatch(instance -> instance.getClass().toString().equals(enemyStr)));
// If there are more than two enemies left: heal if we're not full, otherwise reload to get more ammo
if(getAliveEnemies().size()>2){
}
// If we're not full health:
if (getHP() < getMaxHP()){
// If there are more than two enemies are left: heal!!
if (getAliveEnemies().size() > 2)
return move('h', this);
// If there is more than one enemy left: only heal if we've below 10 HP:
if (getAliveEnemies().size() > 1 && getHP() < 10)
return move('h', this);
// If there is just a single enemy left: just keep shooting and reloading, and hope for the best
}
// If we didn't have to heal, but are out of ammo: reload
if(getAmmo()<1)
return move('r', this);
// If we didn't had to heal and still have ammo left: shoot the enemy that most frequently shot at us
// (with priority to the more recent one, if multiple enemies shot at us an equal amount of times before):
// If no one shot at us yet: shoot at a random enemy:
return move('s',
shotBy.isEmpty() ? getAliveEnemies().get((int)(Math.random()*getAliveEnemies().size()))
: getAliveEnemies().stream()
.filter(enemy -> enemy.getClass().toString().equals(
Collections.max(shotBy.descendingMap().entrySet(), Map.Entry.comparingByValue()).getKey()))
.findFirst().get());
}
}
```
This bot maxes out on HP for its 10 bonus values.
At the start, this bot's entire focus is to stay alive and keep its health at its maximum.
From the moment just two enemies are left alive: it's a bit more lenient with its health and starts focusing more on shooting (but still tries to keep its HP above 10 at all time).
From the moment just a single enemy is left: it just keeps reloading/firing and hopes for the best.
[Answer]
# WinnerBot
```
class WinnerBot:
def __init__(self):
super.__init__(5, 4, 1, 0)
def makeMove(self):
if self.health < 4:
return "h"
if self.ammo < 1:
return "r"
return "s", getShotBy()
```
[Answer]
# FocusFireBot
```
package standoffKOTH;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class FocusFireBot extends PlayerClass {
private PlayerClass focusTarget;
private Map<PlayerClass, Integer> targetedBy = new HashMap<PlayerClass, Integer>();
private List<PlayerClass> targetedLastRound = new ArrayList<PlayerClass>();
protected int move = 0;
private int movesPerRound = 250;
public FocusFireBot() {
super(0, 0, 10, 0);
}
protected int makeMove() {
move++;
if (deadQ()) {
return 0;
}
// fully heal
if (getHP() < getMaxHP()) {
return this.move('h', this);
}
if (focusTarget != null && focusTarget.deadQ()) {
focusTarget = null;
}
// if we have a target we kill or we die
if (focusTarget != null) {
if (getAmmo() < 1) {
return this.move('r', this);
} else {
return this.move('s', focusTarget);
}
}
List<PlayerClass> aliveEnemies = getAliveEnemies();
// if only one enemy is left target it
if (aliveEnemies.size() < 2) {
focusTarget = aliveEnemies.get(0);
} else {
// if someone shot us twice in a row, we set him as target
// if (getShotBy() != null && !getShotBy().deadQ()) {
// focusTarget = getShotBy();
// }
List<PlayerClass> targetedThisRound = getWhoShotYou();
for (PlayerClass player : targetedThisRound) {
if (!player.deadQ()) {
if (targetedLastRound.contains(player)) {
focusTarget = player;
}
targetedBy.merge(player, 1, Integer::sum);
} else {
targetedLastRound.remove(player);
}
}
}
// shoot if we where shot twice in a row
if (focusTarget != null) {
if (getAmmo() < 1) {
return this.move('r', this);
} else {
return this.move('s', focusTarget);
}
}
// fully heal
if (getHP() < getMaxHP()) {
return this.move('h', this);
}
// get enought ammo to sustain focused fire
if (getAmmo() < 50 && getAmmo() + move < movesPerRound) {
return this.move('r', this);
}
// focus on player who shot us the most
List<Entry<PlayerClass, Integer>> shotByList = new ArrayList<>(targetedBy.entrySet());
shotByList.sort(Entry.comparingByValue());
Collections.reverse(shotByList);
for (Entry<PlayerClass, Integer> playerE : shotByList) {
PlayerClass player = playerE.getKey();
if (player.deadQ()) {
targetedBy.remove(player);
} else {
focusTarget = player;
return this.move('s', focusTarget);
}
}
//
focusTarget = aliveEnemies.get(0);
return this.move('s', focusTarget);
}
}
```
If you get his attention there are only two possible outcomes: **You or he dies!**
### Update 1
* added move counter and made reload condition so that it does not reload if it has enough ammo for shooting until end --> reduces ties but overall little impact and requires knowlege of turns per round
* went full armor and health is now most important (even more than shooting) --> more score but also more ties üòÇ
### Last Udate
* now picking of fastest bot than slowest
[Answer]
# NormalBot
```
class NormalBot(PlayerClass):
def __init__(self):
super().__init__(6, 1, 3, 0)
def makeMove(self):
if self.health < 5:
return "h"
if self.ammo < 4:
return "r"
if getShotBy() is None:
return "rh"[self.health > 5]
return "s", last_enemy_who_attacked_me()
```
---
Java version:
```
package standoffKOTH;
public class NormalBot extends PlayerClass {
public NormalBot()
{
super(6,1,3,0);
}
protected int makeMove()
{
if(getHP()<5)
{
return move('h',this);
}
else if (getAmmo()<4)
{
return move('r',this);
}
else if (getShotBy()!=null)
{
return move('s',getShotBy());
}
else if (getHP()<5)
{
return move('h',this);
}
else
{
return move('r',this);
}}}
```
[Answer]
## OneVsOneMeBro
```
package standoffKOTH;
public class OneVsOneMeBro extends PlayerClass{
public OneVsOneMeBro(){
super(9,0,0,1); // Sacrifice 1 HP for 1 Speed
}
protected int makeMove() {
// If there are more than one enemy left:
// heal if we're not max, otherwise reload to get more ammo
if (getAliveEnemies().size()!=1) {
if (getHP()<getMaxHP())
return move('h', this);
else
return move('r', this);
}
// If we're out of ammo: reload
if (getAmmo()<1)
return move('r', this);
// Just a single enemy left, and we have ammo: shoot, shoot, shoot!
return move('s', getAliveEnemies().get(0));
}
}
```
As long as there is more than one enemy left: just heal if we're not max, otherwise gain ammo.
And as soon as just a single enemy is left: keep shooting, unless we have to reload.
Also uses a speed of `1`, so it has a higher chance of going first in the final 1vs1 versus the bots with speed `0`.
[Answer]
# SmartBot
```
package standoffKOTH;
import java.util.ArrayList;
import java.util.List;
public class SmartBot extends PlayerClass {
private PlayerClass lastFired;
public SmartBot() {
super(0, 5, 3, 2);
}
protected int makeMove() {
if (getHP() < 5) {
return this.move('h', this);
}
if (getAmmo() < 2) {
return this.move('r', this);
}
List<PlayerClass> enemies = new ArrayList<PlayerClass>();
enemies = getAliveEnemies();
for (int i = 0; i < enemies.size(); i++) {
PlayerClass enemy = enemies.get(i);
if (!(enemy instanceof RageBot3) && enemy.equals(lastFired)) {
return this.move('s', enemy);
}
}
lastFired =getShotBy();
if (getHP() < 10) {
return this.move('h', this);
}
return this.move('s', enemies.get(0));
}
}
```
Or perhaps not too smart.
As I mentioned before, [I suck at Java](https://codegolf.stackexchange.com/questions/242430/quicksand-piles/242482#242482), so please correct any glaring errors you see. Also, if this bot fails to work during any test runs, please notify me of the error so I can correct my code. Hopefully I got it right.
This bot is quite conservative. If its HP is below 5, it will heal itself.
If its ammo is below 2, it will reload. (But only if its HP is 5 or more.)
Otherwise... it first tries to see if the same bot fired at it twice in a row. Or at least it tries to. Unless two different bots fire at it in a row, `lastFired` will be the same as before, so essentially if nobody has fired at SmartBot for a long time, SmartBot will just keep firing at the last person who shot at it.
If the above condition is true, it fires at that bot. Otherwise...
If its HP is below 10, it just heals itself (as a precautionary measure), otherwise it just shoots at the first bot in the list that is `getAliveEnemies()`.
And because RageBot3 seems to absolutely hate me, I have returned the favor.
So you see... pretty dumb after all.
[Answer]
# WhatABot
```
package standoffKOTH;
import java.util.ArrayList;
import java.util.List;
public class WhatABot extends PlayerClass {
List<Class> randomShooters = List.of(FriendlyAndHealthyBot.class, FriendlyNotFriendlyBot.class, HpKing.class, RageBot.class, RageBot2.class, Player2Class.class);
List<Class> wontShootFirst = List.of(Dexter.class, WhatABot.class, Tank.class, NormalBot.class);
List<PlayerClass> shot = new ArrayList<>();
int turn = -1;
public WhatABot() {
super(10, 0, 0, 0);
}
protected int makeMove() {
if (this.deadQ()) {
return 0;
}
shot.removeIf(PlayerClass::deadQ);
turn++;
// if there's only 1 enemy left, or I'm currently getting attacked, just spam shoot
PlayerClass immediateTarget = null;
if (this.getShotBy() != null && !this.getShotBy().deadQ()) {
immediateTarget = this.getShotBy();
// only retaliate if its not some bot randomly firing
if (!shot.contains(immediateTarget)) {
for (Class randomShooter : randomShooters) {
if (randomShooter.isInstance(immediateTarget)) {
immediateTarget = null;
break;
}
}
}
}
if (getAliveEnemies().size() == 1) {
immediateTarget = this.getAliveEnemies().get(0);
// if the bot won't shoot unless shot first, heal up and fill up ammo before engaging
if (!shot.contains(immediateTarget) && !this.getWhoShotYou().contains(immediateTarget)) {
for (Class bot : wontShootFirst) {
if (bot.isInstance(immediateTarget)) {
if (getHP() < getMaxHP()) {
return this.move('h', this);
} else if (getAmmo() < 40 && getAmmo() + turn < 250) {
return this.move('r', this);
}
}
}
}
}
if (immediateTarget != null) {
if (getAmmo() == 0) {
return this.move('r', this);
} else {
shot.add(immediateTarget);
return this.move('s', immediateTarget);
}
}
if (shot.size() > 0) {
if (getHP() < 10) {
return this.move('h', this);
}
if (getAmmo() == 0) {
return this.move('r', this);
}
return this.move('s', shot.get(shot.size() - 1));
}
if (getHP() < getMaxHP()) {
return this.move('h', this);
}
if (getAmmo() < 30 && getAmmo() + turn < 250) {
return this.move('r', this);
}
// kill fast players first
PlayerClass target = getAliveEnemies().get(0);
if (target.getSpeed() <= this.getSpeed() && getAmmo() < 50 && getAmmo() + turn < 250) {
return this.move('r', target);
}
shot.add(target);
return this.move('s', target);
}
}
```
Bot logic in comments.
[Answer]
# RageBot
```
class RageBot(PlayerClass):
def __init__(self):
super().__init__(10, 0, 0, 0)
def makeMove(self):
if self.health < 5:
return "s", last_one_who_attacked_me()
return "r"
```
---
Java version:
```
package standoffKOTH;
import java.util.Random;
public class RageBot extends PlayerClass {
Random rand = new Random();
public RageBot()
{
super(10,0,0,0);
}
protected int makeMove()
{
if(getHP()<5&&getShotAt()!=null)
{
return move('s',getShotAt());
}
else if (getHP()>4)
{
return move('r',this);
}
else
{
return move('s',getAliveEnemies().get(rand.nextInt(getAliveEnemies().size())));}}}
```
[Answer]
## RageBot3
```
class RageBot3(PlayerClass):
def __init__(self):
super().__init__(8, 1, 0, 1)
def makeMove(self):
target = getShotBy()
if target.deadQ():
for e in getAliveEnemies():
if isinstance(e, SmartBot) and not e.deadQ():
target = e
return "r"
return "s", getAliveEnemies().get(0)
if self.health < 3:
return "h"
elif self.health < 10:
return "s", target
if self.ammo < 6:
return "r"
else:
if self.health < 5:
return "h"
else:
return "s", target
```
---
Java version:
```
package standoffKOTH;
import java.util.Random;
public class RageBot3 extends PlayerClass {
Random rand = new Random();
PlayerClass target = null;
public RageBot3()
{
super(8,1,0,1);
}
protected int makeMove()
{
if(target==null||target.deadQ()) {
if(getShotBy()!=null)
{
target = getShotBy();
}
else if(target==null||target.deadQ()) {
for(PlayerClass p:getAliveEnemies())
{
if(p instanceof SmartBot)
{
target=p;
break;
}
}
}
if(target==null||target.deadQ()) {
target = getAliveEnemies().get(0);
}
}
if(getHP()<3)
{
return move('h',this);
}
else if (getHP()<10)
{
return move('s',target);
}
else if (getAmmo()<6)
{
return move('r',this);
}
else if (getHP()<5)
{
return move('h',this);
}
else
{
return move('s',target);
}
}
}
```
```
[Answer]
# StrategicBot
It has different strategies depending on the dynamics of the game.
`friendliness = remaining players / total number of players` with a deduction if it is being attacked two times in a row by someone.
It targets the last player who attacks it or the next player in the current round.
It tends to heal and reload when the friendliness is higher.
```
package standoffKOTH;
public class StrategicBot extends PlayerClass
{
int total;
PlayerClass foe;
public StrategicBot()
{
super(10, 0, 0, 0);
this.total = this.getPlayers().size();
}
@Override
protected int makeMove()
{
float friendliness;
// The bot gets more aggressive when there are fewer players
if (this.getAliveEnemies().size() == 1)
friendliness = 0;
else
friendliness = (float) this.getAliveEnemies().size() / total;
// When being repeatedly attacked by someone, act more aggressively
if (this.foe != null && this.foe == this.getShotBy())
friendliness -= 0.5;
if (this.foe.deadQ())
this.foe = null;
PlayerClass nextTarget;
if (this.getShotBy() != null && !this.getShotBy().deadQ())
nextTarget = this.getShotBy();
else
nextTarget = this.getAliveEnemies().get(0);
if (this.getAmmo() == 0)
return this.move('r', this);
if (friendliness > 0.7) {
if (this.getHP() < this.getMaxHP())
return this.move('h', this);
else if (this.getAmmo() < 15)
return this.move('r', this);
}
else if (friendliness > 0.35) {
if (this.getHP() < 12)
return this.move('h', this);
else if (this.getAmmo() < 8)
return this.move('r', this);
}
else if (friendliness > 0.15) {
if (this.getAmmo() < 2)
return this.move('r', this);
else if (this.getHP() == 3)
// heal so there won't be a instakill
// probably less valuable when HP < 3
return this.move('h', this);
}
// Does not do anything else when friendliness <= 0.15
return this.move('s', nextTarget);
}
}
```
```
[Answer]
# Dexter
```
package standoffKOTH;
public class Dexter extends PlayerClass {
public Dexter() {
super(0, 10, 0, 0);
}
protected int makeMove() {
if (getHP() < getMaxHP()) { // heal if we're not at full health
return move('h', this);
}
if (getAmmo() == 0) { // reload if we have no bullets
return move('r', this);
} else if (getShotBy() != null) { // if someone shot at us, retaliate
if (getAliveEnemies().contains(getShotBy())) { // only if they're alive
return move('s', getShotBy());
} else {
return move('h', this); // heal otherwise
}
} else {
return move('h', this); // heal if we cannot decide on an action
}
}
}
```
Dexter is a simple man. He puts all the points into his favorite skill Dexterity.
He also fixates on healing **a ton** now. After a ton of testing on my side this should make Dexter compete harder than before..
[Answer]
## RageBot2
```
class RageBot2(PlayerClass):
def __init__(self):
super().__init__(8, 1, 1, 0)
def makeMove(self):
if self.health < 3:
return "h"
elif self.health < 10:
return "s", last_one_who_attacked_me()
if self.ammo < 6:
return "r"
else:
if self.health < 8:
return "h"
else:
return "s", last_one_who_attacked_me()
```
---
Java version:
```
package standoffKOTH;
import java.util.Random;
public class RageBot2 extends PlayerClass {
Random rand = new Random();
public RageBot2()
{
super(8,1,1,0);
}
protected int makeMove()
{
if (getHP()<3)
{
return move('h',this);
}
else if (getHP()<10&&getAmmo()>0&&getShotBy()!=null&&!getShotBy().deadQ())
{
return move('s',getShotBy());
}
else if (getAmmo()<6)
{
return move('r',this);
}
else if (getHP()<8)
{
return move('h',this);
}
else if (getShotBy()!=null&&getAmmo()>0&&!getShotBy().deadQ())
{
return move('s',getShotBy());
}
else if (getAmmo()<1)
{
return move('r',this);
}
else
{
return move('s',getAliveEnemies().get(rand.nextInt(getAliveEnemies().size())));}}}
```
This bot hopes to be RageBot, but smarter.
[Answer]
# ChargeBot
```
class ChargeBot(PlayerClass):
def __init__(self):
super().__init__(5, 0, 0, 5)
def makeMove(self):
if self.ammo == 0:
return "r"
if self.health < 7:
return "h"
return "s", alive_enemies()[-1] # target slowest
```
] |
[Question]
[
I [like](https://codegolf.stackexchange.com/questions/241650/sort-every-dimension) [to](https://codegolf.stackexchange.com/questions/233030/build-me-a-room) [pretty print](https://codegolf.stackexchange.com/questions/236884/remove-submatrices) multidimensional arrays, like this:
```
[ [ [1, 2, 3],
[4, 5, 6] ],
[ [7, 8, 9],
[6, 4, 2] ] ]
```
But it's a pain to do by hand and it'd be nice to have a program that does this for me. Your challenge is to create a program that does this for me, taking a multidimensional array containing only positive integers and prettyprinting it.
Specifically, an array of depth 1 is printed joined by `,` with `[` prepended and `]` appended:
```
[1, 2, 3]
```
An array of depth \$n+1\$, which contains at least one array of depth \$n\$, has its subarrays prettyprinted, joined by newlines and indented by two spaces. All but the last subarray have a comma appended, the last has `]` appended, and the first has its first line indented with `[` instead of two spaces:
[](https://i.stack.imgur.com/YoEb4.png)
Here's a reference implementation:
```
function recursivePrettyPrint(array){
if(array.every(x => typeof x == "number")){
return `[${array.join(', ')}]`;
} else {
return array.map((item, index) => {
let result = recursivePrettyPrint(item) + ',';
result = result.split`\n`;
if(index == 0){
result[0] = '[ ' + result[0];
} else {
result[0] = ' ' + result[0];
}
for(let i = 1; i < result.length; i++){
result[i] = ' ' + result[i]
}
return result.join('\n');
}).join('\n').slice(0,-1) + ' ]';
}
}
function change(){
let array = JSON.parse(document.getElementById('input').value);
let output = document.getElementById('output');
output.innerText = recursivePrettyPrint(array);
}
```
```
<textarea id=input></textarea>
<button id=run onclick=change()>Pretty Print</button>
<pre id=output></pre>
```
Numbers may be multiple digits. The input will always be orthogonal/rectangular, and you may take its dimensions as well. Trailing spaces on lines are allowed.
## Testcases
```
[[892, 759], [962, 251]] ->
[ [892, 759],
[962, 251] ]
[118, 922, 619] ->
[118, 922, 619]
[[966, 639, 616, 255], [622, 483, 87, 241], [453, 870, 728, 725], [163, 936, 48, 967], [261, 833, 87, 200]] ->
[ [966, 639, 616, 255],
[622, 483, 87, 241],
[453, 870, 728, 725],
[163, 936, 48, 967],
[261, 833, 87, 200] ]
[[[[[912, 547], [366, 754]], [[723, 536], [779, 238]]], [[[559, 392], [602, 709]], [[692, 915], [412, 302]]]], [[[[3, 504], [936, 83]], [[352, 442], [425, 375]]], [[[380, 440], [793, 762]], [[850, 321], [780, 457]]]]] ->
[ [ [ [ [912, 547],
[366, 754] ],
[ [723, 536],
[779, 238] ] ],
[ [ [559, 392],
[602, 709] ],
[ [692, 915],
[412, 302] ] ] ],
[ [ [ [3, 504],
[936, 83] ],
[ [352, 442],
[425, 375] ] ],
[ [ [380, 440],
[793, 762] ],
[ [850, 321],
[780, 457] ] ] ] ]
[[[128, 910, 664, 658], [172, 238, 564, 492], [325, 384, 566, 90]], [[876, 819, 764, 105], [583, 528, 731, 839], [480, 126, 692, 875]], [[215, 84, 268, 504], [400, 674, 997, 526], [799, 692, 193, 296]], [[943, 185, 567, 188], [118, 200, 879, 409], [116, 493, 62, 343]]] ->
[ [ [128, 910, 664, 658],
[172, 238, 564, 492],
[325, 384, 566, 90] ],
[ [876, 819, 764, 105],
[583, 528, 731, 839],
[480, 126, 692, 875] ],
[ [215, 84, 268, 504],
[400, 674, 997, 526],
[799, 692, 193, 296] ],
[ [943, 185, 567, 188],
[118, 200, 879, 409],
[116, 493, 62, 343] ] ]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~74~~ ~~73~~ 72 bytes
-1 thanks to [loopy walt](https://codegolf.stackexchange.com/questions/242999/pretty-print-my-arrays/243009#comment547333_243009)
-1 thanks to [dingledooper](https://codegolf.stackexchange.com/questions/242999/pretty-print-my-arrays/243009#comment547352_243009)
```
f=lambda l,s=',\n ':l<[f]and`l`or'[ %s ]'%s.join(f(r,s+' ')for r in l)
```
[Try it online!](https://tio.run/##PVLLbuMwDLz3K3QpHGONQqKeLNovUQU0i25QF64TOCkW@/Uph2rWB0EcksMZyqd/l/fjStfr4XnZf/5@25tlOj8P08tqzPC4PNVD269vr8vrcRuquT@bNtyfHz6O87o77Lbp/GuQuvFw3Mxm5tUs4/Xv@7z8Me7xzpy2eb1I2byevi67cRyvtRamyeTIbTKVk9wputbuqnNlMkwCJMcSSzLJ3TOAhLKIloSKUPxkShYwOIAhamyFmAoOLXVJUPYJ9XJJGSAlJ6X@1m8tZuNjJ8QxaJHH6BxDQ1AzSXX0CUHOood8aT1VY5TYM6k0C2eWeyrBJztVEsDtLbVbWwWjDboDCCy@J3yEu6B0gaI05Xjr8cUiZ1UGC0FO1FMlSsaTriJrVcwYpc4cNsJO0JSCHLHobjKpD5EBNHQHXkeWAFRUsf3hz5DoGCMl56yainiEqPv2ulN90oD5jvB0WECBfnCQE2owUyr/vQcLWVlQ5gyyvmPmn24Hm8SpU3CQyJUIdRm37gT/DYGo4G2C5Y7i2dGOX8wH2W/7Bg "Python 2 – Try It Online")
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 69 bytes
```
(g=j=>a=>+(u=uneval(a))[1]?u:`[ ${a.map(g(j+' ')).join(j)} ]`)`,
`
```
[Try it online!](https://tio.run/##NY7LasMwEEX3/YpZFCIRNcgaPayA0g8RAovWCVYaxzhxIJR@uyvZZHaHM/fOpPiIt6@xG@4ft6H7bsfLtT@3z/noZnJyyR2iO2zJ5Ka@fcQfEin1Vfic9o2H99@4u8SBnEjabgA2lO7StetJon8QGtqwN4BmHsauv5Mj8WVsJRgoaQIDj1ozMEqGAt4IzAZ1AWMsA4F1WJVXKjNaUUjz3GC4XZW2mWylCsjSjVyEV8yXRi4LWMy3alwFqrwo5VInhcoho14ZrHlxfHnD5gKjxapqlQ2KajHLljLlVKB0/gc "JavaScript (SpiderMonkey) – Try It Online")
This answer assume the array only contains positive integers.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~38~~ 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
dΔ€`}\„, ý'[ì']«N©F„
,®N-·úRý„[ ì„ ]«
```
[Try it online](https://tio.run/##LY0xDsIwDEV3TtGNxUipHcf1BRgZWEMkQDAwMTAjIc7AzI6oWJGQWJqdQ3CR4lRk8fPz18/@sFrvtn2/@Vy@53Z5XHxPV6jyexxzO07dfdbdpqZG0D1mk@6ZX/P8tj1WubVRWaLvY3laI7CXBJFCAGGfDKMgAVMwFFFAatKgI7MCKRoHhyBOBx0UQWs29NZGDtM/Hq3FeUOlAA0NkhjB@1LhkYGE/1lqnHlXvlQCCTjohh0Q1sWWO0upTj8) or [verify all test cases](https://tio.run/##NVK9alZBEO3zFJevSTPC7vzs7tjYiJAmgu16QUULGw0kESwCkmdInV78sFQQ0tzb@xB5kc8zez8XLrt7dmbOOTP38@Xbdx8/HL7szj5dXF89nXb0lU52L6@v/t@eH97/vXu83b@5ef347Z6m9eG0r/vTeflxvnx/AeiElp/nT5bf659X6wPufVr32CZEHG5o@fXs0LEyMclMXcmozDj0So0ch0JKPAOaem/OVC1QL0xsecA5I5KZSvYR5aVQEce9IMaiBl61CbVKrDloLC6JKjd8EZKLkAvIUKtUAFwyNdlyUtr4sTwzmUaAgKaabmJZyKTgWKsTS5sH3M2cxDkkJEhPPuACG56DVVFNUtgb4R1VkoY9KGkyQDFo1yihbCTVjrHSEvAUlC5UCw@4WSLhsFjj3eo8H3vXM7x6TlSKUrEWniuHVjIgOlRKUDQMAd48bRUrpGQHg1JOIdrQSYvGSXQopqHgyoyuw1gLhcjjbIRKXNrRkyZwVyX3ivTRK/eRkmGAfRu7q1BuBgUV@1CJ8WICKOykyQeCOSEH/4CohMF/).
**Explanation:**
```
dΔ€`}\...N # Determine the depth of the input:
d # Transform each inner-most integer to a 1 (with >=0 check)
Δ # Loop until the result no longer changes:
€` # Flatten it one level down
}\ # After the loop: discard the resulting list of 1s
„, ý # Join each inner-most list of the (implicit) input with
# ", "-delimiter
'[ì '# Prepend a "[" in front of each string
']« '# Append a "]" after each string
N # Push the reached index of the earlier loop, which is the
# depth of the input-list - 1
© # Store this depth-1 in variable `®` (without popping)
F # Loop `N` in the range [0,®):
„\n, # Push string "\n,"
®N- # Subtract `N` from `®`
· # Double it
ú # Pad the string with that meany leading spaces
R # Reverse it
ý # Join each inner-most list of strings with this as delimiter
„[ ì # Prepend a "[ " in front of each string
„ ]« # Append a "]" after each string
# (after which the result is output implicitly)
```
`dΔ€`}\...N` to determine the depth is taken from [this answer of mine](https://codegolf.stackexchange.com/a/240671/52210).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 96 bytes
```
f(a,i=",\n ")=print1(if(#a[1]',l=!print1("[ ");[(l--&&print1(i))+f(b,Str(i" "))|b<-a];" ]",a))
```
[Try it online!](https://tio.run/##PVLLbuMwDPwVVQt0bawMiHoTbfoTe3R9cA8pDASBEfRSoP@ecqgkPgjicDgcUt7XyzZ97tfrcVjddrDu/WyMHQ/7ZTt/0bAdhz/rTMtfdzo83TA7C@FlHk7T9Px8543jv@Pw4f5/XYbNQmH8@Xid1uXFmsW6dRyv676fvofVTG9Gi@RqJRApI73l7Kh9P9vRmXmeGwdnauZFIi5yD5kWBETNGQ6CFNKspIsEkYEUEDPgAkpq0ZlWBUwEMGWNvUiHhkOpVATlWMCXS6kAQyGhxnu999odH5Mo56SsiN41p56sQeg5FgS1iqEQ23Kry1niyEG9eQznuacKRmVSKwna0YflXjZD0SddAxy22BMxY7ykcilkKar5XhObR86rDRaBWkJPtSyZGHQXVVm5Lo9ehJ0wCVxKkiM33U4NOoj4AJr6CFF7tgRUbPFtPa3CIzF6So68TpXxDFk3HnWr@nAJBijg8bCBhgGgEUikoRxKewyfPGxVQZkrxPqSmW/VhDkDly7BSSJqGe4qbu3x6wQINTxO8txRPDzK8ZvFFLGP8foL "Pari/GP – Try It Online")
A port of [@att's Python answer](https://codegolf.stackexchange.com/a/243009/9288).
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-x`, ~~37~~ 35 bytes
```
"[]"J:0*@a?(fMaJ:",
")WRsRn"
"aJk
```
Recursive full program; takes the array as a nested list in Pip format from the command-line. [Attempt This Online!](https://ato.pxeger.com/run?1=PZA_S4MxEIdx7eY3CHGxYiF3-XN3zaDzCy5dHEKGdymIUAqt4HdxEUr9TvppvDPFJSRP7vfcJR-n_cv-q_nVu--f57fjdsXfN751P63D3eP8cLt9mqe1v1_45fPmsNn5hXN-nl5H6SXxc3XdfGsNkKsTCNWVknTJ3KtrQFgdRr3KRpOg0Yi5usjJaNFU6EYbkx4YpDqyYgjZcOaodWanCHofxWhi7QSogSLagikPB4KqzYzFmob0VxxsLFIqQiYrRknkkgbRFihlKCTpCTjbdGS78RJQH5qISXMpyKDFXqWBop6YYu_9_zN_AQ)
### Explanation
Using `¶` in place of newlines for better readability:
```
"[]"J:0*@a?(fMaJ:",¶")WRsRn"¶ "aJk
a ; Current list
@ ; First element
0* ; Times 0
? ; Is truthy?
; If so, first element is a list:
f ; Apply the main function recursively
M ; to each element of
a ; the current list
J: ; Join the results on
",¶" ; comma + newline
( )WR ; Wrap that string in
s ; space
R ; Replace
n ; each newline with
"¶ " ; newline plus two spaces
; Else, first element is a number:
a ; Current list
J ; joined on
k ; comma + space
"[]" ; Open bracket + close bracket
J: ; joined on the above result
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 66 bytes
```
,|\[\B
$&
\B]
]
], (?=(.+))
],¶$1_
T`d ,``.+_
+`\[]
+`]_
_
_
```
[Try it online!](https://tio.run/##LVE7blwxDOx1ilcYgY0lDIk/iUUQwGdIpxXeBkgKNymClDlXDpCLbYbyPuBB0pCcGZK/fvx@//ntfqc/13l9K0@fjnJ9W@VYZdHx/OXz8@vl5QX3f3@f2lm@3r4fdLu9Xs5yuV3nKjjWWc7jKGe53@ccwdQtFs1wJra2VpmtDQpm8hZ4IeLkEng6Mgy5jqAOodGJtQFQy0elzgN/pjQXCnGkUXgHwN5oyEdNrSmTXzQm04wLVLrpwnV2FjJxXHsPYhlrw9MsSILTQYXvGht29BAtRRVsUnk90idYqmZvMDJkg2KwrkmhbCTdHrkyKvCakiHUnTc8rJJwdtgzbj2pt/WGTqNVcldyG9lx57RKBkS3SUmFoUCcon4QdjhpAQGlVtOzYY6WY5OcT25CIdUYM0dfIw2ijpsRmNjHoyWt0O5KER3le1QRu6TBP4fvslChNgwOOs7tErvF/EEcpDU2gi2hBvsXxZDWfw "Retina 0.8.2 – Try It Online")
### Explanation
The first four lines, which add spaces where necessary, are taken from [Neil's Retina answer](https://codegolf.stackexchange.com/a/243021/16766).
Now, observe that:
* We need to add a newline and an indent after every occurrence of `],`
* The indentation level is equal to the nesting level at that point in the list, which can be calculated by looking at the number of brackets in the remaining part of the list: nesting level = (# of remaining close brackets) - (# of remaining open brackets)
So:
```
], (?=(.+))
```
Match `],` and capture the rest of the line in group 1; then:
```
],¶$1_
```
Replace that with `],` followed by a newline, the contents of group 1, and an underscore for a separator.
```
T`d ,``.+_
```
Transliteration stage: Replace digits, space, and comma with nothing (i.e. delete them) when they appear in any match of `.+_` (i.e. before `_` on a line).
```
+`\[]
```
Repeatedly delete empty matched brackets (which can only occur in the before-`_` context) until none are left.
```
+`]_
_
```
Repeatedly replace close-bracket followed by underscore with underscore followed by two spaces. This has the effect of translating each level of nesting (represented by the unmatched close-brackets) into two spaces of indentation.
```
_
```
Delete the underscores.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 76 bytes
```
,|\[\B
$&
\B]
]
+%1`((.*?\[)((\[)|(?<-4>])|[^][])+(?(4)^),) \[
$1¶$.2$* [
```
[Try it online!](https://tio.run/##LVE5jtwwEMz1ignGhrTbXrAvkg0YHmC/weHCGzhw4sBwOO/yA/yxcTV3BEgiq4@q6v7948/PX@/3O92u4/q6nT@ftuvr3E5ze/7E3/f95elyHce@43PbL1@/2Ld53MbbHPN43i@7HW8HHafr2M787@/5Rc5Pp9O438foIdQ8Jo2oQuI85zaYO4UIVQ7cEKlUNXCtyHDkVgStK/VGYgzAPC@FmnS8mcJVKbQijaI2AFKZun7UlJI0@QQLuWVcwdLcJo6jiZJrxbG1INE@FzzcgzQkFRToLrHgCg/BSWropkXmI32gS7H0BiFdF6gO6ZYtTJy0@SNXewFekjKUWpUFdy@kkg5bxr1l6yWd4TS4UK1G1Xs6bpJSyYHYEqnJ0A1IpSgfDRuUcIDAiEtqdszRc2ya88lNGKhYMHP46ikQdcJO6CS1PyxZAXczimgoX6OKWCUM/RJ1lYUpcXcoaPgvldgt5o/GQVZiIdgSarB/NQxp/gc "Retina 0.8.2 – Try It Online") Link includes test cases. Assumes input contains no spaces (seems awkward to ask for spaces given that this is a formatting challenge). Explanation:
```
,|\[\B
$&
\B]
]
```
Insert the necessary spaces.
```
+%1`
```
Repeatedly replace the first occurrence on each line until no more replacements can be made:
```
((.*?\[)((\[)|(?<-4>])|[^][])+(?(4)^),) \[
```
Match as little indentation (up to and including the parent `[`) as possible, as many subarrays as possible, then the start of a subarray.
```
$1¶$.2$* [
```
Wrap that last subarray to a new line, giving it the indentation it needs converted to spaces (it would have contained `[`s).
60 bytes by using @DLosc's observation that the amount of indent can be calculated from the remaining square brackets:
```
,|\[\B
$&
\B]
]
], (?=((\[)|(?<-2>])|(){2}]|.)+)
],¶$#3$*
```
[Try it online!](https://tio.run/##LVFLblsxDNy/UxiIUdgJG0j8SQTaBMg1ZC2yyCKbLILs6l4rB@jF3KHsBwhPGg45Q/Lz7ev94/VyofNpnF62/Y/ddnqZ225uk3aH59@Hw2kcz4fnXz/5aeJy/MN/5/nx@HAE4d/3/k7297vLZYweTM1i0ghnYqtzbqPWTsFMXgMvRJxcAk8Hw8B1BLUL9UasFYBaPgo17jhJqS4U4qBReAPAXqnLNaeUlMkvKpNpxgUqzXTiOhoLmTiurQWx9LngYRYkwemgwHeJBTt6iJqiimpSeN7oA1WKZm8w0mWBYrCuWULZSJrduNIL8JKSIdScF9ytkHB22DJuLUsv6xWdRi3kruTWs@PGaZUMiC6TkgpdgThFuRZscFIDAkq1pGfDHC3HJjmf3IRCqjJmjr56GkQeVyNUYu@3lrRAuylFNKSvUUWslAr/HL7SQoVqNzho@C@X2C3mj8JBWmIh2BJysH9RDGn@Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: The first two stages add the necessary spaces as above.
```
], (?=((\[)|(?<-2>])|(){2}]|.)+)
```
Match a closing square bracket with a comma, count the number of `[`s in `$#2`, ignore that many `]`s, then count two (spaces of indent) for each extra `]`.
```
],¶$#3$*
```
Break the line after the comma and replace the space with the desired amount of indent.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~75~~ 60 bytes
```
≔⭆¹SθF[]≔⪫E⪪θι∨κ ιθ≔⪪✂θ¹±¹¦¹], θ⪫Eθ⁺× ⁻№⪫…θκω[⁺κ№⪫…θκω]ι],¶
```
[Try it online!](https://tio.run/##hY/NasMwEITvfQrhkwxb0L@05FRyaiFtIL25PhjjJiKundhOS5/eXSspPVYgBMN8M6P6UA11X7Xz/DCOcd/x3TTEbr@pTlwCe@xOl@mq8DwHds5Xd@/9wHhWlFnObshTHzu@ELtTGyd@BhbJ@zLwI7CMZQsYb/BvSTLu2lg3i52anpt9NTVckm@5WUn3xmypfvorIf@2vYz8NX40I88Yy4BtYkfKur/8GtffddusD32yHynoawktlsgE07J/3fTD/Lr9OuitI2E1zwUdqQKgFOCcAWdDCYX0CpQOYEkxqEjRyoIOhhQHKEpSiuAdBIngySSFJckGDZbCvJYQNJJiggCpHDhUELxNnJIWKEk5yhdmMQnq9gYQPeGOFI@YEIkaFLqEodEgg6UFnt60UgZQxAaPYAQmxdFeDU6BNrqkM99/tj8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @Dlosc's observation that the indent can be calculated from the difference in numbers of `[`s and `]`s.
```
≔⭆¹Sθ
```
Input the array and perform Python stringification on it, which joins the elements with `,` but wraps them in `[` and `]` without spaces.
```
F[]≔⪫E⪪θι∨κ ιθ
```
Insert spaces between pairs of `[` or `]`. Unfortunately this also adds a leading and a trailing space.
```
≔⪪✂θ¹±¹¦¹], θ
```
Trim away that leading and trailing space, then split on `],` .
```
Eθ⁺× ⁻№⪫…θκω[⁺κ№⪫…θκω]ι],¶
```
Map over the pieces of strings, calculating the indent from the number of `[`s in all the previous strings minus the number of `]`s in all the previous strings (adjusted because they've been split on `],`), then output the strings each on their own line with the `],` restored (but not on the last line).
[Answer]
# Python3, 230 bytes:
```
E=enumerate
def f(x,d=[]):
m=len(d)-(min(i+1 for i,a in E(d)if not any(d[i+1:]))if any(d)else 0)
return ' '*((len(d)-m)*2)+'[ '*m+str(x)if all(int==type(i)for i in x)else'\n'.join(f(a,d+[i])+','*(i<len(x)-1)for i,a in E(x))+' ]'
```
[Try it online!](https://tio.run/##XVLLbuMwDLznK3Sz3LgLvSUWzbFf4fUhQBzUi8QJXBdIvj7l0EmBrA@GyOEMh5TO1/nzNPpynm63j00/fh/7aTv3q12/V3t9aXabtqvfVuq4OfSj3tWv@jiMelhbtT9Nami2ahjVBwPDXo2nWW3Hq961jL91NXIS1/3hq1emXqmpn7@nUVWqetH6rnisX1y9rlrOHddf86QvQjwc9DDOm818Pfd6qKUdml1Erfo7Vn/@ndjLXm@b3bodOtZoWHZ4h@6lfrX1k8VLzQWqq27niXWZ1raFXKNypK5RLSU@u2g79r36LbG2NIocQ8nSE8KExFlPgBKoETIJtaH4RpXMyWCRDFFiw81cwU9KbeIs@YR6PqSMpEuWS/2Db8yzH3xkuUUMUu5hIsfQIWizY170CUHO7Mz50i1QGyPHnpyYNJjb0AIlbIGseArQ9sZ1D1oLRRNkQ7Ba/AL4iDmDyAUXmZTjg@OLAWbEBrFATm6BSmTEO1lKlqqY0eq/GS22RJbxlAL/YpF9ZScTsSFkwzKLl@YlIMv@yNw7ZZi1hOaMWSPjRVxMlDvwsme5@gAn1uE6sYqCSaDhLEtD2aXyu4VgYCtzlihDbNk20Z1tMbCjtEhQ4MiWCHcZp2USvCoHoYJbCoaWLJ4C6HiKPnjZy@0H)
[Answer]
# [Julia 1.0](http://julialang.org/), 60 bytes
```
>(l,s=",\n ")=try.~l;"$l"catch;"[ $(join(l.>s*" ",s)) ]"end
```
[Try it online!](https://tio.run/##PVJBbuMwDLznFarQg70wCpESJRFF8hHXh6JboCkM76LJAtnLfj3lSMn6IIhDcjhD@fPPenyly/V6GNbptPfTzjk/7s9ff5/@rc/@cfVvr@e3j2c/u8fh89dxG9anw@mHt6rpNI5u8e/bz@vDxe3d76/jdl634TBcxsm/bH7c7R5mojo5ZZ5cJl2AzFUtKqLL5GbNdmehpac0ZyuMiuqMhKAooz3VOLlaDEwEMEmLg1FxxdFKKRuqMaPeLrkA5ExWGu/9Idym2adk1JJaWcTwImlBMBe2eokZQSmmiGNdemoWsTgqN3EBboL2VIY3paYlgTsGXu5tMxhDar4hscaeiAJ/qdElFmsqcu@JNSAXmgw1gpK5p6pYJnJbRmlVUjDq5o2wFSXDc052SG37KdycmBCgqXuIbWhNQE2XhtuEApGkGGo5Cs2W4CGk7Ty2vbaHTFBAjOfDCiocgIPJqMHMuf53nwJkFUNVC8j6llVv3QSjrLlTaLKIqkBdwa07wY/FIKp4nRS0o3h6tOPHiiliH9dv "Julia 1.0 – Try It Online") (with a literal `\n`)
port of [att's great answer](https://codegolf.stackexchange.com/a/243009/98541)
`.~l` tries to apply `~` to each element of `l`, which only works if `l` is not nested (shorter than `l[1] isa Int`)
] |
[Question]
[
## Background
A **[Jordan matrix](https://en.wikipedia.org/wiki/Jordan_matrix)** is a block-diagonal matrix where each block on the diagonal has the structure of
$$
\begin{bmatrix}
\lambda & 1 & 0 & \cdots & 0 \\
0 & \lambda & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \lambda & 1 \\
0 & 0 & 0 & 0 & \lambda
\end{bmatrix}
$$
where all values of \$\lambda\$ are identical inside each block. (A block diagonal matrix is one that can be divided into blocks, so that the blocks on the main diagonal are square and those out of the main diagonal are all zeros. See examples below.)
The following are some examples of a Jordan matrix:
$$
J\_1=\left[\begin{array}{c|c|cc}
2 & 0 & 0 & 0 \\ \hline
0 & 0 & 0 & 0 \\ \hline
0 & 0 & 2 & 1 \\
0 & 0 & 0 & 2 \end{array}\right]\\
J\_2=\left[\begin{array}{ccc|cc|cc|ccc}
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\ \hline
0 & 0 & 0 & 3 & 1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 3 & 0 & 0 & 0 & 0 & 0 \\ \hline
0 & 0 & 0 & 0 & 0 & 3 & 1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 3 & 0 & 0 & 0 \\ \hline
0 & 0 & 0 & 0 & 0 & 0 & 0 & 7 & 1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7 & 1 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 7 \end{array}\right]
$$
The following are more examples of Jordan matrices:
```
[[0]] // 1x1 matrix is always Jordan
[[0, 0],
[0, 0]] // all-zero matrix is also always Jordan
[[3, 0, 0],
[0, 2, 0],
[0, 0, 2]] // diagonal matrix is also Jordan, even if it has duplicates
[[3, 0, 0],
[0, 2, 1], // the one between the two 2s is optional
[0, 0, 2]] // (if it is a zero, the two are in separate blocks)
[[99, 1, 0, 0],
[ 0, 99, 1, 0],
[ 0, 0, 99, 0],
[ 0, 0, 0, 1]] // the matrix may contain numbers >= 10
[[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 3, 1, 0], // same diagonal entries may appear separately
[0, 0, 0, 3, 0],
[0, 0, 0, 0, 1]]
```
The following are not Jordan:
```
[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]] // has a one where it should be zero
[[2, 0, 0],
[1, 2, 0],
[0, 0, 1]] // 1 is at the wrong side of the diagonal
[[1, 1, 0],
[0, 2, 0], // the numbers on the left of and below the
[0, 0, 2]] // non-diagonal 1 are not equal
[[99, 99, 0, 0],
[ 0, 99, 99, 0],
[ 0, 0, 99, 0],
[ 0, 0, 0, 1]] // the matrix may contain numbers >= 10
[[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 3, 2, 0], // all numbers right above the main diagonal
[0, 0, 0, 3, 0], // should be either 0 or 1
[0, 0, 0, 0, 1]]
```
## Challenge
Given a square matrix filled with non-negative integers, determine if it is a Jordan matrix.
Input format is flexible. For output, you can choose to
1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
[Answer]
# JavaScript, 58 bytes
```
a=>a.some((r,y)=>r.some((c,x)=>(r/(r=c)==a[x][x])/-y--<c))
```
[Try it online!](https://tio.run/##jVLN0pswDLznKXSEGUjifNeSWy99hQwHBURwayxqOyG002dPbZPw5a8zneGABNpd7eo7ntBWRvYu11zTpSkuWGxxabmjJDHZmBZbc62q7OyrxKwSU1RpUeDuXPonXeVjnn@p0vTioIDdYrdblyXAagXiLKBDZ@QZpAVUA44WvrGpUS@y8F8G6zJbwPQyzaBS@S8y/DBo@c30hx@6A9jcg/nyildLPLBG9Yw3AWVAJ9IgG5AOWrRQH3slK3Rk/8EhyiziupaANcGe3EAeItRuYNjYQMG9k4H1RU4yUQUVENbM5kE0BFKDpR6N54e94uqHTaMMMcl4FPO24wWL2IlsFjv6dIC0d4Csd2IE7HtCM7Op8R7z4x2LKMs5tKfv8f2q8bpn8BKjQUNLYTMHtuWjqr1hcfGItXmcf4pQ3M4o2uWiU4NhfQAra@9@Ezu39W5GiZebmPPSx25PxqczxaWocQEFdVCleAjdl8Q063y2UMSYNDugn8dPzv8P506Rv/RZkZGH1gHu@URRWof@FObNXqKZwp39JOlnDKyBDYg3sZULt2zYfMWqTTootvAbKtaWFS0VH5Im6dIU/qSXvw "JavaScript (Node.js) – Try It Online")
* When `c==0`
+ `r/(r=c)` is `NaN` or `Infinity`;
+ `(r/(r=c)==a[x][x])` is `false`
+ `(r/(r=c)==a[x][x])/-y--` is `0` or `NaN`
+ `(r/(r=c)==a[x][x])/-y--<c` is false
* When `y==0` (cells on main diagonal) and `c>=1`
+ `(r/(r=c)==a[x][x])/-y--` is `NaN` or `Infinity`
+ `(r/(r=c)==a[x][x])/-y--<c` is false
* When `y==-1` (cells on right side of main diagonal) and `c==1`
+ `r/(r=c)` equals to `r` equals to left cell,
+ `(r/(r=c)==a[x][x])` test if left cell equals to bottom cell
+ `(r/(r=c)==a[x][x])/-y--` is `1` or `0` based on whether left cell equals to bottom cell
+ `(r/(r=c)==a[x][x])/-y--<c` is `true` if left cell not equals to right cell
* When `y==-1` (cells on right side of main diagonal) and `c>=2`
+ `(r/(r=c)==a[x][x])/-y--` is `1` or `0`
+ `(r/(r=c)==a[x][x])/-y--<c` is `true`
* When (`y<-1` or `y>0`) and `c>=1`
+ `(r/(r=c)==a[x][x])/-y--` is a number in range [-Inf, 1)
+ `(r/(r=c)==a[x][x])/-y--<c` is `true`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes
```
ŒDµḢ=Ɲo@ƑḢ>FẠ
```
[Try it online!](https://tio.run/##y0rNyan8///oJJdDWx/uWGR7bG6@w7GJQJad28NdC/4fbteM/P8/OtogNlYHSOooGABpMAXiGwMZYCEuBZCgERIbxMWhxhBDjSFEDapKrCJA0wwx1Bhj02UIdzGaLJgNtRGsxghVHM0XhjAXGhLyKUm@gJiggOkNBQVMjwAA "Jelly – Try It Online")
*-1 because I actually thought to check if the input can contain negative integers*
```
ŒDµ Consider the diagonals of the input matrix.
Ḣ Pop the main diagonal;
Ɲ for each pair of its adjacent elements
= are they equal?
(Especially note that this results in a list of ones and zeroes,
of the same length as the superdiagonal.)
Ḣ Pop the superdiagonal;
o@ are the logical ORs of its elements and the neighbor equalities
Ƒ equal to the neighbor equalities?
F For every element in the flattened remaining diagonals,
> Ạ is the test result strictly greater?
```
Jelly's logical OR is Python's: if the first argument is truthy it is returned, else the second argument is returned. Testing the diagonal equalities' invariance under flipped logical OR with the superdiagonal determines if every element of the superdiagonal is either a 0 anywhere or a 1 "between" two equal elements on the diagonal, since a 0 on the superdiagonal leaves either equality value unchanged, but any non-zero overrides the equality value--passing only if both are 1.
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), 111 bytes
```
|sI^>s[[PgI#1I#s2=#-#1[^0[^1g2[^0=q]][1g2[^0[^1=q]P=#4<s<=#3-sg0>I~<I~s_3P=#4+<s<=#3sg0>I~<I~<[^~=q]]]]g1]`]`=1
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7CsI%5E%3Es%5B%5BPgI%231I%23s2%3D%23-%231%5B%5E0%5B%5E1g2%5B%5E0%3Dq%5D%5D%5B1g2%5B%5E0%5B%5E1%3Dq%5DP%3D%234%3Cs%3C%3D%233-sg0%3EI%7E%3CI%7Es_3P%3D%234%2B%3Cs%3C%3D%233sg0%3EI%7E%3CI%7E%3C%5B%5E%7E%3Dq%5D%5D%5D%5Dg1%5D%60%5D%60%3D1&inputs=%5B%5B1%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%200%5D%2C%20%5B0%2C%200%2C%203%2C%201%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%203%2C%200%5D%2C%20%5B0%2C%200%2C%200%2C%200%2C%201%5D%5D)
Needless to say, Rattle is not built to handle matrices and this approach is pretty brute-force. However, this code really shows off most of Rattle's features!
# Explanation
```
| takes input and parses automatically (Rattle's parser is very
powerful and automatically recognises nested lists)
s saves the list to the first memory slot (slot 0)
I^ gets the length of the list
> move pointer right
s save length of list to slot 1
[[ ... ]`]` nested loop to iterate over array
(inside nested loop)
I won't explain every single command here but the code inside the nested loop is split
into two parts.
First, the code checks to make sure all values that are not on the diagonal or off
the diagonal to the right are all zero and all values off the diagonal to the right
are 1 or 0. If not, it prints a falsy value (0).
Next, it iterates over all values of 1 which appear in the off-diagonal. For each
value of 1 in this off-diagonal, it ensures the value to the left and below the 1
are equal. If not, it prints a falsy value (0).
Knowing these conditions have been checked for, a truthy value (1) is printed if a
falsy value has not already been printed.
```
[Answer]
# [R](https://www.r-project.org/), ~~96~~ ~~93~~ ~~83~~ ~~75~~ 67 bytes
```
function(m,k,j=1:k^2%%(k+1),x=m[!j])any(m[j>1],diff(diag(m))&x,x>1)
```
[Try it online!](https://tio.run/##jZNfb5swFMXf8ynuVHXCqqvGQX2ZlH6APe@t6qRLMMGJsaltCuzLZzYw/iRpVilSMNH9neNzbswp256ySu2c0Coq6JEetuzH8ffm/j46PjBCm23x@u3wRlC1UfF6eGFvNBVZFqUC91FByPeGNi@MnLKoQGdEE@2iNaEsfO4Anp6ANQz6n0BYQFlja@GnNimq1Wwo/vLQfGpNYU1XEL4I3dCkNbre/vKPAwelfPzDjV7ArL5BjClM0M2E9wdC40khHhRCDlqhPFfo0RT4B1cgMhAOcrSQVqUUO3Tc3lRltKe7nINWHBLuau5B4exqDRsbhHQZWkN522HUqwdjELKgIwUNB6HA8hKNtwSJ1LujJQtnbHA283flHAfL/qFXtFjwKRiuPIpbH1ALWJYczago2xkwvhTwG/E8XeiZ3K0u218MrWDwezWJUAB2edY5D3d3YHNdydTn20WzoG/mzMUmsKt01kXsunRro9UerEh9fVn35l8c5@Gy5bJNtauqSLjxJfetS565wEIV3Epdh7efF@8hSqvHsQTWla20A/5eXbr4WsUzh/6PNTo0Yp87wER/8M5qgX6pxvueFTxsyBg7F37EwBq0Afaf9k9/AQ "R – Try It Online")
Takes input as matrix and it's size.
Outputs inverted `TRUE/FALSE` values.
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
lambda m,n:re.sub(f"(.)({10**~-n}\\1)*(0%r|$)"%{n},"",m)>""
import re
```
[Try it online!](https://tio.run/##XYzdSsQwEIXv8xRhcCFTakjau4X6IsaLLptipJ2ENF7Iur56zQ@CCvk555szJ3ykV0/jsUzmWOftcp351tM5Wrm/X8QCQqK4adV1X490N0ZjJ9Qpfj4gnG507wH6DZ8AmNuCj4lHeyw@8m1O3BH3wZJQKKOdrwLlHlaXBBgyBHhmJTXl2/jqyO4CGadpzVuZP6sXbCEA@eZdhZmE6CiJpbieEA/FmFLlsLH8Q9HDj9HNaKVqpr2jrnpsRJf9KkuMsaGI2pInWv@q/Ncy/Gn5Bg "Python 3 – Try It Online")
input is a flatened string of the matrix and its size
output `False` for Jordan and `True` for not jordan
#### Edit:
as it wasn't specified when I post this answer, my solution only works for matrix with single digits elements
## How it works:
* the main idea i to substitute every "jordan" sub patern by the empty string and check if the result is the empty string (every subpart of the matrix was jordan)
* `(.)({10**~-n}\\1)*(0%r|$)"%{n}` with for example `n=4` will give the patern `/(.)(1000\1)*(0{4}|$)/`
[Answer]
# [Wolfram Mathematica](http://www.wolfram.com), ~~150~~ ~~144~~ ~~137~~ 69 bytes
```
With[{m=#,l=Length@#,d=Diagonal},Union@@Join[m~d~#&/@2~Range~l~Join~-Range@l,{If[#2==1,#1,#2]}&~MapThread~{Differences@d@m,m~d~1}]=={0}]&
```
I know... I don't like it either! But this was the shortest code that I could think of, and I'm definitely not an expert. Please take it with a huge grain of salt and enlighten me with your valuable suggestions. [Try it online!](https://tio.run/##dY5NS8UwEEX3/RWFQFcRm7oOzOK5eKIgfuCidDG0SRNoU6nZhZm/Xl9EUGqFuzmHOx8zRmdmjL7HzertzUfXplkLOel7E8boQMhBnzyOS8CJ5GvwSwC4W3xoZx5YVNfQ8BOG0fDEWfPVF8Ek09m2QmmtpGikUB1V/IDvL241OHDK00qevLVmNaE3HzCAoE7rVFNXbY@rDxEs3PZuAVHxc4@BU5FSqWROTbIoU1nvIDNd6KDX/NM7WPENat/7ye/raqfqQ3XJzV@V/yIqaPsE)
**Edit later-** [Michael E2](https://mathematica.stackexchange.com/users/4999/michael-e2) proposed this elegant, much shorter solution: [Try it online](https://tio.run/##dY7BCoJAEIbvPoUgdPKgdRYmqMAoiHyCbR1zDu7G7hDFsr76phAUZvBfvp@Pf6YT3GInmKQITRHKGhUTP4@CDT3ggOrKLSRFccY7GouVNgzri4UdGcuw16YWaoNSdzdtiUkrSBbhZEgxNLCVrR64r6RQvYuci/N0TObTKHZxNoGR/UAz3vKPNzPxhnzqffJ9PZ9U2Ww1ZPVbjX95H/nwAg)
```
IdentityMatrix@Length@#==ReverseSort@Abs@First@JordanDecomposition@#&
```
Explanation for the initial code:
```
(* The Diagonal method extracts diagonal vectors from input matrix *)
With[{m=#, l=Length@#, d=Diagonal},
Union@@(
(* Except for the main diagonal and the one above it,
all other diagonals must be zero: *)
d[m,#]& /@ Complement[Range[-l,l],{0,1}]
(* These diagonals are combined by Union method above *)
)=={0}
&&
(* The Difference of elements of the main diagonal is calculated.
If an element in the secondary diagonal is 1,
its corresponding element in the difference diagonal must be zero *)
And@@
MapThread[If[#1==1,#2==0,#1==0]&, {d[#,1], Differences@ d[#]}]]&
```
[Answer]
# [Desmos](https://desmos.com/calculator), 90 bytes
```
I=wy+x-w
f(L,w)=\prod_{x=1}^w\prod_{y=1}^w\{L[I]=0,x=y,x=y+1:\{L[I]=1\}\{L[I-1]=L[I+w]\}\}
```
Takes input as the flattened matrix and its width. Returns 1 for truthy and NaN for falsy.
[Try it on Desmos!](https://www.desmos.com/calculator/qquqiagcaj)
### Explanation
```
f(L,w)=
\prod_{x=1}^w\prod_{y=1}^w # iterate over all x,y in matrix
\{ # piecewise (case statement)
L[I]=0, # any 0 is OK; multiply by 1
x=y, # any values on main diagonal are OK; multiply by 1
x=y+1: # immediately above the main diagonal
\{L[I]=1\} # must have value 1 (0s matched L[I]=0) and
\{L[I-1]=L[I+w]\} # left and bottom are same
# fall through: multiply by NaN
\}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
⬤θ⬤ι∨¬λ∨⁼κμ∧⁼⊕κμ⁼λ⁼§ικ§§θμμ
```
[Try it online!](https://tio.run/##bUy9DsIgEN59ihuPBJPa1YnBoYu6EwYCJDY9aErR@PZYRByMl0u@3ztz09HMmnK@xjEkFES4cCgwcrhEPM8Jib3pablrWnHi4DdDBNucIZjovAvJWZxYjT8RfZlIQ7DuWd6WTpMNl3rmWZtjzlLKnkNXV/EdgOz@6q11@Ml7pVTeP@gF "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for Jordon, nothing if not. Explanation:
```
θ Input array
⬤ Each row satisfies
ι Current row
⬤ Each cell satifies
λ Current cell
¬ Logical Not i.e. is zero
∨ Logical Or
κ Current row index
⁼ Equal to
μ Current column index
∨ Logical Or
κ Current row index
⊕ Incremented
⁼ Equal to
μ Current column index
∧ Logical And
λ Current value
⁼ Equals
§ικ Value to left
⁼ Equals
§§θμμ Value below
```
Since the `Equals` operator returns `1` or `0`, the penultimate equality only holds for `1`s where the two adjacent values on the main diagonal are equal or `0`s where the values are unequal, but if the value was `0` we skipped it earlier anyway.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 57 bytes
```
m->matrix(#m,,i,j,[1+k=i-j,1-a=m[i,j],m[i,i]-m[j,j]]*a*k)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVBBCsIwEMSfRL2kusGmvVhK-wNfUILspZLWSCgR9C1eCiK-SV9j0kTtRfAQdmZ2Z3fI5a6xk9ud7q81KW5HU7P1I1OsVGg6eaJzBSChgYov20KyBjjDQlVWEuCKFExVjWVigYs28guekxVqvT9TJKwkupMHQxHIzLEZkGlNMYqAVBs0NHYghji3T1iYgieJlyBxYpYBD7qHQ8tCD2LgbmoYCWNjlH4cDn-7g2lkyIcFTkwCfYfgIYS7-E7xuf5_jORHDBH-re99fQE)
Outputs a zero matrix when the input is a Jordan matrix. In PARI/GP's convention, a matrix is truthy if and only if it contains at least one truthy entry.
[Answer]
# [Python 3](https://www.python.org), 92 bytes
```
def f(m,w,h):
for i in range(h-1):i*=w;m[i:i+2]=(m[i]==m[i-~w])<m[i+1],
return any(m[:-1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVIxbsMwDETH-BUcpYYGLGVp3PgljoYAtWoBtRKoNows-UiXLM0j8pP0NaWi2HKLtkMX6cg7ijxQb6fdvq239nh871qdPlzWT5UGzRrsseZ5AnrrwICx4Db2uWJ1Knhu7ov-sSlNbuZSFYyQKgo600Ov-IrAXChMwFVt5yxs7J4keSoUDz0-7s7-1ca_ypJZWWaK5P7GTOH1DPECh4wcGJQ_cOIbt1yiGOkQ3BQUDDCjsiC_akf9V7yYFPtoqhFx7JinO_QOnBxz0ULsK361R4P6WaOHyeT_MCH_NkGLnu2csS3T7LVraPtQKo7wUllaXTZCzm8rHL7LJw)
This is longer than the earlier Python solution, but it supports numbers larger than 9, as required by the challenge. It takes the matrix as a flat list/array of integers in row-major order, and returns False if it's Jordan, True if not.
The loop tests that each triple of diagonal and superdiagonal entries follows the rules, and the diagonals are overwritten with the results. Then `any` checks both that those tests passed and that the rest of the matrix is zero.
This is the first time in my life that I've wanted comparison operators to be left-associative. I almost rewrote the answer in C just for that reason, but I looked it up, and it turns out `<` and `==` have different precedence in C, and `<`'s precedence is higher, which is the opposite of what I need. So much for that.
[Answer]
# [Haskell](https://www.haskell.org/), 91 bytes
```
import Data.Array
j m=and[c==r+1&&v==1&&m!(r,c-1)==m!(r+1,c)|((r,c),v)<-assocs m,v/=0,c/=r]
```
[Try it online!](https://tio.run/##HY3BCoMwEETv/YoURLK4VqNX91DoX4iHJS001qhsglDov6cqDI95c5k3h89rmlJyfl0kqgdHvt1F@HsZlSeen70lksLk@Ua001@1oC0NEB21MGjhp48NcIOu5BAWG5THraIabUUyJM9uplXcHLMxm1yI54HWBg2gbrEF6FtU9ZEdDSqDp6hmSH8 "Haskell – Try It Online")
] |
[Question]
[
A balanced string is a string of parentheses `()` so that every parenthesis is can be matched with another one. More rigorously they are the strings spanned by this grammar:
```
S → (S)S | ε
```
We can turn a string "inside out" by:
* Switching all occurrences of `(` and `)` with each other
* Moving characters from the front of the string to the back until the string is balanced again.
---
Lets do an example.
We start with the balanced string:
```
(()(())())
```
We then switch the parens to make
```
))())(()((
```
Then move characters from the front of the string to the back of the string until the string is balanced.
```
))())(()((
)())(()(()
())(()(())
))(()(())(
)(()(())()
(()(())())
```
Thats our result!
---
Note that some strings can be turned inside out in multiple ways, for example the string
```
(()())
```
When turned inside out can be either:
```
()(())
```
or
```
(())()
```
However every string [has at least one solution](https://chat.stackexchange.com/transcript/message/38554888#38554888).
# Task
Write a program to take a balanced string as input and output that string turned inside out. In cases where there may be multiple valid outputs you need only output one of them. You may use a different brace type (`<>`,`[]` or `{}`) if you so wish.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") competition so you should aim to minimize your size of your source code, as measured by bytes.
## Test Cases
```
(()()) -> ()(()), (())()
(()(())()) -> (()(())())
((())())() -> (()(()()))
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~124~~ ~~120~~ ~~119~~ ~~117~~ ~~113~~ ~~110~~ ~~109~~ ~~106~~ ~~105~~ ~~104~~ ~~101~~ 98 bytes
*4 bytes saved thanks to bartavelle!*
*3 bytes saved thanks to Zgarb*
*1 byte saved thanks to Peter Taylor*
Here's a solution I worked out in Haskell. Its ~~ok right now~~ pretty good thanks to some help I received, but I'm looking to make this shorter, so feedback/suggestions are appreciated.
```
until(!0)g.map d
_!1=1<0
('(':a)!x=a!(x-1)
(_:a)!x=a!(x+1)
_!_=1>0
g(a:b)=b++[a]
d '('=')'
d _='('
```
[Try it online!](https://tio.run/##RYtBC4IwGIbv@xWbBvuGGO46@gKJkCDKS6eKMTFNmiJlIES/fU0v8T6H5zm8d/N63Kx1nzik@/SQndJsSzd5TsP4Syq8uHc3NBZYIupla3paEs0kylVCgANXRrARDYMxloKA/nfkWzONcp2QGowqBBZRdDZXUlJ/RC64N43eXWuaTqndEQSZFPtn0w2LKgAQE34zswTuBw "Haskell – Try It Online")
## Explanation
This program defines 4 functions, the first `(!)` determines if a string is balanced. Its defined as follows:
```
_!1=1<0
('(':a)!x=a!(x-1)
(_:a)!x=a!(x+1)
_!_=1>0
```
This check assumes that the input has an equal number of open and close parens thanks to a suggestion from Peter Taylor.
The next `g` will rotate the string once.
```
g(a:b)=b++[a]
```
Then we have `d` which simply takes a paren and mirrors it
```
d '('=')'
d _='('
```
Finally we have the function we are concerned with. Here we use a pointfree representation of `until(!0)g` composed with `map d`, which maps `d` to the input and applies `g` until the result is balanced. This is the exact process described in the question.
```
until(!0)g.map d
```
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~12~~ 11 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
↔]»:l{Ƨ()øŗ
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTk0JTVEJUJCJTNBbCU3QiV1MDFBNyUyOCUyOSVGOCV1MDE1Nw__,inputs=JTI4JTI4JTI5JTI4JTI4JTI5JTI5JTI4JTI5JTI5)
Explanation:
```
↔ mirror characters
] do ... while the top of stack is truthy
» put the last letter at the start
: duplicate it
l{ length times do
Ƨ() push "()"
ø push ""
ŗ replace ["()" with ""]
if the string left on stack is empty (aka all matched parentheses could be removed), then stop the while loop
```
Note: `l{` could be replaced with [(](https://github.com/dzaima/SOGL/blob/master/P5ParserV0_12/data/charDefs.txt#L202) for 10 bytes, but, sadly, it isn't implemented.
[Answer]
## CJam (20 chars)
```
q1f^0X${~_}%_:e>#)m<
```
[Online demo](http://cjam.aditsu.net/#code=q1f%5E0X%24%7B~_%7D%25_%3Ae%3E%23)m%3C&input=(()(())()))
or for the same char count
```
q1f^_,,{0W$@<~}$W=m<
```
[Online demo](http://cjam.aditsu.net/#code=q1f%5E_%2C%2C%7B0W%24%40%3C~%7D%24W%3Dm%3C&input=(()(())()))
### Dissection
The two versions have a common header and footer
```
q1f^ e# Read input and toggle least significant bit of each character
e# This effectively swaps ( and )
m< e# Stack: swapped_string index
e# Rotates the string to the left index characters
```
Then the bit in the middle obviously calculates how far it's necessary to rotate. Both of them use evaluation and rely on `(` being the CJam decrement operator and `)` being the increment operator.
```
0X$ e# Push 0 and a copy of the swapped string
{~_}% e# Map: evaluate one character and duplicate top of stack
e# The result is an array of the negated nesting depth after each character
_:e> e# Copy that array and find its maximum value
# e# Find the first index at which that value occurs
) e# Increment
```
vs
```
_,, e# Create array [0 1 ... len(swapped_string)-1]
{ e# Sort with mapping function:
0W$@ e# Rearrange stack to 0 swapped_string index
<~ e# Take first index chars of swapped_string and evaluate
}$ e# The result is an array of indices sorted by the negated nesting depth
W= e# Take the last one
```
[Answer]
# JavaScript (ES6), ~~111~~ 105 bytes
(Saved 2 bytes thanks to @CraigAyre, 2 bytes thanks to @PeterTaylor, 2 bytes thanks to @Shaggy.)
```
s=>(r=[...s].map(c=>'()'[c<')'|0])).some(_=>r.push(r.shift(i=0))&&!r.some(c=>(i+=c<')'||-1)<0))&&r.join``
```
**Ungolfed:**
```
s=>(
r=[...s].map(c=>'()'[c<')'|0]), //switch "(" and ")"
r.some(_=>(
r.push(r.shift(i=0)), //move last element to beginning of array, initialize i
!r.some(c=>(i+=c<')'||-1)<0) //check if balanced (i should never be less than 0)
)),
r.join``
)
```
**Test cases:**
```
let f=
s=>(r=[...s].map(c=>'()'[c<')'|0])).some(_=>r.push(r.shift(i=0))&&!r.some(c=>(i+=c<')'||-1)<0))&&r.join``
console.log(f('(()())')); // ()(())
console.log(f('(()(())())')); // (()(())())
console.log(f('((())())()')); // (()(()()))
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~46~~ 38 bytes
```
T`()`)(
(.*?)(((\()|(?<-4>\)))+)$
$2$1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyRBQzNBU4NLQ0/LXlNDQyNGQ7NGw95G18QuRlNTU1tThUvFSMXw/38NDU0NTU0uEAWkIUwIQ0MTAA "Retina – Try It Online") Link includes test cases. Edit: Saved 8 bytes with help from @MartinEnder. The first stage simply transposes the parentheses, while the second stage looks for longest suffix that's a valid balanced prefix, which apparently is a sufficient condition for the rotation to be fully balanced. The balancing is detected using balancing groups. The construct `((\()|(?<-4>\)))+` matches any number of `(`s plus any number of `)`s as long as we have already (`<-4>`) seen as many `(`s. Since we're only looking for a valid prefix we don't have to match the remaining `)`s.
[Answer]
# PHP, ~~110~~ 108 bytes
```
for($s=$argn;;$p?die(strtr($s,"()",")(")):$s=substr($s,1).$s[$i=0])for($p=1;$p&&$c=$s[$i++];)$p-=$c<")"?:-1;
```
Run as pipe with `-nR` or [test it online](http://sandbox.onlinephpfunctions.com/code/64042062d19ae3ce2651f9b367ee6e084aa1dda7).
**breakdown**
```
for($s=$argn; # import input
; # infinite loop
$p?die(strtr($s,"()",")(")) # 2. if balanced: invert, print and exit
:$s=substr($s,1).$s[$i=0] # else: rotate string, reset $i to 0
) # 1. test balance:
for($p=1; # init $p to 1
$p&&$c=$s[$i++];) # loop through string while $p is >0
$p-=$c<")"?:-1; # increment $p for ")", decrement else
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~112~~ ~~103~~ 101 bytes
*-2 bytes thanks to @Mr.Xcoder*
```
k=y=input().translate(' '*40+')(')
while k:
k=y=y[1:]+y[0]
for _ in y:k=k.replace('()','')
print(y)
```
[Try it online!](https://tio.run/##LY7BCsIwEETv@Yqll@xaKRU9FfIX3kqRElcaEtIQUzRfH1PqaeYwb2ZCTsvqr0WvT1ZN0xSrsjI@bAmpS3H2bzcnRgnydOtbSShJfBbjGOwgYA/n8TJMbR77ScBrjfAA4yEPVtkucnCzrjSSPMtKhmh8wkylLv1r7nHj2gT8ZY37CyqIhERil6qHPQzSDw "Python 3 – Try It Online")
[Answer]
# Octave, 62 bytes
```
@(s)")("(x=hankel(s,shift(s,1))-39)(all(cumsum(2*x'-3)>=0)',:)
```
[Try it online!](https://tio.run/##DcxBDkAwFEXRvZj0PakEHZFUbOVHCFE1@Cp2Xx3d0bn38si75jxDWREVPr9LPNcAtbof21PakY0bCAkBS7o0XejrzzSOk29p7MgsUYsFwXLJPw "Octave – Try It Online")
A function that takes the string as input and prints all results.
**Explanation:**
```
hankel(a,shift(a,1)) % generate a matrix of n*n where n= length(s) and its rows contain incresing circulraly shifted s
x=... -39 % convert matrix of "(" and ")" to a mtrix of 1 and 2
")("(x ) % switch the parens
2*x'-3 % convert [1 2] to [-1 1]
cumsum( ) % cumulative sum along the rows
all( >=0)' % if all >=0
( ,:) % extract the desired rows
```
[Answer]
# Mathematica, 78 bytes
```
""<>{"(",")"}[[2ToCharacterCode@#-81//.x_/;Min@Accumulate@x<0:>RotateLeft@x]]&
```
[Answer]
## JavaScript (ES6), 97 bytes
```
f=(s,t=s,u=t.replace(')(',''))=>u?t==u?f(s.slice(1)+s[0]):f(s,u):s.replace(/./g,c=>c<')'?')':'(')
```
Works by recursively rotating the input string until its transpose is balanced, then transposing it.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~35~~ 30 bytes
*Golfed a new approach thanks to @Adám*
```
1⌽⍣{2::0⋄1∊⍎⍕1,¨⍺}')('['()'⍳⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKPd8b/ho569j3oXVxtZWRk86m4xfNTR9ai371HvVEOdQyse9e6qVdfUUI9W19BUf9S7@VHf1FiQtv@OXOoaGpoamprqXFAmkI3gQjhAPQA "APL (Dyalog Unicode) – Try It Online")
Golfing is in progress.
### Explanation
```
'()'⍳⎕ Find the index of each character of the input in the string '()'
(this is 1-indexed, so an input of '(())()' would give 1 1 2 2 1 2)
')('[...] Find the index of the vector in the string ')('
This essentially swaps ')'s with '('s and vice versa
⍣ On this new string, do:
1⌽ rotate it one to the left
Until this results in 1:
1,¨⍺ Concatenate each element of the argument with a 1
This inserts 1 one before each parenthesis
⍕ Stringify it
⍎ And evaluate it, if the parentheses are balanced, this produces no errors
1∊ Check if 1 belongs to evaluated value
If the parentheses were not matches during ⍎, this causes a syntax error
2::0 This catches a syntax error and returns 0
Essentially this code checks if the brackets are balanced or not
```
[Answer]
# [Python 2](https://docs.python.org/2/), 99 bytes
```
r=[0];S=''
for c in input():b=c>'(';r+=[r[-1]+2*b-1];S+=')('[b]
n=r.index(min(r))
print S[n:]+S[:n]
```
[Try it online!](https://tio.run/##DcWxCgIxDADQvV/RLYlF0Rtb4k90DF16KnYwV0IP9OvrwYPXf@O96TKnsVxLygzgXpv51Tc99H0gxcrrHRCSBRaT862E5VSPUg4MhCC1OGW7NH08v/hpikbkujUdPovGErJELXMCIiER/AE "Python 2 – Try It Online")
## In function form for easy test cases:
## [Python 2](https://docs.python.org/2/), 108 bytes
```
def f(s):
r=[0];S=''
for c in s:b=c>'(';r+=[r[-1]+2*b-1];S+=')('[b]
n=r.index(min(r))
return S[n:]+S[:n]
```
[Try it online!](https://tio.run/##TY69DoJAEIT7e4rtdlfQKOWRo@QFrrxcw1@8woUsmOjTI0hMrGa@Zr6Z3st9lGJdu36AgWa2BtSFayy9QzQwjAotJIHZNq6tkLDUzAUN51vMilOzRekzh0wYmmhAnF6SdP2LHklImbe5fnmqgA9iY@aDlfiV1Yds0iQLzDm6CvP9gDE1IRETM/Kvb/DHB9HO6wc "Python 2 – Try It Online")
This uses a slightly different approach - instead of recursively rotating the string, if we think of the parens as incrementing and decrementing some balance counter, then a balanced string must never have a total sum of increments - decrements that is less than 0.
So we take
```
(()(())())
```
invert the parens:
```
))())(()((
```
and convert it to a list of sums of increments/decrements:
```
[-1,-2,-1,-2,-3,-2,-1,-2,-1,0]
```
-3 is the minimum at index 4 (zero based); so we want to shift by that index+1. This guarantees that the cumulative increment/decrement will never be less than 0; and will sum to 0.
[Answer]
## Clojure, 118 bytes
```
#(loop[s(map{\(\)\)\(}%)](let[s(conj(vec(rest s))(first s))](if(some neg?(reductions +(map{\( 1\) -1}s)))(recur s)s)))
```
Returns a sequence of characters, so I'd call it like this:
```
(apply str (f "(()(())())"))
; "(()(())())"
```
First flips brackets, then loops as long as the cumulative sum of bracket count goes negative at some point of the sequence.
[Answer]
# [brainfuck](https://github.com/TryItOnline/tio-transpilers), 82 bytes
```
,[++[->->++<<]-[--->+>-<<]>-->+[-[-<<+>>>>+<<]],]+[<<]>>>[.[-]>>]<[<<]<[<<]>>[.>>]
```
[Try it online!](https://tio.run/##JYlBCoBADAO/s0s3@4LSj4QeVBBE8CD4/tpqKGQ6We/luPZnOyMGRQiDiag6CCQakq2IaVTFMrX7cGFtZpxEtmv9@kvOFBGttd6/ewE "brainfuck – Try It Online")
### Explanation
With each character read, a counter is modified as follows:
* The counter starts at 0.
* After each `)`, the counter increases by 1.
* After each `(`, the counter decreases by 1, unless the counter was 0, in which case the counter is unchanged.
Each prefix is a valid suffix of a balanced string (after inversion) if and only if this counter is 0. This code uses the longest such prefix to form the output.
```
,[ Take input and start main loop
The cell one space right is the output cell (0 at this point),
and two spaces right is a copy of the previous counter value
++ Add 2 to input
[->->++<<] Negate into output cell, and add twice to counter
-[--->+>-<<] Add 85 to output cell, and subtract 85 from counter
>-->+ Subtract 2 from output cell and add 1 to counter
The output cell now has (81-input), and the counter has been increased by (2*input-80)
[-[-<<+>>>>+<<]] If the counter is nonzero, decrement and copy
,]
+[<<] Go to the last position at which the counter is zero
>>> Go to following output character
[.[-]>>] Output from here to end, clearing everything on the way
(Only the first one needs to be cleared, but this way takes fewer bytes)
<[<<] Return to the same zero
<[<<]>> Go to beginning of string
[.>>] Output remaining characters
```
] |
[Question]
[
Your task is to create a program or function that generates a zipper with a length of 10 lines. Each line of the zipper is represented by two dashes `--`:
```
--
--
--
--
--
--
--
--
--
--
```
The program/function will take a percentage (divisible by 10) as input, and the output will be the zipper "unzipped" (dashes separated) from the top by the percentage, revealing the 1-indexed, lowest level repeated 2 times, with all prior levels repeated 4, 6, 8, ...etc. times, while keeping the bottom of the zipper centered.
### Examples
```
>>10%
-11-
--
--
--
--
--
--
--
--
--
>>50%
-1111111111-
-22222222-
-333333-
-4444-
-55-
--
--
--
--
--
>>100%
-11111111111111111111-
-222222222222222222-
-3333333333333333-
-44444444444444-
-555555555555-
-6666666666-
-77777777-
-888888-
-9999-
-10-
```
The input (percentage) can be formatted however you like (50%, .5, 50, 5 [zero implied], etc), and it will always be in the range of 0 to 100 and divisible by 10. The spacing in the examples must be preserved in your output.
[Answer]
# Python 2 - ~~184~~ ~~151~~ 146 Bytes
```
def r(n):
n/=10
for i in range(1,11):
if n<0:print"%s--"%p
elif i>9:print" %s-10-"%p
else:p=" "*~-i;print"%s-%s-"%(p,`i`*2*n);n-=1
```
The last number kinda messed with me a little. I might be able to remove the second if statement if I look at it later.
EDIT: Thx to mbomb007 for removing 3 bytes. Thanks to charredgrass for the formatting tips to help remove lots and lots of bytes! :-D Thanks to TheBikingViking for helping with yet another two bytes!
[Answer]
# Python 2, 74 bytes
```
n=input()
x=0
exec"print' '*x+'-'+`x+1`*(n-x<<1-x/9)+'-';x=min(x+1,n);"*10
```
Saved two bytes by `exec`-ifying a loop, thanks to Dennis.
EDIT: I took a slightly different approach and saved two more bytes.
[Answer]
## PowerShell v2+, ~~130~~ ~~120~~ ~~116~~ 110 bytes
```
param($n)$i=0;10..1|%{" "*$i+(("-"+("$($i+1)"*([math]::Max($n-10+$_,0))*2)),"-10")[$n-$_-eq9]+"-";$i+=$i-ne$n}
```
Edit 1 - Golfed 10 bytes by eliminating `$x` variable and slightly redoing how the string is formulated.
Edit 2 - Golfed another 4 bytes by redoing how input happens and by redoing how `$i` is calculated each loop.
Edit 3 - Saved 6 bytes by OP allowing input as `0..10`, so no need to divide by 10.
Surprisingly difficult!
Takes input as `1`,`5`, etc., stored in `$n`. Sets helper `$i` variable (one of the very rare times that a variable needs to be initialized to `0` in PowerShell), and then starts a loop from `10` to `1`.
Each iteration, we set start our string with a number of spaces equal to `$i`, followed by a pseudo-ternary `(... , ...)[]`. Inside the pseudo-ternary, we select a string of either `-` with a number of digits (the higher of `$n-10+$_` or `0`, multiplied by 2), or the string `-10` -- the selection is based on whether we're at the 10th iteration and our input was `100`. We concatenate that with a final `-`. That resultant string is placed onto the pipeline.
Finally, we increment `$i`, and this was really tricky. We wound up using a binary-cast-to-int trick to only increment `$i` up until it reaches `$n`, and then keeping it at the same value thereafter. This ensures we've reached the "end" of the zipper indentation at the appropriate level.
Once the loop has finished, the resultant strings are all accumulated on the pipeline and output is implicit.
### Examples
```
PS C:\Tools\Scripts\golfing> .\unzip-some-numbers.ps1 70
-11111111111111-
-222222222222-
-3333333333-
-44444444-
-555555-
-6666-
-77-
--
--
--
PS C:\Tools\Scripts\golfing> .\unzip-some-numbers.ps1 100
-11111111111111111111-
-222222222222222222-
-3333333333333333-
-44444444444444-
-555555555555-
-6666666666-
-77777777-
-888888-
-9999-
-10-
```
[Answer]
# Pyth, ~~37~~ 34 bytes
```
~~=h/QTjm+\*;thS,dQj<\*`d20eS,0y-Qd"--"ST~~
=h/QTjm+*;thS,dQj*`d/y-Qdl`d"--"ST
```
[Test suite.](http://pyth.herokuapp.com/?code=%3Dh%2FQTjm%2B%2a%3BthS%2CdQj%2a%60d%2Fy-Qdl%60d%22--%22ST&test_suite=1&test_suite_input=10%0A50%0A100&debug=0)
[Answer]
# Python, ~~95~~ 84 bytes
I wasn't aware lambdas were legal, thanks @Dr Green Eggs and Iron Man
```
lambda p:'\n'.join(' '*min(p,l)+'-'+(2-(l==9))*(p-l)*str(l+1)+'-'for l in range(10))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~48~~ ~~41~~ 35 bytes
```
0:9"@GhX<Z"45h@QVG@-E@8>-OhX>Y"h45h
```
[**Try it online!**](http://matl.tryitonline.net/#code=MDo5IkBHaFg8WiI0NWhAUVZHQC1FQDg-LU9oWD5ZImg0NWg&input=Nw)
[Answer]
# Ruby, 74 bytes
Uses the implied-zero format specified in the question, so `40%` is `f[4]` if the anonymous function is assigned to `f`. If a full percentage is needed, +6 bytes for `n/=10;`
[Try it online!](https://repl.it/CbNa)
```
->n{10.times{|i|puts' '*[i,n].min+"-#{i>8?10:(i+1).to_s*2*(n-i)if i<n}-"}}
```
[Answer]
# Python 3, ~~98, 90, 87~~, 85 bytes.
Takes the number already divided by 10. I can probably remove some of the parens, but this is pretty closed to fully golfed.
```
lambda n:'\n'.join(' '*min(i,n)+'-%s-'%(str(i+1)*(n>i>8or(n-i)*2))for i in range(10))
```
[Answer]
# Haskell, 83 bytes
```
f n=unlines[[[1..y]>>" ",take(2*(n-y))$cycle$show$y+1]>>=(++"-")|y<-min n<$>[0..9]]
```
[Answer]
# Javascript es7, 105 bytes
```
A=>[...Array(10)].map((a,i)=>' '.repeat((d=A<i)?A:i)+('-'+(i+1+'').repeat(d?0:i<9?2*(A-i):1)+'-')).join`
`
```
---
call with
```
f=A=>[...Array(10)].map((a,i)=>' '.repeat((d=A<i)?A:i)+('-'+(i+1+'').repeat(d?0:i<9?2*(A-i):1)+'-')).join`
`
f(10)
f(5)
f(0)
```
[Answer]
# Python 2.7, 113 108 77 bytes
n=input()
for x in range(0,10):
v=str(x+1)\*(n-x)*2
if x*n>89:v='10'
print' '\*min(x,n)+'-'+v+'-'
First time playing golf. Gonna keep going, try to get it <100.
Assumes input is 1-10.
Edit:
Used some tricks from @LeakyNun 's answer (thanks), then crunched it a bit further and got... basically the same answer :/ Didn't know about the `int` string conversion, and 2 - boolean let me get rid of the if statement, which let me get rid of the whole v variable. Very cool.
My version:
```
n=input()
for x in range(10):print' '*min(x,n)+'-'+`x+1`*(n-x)*(2-(x>8))+'-'
```
[Answer]
# Python 2, 81 bytes
```
n=input()/10
for i in range(10):print(' '*min(i,n)+'-'+2*(n-i)/-~(i>8)*`i+1`+'-')
```
[Ideone it!](http://ideone.com/D31bJy)
[Answer]
# Python 2.7, ~~110~~ ~~99~~ ~~95~~ 91 bytes:
```
G=input();i=1;exec"print' '*[~-i,G][i>G]+'-%s-'%[`i`*(2*-~G-i*2),'10'][(i>9)*G>9];i+=1;"*10
```
A full program that takes input by an integer in the inclusive range `[1,10]`, where `10` means `100%` and `1` means `10%`. Can probably be golfed down a bit more.
[Try It Online! (Ideone)](http://ideone.com/qg7Y0p)
[Answer]
# PHP 5.3, ~~92~~ 91 bytes
```
<?for(;$i<10;$i++)echo'
'.str_pad('-'.str_repeat($i+1,$n>9&&$i>8?:($n-$i)*2).'-',22,' ',2);
```
* for PHP 5.3 with `register_globals=1` and `short_open_tags=1` (and `error_reporting=0`)
call in cli with `php-cgi -f <filename> n=<number>`
* number from 0 to 10
* to call in web browser with `<scriptpath>?n=<number>`: prepend `<pre>`
* for 4.0.1 < PHP < 5.3: replace `?:` with `?1:` (+1)
* for PHP>=5.4: replace the first `$n` with `($n=$_GET[n])` (+11)
**ungolfed as a function** (any PHP>=4.0.1)
```
function unzip($n) // $n from 0 to 10
{
for($i=0;$i<10;$i++) // $i = line number -1
$s.='
'.str_pad( // pad the result of the following on both sides
'-'. // prepend '-'
str_repeat($i+1, // print line number
($n>9&&$i>8 ? 1 // in tenth line, if $n is 10: once
: ($n-$i)*2) // else 2*($n-$i) times
).'-' // append '-'
, 22,' ', STR_PAD_BOTH); // pad to 22 width with SPC on both sides
return $s;
}
```
**test suite**
```
echo'<table border=1><tr>';
for($i=0;$i<11;$i++)echo'<th>',$i*10,'%</th>';
echo'</tr><tr>';
for($i=0;$i<11;$i++)echo'<td><pre>', unzip($i), '</pre></td>';
echo '</table>';
```
Now this is new to me: PHP beats JavaScript.
This approach is golfed to the min, I think.
[Answer]
# Julia, 73 bytes
```
x->join([" "^min(x,a)*"-$("$(a+1)"^(x>a?a>8?1:2(x-a):0))-"for a=0:9],'
')
```
First Julia answer! Tips are appreciated.
[Try it online!](http://julia.tryitonline.net/#code=W3ByaW50KCh4LT5qb2luKFsiICJebWluKHgsYSkqIi0kKCIkKGErMSkiXih4PmE_YT44PzE6Mih4LWEpOjApKS0iZm9yIGE9MDo5XSwnCicpKShpKSoiCgoiKWZvciBpPTA6MTBd&input=)
[Answer]
# Perl, 122 bytes
```
$k=<>;for(my $i=0;$i++<10;){$s="-"."$i"x($k/10-$i+1);$p=length $s;$l=$l>$p?$l:$p;printf "%${l}s%s\n",$s,scalar reverse $s}
```
[Answer]
## Common Lisp (Lispworks), 314 bytes
```
(defun f()(let((s(string(read))))(let((n(/(parse-integer(subseq s 0(1-(length s))))10)))(if(> n 0)(progn(dotimes(r n)(progn(dotimes(c r)#1=(format t" "))(format t"-")(if(=(1+ r)10)(format t"10")(dotimes(j(* 2(- n r)))(format t"~S"(1+ r))))(format t"-~%")))(dotimes(d(- 10 n))(dotimes(c n)#1#)(format t"--~%")))))))
```
ungolded:
```
(defun f ()
(let ((s (string (read))))
(let ((n (/ (parse-integer (subseq s 0 (1- (length s)))) 10)))
(if (> n 0)
(progn
(dotimes (r n)
(progn
(dotimes (c r)
(format t " "))
(format t "-")
(if (= (1+ r) 10)
(format t "10")
(dotimes (j (* 2 (- n r)))
(format t "~S" (1+ r))))
(format t "-~%")))
(dotimes (d (- 10 n))
(dotimes (c n)
(format t " "))
(format t "--~%")))))))
```
Usage:
```
CL-USER 2515 > (f)
10%
-11-
--
--
--
--
--
--
--
--
--
NIL
CL-USER 2516 > (f)
50%
-1111111111-
-22222222-
-333333-
-4444-
-55-
--
--
--
--
--
NIL
CL-USER 2517 > (f)
100%
-11111111111111111111-
-222222222222222222-
-3333333333333333-
-44444444444444-
-555555555555-
-6666666666-
-77777777-
-888888-
-9999-
-10-
NIL
```
[Answer]
## APL, 46 bytes
```
{↑(⍳10){(''↑⍨1-⍺⌊a+1),1⌽'--',⍵⍴⍕⍺}¨10↑2×⌽⍳a←⍵}
```
The argument should be given as the percentage divided by 10 (that is: a simple integer, in the range [0,10]).
] |
[Question]
[
A divisor of a number *n* is any number that evenly divides *n*, including 1 and *n* itself. The number of divisors *d(n)* is how many divisors a number has. Here's *d(n)* for the first couple n:
```
n divisors d(n)
1 1 1
2 1, 2 2
3 1, 3 2
4 1, 2, 4 3
5 1, 5 2
6 1, 2, 3, 6 4
```
We can repeatedly subtract the number of divisors from a number. For example:
```
16 = 16
16 - d(16) = 16 - 5 = 11
11 - d(11) = 11 - 2 = 9
9 - d( 9) = 9 - 3 = 6
6 - d( 6) = 6 - 4 = 2
2 - d( 2) = 2 - 2 = 0
```
In this case it took 5 steps to get to 0.
---
Write a program or function that given a nonnegative number *n* returns the number of steps it takes to reduce it to 0 by repeated subtraction of the number of divisors.
Examples:
```
0, 0
1, 1
6, 2
16, 5
100, 19
100000, 7534
```
[Answer]
# C, 52 bytes
```
g,o;l(f){for(g=o=f;o;f%o--||--g);return f?1+l(g):0;}
```
[Answer]
# Python, 49 bytes
```
f=lambda n:n and-~f(sum(n%~x<0for x in range(n)))
```
orlp helped save a byte! And Sp3000 saved two more. Thanks!
[Answer]
# Pyth, 10 bytes
```
tl.ulf%NTS
```
[Test suite.](http://pyth.herokuapp.com/?code=tl.ulf%25NTS&test_suite=1&test_suite_input=0%0A1%0A6%0A16%0A100&debug=0)
## Explanation
```
tl.ulf%NTS
tl.ulf%NTSNQ implicit variables at the end
Q obtain the input number
.u N repeat the following until result no longer unique:
S generate range from 1 to N
f filter for:
%NT T in that range, which N%T is truthy (not zero)
l length of that list
that means, we found the number of "non-divisors" of N
tl number of iterations, minus 1.
```
[Answer]
## Julia, 31 bytes
```
f(n)=n<1?0:f(sum(n%(1:n).>0))+1
```
Straightforward recursive implementation.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
`t~?x@q.]t:\zT
```
[**Try it online!**](http://matl.tryitonline.net/#code=YHR-P3hAcS5ddDpcelQ&input=MTAw)
### Explanation
```
` T % Infinite loop
t~? ] % Duplicate number. Is it non-zero?
x@q. % If so: delete number, push iteration index minus 1, break loop
t:\ % Duplicate, range, modulo (remainder). Divisors give a 0 remainder
z % Number of non-zero elements; that is, of non-divisors
```
[Answer]
## JavaScript (ES6), ~~64~~ 51 bytes
```
f=n=>n&&[...Array(m=n)].map((_,i)=>m-=n%++i<1)|f(m)+1
```
Don't ask me why I was unnecessarily using tail recursion.
[Answer]
# Java, ~~147~~ 93
```
a->{int k,i,n=new Integer(a),l=0;for(;n!=0;n-=k)for(l+=k=i=1;i<n;)if(n%i++==0)++k;return l;}
```
[Answer]
## [Hoon](https://github.com/urbit/urbit), ~~93~~ 76 bytes
```
|=
r/@
?~
r
0
+($(r (sub r (lent (skim (gulf 1^r) |=(@ =(0 (mod r +<))))))))
```
Ungolfed:
```
|= r/@
?~ r
0
=+ (skim (gulf 1^r) |=(@ =(0 (mod r +<))))
+($(r (sub r (lent -))))
```
Returns a function that takes an atom, `r`. Create an intermediate value that contains all the devisors of `r` (Make list [1..n], keep only the elements where (mod r i) == 0). If `r` is zero return zero, else return the incremented value of recursing with r equal r-(length divisors).
The code as-is takes a stupid amount of time to evaluate for n=100.000, entirely because finding the devisors for big numbers makes a giant list and maps over it. Memoizing the divisors gets the correct output for n=10.000, but I didn't bother waiting around for 100.000
[Answer]
# Jelly, ~~10~~ 9 bytes
1 byte thanks to [Dennis ♦](https://codegolf.stackexchange.com/users/12012/dennis).
Port of [my answer in Pyth](https://codegolf.stackexchange.com/a/80432/48934).
```
ÆDLạµÐĿL’
```
[Try it online!](http://jelly.tryitonline.net/#code=w4ZETOG6ocK1w5DEv0zigJk&input=&args=MTY)
[Test suite.](http://jelly.tryitonline.net/#code=w4ZETOG6ocK1w5DEv0zigJkKw4figqw&input=&args=MCwxLDYsMTYsMTAw)
## Explanation
```
_ÆDL$$ÐĿL’
ÐĿ Repeat the following until result no longer unique:
ÆD Yield the array of the divisors
L Yield the length of the array
_ Subtract that from the number
L Number of iterations
’ Minus one.
```
[Answer]
## 05AB1E, ~~12~~ 10 bytes
**Code:**
```
[Ð>#Ñg-¼]¾
```
**Explanation:**
```
[ # start infinite loop
Ð # triplicate current number
># # increase by 1 and break if true
Ñg # get number of divisors
- # subtract number of divisors from number
¼ # increase counter
] # end loop
¾ # print counter
```
[Try it online](http://05ab1e.tryitonline.net/#code=W8OQPiPDkWctwrxdwr4&input=MTY)
Edit: 2 bytes saved and a bug with input 0 fixed thanks to @Adnan
[Answer]
## R, 50 bytes
Pretty simple implementation. [Try it online](http://www.r-fiddle.org/#/fiddle?id=QzLqOkKe)
```
z=scan();i=0;while(z>0){z=z-sum(z%%1:z<1);i=i+1};i
```
[Answer]
# Mathcad, [tbd] bytes
[](https://i.stack.imgur.com/FNaKQ.jpg)
---
Mathcad byte equivalence scheme is yet to be determined. Using a rough keystroke equivalence, the program uses about 39 "bytes". Note that the while and for programming operators only take one keyboard operation each to input (ctl-] and ctl-shft-#, respectively) - indeed, they can only be entered this way from the keyboard.
What you see is exactly what gets put down on a Mathcad worksheet. Mathcad evaluates the equations/programs and puts the output on the same sheet (eg, after the '=' evaluation operator or on the plot).
[Answer]
# MATL, 13 bytes
```
tX`t:\ztt]Nq&
```
[Try it online](http://matl.tryitonline.net/#code=dFhgdDpcenR0XU5xJg&input=MTAw)
Explanation:
```
t % Duplicate input
X` ] % while loop, consumes 1 input
t:\z % calculates n-d(n), by counting number non-divisors
tt % dupe twice, for while loop condition, next iteration and to keep in stack
Nq& % get stack size, decrement, display that value
```
[Answer]
## Mathematica, 35 bytes
```
If[#<1,0,#0[#-0~DivisorSigma~#]+1]&
```
Making use of good old `DivisorSigma`. @MartinBüttner notes the following alternatives:
```
If[#<1,0,#0[#-DivisorSum[#,1&]]+1]&
f@0=0;f@n_:=f[n-DivisorSum[n,1&]]+1
```
[Answer]
## Haskell, ~~43~~ ~~40~~ 39 bytes
```
g 0=0;g n=1+g(sum$min 1.mod n<$>[1..n])
```
Simple recursive approach. Usage example: `g 16` -> `5`.
Edit: @Lynn saved ~~3~~ 4 bytes. Thanks!
[Answer]
## PowerShell v2+, ~~74~~ 67 bytes
```
param($n)for($o=0;$n-gt0){$a=0;1..$n|%{$a+=!($n%$_)};$n-=$a;$o++}$o
```
Seems pretty lengthy in comparison to some of the other answers...
Takes input `$n`, enters a `for` loop with the condition that `$n` is greater than `0`. Each loop iteration we set helper `$a`, then loop through every number from `1` up to `$n`. Each inner loop we check against every number to see if it's a divisor, and if so we increment our helper `$a` (using Boolean negation and implicit cast-to-int). Then, we subtract how many divisors we've found `$n-=$a` and increment our counter `$o++`. Finally, we output `$o`.
Takes a *long* time to execute, since it's a significant for-loop construct. For example, running `n = 10,000` on my machine (1yr old Core i5) takes almost 3 minutes.
[Answer]
# Racket - 126 bytes Down to 98 bytes 91 bytes
An extremely naive solution - could probably be cut down a lot with a decent algorithm and some lisp tricks that I don't know
```
(define(g x[c 0][d 0][i 2])(cond[(= x 0)c][(= i x)(g d(+ 1 c))][(=(modulo x i)0)(g x c d(+ 1 i))][else(g x c(+ 1 d)(+ 1 i))]))
```
Edit: explanation by request. As I said, this is an extremely naive recursive solution and can be much much shorter.
```
(define (g x [c 0] [d 0] [i 2]) ;g is the name of the function - arguments are x (input), c (counter for steps), d (non-divisor counter), i (iterator)
(cond
[(= x 0) c] ;once x gets to 0 c is outputted
[(= i x) (g d (+ 1 c))] ;if iterator reaches x then we recurse with d as input and add 1 to c
[(= (modulo x i) 0) (g x c d (+ 1 i))] ;checks if iterator is non divisor, then adds it to d and increments iterator
[else(g x c (+ 1 d) (+ 1 i))])) ;otherwise just increments iterator
```
Edit 2: 98 byte version with a less dumb algorithm (still pretty dumb though and can be shorter)
```
(define(g x)(if(< x 1)0(+ 1(g(length(filter(λ(y)(>(modulo x y)0))(cdr(build-list x values))))))))
```
Explanation:
```
(define (g x) ;function name g, input x
(if (< x 1)
0 ;returns 0 if x < 1 (base case)
(+ 1 ;simple recursion - adds 1 to output for each time we're looping
(g (length ;the input we're passing is the length of...
(filter (λ (y) (> (modulo x y) 0)) ;the list where all numbers which are 0 modulo x are 0 are filtered out from...
(cdr (build-list x values)))))))) ;the list of all integers up to x, not including 0
```
Edit 3: Saved 7 bytes by replacing `(cdr(build-list x values))` with `(build-list x add1)`
```
(define(g x)(if(< x 1)0(+ 1(g(length(filter(λ(y)(>(modulo x y)0))(build-list x add1)))))))
```
[Answer]
# APL, 22 bytes
```
{2>⍵:⍵⋄1+∇⍵-0+.=⍵|⍨⍳⍵}
```
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 52+2 = 54 bytes
The input number needs to be present on the stack at program start, so there's +2 bytes for the `-v` flag. [Try it online!](http://fish.tryitonline.net/#code=OjApP3Z-bG47Pn4kLV0KMDNbfVw6OgpAQDokPCAgICB2Pz0wOi0xfSt7fiQ_QEAwMSVAOg&input=&args=LXYgMTAw)
```
:0)?v~ln;>~$-]
03[}\::
@@:$< v?=0:-1}+{~$?@@01%@:
```
4 annoying bytes wasted on alignment issues. Bah.
This one works by building the sequence from `n` to `0` on the stack. Once 0 has been reached, pop it and ouput the length of the remaining stack.
By the way , it runs in `O(n^2)` time, so I wouldn't try `n = 100000`...
[Answer]
## [><>](http://esolangs.org/wiki/Fish), 36 + 3 = 39 bytes
```
:?v~ln; >~&
:}\0&
+&>1-:?!^:{:}$%0)&
```
The implementation's relatively straightforward, with each iteration being `sum(n%k>0 for k in range(1,n-1))`. +3 bytes for the `-v` flag, per [meta](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions).
[Try it online!](http://fish.tryitonline.net/#code=Oj92fmxuOyA-fiYKOn1cMCYKKyY-MS06PyFeOns6fSQlMCkm&input=&args=LXY+MTAw)
[Answer]
# Ruby, 42 bytes
```
f=->n{n<1?0:1+f[n-(1..n).count{|i|n%i<1}]}
```
There's a stack overflow error on the largest test case `100000`, so here's an iterative version within **49 bytes**. Takes a while, though, considering the `O(N^2)` complexity.
```
->n{c=0;c+=1 while 0<n-=(1..n).count{|i|n%i<1};c}
```
[Answer]
# Perl 5, 40 bytes
```
sub f{@_?(1,f((1)x grep@_%$_,1..@_)):()}
```
Input and output are as lists of the requisite number of copies of `1`.
[Answer]
# C#, 63 bytes
```
int F(int n)=>n<1?0:F(Enumerable.Range(1,n).Count(i=>n%i>0))+1;
```
[Answer]
## Actually, 17 bytes
```
";╗R`╜%`░l;"£╬klD
```
Try it online! (note: last test case times out on TIO)
Explanation:
```
";╗R`╜%`░l;"£╬klD
" "£╬ while top of stack is truthy, call the function:
;╗ push a copy of n to reg0
R range(1,n+1) ([1,n])
` `░l push the number of values where the following is truthy:
╜% k mod n
(this computes the number of non-divisors of n)
; make a copy
klD push entire stack as list, count number of items, subtract 1
(the result is the number of times the function was called)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
←LU¡Ṡ-oLḊ
```
[Try it online!](https://tio.run/##yygtzv7//1HbBJ/QQwsf7lygm@/zcEfX////Dc0A "Husk – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
©ÒßU-â l
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qdLfVS3iIGw&input=MTAw)
Or 9 bytes without recursion:
```
©@µâ l}f1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=qUC14iBsfWYx&input=MTAwMDAw)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `l`, 5 bytes
```
≬KL-İ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJsIiwiIiwi4omsS0wtxLAiLCIiLCIxMDAiXQ==)
Flagless:
# [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes
```
≬KL-İL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiaxLTC3EsEwiLCIiLCIxMDAiXQ==)
] |
[Question]
[
In this code golf, you need to get the closest number from another one in a list.
The output may be the closest number to the input.
Example:
```
value: (Input) 5 --- [1,2,3] --- 3
```
And, the program may work with negative numbers.
Example:
```
value: (Input) 0 --- [-1,3,5] --- -1
value: (Input) 2 --- [1, 5, 3] --- 1 (Because it gives priority to lower numbers)
```
**RULES:**
As mentioned before, it has to work with negative numbers.
If there are two answers (Example: 0 -- [5,-5]), the program gives priority to the lowest number. (-5)
This is code golf so the shortest code wins!
[Answer]
# Pyth, 6 bytes
```
haDQSE
```
[Test suite](https://pyth.herokuapp.com/?code=haDQSE&test_suite=1&test_suite_input=5%0A1%2C2%2C3%0A0%0A-1%2C3%2C5%0A2%0A1%2C5%2C3%0A4%0A1%2C5%2C3&debug=0&input_size=2)
Input in the following form on STDIN:
```
num
array
```
Explanation:
```
haDQSE
Implicit: Q = eval(input()) (num)
E Evaluate input (array)
S Sort (smaller values to the front)
aDQ Sort by absolute difference with Q.
h Take the first element of the sorted list, the min.
Print implicitly.
```
[Answer]
## Ruby, 34 bytes
```
->n,a{a.sort.min_by{|x|(n-x).abs}}
```
```
a.sort min_by tiebreaks by position in array, so put smaller numbers 1st
.min_by{|x| select the element which returns the smallest val for predicate...
(n-x).abs} (absolute) difference between input num and element
```
[Answer]
# Mathematica, 12 bytes
```
Min@*Nearest
```
Built-ins FTW! Buettner's explanation: "Mathematica has a built-in `Nearest` for this, but it returns a list of all tied numbers. Hence, we need to compose it with `Min` to break the tie."
[Answer]
# Pyth, 8 bytes
```
hS.mabQE
```
Explanation
```
- autoassign Q = eval(input())
.m E - min_values([V for b in eval(input())])
abQ - abs(b-Q)
S - sorted(^)
h - ^[0]
```
[Try it online!](http://pyth.herokuapp.com/?code=hS.mabQE&input=2%0A%5B3%2C+1%5D&debug=0)
[Answer]
## JavaScript ES6, ~~64~~ ~~56~~ 54 bytes
```
(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0]
```
[Try it online](http://vihan.org/p/esfiddle/?code=f%3D(i%2Ca)%3D%3Ea.sort((a%2Cb)%3D%3Es(i-a)-s(i-b)%7C%7Ca-b%2Cs%3DMath.abs)%5B0%5D%0A%0Af(2%2C%20%5B1%2C5%2C3%5D))
Thanks to [@Niel](https://codegolf.stackexchange.com/users/17602/neil) for saving two bytes
Test Snippet:
```
f=(i,a)=>a.sort((a,b)=>s(i-a)-s(i-b)||a-b,s=Math.abs)[0];
[
[5, [1, 2, 3]],
[2, [3, 5, 1]],
[2, [1, 3, 5]],
[0, [-1, 2, 3]],
[5, [1, 2, 3]]
].map(v=>O.textContent+=JSON.stringify(v)+": "+f.apply(null,v)+"\n")
```
```
<pre id=O></pre>
```
[Answer]
# Jelly, ~~7~~ 6 bytes
```
ạżṛỤḢị
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqhxbzhuZvhu6ThuKLhu4s&input=&args=Mg+WzEsIDUsIDNd)
### How it works
```
ạżṛỤḢị Main link. Left input: n (number). Right input: A (list)
ạ Take the asbolute difference of n and the items of A.
ṛ Yield the right argument, A.
ż Zip the left result with the right one.
This pairing causes ties in absolute value to be broken by initial value.
Ụ Grade up; sort the indices of the resulting list by their associated values.
Ḣ Retrieve the first index, which corresponds to the smallest value.
ị Retrieve the item of A at that index.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ạÐṂṂ
```
[Try it online!](https://tio.run/##y0rNyan8///hroWHJzzc2QRE/w8vV/r/P9pQx0jHOFZHIVrXUMdYxxTEMtQxhQjBGaY6uqax/011FAx0FIx0FHQNjYyBbAA "Jelly – Try It Online")
This takes `A` on the left and `n` on the right
I'm guessing the `ÐṂ` builtin didn't exist when Dennis wrote [his answer](https://codegolf.stackexchange.com/a/72062/66833).
## How it works
```
ạÐṂṂ - Main link. Takes A on the left and n on the right
ÐṂ - Keep elements of A with a minimal:
ạ - Absolute difference with n
Ṃ - Take the minimum
```
[Answer]
# [R](https://www.r-project.org/), 37 bytes
```
(x=scan())[order(abs(x-scan()),x)][1]
```
[Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DUzM6vygltUgjMalYo0IXKqZToRkbbRj731TBWMGQi8uI6z8A "R – Try It Online")
After 4 years, 5 bytes shorter than [the previous R answer](https://codegolf.stackexchange.com/a/73105/95126).
Uses the `order()` function with two arguments, to order first by the closeness to the target value, and then to break ties by the array value. Finally outputs the first element after re-ordering.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~17~~ 16 [bytes](https://github.com/abrudz/SBCS)
```
⊢{⌊/⍺/⍨⍵=⌊/⍵}∘|-
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HXoupHPV36j3p3AfGKR71bbSHcrbWPOmbU6P5Pe9Q24VFv36Ou5ke9ax71bjm03vhR28RHfVODg5yBZIiHZ/B/U4U0BUMFIwVjLgMg69B6QwVjBVMuI7CoKVAUxAKKKBgCAA "APL (Dyalog Unicode) – Try It Online")
This is a function which takes a single number as a left argument and a list of numbers as a right argument.
The general structure of this is a fork consisting of:
* the constant right function `⊢` returns the list of numbers
* `|-` calculates the absolute value of each difference between a number from the list and the left argument
* and the dfn `{⌊/⍺/⍨⍵=⌊/⍵}` which is called with the results of the other two functions:
```
⍝ ⍵: absolute differences (|-)
⍝ ⍺: the original list (⊢)
⌊/⍵ ⍝ the minimum of the absolute differences
⍵= ⍝ element-wise equal to the absolute differences
⍺/⍨ ⍝ select all values from the original list where this is 1
⌊/ ⍝ take the minimum
```
A fully tacit function came out at 17 bytes: [`⌊/∘∊((⊢=⌊/)∘|-)⊆⊢`](https://tio.run/##SyzI0U2pTMzJT////1FPl/6jjhmPOro0NB51LbIF8TWBAjW6mo@62oAi/9MetU141Nv3qKv5Ue@aR71bDq03ftQ28VHf1OAgZyAZ4uEZ/N9UIU3BUMFIwZjLAMg6tN5QwVjBlMsILGoKFAWxgCIKhgA).
---
With some help from [Adám](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m), here is a shorter function in the extended variant:
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 12 bytes
```
(⊃⍋⍤|⍤-⊇⊢)∘∧
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X@NRV/Oj3u5HvUtqgFj3UVf7o65Fmo86ZjzqWP4/7VHbhEe9fWAlax71bjm03vhR28RHfVODg5yBZIiHZ/B/U4U0BUMFIwVjLgMg69B6QwVjBVMuI7CoKVAUxAKKKBiC5Y2BKg0B "APL (Dyalog Extended) – Try It Online")
Same arguments as before, `∧` sorts the list ascending and `⊃⍋⍤|⍤-⊇⊢` is applied with the left number and the sorted list as a right argument.
```
- ⍝ the difference between the left argument and each list entry of the sorted list
| ⍝ take the absolute values
⍋ ⍝ the indices that would sort this list (stable)
⊇ ⍝ index with these indices into ...
⊢ ⍝ ... the sorted list. This resorts the list on the absolute difference
⊃ ⍝ pick the first value
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 10 bytes
```
Sti-|4#X<)
```
[**Try it online!**](http://matl.tryitonline.net/#code=U3RpLXw0I1g8KQ&input=WzUgLTVdCjA)
```
S % implicitly input array, and sort. This ensures smaller numbers have priority
t % duplicate
i % input number
-| % compute array of absolute differences
4#X< % arg min. If there are several minimizers, the position of the first is returned
) % index into original array. Implicitly display
```
[Answer]
## Python 2, 56 bytes
```
a=input()
print sorted(input(),key=lambda x:abs(a-x))[0]
```
Gets the target number first `a=input()` - this has to be stored in a variable.
It then sorts the input with the function `lambda x:abs(a-x)` applied (think `map(lambda x:abs(a-x), input())`)
It then takes the minimum value in case of any duplicate values
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÍñaV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=zfFhVg&input=WzUgLTVdCjA)
```
ÍñaV :Implicit input of array U and integer V
Í :Sort U
ñ :Sort by
aV : Absolute difference with V
:Implicit output of first element
```
[Answer]
# [Python 3](https://docs.python.org/3/), 41 bytes
```
lambda n,a:min((abs(n-i),i)for i in a)[1]
```
[Try it online!](https://tio.run/##HYtBCoRADATvviLHDkRwHOYi7EvcPURkMLBGUS/7@tHZY3VV779r2TyW/HqXr67TrOSiw2oO6HTCW2MxzttBRuakPIZPqfhkdUASBOklMguhE7RBoqQ/9VWlqoaGaD/ML2Q8R@ZyAw "Python 3 – Try It Online")
No need to sort, because `min` captures the lowest difference *and* the lowest value.
Also works in [Python 2](https://tio.run/##HYtBCoRADATvviLHDkRwRuYi7EvcPURkMLBGUS/7@tHZY3VV779r2TyW/HqXr67TrOSiw2oO6HTCW2MxzttBRuakPIZPqfhkdUASBInSMwuhE7RBekl/ilWlqoaGaD/ML2Q8R@ZyAw "Python 2 – Try It Online").
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes
```
◄≠⁰O
```
[Try it online!](https://tio.run/##yygtzv7//9H0lkedCx41bvD///@/0f9oUx1jHcNYAA "Husk – Try It Online")
```
◄ # element that minimizes
≠⁰ # difference to arg 1
O # applied to sorted elements
# (implicitly) of arg 2
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{I.x
```
[Try it online](https://tio.run/##yy9OTMpM/f@/2lOv4v//aFMdXVMdQ4NYLgMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmVBsr6SQmJeioGQPZDxqmwRkAAX/VxfrVfzX@R8dHW2oY6RjHKtjGqujEB2ta6hjDGIagHmGOqYgKSNkjq6hkTFEqSlCoamOLpgdCwA).
**Explanation:**
```
{ # Sort the first (implicit) input-list from lowest to highest
.x # Pop the list, and push the value closest
I # to the second input-integer
# (after which it is output implicitly as result)
```
This could have been 2 bytes (`.x`) if we were allowed to output the first instead of the lowest value in the list, if more than one is closest: [try it online](https://tio.run/##yy9OTMpM/f9fr@L/f11DI2OuaEMdUx3jWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WmWCvpJCYl6KgZA9kPGqbBGRUJvzXq/iv8z86OtpQx0jHOFbHNFZHITpa11DHGMQ0APMMdUxBUkbIHF1DI2OIUlOEQlMdXTA7FgA).
[Answer]
# TeaScript, 10 bytes
```
T#(y-l)a)░
```
TeaScript doesn't support array input so in the console run: `TeaScript("T#y-la)░", [[1, 2, 3], 1], {}, TEASCRIPT_PROPS)` to runthis.
## Explanation
```
T# // Sort input by...
(y-l)a // absolute difference with input
)░ // First item in array
```
[Answer]
# R, 42 bytes
```
x=sort(scan());x[which.min(abs(x-scan()))]
```
[Answer]
## Haskell, 38 bytes
```
e#l=snd$minimum$(zip=<<map(abs.(e-)))l
```
Usage example: `2 # [1,5,3]`-> `1`.
For each element in the input list `l` make a pair of the absolute difference of the element with the input number `e` and the element itself, e.g. `e=2`, `l=[1,5,3]` -> `[(1,1),(3,5),(1,3)]`. Find the minimum and discard the difference.
[Answer]
## zsh, ~~75~~ ~~73~~ ~~71~~ ~~70~~ 67 bytes
```
for n in ${@:2};{echo "$[$1-n] $n"}|tr -d -|sort -n|head -1|cut -f2
```
Expects input as command line arguments.
Note that the four spaces in the `echo` is actually supposed to be a tab, but Stack Exchange converts tabs to spaces in all posts.
Not Bash-compatible because of the `for` syntax.
```
for n in ${@:2}; for each argument except the first...
{echo "$[$1-n]\t$n"} output the difference from the first argument
and then the original number
|tr -d - poor man's abs()
|sort -n sort by first num (difference), tiebreaking by second num
(original value)
|head -1 take the thing that sorted first
|cut -f2 print field 2 (aka discard the difference)
```
Thanks to [dev-null](https://codegolf.stackexchange.com/users/48657/dev-null) for 2 bytes!
[Answer]
# [Perl 6](http://perl6.org), 31 bytes
```
{@^b.sort.sort((*-$^a).abs)[0]}
```
### Usage:
```
my &code = {@^b.sort.sort((*-$^a).abs)[0]}
say code 5, [1,2,3]; # 3
say code 0, [-1,3,5]; # -1
say code 2, [1, 5, 3]; # 1
say code 0, [5,-5]; # -5
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ôXêUe>┤
```
[Run and debug it](https://staxlang.xyz/#p=93588855653eb4&i=5,%5B1,2,3%5D%0A0,%5B-1,3,5%5D%0A2,%5B1,5,3%5D%0A0,%5B5,-5%5D&m=2)
[Answer]
# [PHP](https://php.net/), 62 bytes
```
foreach($a as $i){$s[$i]=abs($i-$n);}
asort($s);print key($s);
```
[Try it online!](https://tio.run/##HccxCoQwEAXQPqdI8YsEtNAts9GDiMUoSsJCHGZsZPHsEXzd48T1O3JigxI/wYAiidDluqb3oe6HbLQmB7KkFtn/oRPyHGlRh9yi@HAb0kNOB/WBJZfT/rbrXR2H@gA "PHP – Try It Online")
First PHP answer, please help!
*(Define the number and array in header section)*
[Answer]
# [T-SQL](https://docs.microsoft.com/en-us/sql/t-sql/language-reference?view=sql-server-ver15), 93 Bytes
```
SELECT MIN(B) FROM(SELECT B,abs(B-@v) AS C FROM @A) D WHERE C=(SELECT MIN(abs(B-@v)) FROM @A)
```
Example:
```
DECLARE @A TABLE(B INT);
DECLARE @v INT = 5;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3)) AS A(B);
SELECT MIN(B) -- 3. Finally, select the minimum list value from the rowset
FROM(
SELECT B,abs(B-@v) AS C -- 1. Get list value along with absolute value of the difference.
FROM @A
) D
WHERE C = (SELECT MIN(abs(B-@v)) -- 2. Filter for the smallest absolute difference.
FROM @A
)
```
[Answer]
# C# ~~61~~ 52 bytes
```
int v(int i,int[] a)=>a.Min(x=>(Math.Abs(i-x),x)).x;
```
Or function body only: 29 bytes.
] |
[Question]
[
### The Background
Folks were talking prime factorization in [chat](http://chat.stackexchange.com/transcript/240/15-17) and we found ourselves talking about repunits. [Repunits](https://en.wikipedia.org/wiki/Repunit) are a subset of the numbers known as repdigits, which are numbers consisting of only repeating digits, like `222` or `4444444444444444`, but repunits consist only of `1`.
The first couple repunits are therefore `1`, `11`, `111`, etc. These are referred to by *R*n, so *R*1=`1`, *R*2=`11`, etc., and are generated by the formula `R(n) = (10^n - 1)/9`, with `n > 0`.
Prime factorization of these repunit numbers follows sequence [A102380](https://oeis.org/A102380) in the OEIS. For example:
>
> R1 = 1
>
> R2 = 11
>
> R3 = 111 = 3 \* 37
>
> R4 = 1111 = 11 \* 101
>
> R5 = 11111 = 41 \* 271
>
> R6 = 111111 = 3 \* 7 \* 11 \* 13 \* 37
>
> R7 = 1111111 = 239 \* 4649
>
> ...
>
>
>
### The Challenge
Write a program or function which, when given an input integer *n* with `n >= 2` via [STDIN or equivalent](https://codegolf.meta.stackexchange.com/a/1326/42963), outputs or returns the [novel](http://www.oxforddictionaries.com/us/definition/american_english/novel#novel-2) prime factors for *R*n, in any convenient format. "Novel prime factors" here means all `x` where `x` is a prime factor of *R*n, but `x` is not a prime factor for any previous *R*k, with `1 <= k < n` (i.e., if we write the prime factors for all *R* in sequence, we've not seen `x` before).
### The Examples
```
Input: 6
Output: 7, 13
(because 3, 11, and 37 are factors of a smaller R_k)
Input: 19
Output: 1111111111111111111
(because R_19 is prime, so no other factors)
Input: 24
Output: 99990001
(because 3, 7, 11, 13, 37, 73, 101, 137, 9901 are factors of a smaller R_k)
Input: 29
Output: 3191, 16763, 43037, 62003, 77843839397
(because no factors of R_29 are also factors of a smaller R_k)
```
### The Extras:
* Your code can do anything or nothing if `n < 2`.
* You can assume a "reasonable" upper limit for `n` for testing and execution purposes -- your code will not be *expected* to output for `n = 10000000`, for example, but your algorithm should *work* for such a case if given unlimited computing power and time.
* [Here](http://stdkmd.com/nrr/repunit/) is a site dedicated to the factorizations of repunits for reference.
* I've not gone through the math, but I propose a hypothesis that every *n* has a distinct result for this algorithm -- that is, no *n* exists such that *R*n has no novel factors. ~~I'll offer a **250-point bounty** if someone proves or disproves that in their answer.~~ Thomas Kwa proposed an [elegant proof](https://codegolf.stackexchange.com/a/67111/42963), and I awarded the bounty.
[Answer]
# Proof that every repunit has a novel prime factor
Using [Zsigmondy's Theorem](https://en.wikipedia.org/wiki/Zsigmondy%27s_theorem), the proof is simple. From Wikipedia:
>
> In number theory, Zsigmondy's theorem, named after Karl Zsigmondy,
> states that if ***a > b > 0*** are coprime integers, then for any integer ***n
> ≥ 1***, there is a prime number ***p*** (called a primitive prime divisor) that
> divides ***an − bn*** and does not divide ***ak − bk*** for any positive integer ***k
> < n***, with the following exceptions: [things that don't apply here].
>
>
>
Consider the repunits times 9: that is, ***10n-1***. By Zsigmondy's Theorem with **a=10**, **b=1**, there is some prime ***p*** **|** ***10n-1*** that does not divide any ***10k-1***, ***k < n***.
* Since ***p*** is prime and ***10n-1 = 9 · Rn***, it must divide either **9** or ***Rn***.
* ***p*** cannot divide **9**, since ***9 = 101-1***.
* Therefore ***p*** divides ***Rn***.
* ***p*** cannot divide any ***Rk***, since it doesn't divide ***10k-1 = 9 · Rk***.
Therefore the ***p*** from Zsigmondy's Theorem is a novel prime factor of any ***Rn***, ***n ≥ 2***. ∎
---
## An example of a repeated novel prime factor
The prime **487** is a repeated prime factor of ***R486***:
By the Fermat-Euler theorem, **10487-1 ≡ 1 (mod 487)**. The order of 10 mod 487, that is, the smallest power of 10 that is 1 mod 487, therefore must be a divisor of 486. In fact, the order is equal to 486. It also happens that not only is **10486 ≡ 1 (mod 487)**, it's also **1 (mod 4872)**.
See [here](https://repl.it/B9pA/0) that the order of 10 mod 487 is 486; that is, that no smaller ***10k-1*** is divisible by 487. Obviously, 487 doesn't divide 9, so it must divide ***R486***.
[Answer]
## CJam, 18 bytes
```
{{)'1*imf}%W%:-_&}
```
[Test it here.](http://cjam.aditsu.net/#code=18%0A%0A%7B%7B)'1*imf%7D%25W%25%3A-%7D%0A%0A~p)
Starting at 19 (the first repunit prime after 2) it will take a fairly long time.
### Explanation
This is an unnamed block (CJam's equivalent of a function), which expects the input number `n` on the stack and leaves a list of prime factors instead:
```
{ e# Map this block over [0 1 ... n-1]...
)'1* e# Increment and create a string of that many 1s.
i e# Convert to integer.
mf e# Get its prime factors.
}%
W% e# Reverse the list.
:- e# Fold set difference onto the list, removing from the first list the elements of
e# all other lists.
_& e# Remove duplicates. Unfortunately, this necessary. Thomas Kwa found that the 486th
e# repunit contains 487^2 (where 487 is a novel prime factor).
```
[Answer]
# Pyth, ~~16~~ ~~14~~ 13 bytes
```
-F_m{P/^Td9SQ
```
As best I can tell, 19 takes forever.
```
-F_m{P/^Td9SQ Implicit: Q = input
SQ Inclusive range 1 to Q
Implicit lambda d:
{P unique primes dividing
^Td 10**d
/ 9 //9
m map lambda over the range
m{P/^Td9SQ Unique prime factors of all repunits up to the Qth
_ Reverse the list
-F Reduce by set difference
```
Try it [here](http://pyth.herokuapp.com/?code=-F_mP%2F%5ETd9SQ&input=6&debug=1).
[Answer]
## Haskell 86 bytes
```
import Data.Numbers.Primes
f n=[x|x<-primeFactors$div(10^n-1)9,notElem x$f=<<[1..n-1]]
```
Usage example: `f 8` -> `[73,137]`.
Takes a lot of time and memory for big `n`.
Direct implementation of the definition: take all prime factors `x` of `Rn` which do not show up before (`f=<<[1..n-1]` are all prime factors of `R1 ... R(n-1)`).
[Answer]
# Mathematica ~~82 74~~ 63 bytes
With 11 bytes saved thanks to alephalpha.
```
Complement@@Reverse@FactorInteger[(10^Range@#-1)/9][[;;,;;,1]]&
```
---
**Prime factors of R70**
(10^70 - 1)/9 = 1111111111111111111111111111111111111111111111111111111111111111111111
```
FactorInteger[(10^70 - 1)/9]
```
>
> {{11, 1}, {41, 1}, {71, 1}, {239, 1}, {271, 1}, {4649, 1}, {9091,
> 1}, {123551, 1}, {909091, 1}, {4147571, 1}, {102598800232111471,
> 1}, {265212793249617641, 1}}
>
>
>
---
**Novel prime factors of R70**
```
Complement@@Reverse@FactorInteger[(10^Range@#-1)/9][[;;,;;,1]]&[70]
```
>
> {4147571, 265212793249617641}
>
>
>
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 25 bytes
This works for input up to `16`:
```
10,i:^9/Y[t0)Yftb!w\~s1=)
```
The following version uses **31 bytes** and works up to `18`. For `19` it requires about 4 GB memory (I haven't been able to run it).
```
10,i:^9/Y[t0)5X2Y%Yfotb!w\~s1=)
```
### Example
```
>> matl
> 10,i:^1-,9/t0)5X2Y%Yfotb!w\~s1=)
>
> 6
7 13
```
### Explanation
Consider for concreteness input `6`. First the prime divisors of `111111` are computed; in this case the results are `3`, `7`, `11`, `13`, `37`. Then the modulo operation (division remainder) is computed for all combinations of numbers `1`, `11`, ... `111111` and the computed divisors. This exploits MATL's implicit singleton expansion. The result is in this case a `6`x`5` matrix, with each column corresponding to one of the divisors. Accepted divisors (columns) are those for which only `1` value (namely the last) gives zero remainder.
```
10,i:^9/Y[ % generate vector with `1`, `11`, ... depending on input number, say "n"
t0) % pick the last element: `111...1` (n ones)
5X2Y% % * convert to uint64, so that larger numbers can be handled
Yf % prime factors
o % * convert to double precision, so that modulus can be done
t % duplicate
b % bubble up element in stack
! % transpose
w % swap elements in stack
\ % modulus after division (element-wise, singleton expansion)
~s % number of zero values in each column
1= % is equal to 1? (element-wise, singleton expansion)
) % index divisors with that logical index
```
(\*) Removed in short version
[Answer]
# Julia, 103 bytes
```
R(n)=[keys(factor((10^n-1)÷9))...]
n->(r=R(n);isprime(r)?r:setdiff(r,reduce(vcat,[R(i)for i=1:n-1])))
```
This is an unnamed function that calls a helper function `R`. To call it, give the main function a name, e.g. `f=n->...`.
Ungolfed:
```
function R(n::Integer)
collect(keys(factor((10^n - 1) ÷ 9)))
end
function f(n::Integer)
r = R(n)
if isprime(r)
r
else
setdiff(r, reduce(vcat, [R(i) for i = 1:n-1]))
end
end
```
[Answer]
# LabVIEW, 33 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490)
19 takes forever...
Work by saving all Primes and deleting elements from the last set when they are found in the other array.
[](https://i.stack.imgur.com/dsyaC.gif)
[Answer]
# J, 24 bytes
```
[:({:-.}:)@:q:[:+/\10^i.
```
Expects extended-precision numerics after 6 (e.g. `19x` instead of `19`).
[Try it online!](https://tio.run/##y/r/P81WL9pKo9pKV6/WStPBqtAq2kpbP8bQIC5Tjys1OSNfIU3BDMYwtKyAMY1MEEzLiv//AQ)
There's probably a shorter way to generate the repunits which avoids the caps, too.
# Explanation
```
[: ({: -. }:) @: q: [: +/\ 10 ^ i.
i. Range [0, input)
10 ^ 10 raised to the power of the range
+/\ Running sum of this list (list of repunits)
q: Prime factors of the repunits
@: Composed with
({: -. }:) Unique prime factors of last repunit
{: Factors of last repunit (tail of matrix)
-. Set subtraction with
}: Rest of the matrix (curtail)
```
### How it works, visually
I think that these sorts of visual explanations are easier to stomach for those who don't know J. These are results from the REPL.
```
10 ^ i.6
1 10 100 1000 10000 100000
+/\ 10 ^ i. 6
1 11 111 1111 11111 111111
q: +/\ 10 ^ i. 6
0 0 0 0 0
11 0 0 0 0
3 37 0 0 0
11 101 0 0 0
41 271 0 0 0
3 7 11 13 37
({: -. }:) q: +/\ 10 ^ i. 6
7 13
```
] |
[Question]
[
Given a positive integer n, randomly output n non negative integers that sum to one hundred. n will be at most 200. The output should be present as a list of integers (not sorted).
Your random sample should be uniformly sampled from all lists of n non negative integers that sum to one hundred.
Your code should run in a reasonable amount of time (e.g. should terminate on TIO) for n less than a 200 . This is just to prevent brute force solutions.
# Examples
If n=1 the code should always output 100
If n=2 the code should output 100,0 or 99,1 or 98,2 or 97,3 ... or 2,98 or 1,99 or 0,100 with equal probability. There are 101 different possible outputs in this case.
If n>100 then some of the values in the output will necessarily be 0.
[Answer]
# [R](https://www.r-project.org), 64 bytes
```
\(n,m=rle(c(1,sample(!c(1:99,!1:n-1)),1)))c(m$l[!m$v],!1:n)[1:n]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jU9BasMwELzrFTINRgsK2IVC4yLoP9IghKLYTiTFSOuSUvqSXtxDH5U_9BGVrR56aw_aXWZnZkfvH2G60qjcYI3sPZrWhCixUyjVfi_xLOuqEp8jHtb318cn5rkTwRqmWc2zihVpbjYbXtSNX9cAPD3QzK3stnCr592ygG0qux-fLzQRpRe3d4TcUHNZfGgYfUP-SMKyEmad7ow-0ZlAlbVpMNQa32IXqQrJrm87pOWCx9H9AhuS-CyqYbAvKXqyrfhh9Br7s2cXeD2Kf6Z4yPfYEYTIEC3L-diCJOIbAMl_nqbcvwE)
Implementation of 'sticks-and-stones' as suggested by xnor.
**Ungolfed**
```
function(n){
w=rep(0:1,times=c(n-1,100)) # n-1 zeros, followed by 100 ones
x=sample(w) # randomly shuffle it
y=c(0,x,0) # and add zeros at the start & the end
m=rle(y) # get the lengths of runs of 1s and 0s
o=m$lengths[m$values==1] # lengths of the runs of ones
p=m$lengths[m$values==0]-1 # lengths of the runs of zeros, minus 1
q=sum(p) # so q is the number of zero-length runs of 1s
z=rep(0,q) # repeat zero that many times
return(c(o,z)) # and return the concatenation of the runlengths of 1s and the zero-length runs
}
```
**Golfing tricks**
`rep(0:1,times=c(n-1,100))` -> `!c(1:99,!1:n-1)`
`c(m$lengths[m$values==1],rep(0,sum(m$lengths[m$values==0]-1)))` -> `c(m$l[!m$v],!1:n)[1:n]`
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 46 bytes
```
@(n)diff([0,sort(randperm(n+99,n-1)),n+100])-1
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjTzMlMy1NI9pApzi/qESjKDEvpSC1KFcjT9vSUidP11BTUydP29DAIFZT1/B/moaRgYHmfwA "Octave – Try It Online")
Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s comment. But instead of shuffling a list of zeros and ones, here I generate a random permutation of `1:n+99`, and see the first `n-1` terms as the positions of zeros.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 16 bytes
```
lMc.S+*100N*tQdd
```
[Try it online!](https://tio.run/##K6gsyfj/P8c3WS9YW8vQwMBPqyQwJeX/f2MDAA "Pyth – Try It Online")
Based on xnor's comment.
* `*100N`: 100 `"` characters
* `*tQd`: n-1 space characters
* `.S+`: Concatenate, shuffle
* `c ... d`: Split on spaces
* `lM`: Map to lengths of remaining pieces
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
0+/;.1@,1 0({~#?#)@#~100,<:
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprq7g56Sn4JKfp16ikJZZoVCUmJeSn6tQnJqaoselpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DbT1rfUMHXQMFQw0quuU7ZU1HZTrDA0MdGys/mtypSZn5CukKZjCGEYGMBZQyX8A "J – Try It Online")
Sticks and stones method thanks to [xnor's idea from the comments](https://codegolf.stackexchange.com/questions/247970/sample-integers-that-sum-to-one-hundred#comment554669_247970).
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~125~~ ~~120~~ 115 bytes
* *-5 bytes thanks to @ceilingcat*
```
i=99,j,a[];main(n){scanf("%d",&n);n+=i;for(srand(&n);a[rand()%n]++||i--;);for(;i<n;)j=a[++i]?j+1:!printf("%d ",j);}
```
An implementation of xnor's suggestion in C.
[Try it online!](https://tio.run/##HYxBCsIwEAC/ooVKwiYH8VTX4ENCDktKyoa6SiJ4sH7diLkNwzDRxpVkaY3dNJlsyAe8EYsS/a6RJKlhnAdzEI0CjjHdi6qFZFZ/Rb6jHiUAbBtbi7onyBdBnR15AA7XDMfz/lFYnv23G0zW@Gnt9I1ppaU2@/oB "C (clang) – Try It Online")
[Answer]
# [Desmos](https://desmos.com/calculator), 77 bytes
```
l=[2...n]
L=join(0,[1...99+n].shuffle[l[l0+n>1]].sort,100+n)
f(n)=L[2...]-L-1
```
Uses xnor's Stars and Bars idea.
[Try It On Desmos!](https://www.desmos.com/calculator/yftw79pgpc?nographpaper)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/npcsficqdl?nographpaper)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
т∍ú¦.r#€g
```
Inspired by [*@isaacg*'s Pyth answer](https://codegolf.stackexchange.com/a/248041/52210), using [*@xnor*'s approach](https://codegolf.stackexchange.com/questions/247970/sample-integers-that-sum-to-one-hundred#comment554669_247970).
[Try it online](https://tio.run/##yy9OTMpM/f//YtOjjt7Duw4t0ytSftS0Jv3/f1MA) or [verify a few random outputs at once](https://tio.run/##yy9OTMpM/X@xyUevyOLQ4otNFUd3HFqmV2R0aPGh1dVlSp55BaUlVgpK9pU6XEr@pSUwngtQy6OO3sO7QIqVHzWtSf@vc2ib/X8A).
**Explanation:**
```
∍ # Extend the (implicit) input
т # to length 100
# (resulting in a string - e.g. n=50 becomes "505050...50")
ú # Pad this string with the (implicit) input amount of leading spaces
# (it's important to note that `∍` results in a string instead of integer,
# otherwise this would have resulted in "50" with 505050...50 amount of
# leading spaces instead)
¦ # Remove the first space, so there are input-1 amount of spaces
.r # Randomly shuffle the characters in this string
# # Split it on spaces
€g # Get the length of each inner string
# (after which the result is output implicitly)
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 82 bytes
```
n->Vec(Ser(concat([Set(numtoperm(m=n+99,random(m!))[1..n-1]),m+1]))*(y=1-x)-1/y,n)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN4PydO3CUpM1glOLNJLz85ITSzSig1NLNPJKc0vyC1KLcjVybfO0LS11ihLzUvKBPEVNzWhDPb08XcNYTZ1cbSCpqaVRaWuoW6Gpa6hfqZOnCTVZuTi1BKRJIz21pDwxJ6ckMzdV05qroCgzr0QjTcPIwEATqnTBAggNAA)
Based on [@xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s comment:
>
> It doesn't look like anyone has done this yet, but a slick approach is to make a list of 100 ones and n-1 zeros, shuffle it, and list off the lengths of the n runs of ones separated by zeroes. – [xnor](https://codegolf.stackexchange.com/users/20260/xnor)
>
>
>
PARI/GP doesn't have a built-in for shuffling, but we can generate a random permutation of `[1..n+100-1]` using `numtoperm` and `random`, and see the first `n-1` terms as the positions of zeros.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 94 bytes
```
n->b=binomial;r=random(b(n+99,k=100));[while(r>=s=b(n-l+k-1,k),r-=s;i++;k--)+i|l<-[1..n],!i=0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BDoIwEEX3nkLjpk07BFxp6nARgqbEgpOWQkoNG2_ihsQYz-RtlODqLf7Lf493rwOdm3561mt83WIN-8_JQ15hRb5rSTsVMGh_6VpWMS8OB2kxS1POVTFeyRkWchzwN4ETFjJpuQyAgyIhlAXggu7uCEWWJL6UG8K0_Fe2g4nzMWtMHLVzkVrD1aoP5COr2W5uLOo0LfwC)
The number of possible outputs is `binomial(n+100-1,100)`. Here I first generate a random number `r` in the range `[0..binomial(n+100-1,100)-1]`, and then find the `r`th result. So this is guaranteed to be uniform.
[Answer]
# [Python 3](https://docs.python.org/3/), 88 bytes
```
lambda n:[*map(len,bytes(sample([0]*100+[9]*~-n,n+99)).split(b' '))]
from random import*
```
[Try it online!](https://tio.run/##DcWxDsIgEADQWb@iW@9oNagTJn4JZYAUIgkcF2Dp0l9H3/L46N9CrxE@20g2u91O9NYiW4bkaXVH9w2azZw8aGnEQ8pFKyPOG620KIV4b5xiBzdfZkRzDbXkqVra/8XMpXYxuEbqEOApJeL4AQ "Python 3 – Try It Online")
Also uses the "sticks and stones" method.
This creates a list of 100 0s and n−1 9s, then `sample` gives n+99 elements (which is all of them) in a random order. The result is then converted to `bytes` in order to use `split`; 9 was chosen because it corresponds to the tab character (which is placed in the `bytes` literal for the argument to `split`). Finally, use `map` to take the `len`gth of each piece, and `[*…]` makes it into a list.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 28 bytes [SBCS](https://github.com/abrudz/SBCS)
```
-↑∘{+/¨⍵⊂⍨1@1~⍵}{100≥?⍨⍵+99}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=033UNvFRx4xqbf1DKx71bn3U1fSod4Whg2EdkFNbbWhg8KhzqT1QCMjVtrSsBQA&f=03jUtUjnUe/SR11N2vqaaQqmAA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
A train which takes a single integer. Uses the sticks and stones method, since it translates quite well to APL.
-6 from ovs.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes
```
.+
*
_$
100*@¶
+@v`(.)(.*¶)
$2$1
¶
S`_
%`@
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srXoXL0MBAy@HQNi5th7IEDT1NDT2tQ9s0uVSMVAy5gKJcwQnxXKoJDv//GxoAAA "Retina – Try It Online") Explanation:
```
.+
*
```
Convert to unary (using `_`).
```
_$
100*@¶
```
Decrement the input, append 100 `@`s, and create a work area for the shuffle.
```
+@v`(.)(.*¶)
$2$1
```
Repeatedly select a character randomly from the first line and move it to the start of the second line. (The `+` indicates to repeat, the `@` selects randomly, and the `v` allows the matches to overlap, which doesn't matter here since we're only replacing one at a time.)
```
¶
```
Delete the input area.
```
S`_
```
Split the working area on `_`s. Since there were `n-1` of them, there are now `n` lines.
```
%`@
```
Count the number of `@`s on each line.
[Answer]
# Wolfram Language (Mathematica), 41 bytes
Edit: I have made my code much simpler and shorter.
```
Values[Counts[RandomInteger[{1,#},100]]]&
```
RandomInteger creates a random number between 1 and the given input integer, with uniform probability. This is done 100 times, and Counts tallies up the number of appearances of each number.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7PywxpzS1ONo5vzSvpDg6KDEvJT/XM68kNT21KLraUEe5VsfQwCA2Nlbtf0BRZl6JQ0hiUk5qdFp0ZqxOdaaOIVC2NvY/AA "Wolfram Language (Mathematica) – Try It Online")
Old code from my previous submission is below.
```
Length/@Select[Flatten[Split[RandomChoice[Join[Riffle[Table[1,{#}]&/@#,0]]&/@Flatten[Permutations/@IntegerPartitions[100+#,{#}]-1,1]]],1],Length[#]>1&]&
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 99 bytes
```
f=(n,a=[100])=>--n?f(n,a.flatMap(v=>(s||s++)<p&&(s+=v)>p?[d=s-p|0,v-d]:v,p=Math.random(s=0)*101)):a
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVXNbttGEL7lwKeYQ2ruSiRFKjVSy6aMIAkCF3ETxLkpArQhVzJdapfhLpkUFp8klxzah2qfJrPLH0lpDdSAKHp-vp2Z79vR1z-FTPm3b39Veu3_8neyjonwWLyIwnBJ47nvi8u1sQTrnOlrVpA6nhO126nxmF4UJydEjeOazovLRRorv9iFXu2ny1ntFfE107dByUQqt0TFIR1FYUTpjLVH_fOInjtOIoXS8P7d1bPXNxADnop_aF84kedMPeeJ55x6ThR6zmQytc9T-8RAZxmsZfmSJbdEQDyHewfAwMmcB7nckBVa4fG9aFZ4UOvSUHJV5Vqh574xVkQAknMNGZrCc_y66KrBd2zRoh4nYyBOxGIeO250ib7VAg9tDcGdzARxPXBpA0sggz3nYqNvG7pqQbI1kCMPxHEMAk5OOuSg5GmVcEJUtfWgpqZdfIUx1B6E1IbjRPpqoW9zMRS2xMrIf1h3O5M_hqitpAGeKz7AHI3zQzV9-nMCr6QeGkSIxo7weNSI47SfdjzYFPrffLzjiQ5-53-ovhLa9WuSDAmJ3H6Uhpyot2QDSYags7NzPGqMLM1Nv0iR79M-axS3vqOMyCT4NiHsGO3CJ3Hr2WsjkZWw0ugqrVle8YNat0b9ZvQ1TDqRHChry5npsgX5gTCWH1LGckvaxMxln690-oIjPNhroz6VmvyAVe-RasQh-A82YM6lMBrBdI86lNWTZxkwIoFLcA2DEeSZ0i7MYNUSihENVCL7VHHrUiDXwL8UOAieor-dmuH08T2xvY6s5AIt35Y8yVQmBXlCm59sQW1Y19JDgUrjbmBlCimvM6bRfnhTTREPqUZJnI7gn-FK6Dx4LnPcTbIkVnouF65n33oVi2rLyyyZgS4r7nXGSrENn4FroNzemG2ELPnbSiS6sgXNYM3wQgyapgHOoWAlt4Wae2sma8QYUVtxoIo8Q7JwY1nZ-zANbax19vuKoAIy2i-tvmOs06jv15s3vwV4huIkt3CauMSlC9zHhzunYMpEm6R_bQ1r_H87Yw_Za8UCo0zMfQ9PjUTcD-bm4x5bGVb7LZIvh2vwIMWbVlvDXjiamKk0s3Wc0aMK3CAIXJvR4BM_7S9G_yP1HQ)
A recursive approach that starts with the array `[100]`, and 'splits' it randomly `n` times.
eg. `[27, 51, 22]` -> `[27, 11, 40, 22]`
The hardest (and most costly) part is making sure `[0, 100]` is a possible output.
There is an extremely slim chance (at most approx. 1 in 253, [source](https://stackoverflow.com/a/52095861/14117133)) of the function producing invalid output, when `Math.random()` returns exactly `0`.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 42 bytes
```
100\(:a+,{;9.?rand}${a<}%1+{.1?.@@)>n\.}do
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlvaABEBjEaVonaOtXWlnr2RYl5KbUq1Yk2taqG2tV6hvZ6Dg6adnkxerUp@f//AwA "GolfScript – Try It Online")
For some reason I just *had* to use GolfScript for this. No idea why though, I've never used this language before. Anyways, this is yet another implementation of xnor's idea.
```
100 # push 100 onto the stack
\(:a # store n-1 in variable a
+, # create array of ints from 0 to (100 + n-1) - 1
{;9.?rand}$ # shuffle array, method taken from GS tips page
{a<}% # map items to 0 if they are >=a and to 1 if they are <1
1+ # append 1 to list.
# This is done so that ? always finds a 1 later
{
.1? # find position of first 1 in array
.@@ # move a copy of that position to the back of the stack
)> # discard all elements with an index < (position - 1)
n\ # push a newline onto the stack, flip array back to the top
# The implicit output concats all stack values together :(
.}do # repeat until array is empty
```
The program expects n to be at to top of the stack. TIO's input field does ...unexpected things, so the header field is used to provide input instead.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `W`, 13 bytes
```
‹(₁ʀ℅)₁Ws₍h¯f
```
choose cut positions and sort them, append 100 at the end, calculate the difference
=>`first number, differences...`
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwi4oC5KOKCgcqA4oSFKeKCgVdz4oKNaMKvZiIsIiIsIjUiXQ==)
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 22 bytes
```
'dspn,[r0l?:lf-spr,]pl
```
[Try it online!](https://tio.run/##y6n8/189pbggTye6yCDH3ionTbe4oEgntiDn/38LAA "Ly – Try It Online")
This meets the requirements in that all possible combinations of numbers that sum to 100 could be returned, but I don't think all of them have an equal chance. But someone with better understanding of statistics would have to weigh in to be sure... If that's a disqualification, I'll remove the answer. But from what I can tell, the approach is different from the other algorithms used so it might be interesting?
At a high level, the code loops `N-1` times where `N` is the count requested on STDIN. Each time through the loop it generates a random number in `0-X` where `X` starts at 100 and is decremented by the number added to the list each time. Once the loop is exhausted, it finds the number requires to get the sum to 100 and uses that as the last entry.
```
'dsp - Load "100", save to backup cell and pop from stack
n, - Read list size "N" requested from STDIN, decrement
[r r,]p - Loop once for "N-1" times
0l? - Load backup cell, generate random number in "0-X"
: - Duplicate random pick
lf- - Sub random pick from previous "left to sum" number
sp - Save new "left to sum" to backup cell and pop from stack
l - Load "left to sum" from backup cell
- Stack prints as numbers by default on exit
```
[Answer]
# Python 3.9, 233 226 224 211 Bytes
```
import random
from functools import*
r,p=range,cache(lambda n,s:s<1 if n<1 else sum(p(n-1,k)for k in r(s+1)))
def f(n,s):
k=random.choices(r(s+1),[p(n-1,k)for k in r(s+1)])[0]
return[]if n<1 else[s-k]+f(n-1,k)
```
[TIO link](https://tio.run/##dY0xTsQwEEV7n2LKGdaLHGjQavcKXCCKUHBsYiWescZOwelDpFDQUP3iv6dXvtss/PpWdN9TLqINdORJsokqGeLGvomsFc7zyagtj4P4CnbV7cOPfg74LhwI1zF/TiOwrbd67yBF4GPCWgPULWNBvnZ2oSgKCyQGxXrpiMhMIULEw6ObgeVx9p/9LMmHiidm@3/8gXo3GNDQNuV@@FPt63UZLvFX24smbhjxxTnbOUe0/wA). Slightly longer as the cache decorator is only available in Python 3.9.
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 49 bytes
```
s10 100rn1bx100.*FL{jg_x/0x/ia}{g1-.Js1}w!q0;;)++
```
[Try it online!](https://tio.run/##SyotykktLixN/V9dkPq/2NBAwdDAoCjPMKkCSOtpuflUZ6XHV@gbVOhnJtZWpxvq6nkVG9aWKxYaWFtramv/zyypDc/5b6BgzGUIJoxAhDHQEC5DBUMA "Burlesque – Try It Online")
Inputs are random seed and count.
```
s1 # Save count
0 100rn # Random numbers 0..100 (seeded by second input)
1bx100.*FL # 100 1s
{
j # Reorder stack
g_ # Get head of random number
x/0x/ia # Insert a 0 at that position
}{
g1-.Js1 # Decrement count and check
}w! # While
q0;; # Split on 0s
)++ # Sum each block
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
≔E⊖N⁰θ≔E×χχ¹η⊞υ⁰W⁺θη⊞υ⎇‽ι⁺⊟υ⊟η⊟θIυ
```
[Try it online!](https://tio.run/##TYzLCsIwEEX3/YosZ6BCs@5KdONCKdIfiO1gAnk1D8Wvj4kouLjMDOfcWaQIixO6lH2M6m7hLDwcaQlkyCZa4WR9TpdsbhQAsWdDzYZj96fPylAEPvSMN8prZDWmHCXk1hi7p1SaGEw6R9gaRvbDMwUrwguuwq7OgKrtjzY5D7kddUr8Lhu2x0HZBAcRUxVwLIUPZffQbw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Uses @xnor's method.
```
≔E⊖N⁰θ
```
Create a list of `n-1` `0`s.
```
≔E×χχ¹η
```
Create a list of `100` `1`s.
```
⊞υ⁰
```
Start the output list with one `0` for now.
```
W⁺θη
```
Repeat until all of the `0`s and `1`s have been popped.
```
⊞υ⎇‽ι⁺⊟υ⊟η⊟θ
```
Select one of them at random. If it's a `1`, then increment the latest number in the output list, otherwise push one of the `0`s to the output list, all while removing the `1` or `0` from its list as appropriate.
```
Iυ
```
Output all of the integers.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 94 bytes
```
f=(n,s=100,g=Math.random,i=g()*-~s|0)=>--n?g()*s**n<(i+1)**n-i**n?[...f(n,i),s-i]:f(n+1,s):[s]
```
[Try it online!](https://tio.run/##JY1NCoMwEEb3nsJlYjJBl1VTT9ATiGDwr2NtIo6UUkqP3jTSWcy8Dx7zzeZhqNtw3cG6fvB@1MxK0lmayklfzH5Vm7G9u0vUE@MJfOidcn0GsNWRKUlsyVBkPABgWFWtlBrDE@SSAJs8sMgk8bymxo9uY9g/dVbE4ZShpoiFCMijzllyy6AWN7HxkLiaHdpWtDzyX7fuGAQPQLvpbkD4GvTpPz8 "JavaScript (Node.js) – Try It Online")
Probable ret[0]==s-i is `((i+1)**n-i**n)/s**n`
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
î ÅiLî¬ ö¬¸mÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=7iDFaUzurCD2rLhtyg&input=OA)
] |
[Question]
[
There is a division-free algorithm for computing determinants [published by R.S.Bird in 2011](https://www.sciencedirect.com/science/article/abs/pii/S0020019011002353?via%3Dihub) that uses only matrix multiplications. Given a \$n×n\$ matrix \$X\$, the matrix \$Y=μ(X)\$ is another \$n×n\$ matrix which entries are given by
$$Y\_{i,j} = \begin{cases}
0 & \text{ if } j < i \\
X\_{i,j} & \text{ if } j > i \\
-(X\_{i+1,i+1} + X\_{i+2,i+2} + \cdots + X\_{n,n}) & \text{ if } j = i
\end{cases}$$
Thus entries of \$X\$ below the diagonal are made zero, those
above the diagonal are left unchanged, and each diagonal
entry is replaced by the negated sum of the elements in
the diagonal below it. Note that \$Y\_{n,n} = 0\$.
Define the operation \$A⊗X\$ between two \$n×n\$ matrices \$A\$ and \$X\$ as $$A⊗X=-μ(X) \cdot A,$$ where \$\cdot\$ denotes matrix multiplication.
Now, to obtain \$\det A\$, the determinant of \$A\$, compute
$$A⊗(A⊗(A⊗(...⊗A)))$$
where the operation \$⊗\$ is applied \$n-1\$ times. The resulting matrix is everywhere zero except for its leading
entry, which equals \$\det A\$.
## Example
$$A=\left[\begin{array}{rrr}-2 & -4 & -1 \\0 & 1 & 3 \\-2 & 3 & 1 \\\end{array}\right]$$
$$\mu(A)=\left[\begin{array}{rrr}-2 & -4 & -1 \\0 & -1 & 3 \\0 & 0 & 0 \\\end{array}\right]$$
$$B=A⊗A=-\mu(A)\cdot A= \left[\begin{array}{rrr}-6 & -1 & 11 \\6 & -8 & 0 \\0 & 0 & 0 \\\end{array}\right]$$
$$\mu(B)=\left[\begin{array}{rrr}8 & -1 & 11 \\0 & 0 & 0 \\0 & 0 & 0 \\\end{array}\right]$$
$$A⊗(A⊗A)=A⊗B=-\mu(B)\cdot A=\left[\begin{array}{rrr}38 & 0 & 0 \\0 & 0 & 0 \\0 & 0 & 0 \\\end{array}\right]$$
$$\det A=38$$
# Challenge
Implement Bird's algorithm for computing determinants. For a given input \$A\$ of size \$n > 1\$, your program must output the intermediate steps \$A⊗A\$, \$A⊗(A⊗A)\$, and so on, with \$n-1\$ applications of \$⊗\$. Standard code-golf rules apply. The shortest code in bytes wins.
## Test Cases
```
A: [[0,3,1],[0,2,1],[0,2,1]]
A⊗A: [[0,1,-1],[0,0,0],[0,0,0]]
A⊗A⊗A: [[0,0,0],[0,0,0],[0,0,0]]
A: [[0,3,-1],[3,0,-2],[-2,-3,0]]
A⊗A: [[-11,-3,6],[-4,-6,0],[0,0,0]]
A⊗A⊗A: [[21,0,0],[0,0,0],[0,0,0]]
A: [[3,1,0],[-2,1,-2],[3,-1,-2]]
A⊗A: [[-1,-2,2],[10,-4,0],[0,0,0]]
A⊗A⊗A: [[-22,0,0],[0,0,0],[0,0,0]]
A: [[2,3,3,2],[-2,-2,2,0],[-3,-3,1,2],[-3,3,-3,0]]
A⊗A: [[19,6,-6,-8],[4,4,0,-4],[6,-6,6,0],[0,0,0,0]]
A⊗A⊗A: [[-10,48,0,32],[-24,0,0,0],[0,0,0,0],[0,0,0,0]]
A⊗A⊗A⊗A: [[192,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
A: [[3,-2,2,0],[0,2,-2,2],[0,2,-3,0],[2,0,3,-2]]
A⊗A: [[-9,6,-4,4],[-4,-6,-2,-6],[0,-4,6,0],[0,0,0,0]]
A⊗A⊗A: [[-8,-4,-12,-4],[12,16,0,0],[0,0,0,0],[0,0,0,0]]
A⊗A⊗A⊗A: [[56,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
A: [[-3,-1,0,0],[-1,2,3,2],[3,0,-3,0],[2,0,2,-3]]
A⊗A: [[11,6,3,2],[-7,-12,-13,-6],[-9,0,9,0],[0,0,0,0]]
A⊗A⊗A: [[2,-9,-13,-6],[42,18,0,0],[0,0,0,0],[0,0,0,0]]
A⊗A⊗A⊗A: [[-12,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~43~~ 41 bytes
```
{{+/'y*/:(u*|+\|+/x*u)-x*++\u:=#x}\x:\:x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJydUkFuwjAQvPsVlnooJF4la7tpiNQD7yBc+QFSKuAD/UD/15d01jZOiGjaIpC83p2d2dn40J1OZfX8XlTd6licy/5cVkNxXNNQlGV/7N6ehks/dH03XJQ66BVZTV4TK611rVk7CZB0mteKiARTyy0C7CS4qUcGhwrZREG4ZQwYdJ0KnDDShTBjRNXp3G4hEluc/DlVBDOjHqEymNxy7GIeZWkbtSiI10kA3FflYGHSJRxrpSq17bTe7WrjDO8NTjs592r79fEpiIhhQ7GIXz4TKAF3s+qImigFFoc8WQRkDbmRKKkRs6QbAXhDzYKi5WVJWAtpCHGUlBEkmksiZ6TOGM0vKJK1y5IWLp25ugNpHMCJJY55AdzxzRvTiF1qAfLGy5Y8wpCcbOHeVBjbtyi5KOzNzXQ/9Wbx6wB2oW/KkNebDcqzSSsMoQtZ4XN31h2cwmL+xLKrJvTi/ovXVjDENm4HJzcPmH1p/ueVwsuJRQQ2feTwlkez4nz+WRmG0ot4jXOzi26xh9psFt0CvRkbPMy2D5gV1T+5/QZEPD9x)
Brutally golfed by ngn.
-2 bytes because it is allowed to output starting with A itself.
```
input: matrix A with size n * n
{{...}\x:\:x} scan over the list of n copies of A
{...} inner fn: x is running matrix, y is A
u:=#x u: identity matrix of size n
x*++\ x * transpose of row-wise cumsum of u
(keep upper-triangular part of x)
(...)- subtract the above from...
+/x*u diagonal entries of x as a flat list
u*|+\| cumsum in reverse, placed back on the diagonal
the subtraction gives -mu(x)
+/'y*/: backwards matrix product with A
```
---
# [K (ngn/k)](https://codeberg.org/ngn/k), 62 bytes
```
{1_(#1_x){+/'@[;;:;]'[-y*|\'=#y;!#y;|0,+\|1_y@'!#y]*\:x}[x]\x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJydUltuwjAQ/PcpXPHByyuytpuGoEpwjhDxxxlAwAV6gd6vJ+msbZyAaNoigryP2Z2dtff1iXeTEe8O09N8MV43q1W9ascNHWfn7fh9dFy94H8uzHx75t1xPYbbzrb14dIc2u3hotReT8hq8ppYaa0LzdqJgaDTPFVEJJhCvAiwPeMmHzs4ZMimFgQvY9BBFynBCSNVMDNGWJ3O5RYkscTJxykjmLvWHVQGEy/bLsaRlrKOiwJ5kQjQ+8ocJPSqpMdUqYXa1Fo3TWGc4dbgtL2zVZuvj09BRAwbikn88plACdjcZTtUjyl0cYiThUHWkOsaJTZilnApAG+oHGC0PEwJaSEMIo6UMoJY95SIGckzRvMDjGTtMKWFSmeu6tA0DuBEEse4AB7o5qUpRS5VAHnjZUseZgj2tvBoKoztK6RcJPbmZrqfajP5dQA7UNfvkNebBcqzSSsMpgtR6ecerDsohcR8xbKrMtTC/0VrJRhiG7eDk8snxL6W/9NK4eXEJAybLjm85U6sKL+/Voag9CLe4tzsolrsoTDLQbVAL7sCD7HVE2KF9U9qvwFQ0EVO)
### How it works
The first time actually using ternary each (given a ternary function and three input lists, map over the triples) in code golf. It works so well that I can't think of any other way to do the job.
```
input: matrix A
{1_(#1_x){f}[x]\x} repeat applying curried function f[A] to A
(size of A - 1) times, and then remove the first item
f:{+/'bigThingOnY*\:x} matrix multiply -mu(y) with x, where
y is the current running matrix and x is original A
bigThingOnY: @[;;:;]'[-y*|\'=#y;!#y;|0,+\|1_y@'!#y]
@[;;:;]'[u;v;w] ternary amend each; for each row in u and each number in
v and w, replace v-th value in u with w
u:-y*|\'=#y negation of y, with all entries below diagonal set to 0
v:!#y indices of y (when zipped, overwrites diagonal entries)
w:|0,+\|1_y@'!#y diagonal of y, remove 1st, reverse, cumsum,
prepend zero, and reverse back
```
[Answer]
# [R](https://www.r-project.org/), ~~113~~ ~~109~~ ~~103~~ ~~96~~ 95 bytes
Or **[R](https://www.r-project.org/)>=4.1, 88 bytes** by replacing the word `function` with `\`.
*-4 bytes and another -7 thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(A,B=A)for(i in 2:nrow(A))B=print((diag(sum(b<-diag(B))-cumsum(b))-B*upper.tri(B))%*%A)
```
[Try it online!](https://tio.run/##lY/BisIwEIbvfQoRhBmZkTTxJPbQPsMevdRqJYekJbbsvn03Gauit4Zk@JkwH9@EqS2mdvTNYDsPJVVFiW0XwK6sX@mDD90vlIhV0QfrB4CLrW9wHx2cjyy5QuRmdNKKsdqOfX8NuyHY9LXZbkqcwBWujp0/aECRoZwU6WfF2KAfxKwFh1lTD7A@eX6ek19j9j3PeSyKWMuNcSHjYcBJIRbhsV7ISHOG9CyhE8@km5Momdlrv8xrRil6UR8LSjRiuYjIslwCchIz8tQbmegfyOkf "R – Try It Online")
Straightforward approach.
The terms on the diagonal are calculated as `cumsum-sum`.
---
Solution shorter for R>=4.1, by [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) again.
### [R](https://www.r-project.org/), 97 bytes
Or **[R](https://www.r-project.org/)>=4.1, 83 bytes** by replacing two `function` appearances with `\`s.
```
function(A,B=A)Map(function(i)B<<-(diag(sum(b<-diag(B))-cumsum(b))-B*upper.tri(B))%*%A,2:nrow(A))
```
[Try it online!](https://tio.run/##lY/BDoIwDEDvfAaJSWtaMzZPBg5w9@bRC6IYDhsEIfr3uFXU6I2la5o2fXntpzqb6tFVQ9M6yKnIctyXHXxaDRZpynBuyivcRgunlKUuELkarbR8WazHrrv0m6Fvwmi1XuWkd65v75AjTmAzW/rZAypQZCghRfqd0TfogBjVYDGqygHio@P3O7oYo/99TnxSxFrClwsZLwMOCj4Jj/VCRtgzpGcJHXgmREKiZGav7TKvGaXoQ30dKKURy0VEluMCkIOYka@@yED/QU5P "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/) + numpy, 117, 99, 97, 91, 89(@Dingus), 88 bytes
```
from numpy import*
def f(M):
N=M;T=triu(M==M)
for _ in M:N=T@N[T&T.T,print(N)]*M-T*N@M
```
[Try it online!](https://tio.run/##nVRtjpswEP3vU1hEqkzWjmKgNEllaXMA8osfK9FohQRsUQlQ4rTJFXqB3q8XSWds8tEoZdtVJMaZr/fe2Jr2oD83tX88Fl2zofVu0x5ouWmbTo9Jlhe0YJG7IHSloo@x0l25Y5FSkUto0XT0mZY1jRYrFT@ukvhdPIl525W1Zit3PY5EPF49Rkedb/VWOY5DlgtKk2TKfS7XHKx3Zddk@evHT8ywOZILG4Tf2fZJfWJyE71kXSGZLj74hQcH4XHhXxr1aEJKdIeYEHARDiB6chgSpBk3AEkLiRTwdAsJPo5xCdSCAUThecOQHqj0@UkdNLUEfJQkrR8T7uiWcx6iXDGDpIAHOKUAjsZ5NYV7rIB2MIOQb4ED/ge7v9WewU8EvIG66w7n8Z4F4rPpR2iOvvFiP//OuI1SkHi@YpxVaGrh/ytaZ5gjpGenA1aGbxD7Pvw/rcK8HBuEg9dfsnnLF7Go/PZaJQjqX8QHy1v6Vi3MYcrng2ohe34pCEDs7A1iEfXf1OJiMCuCKmrsZNtWpWbOp3q5cNxELmAiuGwwiPvGJMFKQqvwcylwYC/h0vqeVl8Yri16KPMqo2nXpQeWf0srhgXJdO26rwUN5AkPWWC7OyU9OhA1dTrftFWqc2U5ENqYjajM17KzK3L8ZAgizB5hnkx/m8323EA85193gLHndb7X7NTaRZyC3fiI7atsB0LIKFM@GUWqS@us2UzQYGuR8exBcgYGikYWD7c8r8o6rV4mWa5ZNEm3@tDmrKiaVAPg8Tc "Python 3 – Try It Online")
[Old version](https://tio.run/##nVRtjpswEP3vU1hEqkzWjmKgNEllaXMA8osfK9FohQRsUQlQ4rTJFXqB3q8XSWds8tEoZdtVJMaZr/fe2Jr2oD83tX88Fl2zofVu0x5ouWmbTtMxyfKCFixyF4SuVPQxVrordyxSKnIJLZqOPtOyptFipeLHVRK/iycxb7uy1mzlrseRiMerx@io863eKsdxyHJBaZJMuc/lmoP1ruyaLH/9@IkZNkdyYYPwO9s@qU9MbqKXrCsk08UHv/DgIDwu/EujHk1Iie4QEwIuwgFETw5DgjTjBiBpIZECnm4hwccxLoFaMIAoPG8Y0gOVPj@pg6aWgI@SpPVjwh3dcs5DlCtmkBTwAKcUwNE4r6ZwjxXQDmYQ8i1wwP9g97faM/iJgDdQd93hPN6zQHw2/QjN0Tde7OffGbdRChLPV4yzCk0t/H9F6wxzhPTsdMDK8A1i34f/p1WYl2ODcPD6SzZv@SIWld9eqwRB/Yv4YHlL36qFOUz5fFAtZM8vBQGInb1BLKL@m1pcDGZFUEWNnWzbqtTM@VQvF46byAVMBJcNBnHfmCRYSWgVfi4FDuwlXFrf0@oLw7VFD2VeZTTtuvTA8m9pxbAgma5d97WggTzhIQtsd6ekRweipk7nm7ZKda4sB0IbsxGV@Vp2dkWOnwxBhNkjzJPpb7PZnhuI5/zrDjD2vM73mp1au4hTsBsfsX2V7UAIGWXKJ6NIdWmdNZsJGmwtMp49SM7AQNHI4uGW51VZp9XLJMs1iybpVh/anBVVk2oAPP4G "Python 3 – Try It Online")
[Old version](https://tio.run/##nVRdjpswEH73KSzyYqgdxZjShAppcwDytA8r0WiFBGxRCVDitMkVeoHerxdJZ2zy0yhl21Ukxpm/7/vG1nQH/blt1PFY9u2GNrtNd6DVpmt7TT2SFyUtWeJGhK7i5ONjrPtqxxLPm7mElm1Pn2nV0CRaxY8PeZW9sJWbRrzrq0bDce0l4tFbPSRHXWz1NnYchywjStN0xhWXaw7Wv7Jrsvz14ydm2BzJhQ3C72yHpCExvYlesq6QTBcFfuHDQfhcqEujAU1Iie4QEwIuwhFEX45DgjTjBiBpIZECnm4hwccxLoFaMIIofH8c0geVip/UQVNLQKEkaf2YcEe3XPAQ5Yo5JAU8wCkFcDTOqyncYwW0gzmElAUO@B/s/lZ7Bj8R8Efqrjucx3sWiM9mGKE5KuPFfurOuI1SkHi@YpxVaGrh/yta55gjpG@nA1aGbxD7Pvw/rcK8HBuEgz9csnnLF7Go/PZaJQgaXsQHy1sqqxbmMOOLUbWQvbgUBCB2/gaxiPpvanExmBVBY2rsdNvVlWbOp2YZOW4qI5gIrhsM4sYxSbCU0Mb4uRQ4sJlwbX3P6i8MFxc9VEWd06zvswMrvmU1w4J0tnbd14IG8oSHLLDdnZIBHYiaOl1sujrTRWw5ENqajRibr2VnV6T3ZAgizB5hnkx/m8323EA8F193gLHnTbHX7NTaRZyS3fiI7RvbDoSQSR4rMkniPmvydjNFg61FzvN3kjMwUDSxeLjneV01Wf0yzQvNkmm21YeuYGXdZhoAj78B "Python 3 – Try It Online")
[Old version](https://tio.run/##nVRRjpswEP33KSzyY7Z2FGNKk1RIzQHIBWgUocVsUQlQ4rTJFXqB3q8XSWdsQtIope0KibHHb@bNG1vTnsynplbnc9E1O1ofdu2Jlru26Qx9IrkuaMESf0noOk4ILZqObmlZ0ySVy81yHT9v07zMXtja/2C6klW6BrS/eUoEbA/oTt63XVkbWJ6N3pt97HkeWS0pTdMZV1xuONjgxm7I6uf3H4hwGMmFO4RvsD2oB6Z3p1fUDZPNosAvAliIgAt1TdSzCSnRHSEg5CIaYQzkOCVIs24gko4SS8DVPSX4OJ5LKC0cYRRBME4ZgErFL@ogqStAoSTp/Ah4oFsueIRyxRxAIQ@xSyEsrfOmC4@qgrLDORwpRxzy36r7U@xAfikgGIm7zTC0dxCIz6ZvoV0q68V86kG7rVKQOFwx9iqysbD/i9Y5YoQMXHfAyugVYt9G/6dV2JfjDmER9Jds3/JVLCq/v1YJgvoX8c7VLZVTC32Y8cWoWkAvrgEhiJ2/Qiyy/ptaHAx2RNCYWjvdt1VpmPexXi09HycOITiB8BCHkAXBaEIb4@8a4PmE4vD6llWfGY4veip1ldOs67IT01@zimFAOtv4gLRzbUhpRxs4H4T0BFCLjTN611aZ0bGjIbSxsy62f1eAG35HW0LTb7hNudVfDpDzyGt9NOySyse8BbvzEZcndhkIIZM8VmSSxF1W581uigZTi5znbyRnYCBo4vhwgPOqrLPqZZprw5JptjenVrOiajIDhOdf "Python 3 – Try It Online")
[Old version](https://tio.run/##nVRRjpswEP33KSzyY7Y2ijGlSSqk5gDka//SaIWE2aISoMRpkyv0Ar1fL5LO2ISkUcpuV0iMmXkzb95gTXs0X5panU5F12xpvd@2R1pu26Yz9IHkuqAFS/0FoaskJbRoOvpEy5qma7nYLFYJy8vsma38T6YrWaVrwPoPafDoB48CXHsMpR/brqwNHE9G78wu8TyPLBeUrtdTrrjccLDhld2Q5e@fvxDhMJILF4RnsD2oB65vohfUFZOtosAvQjiIkAt1KdSzCSnRHSMg4iIeYQzlOCVIs24gko4SW8DTLSX4OMYltBaNMIowHKcMQaXiZ3VQ1DWgUJJ0fgTc0S3nPEa5YgagiEc4pQiO1nk1hXtdQdvRDELKEUf8r@7@lTuQnxsIR/KuKwzjHQTitelHaI/KerGeujNuqxQkDr8YZxXbXPh@QesMMUKGbjpgZfwGse/j/9Mq7M1xQTiE/U@2d/kiFpXf/lYJgvob8cH1LZVTC3OY8vmoWkDPLwkRiJ29QSyyvk4tLga7ImhCrQ12bVUa5n2ulwvPx51DCO4gDOIasiBYTmgTfF0SPJ9QXF8/suorwwVGj6Wucpp1XXZk@ntWMUxYTzc@IO1mG0ra5QbOOyk9AfRi84zetlVmdOJoCG3srkvs2zXglt/BttD0H9yWfNLf9lDzwGt9MOxcyse6BbvxEVcncRUIIZM8UWSSJl1W5802QIOlRc7zd5IzMJA0cXy4wnlV1ln1HOTasDTIdubYalZUTWaA8PQH "Python 3 – Try It Online")
[Old version](https://tio.run/##nVRtjpswEP3vU1jkj@naUQyUJqyQmgMkF6AoQgu0qHzVcdrkCr1A79eLpDM2IWmU0naFxNjjN/Pmja3pT/pT1/rnc6m6hraHpj/Rquk7pekbkhclLdnGjQhVsdolUV20sE2TKBIyfd7Gm6cFoWWn6I5WLVWJjNJomyiuUhG/HJr9oWF26wJYq@rAtu57sXnuVdVqWJ91sdf72HEcso4oTZIF97lMOVjvxqZk/fP7D0RYjOTCHsI32gE0AJO70yvqhslk8cEvPFgIjwv/mmhgE1KiO0RAwEU4wejJaUqQZtxAJC0lloCre0rwcTyXUFowwSg8b5rSA5U@v6iDpLYAHyVJ60fAA91yxUOUK5YACniAXQpgaZw3XXhUFZQdLOHIt8QB/626P8WO5JcCvIm42wxje0eB@GyGFpqlb7yYz3/QbqMUJI5XjL0KTSzs/6J1iRghPdsdsDJ8hdi34f9pFebl2ENYeMMlm7d8FYvK769VgqDhRbyzdUvfqoU@LPhqUi2gV9eAAMQuXyEWWf9NLQ4GMyJoTI2d7/u60sz50K4jx8V5QwjOHzzEEWRAMK7Qxvi7BjguoTjQvmX1Z4YjjZ6qos5pplR2YsXXrGYYkCxSF5Bmqo0pzWAD54OQgQBqMXG6aPo600VsaQjtzKyLzd8WYIff0ZTQDRtuUu6KLwfIeeRtcdTsksrFvCW78xGbJ7YZCCGzPPbJbBOrrM27Zo4GU4uc50@SMzAQNLN8ONR5XbVZ/XGeF5pt5tlen/qClXWXaSA8/wI "Python 3 – Try It Online")
# Detailed explanation
(refers to the latest and greatest versison (88 bytes))
We start with a sizeable upfront investment to create auxiliary matrix T which is just an upper triangular mask.
T is then used
* to extract the upper triangle of other matrices (obvious),
* to form another mask for extraction of the diagonal (Still rather obvious by and-ing with its transpose `T&T.T`) and
* to do the cumsum: matrix-vector multiplication Tv with a triangular matrix of ones yields the cumsum of v. Conveniently, we can choose between left-to-right and right-to-left summmation by using upper or lower triangles.
To avoid having to reinsert the cumsum into the diagonal we utilise the fact that matrix-matrix multiplication DM with a diagonal matrix D is the same as python style broadcasted pointwise multiplication with the diagonal reshaped into a column.
Extracting and reshaping the diagonal is done in one indexing operation `N[T&T.T,print(N)]`. The purpose of placing the print statement in this particular spot is that we can make good use of its return value, `None`. `None` as an index inserts a new axis which here has the effect of creating a column instead of a row.
# Avoiding explicit import, 84 bytes
```
def f(M):
N=M;T=(M==M).cumsum(1);T=T>=T.T
for _ in M:N=T@N[T&T.T,print(N)]*M-T*N@M
```
[Try it online!](https://tio.run/##nVVbrpswEP1nFRaRKpPaKAZKk1SubhZAvvi4Eo2uUIEWlVeJ0yZb6Aa6v24knbHJo1HKba8iMc68zjmDNXQH9blt/OMxywtS0MhZWmQto3expJGUkeN@3NXbXU2FA674vYzd2CJF25MnUjYkWq5l/LBO4lfgZ11fNoqunc004vF0/RAdi76tSbOruwMp667tFZlaKt@qrbRt21otCUmSGfOZ2DCw3pXdWKtfP35ihskRjJsg/M52SBoSk5voJesKSXfxwc89OHCPcf/SaEDjQqA7xISA8XAE0RPjkCBNuwFIGEikgKdbSPAxjAugFowgcs8bh/RApc9O6qCpIeCjJGH8mHBHt1iwEOXyOSQFLMApBXDUzqsp3GMFtIM5hHwDHLA/2P2t9gx@IuCN1F13OI/3LBCvzTBCffS1F/v5d8atlYLE8yvGWYW6Fv4/o3WOOVx4ZjpgRfgCsW/C/9PK9c0xQTh4w0vWd/kiFpXfvlYBgoYb8dbwFr5RC3OYscWoWsheXAoCEDt/gVhE/Te1uBj0iiCSaOtuu6pU1P7QrJa2k4glTAQXEAZxB@kk2FpoJT4uBbZjEdxr39PqC8XNRg5lXmUk7fv0QPNvaUWxIJltHOe5oIY84SELbHenZEAHorpO5XVXpSqXhoNFWr0lpX4admZtTh81QYTZI8yj7m@y6Z5piKf86w4w9qzJ94qeWjuIU9Abn2X6StPBsqxJJn1rEsk@bbK2dtFga56x7LVgFAwUTQwefghYVTZp9cnNckUjN92qQ5fTompTBYDH3w "Python 3 – Try It Online")
Bypassing the call to `triu` the last reference to the toplevel numpy namespace has been removed; the import statement is therefore no longer required. Feels a bit ugly to me but [seems to be legal](https://codegolf.meta.stackexchange.com/a/10085/107561).
[Answer]
# [J](http://jsoftware.com/), 67 bytes
```
1}.(+/ .*~0-]((*0+/\"1@,~1&}.)+]*$@[$[:(-+/\.)*&,)=@i.@#)^:(<@#@])~
```
[Try it online!](https://tio.run/##bY5NDoIwEIX3nGICDbYFSn9YVUmamLhy5RaxCyNRN54Aro5tETVoMvMymb73Te9jzFYd1BpWkAMH7bpgsD3sd6PoGc5KYHTgRYsx5Vl5jIXJB5H2jGQtRaZBjcaF2zNC05zU5sZMQk4ab0xiWjKMJIou5@sD8LojoEAh7lS4I3LWP@9WOOFgZSg3LjwTwXqEk@C38stTQYX8XoF8QaT3K18CAlItuT6jZiuHd2r6QBjV7xUbjvuA9WAVmn8iPj0@AQ "J – Try It Online")
`1} …^:(<@#@])` repeat `n-1` times, returning the intermediate results. `=@i.@#` identity matrix. `]*$@[$[:(-+/\.)*&,` running sum of the diagonal. `(*0+/\"1@,~1&}.)` everything on the right of the diagonal stays the same. `+/ .*~0-` matrix multiplication of the negative with the original matrix.
[Answer]
# JavaScript (ES6), 121 bytes
Essentially the same as below, but returns an array of \$n\$ matrices, the first one being the input matrix.
```
A=>A.map((_,i)=>m=i?m.map((r,y)=>r.map((_,x)=>r.reduce((q,v,k)=>y>k?q:m.map((r,z)=>v-=y<k|z<k?0:r[z])|q-A[k][x]*v,0))):A)
```
[Try it online!](https://tio.run/##VVHBcoIwEL37FdxM2g0DpNODFRwO/QKPaaaTQbSIEIyUUcd/p9kgaE/73tv3djPZverUKTNF07Jab/J@G/dpnKR@pRpCvqGgcVLFxaoaBAMXK5ixe3bE5JvfLCfkCB2UVrkk5eq4mBJXK3UsvizL23VZroKFEVdJb0eWilKKs3zpIKCULlLaf4iZ5wnBImBvwEIJIoAQuK1W4hBKCc4QOILd6Kk@NV2WQwAsGsLMktFgs5Y4ORwMGEB0N@AuDmMyssOdneOUcNDR8H/m5MPHIBkhd6rtYWTawdzOYJhsh94Xujc/EhiXciZn/labT5X9kMqLEy/T9Ukfcv@gd2RLKuq@2nWGXzcIhyt1CDu/1evWFPWOUL9Rm3WrTEs4pf5eFzWZe/MJftXPGJn36qGKhc3tsZtctSR8tyfr/wA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), ~~132 128~~ 126 bytes
A naive implementation of Bird's algorithm. Returns an array of \$n-1\$ matrices.
```
A=>A.slice(1).map(_=>m=m.map((r,y)=>r.map((_,x)=>r.reduce((q,v,k)=>y>k?q:m.map((r,z)=>v-=y<k|z<k?0:r[z])|q-A[k][x]*v,0))),m=A)
```
[Try it online!](https://tio.run/##VVHLbsIwELzzFblht@soiaseKA7KoV/A0bVQFBIaQh6YNALEv6deG1J62pnZmV3Lu0@H9JTpsutZ027zsRBjIuLEPx3KLCch9eu0IxsR16K2kGi4UBFrRzZwtkTn2x9jJ0cYoDLKJa5Wx8WUuBppYOKyrG7XZbUKFlpeFb0dWSIrJc/qZYCAUgq1SOj4IWeeJyWLgL0BCxXIAELgphqJQ6gUWENgCXajp/rUtFkOAbDIhZkhD4PJGmLl0BkwgOhuwF0cHsnIDLd2jlNCp6Ph/8zJh49B8oDcqqaHkWkHszsDN9kMvS@0b/5LYFypmZr5Ras/0@yb1J6IvaxtTu0h9w/tjhSkdpeyHffvGqG704Bw8Pt23euy2RHqd@l23ae6J5xSf9@WDZl78wl@Nc8YmffqoYqFzc25uzztSfhujjb@Ag "JavaScript (Node.js) – Try It Online")
### Commented
```
A => // A[] = input matrix of size n x n
A.slice(1).map(_ => // repeat n - 1 times:
m = // update m[]
m.map((r, y) => // for each row r[] at position y in m[]:
r.map((_, x) => // for each value at position x in r[]:
r.reduce((q, v, k) => // for each value v at position k in r[],
// using q as an accumulator:
y > k ? // if y is greater than k:
q // leave q unchanged
: // else:
m.map((r, z) => // for each row r[] at position z in m[]:
v -= // subtract from v:
y < k | // if y is less than k
z < k ? // or z is less than k:
0 // leave v unchanged
: // else:
r[z] // subtract r[z] = m[z][z]
) | // end of map()
q - A[k][x] * v, // subtract A[k][x] * v from q
0 // start with q = 0
) // end of reduce()
) // end of map()
), // end of map()
m = A // start with m[] = A[]
) // end of map()
```
[Answer]
# [Lua (LuaJIT)](https://luajit.org/), ~~451~~ 392 bytes
```
function det(A)
local n,Y,X,y,yl,x=#A,{},{}
for i=1,n do x={} for j=1,n do x[#x+1]=A[i][j] end Y[#Y+1],X[#X+1]={},x end
for l=1,n-1 do
o(l,X)
for i=1,n do for j=1,n do Y[i][j]=0 end end
for i=n,1,-1 do for j=n,i,-1 do
y = j>i and -X[i][j] or (i==n and 0 or yl+X[i+1][i+1])
yl = i==j and y or yl
for k=1,n do Y[i][k]=Y[i][k]+y*A[j][k] end
end end
Y,X=X,Y
end
o(n,X)
end
```
[Try it online!](https://tio.run/##hVFtjpswEP3PKUbiB9CMER//KnklbgFC/Ig2SWvWMquESKCIC@wF9n69SDpje0PSdrcIwcx43ps3z/q8Ffq87dV4PZzN86gGA0OssUogANDD81aDAQlhdUtPlEZVlKan8ajMj/S4f42jX2/vVYRa5EmaRt@hjaj9MBxByRwN7AZKAdQB1FMO48@9sTlYrhMhMLKFvdkF9@XWlZmovyeyVP0j1V9kK93tKK5a1bV9l/xzWsc4V3ylzcbYFZOAahCs/uz2Y1wlgTcHG6xxxlnjJMMKLwu9wf3qMMnL8rADTG04bfJOejk8FJo2bKiGdRvWfEZEk1XDSM1Ikbv9@X7q5A@DHwc0jlhmltrt5LoN5miJPMCg8jlYM2Yyo39SsCWcqL0@6oyVlMZWM05nvaFD0mk/zs9ZE5baets2u7bbBb48aHvppP9v5m8VzaDI61wVk7Oyxob9D4bY8NIUXsl/uFwyLDEnszMs7v5LYK8OIuGfKFjbBfeVmKEoKBAFCko@hxA/HdvG3EGYgqNPIQVNKfGDvSBJlqDkSbmrc8P/5t6QvBQnH2Fpq3TGJF/oEFZp5qbTYC/K7r5yMOGyXH8D "Lua (LuaJIT) – Try It Online")
[Old version](https://tio.run/##hVFtjptADP3PKSzxA2g8iIF/laYStwAhfkQb0sKOhoiAFBTlAr3A3m8vkno@AmHb3UZRMraf37Of5bRnctp37Xg/TuplbHsF/TSepjGUmEfgAcj@ZS9BgQA/X8IzhUEexPF5HFr1Mx6aUxi8/37LA5SMR3EcfIcqIPixH6AVHBUcegoB2iO0PziMvxplYjBcZ@rAwCQadfCe05VNa6LumchQdVuqv8hWuqUU5lVbV10d/VOt1n02eaLNxtAmI49y4K0mHZoxzCPPmYMlFjjjLIWf4/VGX@/D4hZ4EVTZ7gKXyr/seC3cWE68rPySslhUfqGrRHrRMxheqXsZt8zLuYrog99bndLyi0QrOBULUMjRsLnubom9xebW2AyzYIXlse7Jc7MeoxVCPWDJw35CUDjLHfXRIubn6Shk2bw5hB7hdTPzay3c/27@lpM0vRx83YQOIAosjUXOEaUdGZpxGhQUFUnzWpfvdDq4XhPMkNOlEkyf/m@euToEzH0Cb4UzjcswQZbSg6XIKPi8hfipbIDctmgK/fq0JSWVDB/sKY1kCDKtxG1eA/6nu3TqpXTweGYmSzVN8sUczEyaWHUSdkOZ3VcOTXi73f8A "Lua (LuaJIT) – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~62~~ 38 bytes
```
{-⍺+.×⍨(+\-+/)@(∘.=⍨⍳∘≢)⍵×∘.≤⍨⍳≢⍵}\≢⍴⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/v1r3Ue8ubb3D0x/1rtDQjtHV1td00HjUMUPPFijwqHczkPmoc5Hmo96tQCVA4UedS6ASnYuAgrUxYHrLo66m/2mP2iY86u171NX8qHcNUOzQeuNHbRMf9U0NDnIGkiEensH/0xQgQl7B/n7q0dEGOsY6hrE6QNoIiY5V58KiThekwFjHQEfXCMjQNdLRBXKwqAWaCBQHqzCEqAXpBbEw1RoBzTXWgZlnBLQdrNMYZLYhRBykAKdNcC0gh4M4MKYxWBQoB9KNzWZdsKMMIPYBrYI6A@w/hGaQSUDNAA "APL
(Dyalog Extended) – Try It Online")
Breaking from right to left:
1. `≢⍴⊂` : \$[A,A,\cdots,A]\$ (produces \$n\$ copies of input);
2. `{...}\` : \$[A,A⊗A,A⊗(A⊗A),\cdots]\$ (`{...}` implements \$⊗\$);
3. `⍵×∘.≤⍨⍳≢⍵`: upper triangular matrix;
4. `(+\-+/)@(∘.=⍨⍳∘≢)` : replace diagonal by the negated sum. Thus,
`(+\-+/)@(∘.=⍨⍳∘≢)⍵×∘.≤⍨⍳≢⍵` is \$\mu(X)\$. `(+\-+/)` is a very nice trick to compute the new diagonal, using a *train*: `(+\diag)-(+/diag)`;
5. `-⍺+.×⍨...`: \$-\mu(X)\cdot A=A⊗X\$.
Many thanks to
@rak1507, @Adám and @Marshall for this nice improvement!
```
{((⌽0,+\¯1↓⌽1 1⍉⍵)(×⍤0 1)⍺)-((⍵×(∘.<)⍨(⍳≢⍵))+.×⍺)}\((≢⊢)⍴(⊂⊢))
```
[Old version](https://tio.run/##dY8xSwNBEIV7f8V12SW7Yfe2tbNRCwXPLkkRuItNUAsLRWwUDnO4QRGJdbCwEFJomkCa5J/MHznf7BkVPJvdmbffezPbOx3o9KI3ODnS2flZdpxmaVleCkF3C6OaneXUUv6IxkaW/JD8TIrVmPyLiawkP5caqJ@txoJun1ubkF7Rv9Nwwqhsthiey6sOMGjFBMSHoOKaS1n2Kb8nP6LihvwbXpZTR/kDjZ6Sgy2ch9s7SdmPKmk32d9rtNtGOWW7Cnf86@42Nmo4zYBTRukYhY6VRlPDIhF6IGzFsperv2yMXKfWeTGmB6fjbFvpDPw76dvCi3OzLl1Q8cbuusk6LGWqeRj1tUb434@Zk2D@BA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
≔θηF⊖Lθ«≔EηEκΣEθ×⎇⁼πλΣEη∧›ςλ§ρς∧›πλ±§κπ§ξνη⟦⭆¹η
```
[Try it online!](https://tio.run/##VY/NasMwEITPyVPouIIN5OfYkyGlFJpSSG5CB2FvbVNbsdeKSQh9dnWVOJScRjvzaYfNK8f50TUxZsNQlx56VJV@mX8fWcGWcqaWfKACPsiXoYJea62u89lE71wHFaokP6j2p/bmyI5D3dIAB2Lv@AKv/ck1A3SoGv2PycfMF/DG5AIxjPc0C@@@oDMwqlHK9DM0rfikUkZ4sNLdTezknFF5re9eumf2xbUPYPZBtEztqxRYiX5jNMZscLHGNS4tmqVoGh7Pzc2VDBNkrY2LsfkD "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔θη
```
Start with the output `X` equal to the input.
```
F⊖Lθ«
```
Repeat `n-1` times.
```
≔EηEκΣEθ×...§ξνη
```
Matrix multiply `-μ(X)` by `A`.
```
⎇⁼πλΣEη∧›ςλ§ρς∧›πλ±§κπ
```
Dynamically generate `-μ(X)` as part of the multiplication; for elements on the main diagonal, sum the elements further down on the diagonal, otherwise negate or zero the element depending on whether it is above or below the diagonal.
```
⟦⭆¹η
```
Pretty print the latest result. (Normal printing would save 1 byte but be almost impossible to read.)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 80 bytes
```
a->[x=matrix(n,,i,j,if(i>j,0,i-j,-x[i,j],sum(k=i+1,n,x[k,k])))*a|l<-[2..n=#x=a]]
```
[Try it online!](https://tio.run/##RY7BbsMgEER/BaUXSGcjwEcH/wjiwMURdmIhJ5WolH93dp1GvcAwM/uWmtdCl7qNKmyZhtjCLT/W0vQCFEwooy7DBItCE6hF9hLuPzc9h/LtsKDFGXMyxhzz83qm6E@nJXy1kFPacq3XX50VDaquZXmwPMjjoEadjYGK0aKD6y3850zsikmu73gt@Z48iKUE3IUVw0kgJb4l8DzR4d31jOFSJ1NOPIn@CX@5LBP5Fpz27Epx59HOtsJhxI7ef/PpyUhKZnsB "Pari/GP – Try It Online")
] |
[Question]
[
A simple Markov Model will be used in this question. For more information about Markov Chains, see <http://setosa.io/ev/markov-chains/>.
Take a string. For this example, we will use the word:
```
reader
```
Now, for each character, take the characters that appear after each occurence of the character in the string. (``^`` represents the start of the string and ``$`` represents the end)
```
`^` -> {'r'} # After the start of the string, there is an `r`.
'r' -> {'e', `$`} # After the first `r` (*r*eader), there is an `e`
# after the second (reade*r*), there is the end of the string.
'e' -> {'a', 'r'}
'a' -> {'d'}
'd' -> {'e'}
```
Now, starting from the start of the string, pick randomly from one of the characters in the next set. Append this character and then pick from the characters in its next set, and so on until you get to the end. Here are some example words:
```
r
rereader
rer
readereader
```
If a character appears after another character multiple times, it is more likely to be chosen. For example, in `cocoa can`, after a `c`, there is a two thirds of a chance of getting an `o` and a one thirds chance of getting an `a`.
```
'c' -> {'o', 'o', 'a'}
```
# Challenge
Create a program that takes no input and outputs a random string generated using a Markov Chain, like above, where the input to the chain is the program's source.
1. The program must have at least two characters, two of which must be the same (To prevent "boring" chains that only have one output)
2. You can modify the model to use bytes instead of characters if you wish, but change "characters" to "bytes" in rule 1
3. The program should output strings randomly with the expected frequency in theory
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program wins!
[Answer]
# JavaScript, ~~217~~ 215 bytes
```
a="a=q;a=a.replace('q',uneval(a));for(b=c='a';d=a.split(c),c=d[Math.random()*~-d.length+1|0][0];b+=c);alert(b)";a=a.replace('q',uneval(a));for(b=c='a';d=a.split(c),c=d[Math.random()*~-d.length+1|0][0];b+=c);alert(b)
```
Note that this uses `uneval`, which is only supported by Firefox. Sample runs:
```
a=ale(a.lend[Ma=d[Macepla.ler(b+=c)b=q;fom(a=q;a=dort(b+1|0],c);a.lit(a)
at(c=c;d[0],c=q;ath+1|0][0];dorerac=ac=d[Ma),c;)*~-d[Ma=alenepl(b+=ac=c;a=c;d[2];d.re(c;fom()
a="a[0],und=d=a)
angt(b),und=d.l(b=a)
a)
ale(a.rth.revanepleplit(b)
ac);fore(b)*~-d.r(b+1|0];fora';a)*~-d.splalith+=dorth+=c=";ath+=a.length+=';ale(b)
a.r(b=c=a)b+1|0],und[0][0];d.splerath.spleneva)";ath.r(ceneplith+=d=aceple(c;)*~-d=';ala';)b='ac;fom(b=c;a.ler(b=d=d[Ma.rt(c=cendor()*~-d='a=";ac;a.spla)b=ceva=';a=d.rt(angt(alength+1|0],c;angt()
al(ac=dorth+1|0][0][0][0][Ma.split()
```
As you can see, it's mostly gibberish, but that is to be expected ;) The OP has created a [JSFiddle](http://jsfiddle.net/kabkfLak/3/embedded/result,js,js,html,css,resources/) which demonstrates that the chance of an output being syntactically valid JS is about 6.3%.
---
If self-reading functions were allowed, this could be 78 bytes of ES6:
```
f=(c="f",p=("f="+f).split(c),q=p[Math.random()*~-p.length+1|0][0])=>q?c+f(q):c
```
Very, very rarely, this outputs syntactically valid JS:
```
f=>e?c+f():c
f=>e?c=>engt():c
f=>e?c=(e):c
f=>e?c=>e=>ength.split():c
f=p=>q?c+f():c
f(q).sp=",p[Mat(q?c=(),plith.lith.sp.sp[0]).lendom().lith+f=>q=p.lendom(",p=p=>q?c+f():c
f(q),q?c=(c=(q)*~-p[0]):c
f().random(),q?c=(c=p[0]):c
f=>q?c=(q="+f"+f).rath.split(c):c
f="+1|0])=().lith.rat()*~-p=>q?c=p[Mat(c=",q?c=p.rath.splendom()*~-plength.splith.lendom(c):c
```
My favorite of the function names it's created is `.splendom()` (`split` + `length` + `random`)
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 64 bytes
This was fun.
```
t:V Y\"m:"Yt@0T9=A OyY@>RC(t(Xy).'.)"ST["t:V Y"RPy";Vm"C9]\";Vm<tab>
```
`<tab>` represents a literal tab character (`0x09`). [Try it online!](http://pip.tryitonline.net/#code=dDpWIFlcIm06Ill0QDBUOT1BIE95WUA-UkModChYeSkuJy4pIlNUWyJ0OlYgWSJSUHkiO1ZtIkM5XVwiO1ZtCQ&input=)
### How?
TL;DR: escaped-string syntax, repr, and eval.
For strings that need to contain literal `"` characters, Pip has *escaped strings*, using `\"` as the delimiter. A standard quine using escaped strings would look like this:
```
V Y\""V Y".RPy\"
```
That is: `Y`ank (storing as `y`) a string containing `"V Y".RPy` and e`V`al it. `RPy` takes the repr of `y`, to which we prepend the literal string `V Y`. Finally, output the result of the eval.
The structure of the Markov quine is similar, except that we want to save the code instead of outputting it and then do some stuff with it afterwards. `t:V Y\"...\"` assigns the eval result to `t`. Inside the eval'd code, `m:"..."` assigns a string of code to `m`, which we will evaluate at the end with `Vm`.
`ST["t:V Y"RPy";Vm"C9]` builds a list containing
```
"t:V Y" Literal string
RPy Repr(y)
";Vm" Literal string
C9 Tab character
```
and converts it to a string, which by default concatenates all the items. This section is equivalent to `"V Y".RPy` in the original quine. Since it is the last expression in the big eval string, its value is what the `V` operator returns, and thus what gets assigned to `t`.
Thus, after the eval and assignment, `t` is equal to the full code, and `m` contains
```
Yt@0T9=A OyY@>RC(t(Xy).'.)
```
Now `Vm` evaluates that as code. Let's break down what happens.
```
We'll use y to hold the current character in the chain
Yt@0 Yank first character of t into y (chain always starts there)
Oy Output y without newline each time we...
T9=A Loop till ASCII code of y equals 9 (tab)
Since there's only one literal tab, at the end of the program,
this satisfies the Markov chain ending requirement
Xy Generate a regex that matches y
( ).'. Concatenate . to regex: now matches y followed by any character
(t ) Find all matches in t (returns a list)
RC Random choice from that list
Y@> Slice off the first character and yank the remaining one into y
```
A couple notes:
* Ending the code with a literal tab was shorter than doing a regex test for "next character or end of string."
* The regex I used does not work properly if there are doubled characters in the code; for instance, applying it to `xxy` would return only `xx` and not `xy` in the matches. Fortunately, however, there are no doubled characters in this code, so it doesn't matter.
[Answer]
## MS-DOS machine code (.COM file), 126 bytes
(A 63-byte variant would be possible if the program was allowed to read its own code.)
The first half (63 bytes) of the program are code and look like this:
```
FC BE<3F>01 AC 50 88 C2 B4 02 CD 21 E8 1A 00 59
4E AC 81 FE<7E>01 7C 03 BE<3F>01 38 C1 75 F2 FE
CA 75 EE 81 FE<3F>01 75 DB 8A 16 00 80 31 C0 8E
D8 31 C9 AC 00 C2 E2 FB 0E 1F 88 16 00 80 C3
```
The second half (63 bytes) are data and are a 1:1 copy of the code.
(In the 63-byte variant reading its own code, the bytes marked with "<>" have different values and the second half of the program is not present.)
I'm also not sure about the random generator's probability distribution:
The program uses the fact that the clock counters and other information modified by interrupts are stored in segment 0 to generate random numbers.
Converted to assembly code the program looks like this:
```
# 0x100:
cld # Ensure SI is being incremented
mov si, programEnd # Move SI to the first byte of the copy of the program
nextOutput:
lodsb # Load one byte of the program ...
push ax # ... save it to the stack ...
mov dl, al # ... and output it!
mov ah, 2
int 0x21
call pseudoRandom # Create a random number (in DL)
pop cx # Take the stored byte from the stack
dec si # Go back to the last byte loaded
nextSearch:
lodsb # Load the next byte
# If we loaded the last byte ...
cmp si, 2*programEnd-0x100
jl notEndOfProgram # ... the next byte to be loaded ...
mov si, programEnd # ... is the first byte of the program.
notEndOfProgram:
cmp cl, al # If the byte loaded is not equal to ...
# ... the last byte written then ...
jne nextSearch # ... continue at nextSearch!
dec dl # Decrement the random number and ...
jnz nextSearch # ... continue at nextSearch until the ...
# ... originally random number becomes zero.
cmp si, programEnd # If the last byte read was not the last byte ...
jnz nextOutput # ... of the program then output the next ...
# ... byte!
# Otherwise fall through to the random number generator
# whose "RET" instruction will cause the program to stop.
# The random number generator:
pseudoRandom:
mov dl, [0x8000] # Load the last random number generated
# (Note that this is uninitialized when
# this function is called the first time)
xor ax, ax # We use segment 0 which contains the ...
mov ax, ds # ... clock information and other data ...
# ... modified by interrupts!
xor cx, cx # Prepare for 0x10000 loops so ...
# ... all bytes in the segment are processed ...
# ... once and the value of SI will be ...
# ... unchanged in the end!
randomNext:
lodsb # Load one byte
add dl, al # Add that byte to the next random number
loop randomNext # Iterate over all bytes
push cs # Restore the segment
pop ds
mov [0x8000], dl # Remember the random number
ret # Exit sub-routine
programEnd:
## Place a copy of the code as data here ##
```
[Answer]
# C, 306 ~~328~~ ~~585~~ ~~611~~ ~~615~~ ~~623~~ ~~673~~ ~~707~~ bytes
Source code:
```
p[256][256]={0};char*X="p[256][256]={0};char*X=%c%s%c,Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}",Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}
```
With newlines and whitespace added for legibility/explanation:
```
01 p[256][256]={0};
02 char*X="p[256][256]={0};char*X=%c%s%c,Y[999],c,j,*a;main(){sprintf(Y,X,34,X,34);for(a=Y;*a;a++)p[*a][*(a+1)]++;for(j=*Y;putchar(c=j);)while(p[c][++j]<<16<rand());}",
03 Y[999],c,j,*a;
04 main(){
05 sprintf(Y,X,34,X,34);
06 for(a=Y;*a;a++)p[*a][*(a+1)]++;
07 for(j=*Y;putchar(c=j);)
08 while(p[c][++j]<<16<rand());
09 }
```
## Explanation
`Line 01`: `p[][]` holds the counts of one character following another.
`Line 02`: `X` contains the program's source, escaped with `%c%s%c`.
`Line 03`: `Y` will contain the program's literal source. `c`, `j`, `*a` are counting variables.
`Line 05`: Set `Y` to contain the quine.
`Line 06`: Count letter occurrences in `p[][]`.
`Line 07`: Print the current state.
`Line 08`: Find the next character randomly, proportional to the counts in `p[][]`.
Sample output:
`p[++);p[99]=Y;putfor(aind(a++j,*a+j=j,c][c,*an(arile(pr*Y,Y[256]<<1);)][*Y,Y;)wha+++j=*aintfor*Y;prin(a+j]=j][256<1)pr(a;a;f(p[char(Y;for());};a;ma;ma=%s%chain(Y;ar(j][256<<<1)p[256<<raile(cha][9]<rin(j,34,34,Y[256]+j,Y,34,Y,c=Y,*a;*a;for(){0}`
[Answer]
# [Perl 5](https://www.perl.org/), 81 bytes
Based on the standard quine and [my answer to this question](https://codegolf.stackexchange.com/questions/92638/faux-source-code/94958#94958):
```
$_=q{@$=a^E;@$="\$_=q{$_};eval"=~/(?<=\Q$@\E).?/g,print$@while$@=$$[rand@$]};eval
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3raw2kHFNjHO1RpIKcWABVTia61TyxJzlGzr9DXsbWxjAlUcYlw19ez103UKijLzSlQcyjMyc1JVHGxVVKKLEvNSHFRiIVr@/wcA "Perl 5 – Try It Online")
As with the [faux source code answer](https://codegolf.stackexchange.com/questions/92638/faux-source-code/94958#94958), this sometimes produces valid Perl, but very infrequently (<2%):
```
$$$\_=al
$\_=a^E;eval
$\_=al
$$=q{$$]};eval
$@=a^E;@whil
$\_=q{@\E;e$]};evaleva^E;eval
$$=q{@\$\_=a^E;evant$@$="=$$]};evaleval
$\_=q{@whind@$\_=$]};eval
$\_=q{@\$@=~/(?<=\$[rilevale$=ant$[rint$\_};evaleval
$\_=aleval
$\_=q{@$\_};@whil
$$=q{@$=q{@$=\E;evand@whint$\_};eva^E).?<=$=~/g,prand@$\_=al"\E;e$@\E).?/g,prant$\_};evaleval
$\_=\$_=~/g,prind@=q{$]};@$@\Q$$$_};e$@$_=q{@$_=~/g,pril
$_=q{$=aleval"\E;evaleva^E;eva^E).?/g,pra^E;eva^E).?/(?/g,print$@$_};eval
$@=q{$_=~/(?<="\$_};eval
```
[Answer]
# Ruby, 152 bytes
```
0;s="0;s=%p<<33
0until putc($/=Hash[[*(s%%s).chars.each_cons(2)].shuffle][$/])==?"<<33
0until putc($/=Hash[[*(s%s).chars.each_cons(2)].shuffle][$/])==?!
```
Sample output:
```
0;s.c($/=Has(s).ears(2).ch[*(2)=Hacontc(2).ears.eas=Has==Hars%putc($/]).ears%sh_chuffl puns=Hachach[$/==?!
```
or
```
0;s.ch[*($/=%pufl puns($/=%s.shas($/=Harsh_chutilears)])].e]).s)=Hac($/=="<<33\ntile].chufffle][[$/=Hars%sh_c(2)=%p<<<<<33
0;s)].ears)=Hars).c(s).eacon0un0;sh_c($/][*(s.s=Hacons=?!
```
Quines using string formatting via `"s%s"`, and does the Markov chaining by taking all two-character slices, shuffling them, and turning them into a Hash dictionary, where for duplicate keys the last appearance defines the value. To avoid adding extra logic for the beginning, I track the most recently output character using `$/`, which is automatically initialized to a newline, and ensure that newlines are always followed in the code by `0`, the same character the code starts with. For the end, I manipulate the source code so that there's only one `!` so we always end after the bang, using `<<33` to add it without the literal. This could be golfed further using an unprintable single-digit character instead of ASCII 33, but that seemed too annoying.
[Answer]
# Rust, 564 bytes (not competitive)
```
extern crate rand;fn main(){let t=("extern crate rand;fn main(){let t=", ";let mut s=format!(\"{}{:?}{}\",t.0,t,t.1).into_bytes();s.push(0);let mut r=rand::thread_rng();let mut c=s[0];while c!=0{print!(\"{}\",c as char);let u=s.windows(2);c=rand::sample(&mut r,u.filter(|x|x[0]==c),1)[0][1];}}");let mut s=format!("{}{:?}{}",t.0,t,t.1).into_bytes();s.push(0);let mut r=rand::thread_rng();let mut c=s[0];while c!=0{print!("{}",c as char);let u=s.windows(2);c=rand::sample(&mut r,u.filter(|x|x[0]==c),1)[0][1];}}
```
Since I already had written a pretty neat Rust quine for another question, I thought I'd adapt it for this, since it seemed simple enough. While the original was small, though, for this I have made very little attempt to minimize size. Here's an expanded version to explain what's going on:
```
// Random numbers are removed from the standard library in Rust,
// I had to make a cargo project to even compile this...
// Rust is hardly a golfing language.
extern crate rand;
fn main(){
// The quine is fairly simple, we just make a tuple with
// "everything before this tuple" as first element, and
// "everything after this tuple" with any quotes escaped
// as second. That makes it really easy to print.
let t=("[...before...]", "[...after...]");
// Instead of printing it, we save it as a byte vector
// and append 0
let mut s=format!("{}{:?}{}",t.0,t,t.1).into_bytes();
s.push(0);
// Start with the first character
let mut c=s[0];
let mut r=rand::thread_rng();
while c!=0 {
print!("{}",c as char);
// We slide a 2 wide window over it to save a vector
// of all bigrams.
let u=s.windows(2);
// Filter it to only those which have the current character
// as first. Take one at random, its second is our next
// character.
c=rand::sample(&mut r, u.filter(|x|x[0]==c), 1)[0][1];
// Keep at it until the 0 byte is generated.
}
}
```
Sample output 1:
```
eran(),0{ller=samarin chas c).pr,teteran mut madoletet manthilaplerng().wind_byt.wit();let.u.0][*s=[*s.plleas.wshit, rnd:Vec<_byte mputextet ut t leat=r,t rant!=r().filllet rng();lar("{}{let.ind_byt.what amusarando_ramut!=st ct!(\").0]=colet!(&lec<_ret.plec=s.whrararandormpr=saile ret=r,0]=r);le(\"),t und;fint.prilt!();ler(2).forap(&ler=s(),t ut rat mu:t=ramund:Ve s.putec==[0];wst and_byt sh(\"et c s[1), munwhras[0];c=s=s="etornws(2)[0, ain(|x|x[0,0,0];fowile c ct(&l=",tes().co_byt().wrmat ash(|x|x[*s.lethrant.wrarmu.file(\"et, r==[1);uterile().0,t ando_rinwhas=[0{}"ect.wilant!("{ple mut, mut mamprmant,0];le(&lec=s.1),t co_>=fin mamustec!(\",c=[0];}}",0];leteteat.ust(",ternwhashrarmut ler("erat,0]==file and_reter==s.utet an letet.ut=", ras.1);fin("{:?}"et t letes[*sado_bytet rnd::Verain s[0];whant(){}{}\"echin s(2);lerad;wst reth(\",t u.iletermat c 1];}{}
```
Sample output 2:
```
et!().0][0][0{}
```
[Answer]
# Python 2, 211 bytes
Outputs the result to `stderr`.
```
import random;X='q=[(list(t)+["$$"])[i+1]for i in range(len(t))if t[i]==c];c=random.choice(q)\nif c=="$$":exit(o)\no+=c\nexec X';s='import random;X=%r;s=%r;q=t=s%%(s,X);o=c="i";exec X';q=t=s%(s,X);o=c="i";exec X
```
[**Try it online**](https://tio.run/nexus/python2#bY7BCoMwEER/JQTFBNtCrw37H0LMQbaxLthsTXLwx3u2Eeml9DKHeTPDbPR8ccwiDuHOT9NBs4BVM6Wssm6trCrptKX26kaOggSFPfrwavahJDSNIltyAOgMwrFywYkJvVp0HwpHgH3m5lfKiovHLWAf/OpRdI1J0Px@qGNxiyyQIdW1SqdOGwYESdJ8ewf8x7btHfiMA07@Aw)
**Sample output:**
```
i+[(s,X)));exenit(or;q=rt(t(t(t);o='ic\n(q)+1]=c\ndor randort))\ngeno));X)\nge(st))ic]=";oic=%ran(s%%(s%rt(q)\ngexe(s=st(t[(s=[if X=%(ompoiforanom;e(t X="$"$"ic="$"i";X=c rt X
```
**Brief Explanation:**
* This program uses the `s='s=%r;print s%%s';print s%s` quine format. I create a string `s`, which will contain the entire program.
* The string `X` contains the procedure to execute recursively.
* The procedure builds the output string `o`, which will be printed to `stderr` upon reaching the end of the Markov chain.
* The end of the chain is represented by the string `$$`, using two characters so that the program will work for all strings. I could have used a character not in my program like `chr(0)`, but I think that's longer.
* The character chosen each execution is placed in `c`, which (along with `o`) is initialized to the first character of the program.
* The list of characters that follow each occurrence of choice `c` in the string `t` (the variable holding the quine of the source code) is `q`, which will be chosen from for the next selection of `c`.
[Answer]
## PHP, ~~144~~ ~~135~~ ~~130~~ ~~120~~ ~~272~~ ~~220~~ 212 bytes
```
<?$e='$p=$n="";foreach(str_split($s)as$w)$p=$m[$p][]=$w;do echo$n=$m[$n][array_rand($m[$n])];while("\n"!=$n);
';$s='<?$e=%c%s%1$c;$s=%1$c%s%1$c;$s=sprintf($s,39,$e,$s);eval($e);';$s=sprintf($s,39,$e,$s);eval($e);
```
Or, formatted for readability:
```
<?$e='$p = $n = "";
foreach (str_split($s) as $w) {
$p = $m[$p][] = $w;
}
do {
echo $n = $m[$n][array_rand($m[$n])];
} while ("\n" != $n);
';$s='<?$e=%c%s%1$c;$s=%1$c%s%1$c;$s=sprintf($s,39,$e,$s);eval($e);';$s=sprintf($s,39,$e,$s);eval($e);
```
**Sample output:**
```
<?p=')ay_r_gecorr_splililen]=$p=$w;
```
and:
```
<?p=$n=$ntststs$m[$n=$m[ay_r_chondo$n=$ph(s$nt(fitstr_r_geantentr_s('m[$n=$n"!=$p etstsp][$w;d(fililile(s$w)$nt(sphor_str_getrarast(''''m[$n='m[$m';
```
and:
```
<?p=$who eay_re($n=$n=$nt(')];d(fililileando et($m[]=$pleay_ch(')aray_ren='''))ay_st_r_s($m[$m[asp])ay_co$m[$p $phorentechitr_rean)][$n=$nd("\n"!=$n=$wh(filend('')ay_gen=$ndo$nt_rasp=$n][$p=$whp=$n='m[$n"\n)))))][$w;dorechph(';dorracho$ple_s$w;fil
```
and:
```
<?ph($n);
```
**PHP Cheating, 117**
For the curious, if we cheat by reading our own source, we can do 117:
```
<?=$p=$n='';foreach(str_split(file('m')[0])as$w)$p=$m[$p][]=$w;do echo$n=$m[$n][array_rand($m[$n])];while("\n"!=$n);
```
[Answer]
# [Julia 1.7](http://julialang.org/), 103 bytes
```
(c='(';a=:((c = (q = "(c='(';a=:($(a)))|>eval")[(print(c) != 1) + rand(findall(c, q))]):eval(a)))|>eval
```
[Try it online!](https://tio.run/##TU49C8IwFNz9Fc8q9D0MhUxCJA66uTqKwyOtmhKiTaI4@N9jOihdjuO@uP7pLMt3XsBhZCCb9WzHsWsu1rfsHBql9jcOAqJSxxSsvxJo@LlaoyEB5u5cZxJGIshodI31hrVCNCWLQ4Fqoi6Rieiz7V7sKjrho6ymsgNzDZJgBYF9i/8DAgaiM6kxPmnm/AU "Julia 1.0 – Try It Online")
All those spaces are painful but necessary because the code is stored in an `Expr` (AST), which will add spaces when interpolated. Replace `print(c)` with `println(q)` to check the validity of the quine.
based on this quine:
`(a=:(print("(a=:($(a)))|>eval")))|>eval` [Try it online!](https://tio.run/##yyrNyUw0rPj/XyPR1kqjoCgzr0RDCcxW0UjU1NSssUstS8xRgrP@/wcA "Julia 1.0 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 18 bytes
```
`{Ȯq‛DĖ+$/Ḣ℅h:₴`DĖ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHvIrnHigJtExJYrJC/huKLihIVoOuKCtGBExJYiLCIiLCIiXQ==)
## Sample outputs:
```
`{Ȯq‛DĖ
`DĖ
`{Ȯq‛DĖ+$/Ḣ℅h:₴`{Ȯq‛DĖ
`DĖ+$/Ḣ℅h:₴`{Ȯq‛DĖ+$/Ḣ℅h:₴`DĖ+$/Ḣ℅h:₴`{Ȯq‛DĖ+$/Ḣ℅h:₴`DĖ
`DĖ+$/Ḣ℅h:₴`{Ȯq‛DĖ
```
## Explanation:
```
` `D # push this string to the stack and triplicate => [ <code> , <code> , <code> ]
Ė # Execute the top => [ <code>, <code> ]
{ # While true
Ȯ # push the second to last item on the stack => [ <code> , <code> , <code> ]
q‛DĖ+ # quote and add ‛DĖ => [ <code> , <code> , `<code>`DĖ ]
$ # swap => [ <code> , `<code>`DĖ , <code> ]
/Ḣ # split and discard the first element => [ <code> , [`DĖ] ]
℅h # choose at random an element and get it's first element => [ <code> , ` ]
:₴ # duplicate and print without a newline => [ <code> , ` ]
## on loop ##
{ # While true
Ȯ # push the second to last item on the stack => [ <code> , ` , <code> ]
q‛DĖ+ # quote and add ‛DĖ => [ <code> , ` , `<code>`DĖ ]
$ # swap => [ <code> , `<code>`DĖ , ` ]
/Ḣ # split and discard the first element => [ <code> , [<code>, DĖ] ]
℅h # choose at random an element and get it's first element (or error and stop the program) => [ <code> , <char> ]
:₴ # duplicate and print without a newline => [ <code> , <char> ]
```
## Also 18 bytes
```
`q‛:Ė+:{h~/$₴Ḣ℅`:Ė
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYHHigJs6xJYrOntofi8k4oK04bii4oSFYDrEliIsIiIsIiJd)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~103~~ 102 bytes
```
exec(s:="from random import*;c='e'\nwhile c:print(end=c);c=choice(f'exec(s:={s!r})'.split(c)[1:])[0]")
```
[Try it online!](https://tio.run/##NczBCsIwDIDhV5m7tPEgihep9EnmDpJlNLClIS1MEZ@97uLpP3zw67umLNebWmv0IvQlxH62vHb2lGkPr5qtHu8YHbmHbIkX6jCosVRPMkWE3TBlRvKz@z8@5WBfcKeiC1ePMFzCCMN57KG1Hw "Python 3.8 (pre-release) – Try It Online")
the program stops by crashing due to an `IndexError`. To avoid crashing, `[0]` must be replaced by `[:1]` for the cost of 1 byte
## How it works?
* I started from the quine `exec(s:="print('exec(s:=%r)'%s)")`
then the core program is the following :
```
from random import*
c='e'
while c:
print(end=c)
c=choice('<the quine string>'.split(c)[1:])[0]
```
* I assign `c` to the first letter of our quine (`e`).
while c is not the empty string :
* I print `c`
* I randomly choose a successor of `c` beween all possible successor
to choose a successor :
* let say our string is `"abacbdeb"` and I want a successor of `'b'`:
* I split the string using `'b'` as separator : `['a','ac','de','']`
* I remove the first substing which corresponds to the char before the first occurence of `b` : `['ac','de','']`
* I take up to 1 char of these substring : `['a','d','']`
If the char is at the end of a string, it will have the empty string as potential successor and will crash the program when atempting to get its first character. It only works beacuse no char is repeated twice.
] |
[Question]
[
We've had a [couple](https://codegolf.stackexchange.com/questions/60315/primes-of-ulams-spiral) of [challenges](https://codegolf.stackexchange.com/questions/4577/show-ulams-spiral) about the Ulam spiral. But that's not enough.
In this challenge we will plot a triangular Ulam spiral (as opposed to the usual, square Ulam spiral). Here's a sketch of what the spiral looks like.
[](https://i.stack.imgur.com/n4BpX.png)
As we know, the [Ulam spiral](https://en.wikipedia.org/wiki/Ulam_spiral) arranges all natural numbers in an outward spiral, and marks only those that are prime. So in the above sketch only the numbers that appear in black (the primes) would be shown.
## The challenge
Accept a number *N* as input and display the triangular Ulam spiral up to that number.
* Input can be stdin or function argument.
* The spiral should turn in the positive direction (that is, counter-clockwise), as in the above figure.
* Any of the 120-degree turns of the above figure would be valid, and the turn may be different for different inputs. But the lowest side of the implied triangles should be horizontal, as the only allowed turns are (multiples of) 120 degrees.
* The code should run theoretically (given enough time and memory) for any *N* up to what is allowed by any intermediate calculations you do with your default data type. `double` is enough; no need for large integer types.
* All built-in functions allowed.
* I won't accept my own answer (not that I think it would be the shortest anyway...).
## Output formats
Choose any of the following.
1. **Display a graph** with a marker (dot, circle, cross, whatever you prefer) at prime numbers, and nothing at non-prime numbers. Scale need not be the same for the two axes. That is, the implied triangles need not be equilateral. Axes, grid lines and axis labels are optional. Only the markers at the prime numbers are required.
An example output for *N* = 12 would be as follows (compare with the above sketch). The second plot is a more interesting example, corresponding to *N* = 10000.
[](https://i.stack.imgur.com/sCN3u.png)
[](https://i.stack.imgur.com/Dkq3j.png)
2. Produce an **image file** with the above, in any well known image format (such as png, tiff, bmp).
3. Display the spiral as **ASCII art**, using a single character of your choice for primes and blank space for non-primes, with a blank space to separate number positions in the same row. Leading or trailing spaces or newlines are allowed. For example, the *N* = 12 case using `o` as character would be
```
o
· ·
· o ·
o · ·
· o · o
```
where of course only the `o` mark at primes would actually be displayed. The `·` at non-primes is shown here for reference only.
# Winning criterion
~~The actual reward is seeing for yourself those amazing patterns~~ Code golf, shortest code wins.
[Answer]
## CJam, ~~49~~ 42 bytes
```
Lri{)mp0S?}%{1$,)/(a@Wf%z+\L*}h;eeSff*W%N*
```
Input as a single integer in STDIN. Output as an ASCII grid with `0` for primes. The rotation of the spiral is not consistent: the largest number of the spiral will always be on the bottom row.
[Test it here.](http://cjam.aditsu.net/#code=Lri%7B)mp0S%3F%7D%25%7B1%24%2C)%2F(a%40Wf%25z%2B%5CL*%7Dh%3BeeSff*W%25N*&input=2346)
### Explanation
The basic idea is to represent the triangle as a ragged 2D array while doing the computation. You get this array by reversing the lines and aligning all rows to the left:
```
4
5 3
6 1 2
7 8 9 A
```
Would be represented as
```
[[7 8 9 A]
[6 1 2]
[5 3]
[4]]
```
Since we've mirrored the line, we want to roll up the spiral in a *clockwise* manner. That's convenient, because all we need to do is rotate the triangle counter-clockwise and prepend the next sublist in order. We can rotate the ragged array by reversing all lines and transposing it:
```
[[B C D E F]
[[7 8 9 A] [[A 9 8 7] [[A 2 3 4] [A 2 3 4]
[6 1 2] reverse [2 1 6] transpose [9 1 5] prepend [9 1 5]
[5 3] ----> [3 5] ------> [8 6] ----> [8 6]
[4]] [4]] [7]] [7]]
```
So here is the code. One detail I'd like to draw attention to is the last bit that creates the triangular layout. I think that's rather nifty. :)
```
L e# Push an empty array. This will become the spiral.
ri e# Read input and convert to integer N.
{ e# Map this block over 0 to N-1...
) e# Increment to get 1 to N.
mp e# Test for primality.
0S? e# Select 0 or a space correspondingly.
}%
{ e# While the list we just created is not empty yet...
1$ e# Copy the spiral so far.
,) e# Get the number of lines and increment.
/ e# Split the list into chunks of that size.
(a@ e# Pull off the first chunk, wrap it in an array, pull up the spiral.
Wf% e# Reverse the lines of the spiral.
z e# Transpose the spiral.
+ e# Prepend the new line.
\L* e# Swap with the remaining chunks and join them back together into a single list.
}h
; e# Discard the empty list that's left on the stack.
ee e# Enumerate the spiral. This turns each line into a pair of 0-based index
e# and the line itself.
Sff* e# Multiply each element of each pair with a space. For the enumeration index i,
e# this produces a string of i spaces - the required indentation (keeping in
e# mind that our spiral is still upside down). For the line itself, this
e# riffles the cells with spaces, creating the required gaps between the cells.
e# All of this works because we always end the spiral on the bottom edge.
e# This ensures that the left edge is always complete, so we don't need
e# different indentation such as in the N=12 example in the challenge.
W% e# Reverse the lines to make the spiral point upwards.
N* e# Join the lines with linefeeds.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~48~~ 36 bytes
```
:1-H*X^.5+Y[2j3/*YP*ZeYsG:Zp)'.'2$XG
```
Uses [current release (9.3.0)](https://github.com/lmendo/MATL/releases/tag/9.3.0).
[**Try it online!**](http://matl.tryitonline.net/#code=OjEtSCpYXi41K2syajMvKllQKlplWXNHOlpwKScuJzIkWEc&input=MTAwMA) ~~No idea how the online compiler manages to translate graphic output to ASCII, but it does~~ This produces an approximate ASCII plot thanks to an [Octave feature](https://stackoverflow.com/a/13747962/2586922) that is supported by the online compiler!
*Edit (April 4, 2016): the function `Y[` has been renamed to `k` since release 13.0.0. The link to the online compiler incorporates this change, so that the code can be tested.*
### Example
```
>> matl
> :1-H*X^.5+Y[2j3/*YP*ZeYsG:Zp)'.'2$XG
>
> 20000
```
produces the graphical output (MATLAB version shown):
[](https://i.stack.imgur.com/oQD6D.png)
### Explanation
The code uses complex numbers to trace the path followed by the spiral. As can be seen from the first figure in the challenge, each straight leg of the spiral is a segment with increasing length 1, 2, 3, 4 ... and cyclically increasing orientation 120 degrees, 240 degrees, 0 degress, 120 degress...
The code first generates the individual complex displacements from each integer number to the next. These complex displacements have magnitude 1 and angle `2*pi/3`, `4*pi/3` or `0` (in radians). Thus they can be easily generated as imaginary exponentials. For that, the integer sequence 0,1,2,2,3,3,3,4,4,4,4... is used first.
This integer sequence is almost like the "n appears n times" sequence ([OEIS A002024](https://oeis.org/A002024)), and can be obtained as `floor(sqrt(2*n)+.5)` where `n` is 0,1,2,3,... . Multiplying by `2j*pi/3`, where `j` is the imaginary unit, produces the desired complex displacements.
The displacements are accumulated to compute the positions corresponding to the integer numbers in the spiral. The first integer number in the spiral, which is `1`, is arbitrarily located at position `1` in the complex plane.
Finally, the positions corresponding to non-prime numbers are discarded, and the rest are plotted in the complex plane.
```
:1-H*X^.5+Y[ % floor(sqrt(2*n)+.5) for n from 0 to N-1, where N is implicit input
2j3/*YP*Ze % exp(2j*pi/3* ... )
Ys % cumulative sum. Produces complex positions
G: % vector 1,2...,N, where N is previous input
Zp % logical index to select only prime numbers
) % use that index to keep only complex positions of primes
'.'2$XG % plot using marker '.'
```
[Answer]
Drawing should be done with
# LaTeX / PGF, 527 ~~594~~ bytes
```
\documentclass{standalone}\usepackage{pgf}\let\z\let\z\e\advance\z\f\ifnum\z\h\the\z\a\newcount\a\i\a\j\a\l\a\x\a\y\a\p\a\q\a\n\i=1\l=1\p=-1\q=1\def\m#1{\e\i by1\e\j by1\e\x by\h\p\e\y by\h\q\pgfmathparse{isprime(\h\i)}\f\pgfmathresult=1\pgfpathcircle{\pgfpoint{\h\x cm}{\h\y cm}}3pt\fi\f\j=\l\e\l by1\j=0\f\p=1\p=-1\q=1\else\f\p=-1\p=0\q=-1\else\p=1\q=0\fi\fi\fi\f#1>0\e#1by-1\m#1\fi}\begin{document}\begin{pgfpicture}\pgftransformcm10{cos(60)}{sin(60)}\pgfpointorigin\n=4000\m\n\pgfusepath{fill}\end{pgfpicture}\end{document}
```
527 bytes is the full document as above, i.e. including preamble and parameter (here 4000, so ~523 without parameter). Produces a PDF file.
Basic idea: well, just draw. Uses [a matrix transformation](https://tex.stackexchange.com/a/61190/23992) for a triangular grid. Only problem is that also the dots are affected (and stretched) out by the transformation. So I choose for ellipse markers :) what I mean by that is clear in the second image (n=250, 5pt).
Another caveat: can only handle up to a bit less than 5000 because of TeX's maximum stack size. The first image is for n=4000. [Apparently it is possible to increase the stack size](https://tex.stackexchange.com/a/27586/23992), I didn't try it.
Uses PGF's `isprime()`.
[](https://i.stack.imgur.com/rKbjo.png)
[](https://i.stack.imgur.com/W7ryk.png)
Ungolfed:
```
\documentclass[border=10cm]{standalone}
\usepackage{pgf}
\newcount\ulami
\newcount\ulamj
\newcount\ulamlen
\newcount\ulamx
\newcount\ulamy
\newcount\ulamdx
\newcount\ulamdy
\ulami=1 %
\ulamj=0 %
\ulamlen=1 %
\ulamdx=-1 %
\ulamdy=1 %
\ulamx=0 %
\ulamy=0 %
\def\ulamplot#1{%
\advance\ulami by 1 %
\advance\ulamj by 1 %
\advance\ulamx by \the\ulamdx %
\advance\ulamy by \the\ulamdy %
\pgfpathmoveto{\pgfpoint{\the\ulamx cm}{\the\ulamy cm}}
\pgfmathparse{isprime(\the\ulami)}
\let\r=\pgfmathresult
\ifnum\r=1
\pgfpathcircle{\pgfpoint{\the\ulamx cm}{\the\ulamy cm}}{5pt}
\fi
\ifnum\ulamj=\the\ulamlen %
\advance\ulamlen by 1 %
\ulamj=0 %
\ifnum\ulamdx=1 %
\ulamdx=-1 %
\ulamdy=1 %
\else%
\ifnum\ulamdx=-1 %
\ulamdx=0 %
\ulamdy=-1 %
\else%
\ulamdx=1 %
\ulamdy=0 %
\fi
\fi
\fi
\ifnum#1>0 %
\advance#1 by -1 %
\ulamplot{#1}%
\fi
}
\begin{document}
\begin{pgfpicture}
\pgfmathsetmacro{\x}{cos(60)}
\pgfmathsetmacro{\y}{sin(60)}
\pgftransformcm{1}{0}{\x}{\y}{\pgfpointorigin}
\pgfpathmoveto{\pgfpointorigin}
\color{blue}
\newcount\ulamn
\ulamn=400
\ulamplot{\ulamn}
\pgfusepath{stroke,fill}
\end{pgfpicture}
\end{document}
```
[Answer]
# Mathematica, 94 bytes
```
ListPlot@Accumulate[Join@@Table[ReIm@Exp[2i Pi/3I],{i,2#^.5},{i}]][[Prime@Range@PrimePi@#-1]]&
```
**Result**
```
%[10000]
```
[](https://i.stack.imgur.com/652of.png)
[Answer]
# Python, 263 bytes
Being new to Python, there is surely room for improvement :)
```
from matplotlib.pyplot import*
from math import*
def f(m):
s=[];X=[];Y=[];i=x=y=0
while len(s)<m:i+=1;s+=[i%3*pi*2/3]*i
for i in range(m):
x+=cos(s[i]);y+=sin(s[i]);j=i+2
if all(map(lambda a:j%a>=1,range(2,int(j**.5+1)))):X+=[x];Y+=[y]
scatter(X,Y);show()
```
Example:
```
f(100000)
```
[](https://i.stack.imgur.com/Io4K3.png)
[Answer]
# R, 137 bytes
Uses only built-in functions, even for prime numbers. Given its vectorized approach instead of iterative, it is fast, but cannot handle huge numbers.
Golfed:
```
g=function(m){M=1:m;s=rep(M,M)[M]%%3*pi*2/3;k=cumsum;j=sapply(seq(s)+1,function(n)n<4|all(n%%2:n^.5>=1));plot(k(cos(s))[j],k(sin(s))[j])}
```
Ungolfed:
```
g=function(m) {
M = 1:m
s = rep(M,M)[M] %% 3 * pi * 2/3
k=cumsum
j=sapply(seq(s)+1,function(n)n<4|all(n%%2:n^.5>=1)) # primes
plot(k(cos(s))[j],k(sin(s))[j]) # cumulated coordinates
}
```
Example:
```
g(10000)
```
[](https://i.stack.imgur.com/uO2Fs.png)
] |
[Question]
[
Based on the "binary, but with twos" notation mentioned in [this numberphile video](http://youtu.be/zv5M9zuZiXo?t=1m21s), write a function that takes a single number as input and outputs *all* variations of that number in a "binary" system where twos are allowed.
### Rules
* Code must only be a function/method, not a full program
* Input is an integer passed as the sole parameter to the function
* Output is *all* valid variations of the input number converted to "binary, but with twos" notation
* Output is the return value of the function, but can be in whatever format is convenient as long as it's obvious (eg, 3 ints, 3 strings, comma/space delimited string, array of ints, etc), order is unimportant
* In the unlikely event that a language happens to contain a built-in function to achieve the result, it's disallowed
* Shortest code in bytes is the winner
### Explanation of the output
By example, if you're passed the number `9`, you can convert it to binary as `1001`, but if you allowed `2`s in each position, you could also write it as `201` (i.e. `2*4 + 0*2 + 1*1`), or `121` (i.e. `1*4 + 2*2 + 1*1`), as shown in this table:
```
+----+----+----+----+
| 8s | 4s | 2s | 1s |
+----+----+----+----+
| 1 | 0 | 0 | 1 |
| 0 | 2 | 0 | 1 |
| 0 | 1 | 2 | 1 |
+----+----+----+----+
```
So, if passed `9`, your function would need to return the three numbers, `1001`, `201` and `121`.
Format and order are irrelevant, so long as it's obvious (i.e. `[121,201,1001]`, `"0201 0121 1001"`, `("1001","121","201")` are valid results when given an input of `9`).
### Examples
* `2` => `10, 2`
* `9` => `1001, 201, 121`
* `10` => `1010, 210, 202, 1002, 122`
* `23` => `2111, 10111`
* `37` => `100101, 20101, 100021, 20021, 12101, 12021, 11221`
[Answer]
## GolfScript (25 bytes) / CJam (19 17 bytes)
GolfScript:
```
{:^.*,{3base}%{2base^=},}
```
This creates an anonymous function (see meta discussion about [permissibility of anonymous functions](http://meta.codegolf.stackexchange.com/q/1501/194)).
[Online demo](http://golfscript.apphb.com/?c=ezpeLiosezNiYXNlfSV7MmJhc2VePX0sfQoKIyMgVGVzdCBzdWl0ZQpbMiA5IDEwIDIzIDM3XSV7WycgJ10qcHV0c30v)
A straight translation into CJam is (with thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for shaving a couple of characters)
```
{:X_*,3fb{2bX=},}
```
### Dissection
```
{ # Function boilerplate
:^ # Store parameter as variable ^
.* # Square parameter - see detailed explanation below
,{3base}% # Produce an array of 0 to ^*^-1 in ternary
{2base^=}, # Filter to those which evaluate to ^ in binary
}
```
The reason for the squaring operation is that we need to iterate up to the largest possible value whose ternary representation, interpreted in binary, is equal to `^`. Since `2 = 10`, the "normal" binary representation of `^` is the one which matters. If we convert that to ternary, we find that the "worst" cases are powers of 2. An optimal approach would be to take the argument to the power of `ln 3/ln 2 ~= 1.585`, but squaring is much shorter.
[Answer]
# Python 2 (59 bytes)
```
S=lambda n,B="":[B][n:]or~n%2*S(n/2-1,"2"+B)+S(n/2,`n&1`+B)
```
*(Much thanks to @grc, @xnor and @PeterTaylor for helping out in chat)*
Simple recursion, call with `S(23)` or similar.
## Explanation
The general idea is that if `n`'s binary expansion ends in a `1`, then any pseudo-binary ("binary, but with twos") expansion must also end with a `1`. Otherwise it could end with `0` or `2`.
Hence we look at the last bit of `n`, divide out and branch accordingly.
## Dissection
```
S=lambda n,B="": # Lambda expression
[B][n:]or # Short circuit, return [B] if n==0 else what follows
~n%2* # Keep next list result if n is even else turn into []
S(n/2-1,"2"+B) # Add a "2" to B, recurse
+
S(n/2,`n&1`+B) # Add "0" or "1" to B depending on n's last bit, recurse
```
Variables:
* `n`: The number we want to find pseudo-binary expansions of
* `B`: A pseudo-binary string being built right-to-left
[Answer]
# Bash+coreutils, 77
```
f()(seq `dc -e2o$1p`|sed '/[3-9]/d;s/.*/&n9P2i&pAi/'|dc|grep -Po ".*(?= $1)")
```
(That is a `TAB` character in the grep expression.)
This is bending this rule a bit:
*"In the unlikely event that a language happens to contain a built-in function to achieve the result, it's disallowed"*
It turns out that `dc` has **the reverse** of what we need built in. For instance if we set the input base to 2 and input a binary number with twos, it will correctly parse it. (Similarly if the input mode is base 10, then A-F are parsed as decimal "digits" 10-15).
`seq` creates a list of all decimal numbers up to the standard binary representation of n, parsed as a decimal. Then all numbers that contain anything other than {0,1,2} are filtered out. Then `dc` parses the remaining numbers as binary to see which evaluate back to n.
Bash functions can only "return" scalar integers 0-255. So I'm taking the liberty of printing the list to STDOUT as my way of "returning". This is idiomatic for shell scripts.
### Output:
```
$ f 2
2
10
$ f 9
121
201
1001
$
```
[Answer]
# Haskell, 82
```
t n=[dropWhile(==0)s|s<-mapM(\_->[0..2])[0..n],n==sum[2^(n-i)*v|(i,v)<-zip[0..]s]]
```
this is just a brute-force solution. it is very inefficient, because it is expected to crunch through 3^n possibilities.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes, language postdates challenge
```
ṗ@3Ḷ¤Ḅ=¥Ðf
```
[Try it online!](https://tio.run/nexus/jelly#ARgA5///4bmXQDPhuLbCpOG4hD3CpcOQZv///zU "Jelly – TIO Nexus")
A bruteforce solution up to a number of hyperbits equal to the input (this format is known as "hyperbinary"). As such, it's incredibly inefficient, running in O(3n).
## Explanation
```
ṗ@3Ḷ¤Ḅ=¥Ðf
ṗ@ Construct all lists with the given length, and elements taken from
3Ḷ¤ the list [0,1,2]
Ðf then take only those elements which
Ḅ=¥ when interpreted as binary, equal {the original number}
```
[Answer]
# PHP, 138 Bytes
```
function p($v,$i=0,$r=""){global$a;if($v==0)$a[]=$r?:0;elseif($v>0)for(;$l<3;)p($v-2**$i*$l,$i+1,+$l++.$r);}p($argv[1]);echo join(",",$a);
```
## Breakdown
```
function p($v,$i=0,$r=""){
global$a;
if($v==0)$a[]=$r?:0; # fill result array
elseif($v>0) # make permutations
for(;$l<3;)
p($v-2**$i*$l,$i+1,+$l++.$r); #recursive
}
p($argv[1]);
echo join(",",$a); # Output
```
[Answer]
C++, 159 bytes
```
void c(int x,string r){int i,t=0,s=r.size();if(s<8){if(r[0]>48){for(i=0;i<s;i++)t+=(r[s-i-1]-48)*1<<i;if(t==x)cout<<r<<" ";}for(char n=48;n<51;n++)c(x,r+n);}}
```
Test it [here](https://ideone.com/U2qXBl)
[Answer]
# k, 21 bytes
Uses the same method as Peter Taylor's Golfscript answer
```
{X@&x=2/:'X:3\:'!x*x}
```
Examples:
```
k) {X@&x=2/:'X:3\:'!x*x}9
(1 2 1;2 0 1;1 0 0 1)
k) {X@&x=2/:'X:3\:'!x*x}10
(1 2 2;2 0 2;2 1 0;1 0 0 2;1 0 1 0)
```
[Answer]
# [Haskell](https://www.haskell.org/), 80 bytes
```
f 0=[[]]
f n=((++[n-2*d])<$>f d)++[x|n==2*d,x<-(++[2])<$>(f$d-1)]where d=n`div`2
```
[Try it online!](https://tio.run/##JY3PCoIwAMbvPcWH7LDlBjYPETifoE4dOtigxRxKuiStJHr3ter28fv@NWa81F0XgkOmqkrrhYNXlKZp5YVcWs0KUjpYFsH89kpFxudCfAPyZ1JHrFgx/WzqWw2r/Mm2j5MM3QiFSnJsOFYZh8w58rVe9Kb10enNsMNwn/bTbetB8GqHQzs1oEeDsyjp2FyfMPE2gSiRpOmfnBlDXCbfPlyU4QM "Haskell – Try It Online")
Recursive solution, and my first Haskell golf.
```
-- recursive definition
-- base case: a sum of 0 is possible as simply a 0-length "binary-with-two" string
f 0=[[]]
-- f n=all possibilities to form n
f n =
-- like normal binary, can have a last digit of 0 or 1 if even or odd, respectively
-- consider n`mod'`2 = n-2*d
(
(++[n-2*d])<$> -- add that last digit to each
f d -- possibility from n/2
)
-- additional possibility of last digit 2, only if n is even
n==2*d -- if n is even:
[x| ,x<-(++[2])<$>(f$d-1)] -- add that last digit 2 to each possibility from (n-2)/2
where d=n`div`2
```
] |
[Question]
[
Write a program that takes two lines of input and uses the first as a key phrase to encrypt the second according to the Playfair encryption technique.
[Wikipedia describes Playfair encryption in some detail](http://en.wikipedia.org/wiki/Playfair_cipher), but to avoid any ambiguity, here's a brief summary:
**1. Generate a key table:**
Replace all occurrences of `J` in the key phrase with `I`, then strip all non-alphabet characters and repeated characters. Insert into a 5×5 encryption table, filling the remaining cells with the rest of the alphabet (except `J`; we don't like `J`).
Example:
```
S T A C K
O V E R F
Stack Overflow --> STACKOVERFLW --> L W B D G
H I M N P
Q U X Y Z
```
**2. Prepare the message to be encrypted**
Replace every `J` with an `I`, strip all non-alphabet characters and split into pairs, using an `X` to break any pairs that contain the same letter twice. If you end up with an odd number of letters, add `X` at the end. (Note: Numerals have to be spelt out in full — `ONE`, `TWO`, `THREE`, etc. — but you can assume this has already been done for you.)
Example:
```
In:
The cat crept into the crypt, crapped, and crept out again.
Out:
TH EC AT CR EP TI NT OT HE CR YP TC RA PX PE DA ND CR EP TO UT AG AI NX
```
**3. Encryption**
Encrypt each pair of letters in turn. If they are in different rows and columns of the key table, replace each with the letter from the same row in the column where the other letter is found (e.g., `VM`⇒`EI`, `LZ`⇒`GQ`). If they are in the same row (or column), choose the two characters immediately to the right (or below), wrapping around if necessary (e.g., `OE`⇒`VR`, `ZG`⇒`KP`).
Example:
```
In:
TH EC AT CR EP TI NT OT HE CR YP TC RA PX PE DA ND CR EP TO UT AG AI NX
Out:
SI RA CA RD FM VU IC VS MO RD ZN AK EC MZ MF BC YN RD FM SV TV KB TM MY
```
The string produced by this process is the encrypted message, which your program should output.
# Rules:
* The input text and key may be obtained from `stdin`, command line arguments or other such sources. Hard-coded input is not allowed.
* Your program must accept both upper and lower case text for the pass phrase and message.
* The encrypted output may be upper or lower case.
* Your program should accept key phrases of at least 64 characters in length, and message texts of at least 16 KB.
* You are not required to handle non-ASCII input.
* You may ignore the possibility of the letter pair `XX` occurring during encryption.
* There is no need to add whitespace to the output of the program.
* Your answer should include an example of a message, key phrase and encrypted output produced by your program.
* **This is a code golf challenge, so the answer with the shortest code (in bytes) will win.**
---
>
> **NOTE:** Please remember that you only need to break consecutive letters if they appear **in the same pair**. So for example `MASSACHUSETTS` should be encrypted as `MA SX SA CH US ET TS` — the double `S` has to be split, but the double `T` doesn't.
>
>
>
[Answer]
## ~~J~~ I\*, ~~536~~ ~~431~~ ~~417~~ ~~380~~ ~~263~~ ~~218~~ ~~203~~ ~~197~~ ~~186~~ 167
```
p=:4 :0
a=.u:65+9-.~i.26
,_2(5|,:~@|.@(=/)+$$,A.~5*1-0{=/)&.(5 5#:(~.n x,a)&i.)\(,'X'#~2|#)(({.,'X',}.)~1+2*1{&I._2{.\2=/\]) ::]^:_(n=:a(e.~#])'JI'charsub toupper)y
)
```
(with extensive suggestions from @algorithmshark)
example use:
```
'Stack Overflow' p 'The cat crept into the crypt, crapped, and crept out again.'
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
```
splits input correctly:
```
d=:(({.,'X',}.)~1+2*1{&I._2{.\2=/\]) ::]
d^:_ 'MASSACHUSETTS'
MASXSACHUSETTS
```
---
\*replace every `J` with an `I`, right?
[Answer]
## Ruby, ~~461~~ ~~411~~ ~~366~~ ~~359~~ ~~352~~ ~~346~~ 330 characters
```
k,m=$<.map{|x|x.tr(?j,?i).upcase.tr('^A-Z','').chars}
t=[*((k&k)|[*?A..?Z]-[?J]).each_slice(5)]
m=(m*'').gsub(/(.)\1/,'\1X\1').chars
c=->n{[t.index{|r|k=r.index n},k]}
$><<(m.size%2<1?m:m+[?X]).each_slice(2).map{|p,q|a,b,d,e=*c[p],*c[q]
a==d ?[t[a][(b+1)%5],t[d][(e+1)%5]]:b==e ?[t[(a+1)%5][b],t[(d+1)%5][e]]:[t[a][e],t[d][b]]}*''
```
Thanks to @daniero for saving... err, a *lot* of bytes. \o/
Here's the ungolfed code:
```
key = gets.chomp
msg = gets.chomp
transform = ->str{
str.gsub! 'j', 'i'
str.upcase!
str.gsub! /[^A-Z]/, ''
str.split('')
}
# 1. Generate a key table
key = transform[key]
chars = key.uniq + ([*?A..?Z] - key - ['J'])
tbl = Array.new(5) {
Array.new(5) {
chars.shift
}
}
# 2. Prepare the message
msg = transform[msg]
msg = msg.join('').gsub(/(.)\1/){ "#{$1}X#{$1}" }.split('')
msg = (msg.length % 2 == 0 ? msg : msg + ['X']).each_slice(2).to_a
# 3. Encryption
coords = ->chr{
i = -1
[tbl.index{|row| i = row.index chr}, i]
}
msg.map! do |c1, c2|
c1, c2 = coords[c1], coords[c2]
if c1[0] == c2[0]
# same row
[tbl[c1[0]][(c1[1] + 1) % 5], tbl[c2[0]][(c2[1] + 1) % 5]]
elsif c1[1] == c2[1]
# same column
[tbl[(c1[0] + 1) % 5][c1[1]], tbl[(c2[0] + 1) % 5][c2[1]]]
else
# neither
[tbl[c1[0]][c2[1]], tbl[c2[0]][c1[1]]]
end
end
# Output!
puts msg.join
```
Here's some sample outputs:
```
llama@llama:...code/ruby/ppcg23276playfair$ printf 'Stack Overflow\nThe cat crept into the crypt, crapped, and crept out again.\n' | ./playfair.rb; printf 'This is a password!\nProgramming Puzzles and Code Golf is a Stack Exchange site.\n' | ./playfair.rb
SIRAVXRDFMVUUYVSBLRDZNYVECMZMFBCYNRDFMSVTVKBVBMY
WDDEDSXIXOQFBTUYVQFISQWGRPFBWMESATAHHGMBVEITQFFISHMI
```
[Answer]
# C: ~~495~~ ~~401~~ ~~355~~ 341 characters
~~It's just a rough sketch as of now. I should be able to shave off at least a hundred characters.~~
Goal accomplished: more than a hundred characters (154 as of now) have mysteriously vanished from the code.
```
p[25],l[96],a=1,b,c;o(x,y){putchar(p[x%5^y%5?x/5*5+(x/5^y/5?y:x+1)%5:(x+5)%25]);}main(){for(;a&&((a=(b=getchar())>31)||(b=65))||b++<90;c=0)for(b&=-33;b/65-b/91&&p[c]^b-(b==74);p[c++]||(p[--c]=b-(b==74),l[b]=c));for(;b=getchar(),b=b>31?b&-33:(c=88),b=b/65-b/91?a?a^b?(c*=c==88,b):(c=b,88):(a=b,0):0,a&b&&(o(a=l[a],b=l[b]),o(b,a),a=c),c^88;);}
```
With some pleasant whitespace:
```
p[25],l[96],a=1,b,c;
o(x,y){
putchar(p[
x%5^y%5
?x/5*5+(x/5^y/5?y:x+1)%5
:(x+5)%25
]);
}
main(){
for(;
a&&(
(a=(b=getchar())>31)||
(b=65)
)||b++<90;
c=0
)for(
b&=-33;
b/65-b/91&&
p[c]^b-(b==74);
p[c++]||(
p[--c]=b-(b==74),
l[b]=c
)
);
for(;
b=getchar(),
b=b>31
?b&-33
:(c=88),
b=b/65-b/91
?a
?a^b
?(c*=c==88,b)
:(c=b,88)
:(a=b,0)
:0,
a&b&&(
o(a=l[a],b=l[b]),
o(b,a),
a=c
),
c^88;
);
}
```
I wrote the first iteration of the program on the verge of falling asleep, so it had a lot of superfluous meaningless statements and such. Most of that is rectified, but there are quite a few areas where improvement is most definitely possible.
[Answer]
# Matlab - 458 chars
```
function p=pf(k,p)
k=[upper(k),65:90];k(k==74)=73;k(k<65|k>90)='';[~,i]=unique(k,'first');k=reshape(k(sort(i)),5,5);e=[k,k(:,1);k(1,:)];p=upper(p);p(p==74)=73;p(p<65|p>90)='';n=length(p);for i=1:2:n
if i<n&&p(i)==p(i+1)p=[p(1:i),88,p(i+1:end)];end
n=length(p);end
if mod(n,2)p=[p,88];n=n+1;end
for i=1:2:n [x,y]=find(k==p(i));[w,z]=find(k==p(i+1));p(i:i+1)=[k(w,y),k(x,z)];if x==w p(i:i+1)=[e(w,y+1),e(x,z+1)];end
if y==z p(i:i+1)=[e(x+1,z),e(w+1,y)];end
end
```
Some examples:
```
octave:180> pf('Stack Overflow', 'The cat crept into the crypt, crapped, and crept out again.')
ans = SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
octave:181> pf('This is a password!','Programming Puzzles and Code Golf is a Stack Exchange site.')
ans = WDDEDSXIXOQFBTUYVQFISQWGRPFBWMESATAHHGMBVEITQFFISHMI
octave:182> pf('Matlab needs lambdas', 'Who thought elseif is good syntax?')
ans = XGQMFQPKQDSACDKGRIFPQNILDMTW
```
[Answer]
# Haskell - 711
Demo:
```
[timwolla@/data/workspace/haskell/PCG]ghc pcg-23276.hs
[1 of 1] Compiling Main ( pcg-23276.hs, pcg-23276.o )
Linking pcg-23276 ...
[timwolla@/data/workspace/haskell/PCG]./pcg-23276 "Stack Overflow" "The cat crept into the crypt, crapped, and crept out again."
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
```
Code:
```
import Data.List
import Data.Char
import Data.Maybe
import System.Environment
main=do a<-getArgs
putStrLn$concat$map(x (a!!0))$map(\x->if (length x)==1 then x++"X"else x)$s 2$concat$map(\x->if (length x)==1then x else intersperse 'X' x)$group$p (a!!1)
p=map(\x->if x=='J' then 'I' else x).filter(isUpper).map toUpper
k x=y++(delete 'J'$['A'..'Z']\\y)where y=nub$p x
u l m=(div i 5,mod i 5)where i=fromJust$elemIndex l$k m
x y z
|a/=c&&b/=d=(e!!(a*5+d)):(e!!(c*5+b)):[]
|a==c=(e!!(a*5+(mod(b+1)5))):(e!!(c*5+(mod(d+1)5))):[]
|True=(e!!((5*(mod(a+1)5))+b)):(e!!((5*(mod(c+1)5))+d)):[]
where
o=u(z!!0)y
t=u(z!!1)y
a=fst o
b=snd o
c=fst t
d=snd t
e=k y
s _ []=[]
s n l=(take n l):(s n(drop n l))
```
Large version:
```
import Data.List
import Data.Char
import Data.Maybe
encryptAll key text = map (encrypt key) (transformValue text)
clean x = map (\x -> if x == 'J' then 'I' else x) $ filter (isUpper) $ map (toUpper) x
transformKey x = y ++ (delete 'J' $ ['A'..'Z'] \\ y)
where y = nub (clean x)
transformValue x = map (\x -> if (length x) == 1 then x ++ "X" else x) $ split 2 $ concat $ map (\x -> if (length x) == 1 then x else intersperse 'X' x) $ group $ clean x
search letter key = (div index 5, mod index 5)
where index = fromJust $ elemIndex letter $ transformKey key
encrypt key chars
| rowA /= rowB && colA /= colB = (key' !! (rowA * 5 + colB)) : (key' !! (rowB * 5 + colA)) : []
| rowA == rowB = (key' !! (rowA * 5 + ((colA + 1) `mod` 5))) : (key' !! (rowB * 5 + ((colB + 1) `mod` 5))) : []
| otherwise = (key' !! ((5 * ((rowA + 1) `mod` 5)) + colA)) : (key' !! ((5 * ((rowB + 1) `mod` 5)) + colB)) : []
where
rowA = fst $ search (head chars) key
colA = snd $ search (head chars) key
rowB = fst $ search (last chars) key
colB = snd $ search (last chars) key
key' = transformKey key
-- http://stackoverflow.com/a/12876438/782822
split :: Int -> [a] -> [[a]]
split _ [] = []
split n l
| n > 0 = (take n l) : (split n (drop n l))
| otherwise = error "Negative n"
```
[Answer]
# Pyth - 111
Too late for competing, I just wanted to share. Here's
[the encoder](https://pyth.herokuapp.com/?code=L%40G%3Arb0%5Cj%5CiJ%7By%2BwGKywWhZ%3DZh%2a2xlR%7BRcK2+1IhZ%3DKXZK%5Cx%3BM%40J%2BG%3F%21eH5%3F%21hH%3Fq4%25G5_4+1eHVcK2A%2CxJhNxJeN%3DZ-V.DH5.DG5pgGZpgH_RZ&input=Stack+Overflow%0AThe+cat+crept+into+the+crypt%2C+crapped%2C+and+crept+out+again.&debug=0)
and
[decoder](https://pyth.herokuapp.com/?code=L%40G%3Arb0%5Cj%5CiJ%7By%2BwGKywWhZ%3DZh%2a2xlR%7BRcK2+1IhZ%3DKXZK%5Cx%3BM%40J%2BG%3F%21eH_5%3F%21hH%3F%21%25G5+4_1eHVcK2A%2CxJhNxJeN%3DZ-V.DH5.DG5pgGZpgH_RZ&input=Stack+Overflow%0Asiracardfmvuicvsmordznakecmzmfbcynrdfmsvtvkbtmmy&debug=0)
```
L@G:rb0\j\iJ{y+wGKywWhZ=Zh*2xlR{RcK2 1IhZ=KXZK\x;M@J+G?!eH5?!hH?q4%G5_4 1eHVcK2A,xJhNxJeN=Z-V.DH5.DG5pgGZpgH_RZ
```
**Explanation:**
```
L b L defines common method y(b); 2 calls helps us saving two bytes
r 0 lowercase r(b,0)
: \j\i : replaces all occurrences of "j" with "i"
@G strips all non-alphabetic characters; G = pyth built-in alphabet
w first input argument
+ G appends the alphabet (G)
y calls y(b)
{ { makes set (removes duplicated characters)
J assigns result to 'J' (KEY VARIABLE)
Kyw assigns output from y(second input argument) to 'K' (TEXT VARIABLE)
WhZ ; While (Z+1 != 0) <-> While (Z != -1) <-> While mismatched items found
cK2 list of K pairs. e.g. 'ABCCDDE' -> [AB, CC, DD, E]
lR{R l length of { unique characters. e.g. [2, 1, 1, 1]
x 1 1-length first index. e.g. 1
h*2 *2+1 (Index in K) e.g. 3 'ABC CDDE'
=Z Assigns to 'Z'
IhZ if (Z != -1) <-> if (mismatched found)
=KXZK\x X Inserts at Z index in K an 'x' and reassigns to 'K' e.g. 'ABCXC...'
M M defines function g(G, H) where G index H vector (INDEX CONVERSION)
?!eH if (same col)
5 then +5
?!hH else { if (same row)
?q4%G5 then if (last col)
_4 then -4
1 else +1
eH else col
+G index += increment
@J J[index]
VcK2 V loops over cK2 list of K pairs
,xJhNxJeN x returns pair members index in J
A A assigns G = xJhN, H = xJeN
.DH5 .D returns [row, col] = [i/5,i%5] of 5xn matrix from index of H
.DG5 idem. of G
-V Subtracts vectors (RELATIVE POSITION)
=Z Assigns to 'Z'
pgGZ p prints g(G, Z) return value
pgH_RZ p prints g(H, _RZ) return value, and _R changes signs of Z vector
```
**Sample Key/Message/Output:**
```
Stack Overflow
Gottfried Leibniz is famous for his slogan Calculemus, which means Let us calculate. He envisioned a formal language to reduce reasoning to calculation.
lfaukvvnrbbomwpmupkoexvqkovfimaqohflcmkcdsqwbxqtlintinbehcbovttksbtybsavmormwuthrhrbkevfxebqbspdxtbfsvfrwyarfrctrhmpwkrssbtybsvurh
```
[Answer]
# C, 516
Linefeeds added for improved ~~legibility~~ presentation. (Legibility went out the window, I'm afraid.)
```
#define Z(u,v) putchar(o[u]),putchar(o[v])
#define X while((Y=getchar())>31){Y&=223;if(Y==74)Y--;if(Y<65||Y>90
P,L,A,Y,f,a,i,r,c=512,o[25],d[2],*e=o;Q(){for(i=0;o[i]!=d[0];i++);i-=(f=i%5);
for(r=0;o[r]!=d[1];r++);r-=(a=r%5);if(f==a)Z(f+(i+5)%25,a+(r+5)%25);
else if(i==r)Z((f+1)%5+i,(a+1)%5+r);else Z(a+i,f+r);}main(){X||c&(A=1<<Y-65))continue;
c|=A;*e++=Y;}A=1;Y=65;for(P=0;P<25;P++){if(!(c&A))*e++=Y;
if(++Y==74)Y++,A+=A;A+=A;}L=0;X)continue;if(L&&Y==*d)d[1]=88,Q(),*d=Y;
else d[L]=Y,L=1-L;if(!L)Q();}if(L)d[1]=88,Q();}
```
**Example:**
```
$ ./pf
Playfair
The quick brown fox jumps over the lazy dog
QMHNPEKSCBQVTPSVEPEFTQUGDOKGAYXFRTKV
```
[Answer]
# Python 3, ~~709~~ ~~705~~ ~~685~~ 664
Accepts input from stdin.
```
from string import ascii_uppercase as a
from itertools import product as d
import re
n=range
k=input()
p=input()
t=lambda x: x.upper().replace('J','I')
s=[]
for _ in t(k+a):
if _ not in s and _ in a:
s.append(_)
m=[s[i:i+5] for i in n(0,len(s),5)]
e={r[i]+r[j]:r[(i+1)%5]+r[(j+1)%5] for r in m for i,j in d(n(5),repeat=2) if i!=j}
e.update({c[i]+c[j]:c[(i+1)%5]+c[(j+1)%5] for c in zip(*m) for i,j in d(n(5),repeat=2) if i!=j})
e.update({m[i1][j1]+m[i2][j2]:m[i1][j2]+m[i2][j1] for i1,j1,i2,j2 in d(n(5),repeat=4) if i1!=i2 and j1!=j2})
l=re.findall(r'(.)(?:(?!\1)(.))?',''.join([_ for _ in t(p) if _ in a]))
print(''.join(e[a+(b if b else 'X')] for a,b in l))
```
Example:
```
mfukar@oxygen[/tmp]<>$ python playfair.py
Stack Overflow
The cat crept into the crypt, crapped, and crept out again.
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
```
[Answer]
## Python: 591 bytes
```
import sys
l=list
n=len
a=[sys.stdin.readline().upper().replace('J','I') for i in (1,2)]
b=l('ABCDEFGHIKLMNOPQRSTUVWXYZ')
def z(x):
a=0
if x in b:
b.remove(x)
a=1
return a
c=l(filter(z,a[0]))+b
d=[x for x in a[1] if x in c]
e=1
while e<n(d):
if d[e-1]==d[e]:
d.insert(e,'X')
e+=2
if n(d)%2>0:
d+='X'
def y(i):
z=c.index(d[i])
return z/5,z%5
x=lambda i,j:c[(i%5)*5+(j%5)]
def w(i):
e,f=y(i)
g,h=y(i+1)
if e==g:
z=x(e,f+1)+x(g,h+1)
elif f==h:
z=x(e+1,f)+x(g+1,h)
else:
z=x(e,h)+x(g,f)
print z,
e=0
while e<n(d):
w(e)
e+=2
print
```
This uses `stdin` to get the key and the message in that order. I hope it's not cheating to use a flat list to store the encryption matrix, because that made working with the matrix pretty simple. Here are some example runs:
```
>python playfair.py
Stack Overflow
The cat crept into the crypt, crapped, and crept out again.
SI RA CA RD FM VU IC VS MO RD ZN AK EC MZ MF BC YN RD FM SV TV KB TM MY
>python playfair.py
Stack Overflow
The quick red fox jumps over the lazy brown dog.
SI OX TU KS FR GR EQ UT NH OL ER VC MO BS QZ DE VL YN FL
```
[Answer]
## Java - 791
My first golf, so any criticism is welcome. Using Java because I shouldn't. It doesn't seem so bad; less than double the size of the current leader. I was expecting it to be bigger since it's, well, *Java* :)
```
public class P{static String c(String s){return s.toUpperCase().replace('J','I').replaceAll("[^A-Z]","");}static int f(char[]a, char n){for(int i=0;i<a.length;i++)if(a[i]==n)return i;return -1;}public static void main(String[]a){int i=0,k,l;char j=0;String g=c(a[0]);char[]e,b,h=c(a[1]).toCharArray();b=new char[25];for(;j<g.length();j++)if(j==g.indexOf(g.charAt(j)))b[i++]=g.charAt(j);for(j=65;i<25;j++)if(f(b,j)<0&&j!=74)b[i++]=j;e=new char[h.length*2];for(i=0,j=0;j<h.length;){if(i%2>0&&h[j]==h[j-1])e[i++]=88;e[i++]=h[j++];}if(i%2>0)e[i++]=88;for(j=0;j<i;j+=2){k=f(b,e[j]);l=f(b,e[j+1]);if(k/5==l/5){e[j]=b[(k/5*5)+((k+1)%5)];e[j+1]=b[(l/5*5)+((l+1)%5)];}else if(k%5==l%5){e[j]=b[(k+5)%25];e[j+1]=b[(l+5)%25];}else{e[j]=b[(k/5*5)+(l%5)];e[j+1]=b[(l/5*5)+(k%5)];}}System.out.println(e);}}
```
With auto-format:
```
public class P {
static String c(String s) {
return s.toUpperCase().replace('J', 'I').replaceAll("[^A-Z]", "");
}
static int f(char[] a, char n) {
for (int i = 0; i < a.length; i++)
if (a[i] == n)
return i;
return -1;
}
public static void main(String[] a) {
int i = 0, k, l;
char j = 0;
String g = c(a[0]);
char[] e, b, h = c(a[1]).toCharArray();
b = new char[25];
for (; j < g.length(); j++)
if (j == g.indexOf(g.charAt(j)))
b[i++] = g.charAt(j);
for (j = 65; i < 25; j++)
if (f(b, j) < 0 && j != 74)
b[i++] = j;
e = new char[h.length * 2];
for (i = 0, j = 0; j < h.length;) {
if (i % 2 > 0 && h[j] == h[j - 1])
e[i++] = 88;
e[i++] = h[j++];
}
if (i % 2 > 0)
e[i++] = 88;
for (j = 0; j < i; j += 2) {
k = f(b, e[j]);
l = f(b, e[j + 1]);
if (k / 5 == l / 5) {
e[j] = b[(k / 5 * 5) + ((k + 1) % 5)];
e[j + 1] = b[(l / 5 * 5) + ((l + 1) % 5)];
} else if (k % 5 == l % 5) {
e[j] = b[(k + 5) % 25];
e[j + 1] = b[(l + 5) % 25];
} else {
e[j] = b[(k / 5 * 5) + (l % 5)];
e[j + 1] = b[(l / 5 * 5) + (k % 5)];
}
}
System.out.println(e);
}
}
```
Sample output:
```
>java P "Stack Overflow" "The cat crept into the crypt, crapped, and crept out again."
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
>java P "Write a PlayFair encryption program" "Write a program that takes two lines of input and uses the first as a key phrase to encrypt the second according to the Playfair encryption technique."
RITEWFCPGMWPGEBLYTWYQTXWINOLMWVNLECAXRNBURZWXWQILEWUWYWNQTFLDINWWEMICOTPYRIKWZRMGCBPGUOGPUWOKYGIQILYPFAPTIWMDPFLETGCEWODOWDZTZ
```
[Answer]
# JS (node) - 528 466
```
k=n(2)+'ABCDEFGHIKLMNOPQRSTUVWXYZ',p=n(3),t=o=''
for(i=0;i<k.length;i++)if(!~t.indexOf(k[i]))t+=k[i]
for(i=0;i<p.length;){a=f(c=p[i++]),b=f(!(d=p[i])||c==d?'X':(i++,d))
if(a.x==b.x)a.y=(a.y+1)%5,b.y=(b.y+1)%5
else if(a.y==b.y)a.x=(a.x+1)%5,b.x=(b.x+1)%5
else a.x=b.x+(b.x=a.x,0)
o+=t[a.x+a.y*5]+t[b.x+b.y*5]}console.log(o)
function f(c){x=t.indexOf(c);return{x:x%5,y:x/5|0}}
function n(a){return process.argv[a].toUpperCase().replace(/[^A-Z]/g,'').replace(/J/g,'I')}
```
Sample output:
```
$ node playfair "Stack Overflow" "The cat crept into the crypt, crapped, and crept out again."
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
$ node playfair "Lorem ipsum" "dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
CRORSDAHGAMQKPXDOFQMQAMSBSSPUPBPTDMOAHURNRCRLUAULRGNMLCPLSKDSBSBSQQAHMIGRERYMQCROREMAGDTSZIMUHAIAQRQALSGLAHSLZRQPIETAPDXRPNMSFRYMEBPZGHARKIEMIOGROIGREPUHSUPAQIMUHAPUOYRPGRLLRCRKPXDUYAINZ
```
[Answer]
# PHP 582
```
<? list($i,$k,$v)=array_map(function($v){return str_split(preg_replace('#[^A-Z]#','',strtr(strtoupper($v),'J','I')));},$argv);@$i=array_flip;$k=$i($k)+$i(range('A','Z'));unset($k['J']);$k=array_keys($k);$q=$i($k);for($i=1;$i<count($v);$i+=2){if ($v[$i-1]==$v[$i]){array_splice($v,$i,0,'X');}}if(count($v)%2)$v[]='X';for($i=1;$i<count($v);$i+=2){$c=(int)($q[$v[$i-1]]/5);$d=$q[$v[$i-1]]%5;$e=(int)($q[$v[$i]]/5);$f=$q[$v[$i]]%5;if($c==$e){$d=($d+1)%5;$f=($f+1)%5;}elseif($d==$f){$c=($c+1)%5;$e=($e+1)%5;}else{$t=$f;$f=$d;$d=$t;}$v[$i-1]=$k[$c*5+$d];$v[$i]=$k[$e*5+$f];}echo join($v);
```
[Ungolfed](https://github.com/einacio/codegolfing/blob/master/playfair.php)
[Decoder](https://github.com/einacio/codegolfing/blob/master/unplayfair.php)
outputs
```
$ php playfair.php "Stack Overflow" "The cat crept into the crypt, crapper, and crept out again."
SIRACARDFMVUICVSMORDZNAKECMZMFECYNRDFMSVTVKBTMMY
$ php playfair.php "This was codegolf?" "The full J answers is shorter than my preparation code :("
HIOKVGFHCMWTKZWSIYWIEPWAMWTCPNXQZKMOMEHSCPODEA
```
[Answer]
## Perl, 265
Very straightforward.
```
chomp(($k,$_)=map{uc=~y/A-Z//cdr=~y/J/I/r}<>."@{[A..Z]}",~~<>);1while$k=~s/((.).*)\2/$1/;while(/(.)((?=\1|$)|(.))/g){($a,$b,$c,$d)=map{$e=index$k,$_;5*int$e/5,$e%5}$1,$3||X;print substr$k,$_%25,1 for$a-$c?$b-$d?($a+$d,$c+$b):($a+5+$b,$c+5+$d):(++$b%5+$a,++$d%5+$c)}
```
Indented:
```
chomp(($k,$_)=map{uc=~y/A-Z//cdr=~y/J/I/r}<>."@{[A..Z]}",~~<>);
1while$k=~s/((.).*)\2/$1/;
while(/(.)((?=\1|$)|(.))/g){
($a,$b,$c,$d)=map{$e=index$k,$_;5*int$e/5,$e%5}$1,$3||X;
print substr$k,$_%25,1 for
$a-$c
?$b-$d
?($a+$d,$c+$b)
:($a+5+$b,$c+5+$d)
:(++$b%5+$a,++$d%5+$c)
}
```
[Answer]
# CoffeeScript - 610
Demo:
```
[timwolla@/data/workspace/js/PCG]coffee pcg-23276.coffee "Stack Overflow" "The cat crept into the crypt, crapped, and crept out again."
SIRACARDFMVUICVSMORDZNAKECMZMFBCYNRDFMSVTVKBTMMY
```
Code:
```
String::r=String::replace
_=(t,l)->
for r in[0..4]
for c in[0..4]
return [r,c]if l is t[r][c]
K = {}
K[c]=c for c in (process.argv[2].toUpperCase().r(/J/g, 'I').r x=/([^A-Z])/g, '')
for i in[1..26]when i!=10
c=String.fromCharCode 64+i
K[c]=c
K=(c for c of K)
t=(K[s..s+4]for s in[0..24]by 5)
v=process.argv[3].toUpperCase().r(/J/g,'I').r(x,'').r(/(.)\1/g,'$1X$1').r /(..)/g, '$1 '
o=""
for p in v.trim().r(/\s([A-Z])$/, ' $1X').split /\s/
[a,b]=p.split '';[d,f]=_ t,a;[e,g]=_ t,b
o+=if d!=e&&f!=g
t[d][g]+t[e][f]
else if d==e
t[d][++f%5]+t[e][++g%5]
else
t[++d%5][f]+t[++e%5][g]
console.log o
```
Ungolfed version:
```
search = (table, letter) ->
for row in [0..4]
for column in [0..4]
return [ row, column ] if letter is table[row][column]
encrypt = (key, value) ->
key = key.toUpperCase().replace(/J/g, 'I').replace /([^A-Z])/g, ''
keyChars = {}
keyChars[char] = char for char in key
for i in [1..26] when i != 10
char=String.fromCharCode 64 + i
keyChars[char] = char
keyChars = (char for char of keyChars)
keyTable = (keyChars[start..start+4] for start in [0..24] by 5)
value = value.toUpperCase().replace(/J/g, 'I').replace(/([^A-Z])/g, '').replace(/(.)\1/g, '$1X$1').replace /(..)/g, '$1 '
pairs = value.trim().replace(/\s([A-Z])$/, ' $1X').split /\s/
out = ""
for pair in pairs
[a,b] = pair.split ''
[rowA, colA] = search keyTable, a
[rowB, colB] = search keyTable, b
if rowA!=rowB&&colA!=colB
out += keyTable[rowA][colB]+keyTable[rowB][colA]
else if rowA==rowB
out += keyTable[rowA][++colA%5]+keyTable[rowB][++colB%5]
else
out += keyTable[++rowA%5][colA]+keyTable[++rowB%5][colB]
out.replace /(..)/g, '$1 '
console.log encrypt process.argv[2], process.argv[3]
```
] |
[Question]
[
Given the topography of land in ASCII picture format, figure out where lakes would go and fill them in. Assume an infinite amount of rain.
## example
**input**
```
#
##
# ####
# #########
## ###########
## ############# ####
## ############## #####
################# #######
#########################
#########################
```
**output**
```
#
##
#@####
#@@@@#########
##@@###########
##@#############@@@####
##@##############@@#####
#################@#######
#########################
#########################
```
The input will contain only spaces and `#` marks. Each line will be the same length. The output should be the identical `#` pattern with spaces where water would accumulate filled in with `@` marks.
The bottom input row will always be all # marks. There will be no holes or overhangs in the land. Shortest code wins.
[Answer]
## sed -r, 27 24 (27 with `-r`)
24 (27):
```
:;s/(#|@) ( *#)/\1@\2/;t
```
27 (30):
```
:e;s/([#@]) ( *#)/\1@\2/;te
```
Competes with the better of the two perl solutions
[Answer]
## Perl, 25
```
s/# +#/$_=$&;y| |@|;$_/ge
```
[Answer]
## Perl (>= v5.9.5), 24 chars
Run with `perl -p`:
```
1while s/#.*\K (?=\S)/@/
```
[This requires Perl 5.9.5 or later to use the special escape `\K`.](http://perldoc.perl.org/perl595delta.html#%5cK-escape)
[Answer]
## Windows PowerShell, 36 ~~74~~ ~~138~~
```
$input-replace'(?<!^ *) (?! *$)','@'
```
[Answer]
## [Retina](https://github.com/mbuettner/retina/), 10 bytes
Retina is (much) newer than this challenge. But this solution is too neat not to post it:
```
T` `@`#.*#
```
[Try it online.](http://retina.tryitonline.net/#code=VGAgYEBgIy4qIw&input=ICAgICAgICAgIyAgICAgICAgICAgICAgIAogICAgICAgICAjIyAgICAgICAgICAgICAgCiAgICAgICMgIyMjIyAgICAgICAgICAgICAKIyAgICAjIyMjIyMjIyMgICAgICAgICAgIAojIyAgIyMjIyMjIyMjIyMgICAgICAgICAgCiMjICMjIyMjIyMjIyMjIyMgICAjIyMjICAKIyMgIyMjIyMjIyMjIyMjIyMgICMjIyMjIAojIyMjIyMjIyMjIyMjIyMjIyAjIyMjIyMjCiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMKIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIw)
This is simply a transliteration stage which replaces spaces with `@`, but the operation is restricted to matches of `#.*#`, i.e. characters which are surrounded by land on both sides.
[Answer]
## Ruby 1.8, 30 characters
```
#!ruby -p
gsub(/# +#/){$&.tr" ","@"}
```
If anyone has an idea why this doesn't work in Ruby 1.9 (tested with 1.9.2p0 and 1.9.2p204), even though the documentation says [it should work](http://ruby-doc.org/core/classes/Kernel.html#M001425), let me know!
[Answer]
# Python, ~~95~~ 92 bytes
```
for s in S.split('\n'):b=s.find('#');e=s.rfind('#');print s[:b]+s[b:e].replace(' ','@')+s[e:]
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
aR:`#.*#`_TRs'@
```
Takes input as a multiline string via command-line argument: [Try it online!](https://tio.run/##K8gs@P8/McgqQVlPSzkhPiSoWN3h////CjCgrIAKuBAyylhllIESaFJcykgyKHJcIJ4yAqDKKCujSkEoDBmYESAZNABTiCmjTFAGAA "Pip – Try It Online") (Alternately, specify the `-rn` flags and change the first `a` to `g`, and you can give input via stdin: [Try it online!](https://tio.run/##K8gs@P8/PcgqQVlPSzkhPiSoWN3h/38FGFBWQAVcCBllrDLKQAk0KS5liHooQJFRRpJAlgLJKCujSkEoDBmYESAZNABTiCmjTFDmv25RHgA "Pip – Try It Online"))
Same idea as the Retina answer: replace every match of the regex `#.*#` with the result of transliterating space to `@` in the match. Pip can't match Retina's terseness for a pure regex problem--but it's not everyday that you can tie with Jelly, after all.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~17~~ 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
|εγć?D¨ð'@:sθJJ,
```
[Try it online.](https://tio.run/##MzBNTDJM/f@/5tzWc5uPtNu7HFpxeIO6g1XxuR1eXjr//yvAgLICKuBCyChjlVEGSqBJcYFNUYYBZBkQT1kZixRIRlkZVQpCYcjAjADJoAGYQkwZZYIyAA)
**Explanation:**
```
| # Take all input-lines as list
ε # For each line:
γ # Split the line into chunks of consecutive equal characters
# i.e. " ## # " → [' ','##',' ','#',' ']
ć # Split into head and the rest of the list
# i.e. [' ','##',' ','#',' '] → ['##',' ','#',' '] and ' '
? # Print this head
D # Duplicate the rest of the list
¨ # Remove the last element
# i.e. ['##',' ','#',' '] → ['##',' ','#']
ð'@: # Replace every space with a "@"
# i.e. ['##',' ','#'] → ['##','@@@','#']
sθ # Swap so the duplicated list is at the top, and take the last item as is
# i.e. ['##',' ','#',' '] → ' '
JJ # Join the lists and individual items in the list together to a single string
# i.e. ['##','@@@','#'] and ' ' → "##@@@# "
, # Print with trailing new-line
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes
```
□⟑Ġvṅḣ$₴:Ṫ\@Ḟ$¤ptJṅ,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLilqHin5HEoHbhuYXhuKMk4oK0OuG5qlxcQOG4niTCpHB0SuG5hSwiLCIiLCIgICAgICAgICAjICAgICAgICAgICAgICAgXG4gICAgICAgICAjIyAgICAgICAgICAgICAgXG4gICAgICAjICMjIyMgICAgICAgICAgICAgXG4gIyAgICMjIyMjIyMjIyAgICAgICAgICAgXG4jIyAgIyMjIyMjIyMjIyMgICAgICAgICAgXG4jIyAjIyMjIyMjIyMjIyMjICAgIyMjIyAgXG4jIyAjIyMjIyMjIyMjIyMjIyAgIyMjIyMgXG4jIyMjIyMjIyMjIyMjIyMjIyAjIyMjIyMjXG4jIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjXG4jIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIl0=)
## How?
```
□⟑Ġvṅḣ$₴:Ṫ\@Ḟ$¤ptJṅ,
□ # All inputs wrapped in a list
⟑ # Open an apply lambda, apply for each:
Ġvṅ # Group consecutive identical characters
ḣ # Head extract, push a[0], a[1:]
$ # Swap
₴ # Print without a trailing newline
:Ṫ # Duplicate and remove the last item
\@Ḟ # Replace all spaces with "@"
$ # Swap
¤p # Prepend an empty string for the case that the list is empty
t # Last item
J # Join top two things on the stack together
ṅ # Join by nothing
, # Print with trailing newline
```
[Answer]
# Javascript (ES6), 44 bytes
```
x=>x.replace(/# +#/g,s=>s.replace(/ /g,"@"))
```
[Answer]
# Javascript, 107 bytes
```
var f=function(x){return x.replace(/# +#/g, function(x){return "#"+new Array(x.length-1).join("@")+"#";})};
```
Ungolfed:
```
var f = function(x) {
return x.replace(/# +#/g, function(x){
return "#" + new Array(x.length - 1).join("@") + "#";
})
};
```
[Answer]
# Python, 108 106 92 bytes
```
import re
n=1
while n: S,n=re.subn('# +#',lambda m:'#'+'@'*len(m.group(0)[2:])+'#',S)
print S
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
Ỵ”@ẹ”#ṂrṀḟƲ$¦€Y
```
[Try it online!](https://tio.run/##y0rNyan8///h7i2PGuY6PNy1E0gpP9zZVPRwZ8PDHfOPbVI5tOxR05rI/w93dD3cOe1w@///6urqXAowoKyACpBklLHKKAMl0KS4lCHqoQBFRhlJAlkKJKOsjCoFoTBkYEaAZNAATCGmjDJhGWA4AAA "Jelly – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 28 bytes
```
'# +#'⎕R{'@'@(' '∘=)⍵.Match}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X11ZQVtZ/VHf1KBqdQd1Bw11BfVHHTNsNR/1btXzTSxJzqj9n/aobcKj3r5HXc2Petc86t1yaL3xo7aJQC3BQc5AMsTDM/h/mgKQ5RXs76egrqQAA8oKqCAmDyGljF1KGSiDJheTpwzRAQWoUspIMshyYCllZVQ5CIUpBTMELIUGYCqxSCkTllJSBwA "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
## Task
Given a non-empty list of positive digits, group them into sublists of equal sum. You may output any subset of solutions with maximal number of sublists (equivalently, minimal sum).
The input may contain repeat elements. There may not exist any solution but the singleton list containing the input itself. The output does not need to be in any particular order. You may not assume in the input list is in any particular order.
## Format
You must accept a non-empty list of positive integers and output a 2D list of those integers, both in any reasonable format. Since I have restricted the inputs to 1-9, you may just accept a string of digits as input. However, your output give an obvious indication as to how the sublists are split.
## Test Cases
These only show one solution, but if more exist, you may output them instead, or multiple, etc.
```
[9, 5, 1, 2, 9, 2] -> [[9, 5], [1, 2, 9, 2]]
[1, 1, 3, 5, 7, 4] -> [[1, 1, 5], [3, 4], [7]]
[2, 9, 6, 1, 5, 8, 2] -> [[2, 9], [6, 5], [1, 8, 2]]
[2, 8, 3, 9, 6, 9, 3] -> [[2, 3, 9, 6], [8, 9, 3]]
[5, 4, 1] -> [[5], [4, 1]]
[3, 8, 1, 4, 2, 2] -> [[3, 1, 4, 2], [8, 2]]
[6, 9, 3, 8, 1] -> [[6, 3], [9], [8, 1]]
[4, 1, 6, 9, 1, 4, 5, 2] -> [[4, 1, 6, 1, 4], [9, 5, 2]]
[8, 7, 8, 6, 1] -> [[8, 7], [8, 6, 1]]
[2, 7, 4, 5] -> [[2, 7], [4, 5]]
[5, 2, 1, 4, 4] -> [[5, 2, 1], [4, 4]]
[5, 7, 4, 6, 2] -> [[5, 7], [4, 6, 2]]
[4, 1, 6, 6, 9] -> [[4, 9], [1, 6, 6]]
[2, 6, 4] -> [[2, 4], [6]]
[6, 3, 1, 6, 8, 4, 5, 7] -> [[6, 3, 1, 6, 4], [8, 5, 7]]
[2, 2, 2] -> [[2], [2], [2]]
[2, 4, 5] -> [[2, 4, 5]]
```
[Here](https://tio.run/##XVHLboMwEDzjr1jlFFRaJapyiUS@IjcUVW5YiFU/0LK0yddTr0GF9OTRzsOj3e7Bt@Dfx7Gh4MAwEodgezCuC8TQIbmBNZvge6VqbKAP9hu3mkg/8qPKOLC2UEI/uHmosiYQsKYWGYwH0r7FrTN@5gtIHjEnZaAaSYTrv5YPskzH@Ooi6PqH@oh2AiThLu4Uk/SZiS3hJY5Pc41pnH0S6q8EI13CPcGrwOp@WZxl@WzTSXGdFKsOqxZoezw@JexmMyEP5EErNW80rqMOTqmfm7EIZxrEaNG3fItpE/smj/G8PRSw38WN@sHJX9U/eh/pQw6yg49l1VNYHjvGW8lp0sUkIiaZdEEp15FEyLiAzetpUwiRj@Mv) is an extremely inefficient test case generator.
[Answer]
# [J](http://jsoftware.com/), 65 bytes
```
<@/:~((i.~/:~@;&.>)>@{])[:(\:#&>)@,@(g/.~+/&>)g=:<@#~"#.2#:@i.@^#
```
[Try it online!](https://tio.run/##RY9Ra4MwFIXf/RWHCjXZbDq1WpvWEjbY09jDXrsOpLPVYW2HCi0D/3p3Y5EQJNzvHM@5@bmNhLNHIuHAxRMkfROBl4@319tKTWXHWCE6utVyLNZ8rf62fCPZp7THa65cxQ5T0T1OaTgkcqXsbmQL35aqEOrLvnHr/VkgT2tkl3O2a7JvlFl1aHIXaVmibo@k/LZp6aKtilOFY9rs8qxGUZ3bxmqyukkEZpDOBdkuPykGltgcD2BespG26kTfrbYaXTGRY0a7cizVlnPscXUsy4fOwQIhPPh0@1ZwRx6dgPAcswFpPSIcIiafP8CYfFpYIBhgSHt5wxCQwyPgm/DerPHgIXsPtS804THVx7rTtM21w/T4/S8zA7QemYR7MEWbhMjYI9pC63FfOzcP1bt6w0Da7R8 "J – Try It Online")
A different approach to brute force. All test cases execute in a few seconds
on TIO.
Consider `2 7 4 5`...
* `g=:<@#~"#.2#:@i.@^#` Generate all subsets of the input, and save the verb
that does this as `g` so we can use it again later.
```
┌┬─┬─┬───┬─┬───┬───┬─────┬─┬───┬───┬─────┬───┬─────┬─────┬───────┐
││5│4│4 5│7│7 5│7 4│7 4 5│2│2 5│2 4│2 4 5│2 7│2 7 5│2 7 4│2 7 4 5│
└┴─┴─┴───┴─┴───┴───┴─────┴─┴───┴───┴─────┴───┴─────┴─────┴───────┘
```
* `(g/.~+/&>)` Group subset elements by sum, and for each group of same-sum
elements, generate all of *its* subsets:
```
┌┬─────────┬─────┬───────────┐
││┌┐ │ │ │
││││ │ │ │
││└┘ │ │ │
├┼─────────┼─────┼───────────┤
││┌─┐ │ │ │
│││5│ │ │ │
││└─┘ │ │ │
├┼─────────┼─────┼───────────┤
││┌─┐ │ │ │
│││4│ │ │ │
││└─┘ │ │ │
├┼─────────┼─────┼───────────┤
││┌───┐ │┌───┐│┌───┬───┐ │
│││2 7│ ││4 5│││4 5│2 7│ │
││└───┘ │└───┘│└───┴───┘ │
├┼─────────┼─────┼───────────┤
││┌───┐ │┌─┐ │┌─┬───┐ │
│││2 5│ ││7│ ││7│2 5│ │
││└───┘ │└─┘ │└─┴───┘ │
├┼─────────┼─────┼───────────┤
││┌───┐ │ │ │
│││7 5│ │ │ │
││└───┘ │ │ │
├┼─────────┼─────┼───────────┤
etc...
```
* `[:(\:#&>)@,@` Flatten, and sort down by length:
```
┌─────────┬───────┬───────────┬──┬───┬───┐
│┌───┬───┐│┌─┬───┐│┌───┬─────┐│┌┐│┌─┐│┌─┐│
││4 5│2 7│││7│2 5│││7 4│2 4 5││││││5│││4││ ...etc..
│└───┴───┘│└─┴───┘│└───┴─────┘│└┘│└─┘│└─┘│
└─────────┴───────┴───────────┴──┴───┴───┘
```
* `<@/:~((i.~/:~@;&.>)>@{])` Find the first one whose elements match those of
the input, and open it:
```
┌───┬───┐
│4 5│2 7│
└───┴───┘
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
Œ!ŒṖ€Ẏ§E$ƇLÐṀ
```
[Try it online!](https://tio.run/##fZKxSsRAEIb7e4oVLGORyybZbezsrAUJW9rIvYBdFCHdISeIoCJoYWMpctHOEN9j8yJxZnZ2L5e7M4SQZP5v5p@ZPT@bzS76vl3stQtb33VX7/Zr/vN2tP9bHTc3ti779tbWr135KA4ORVc@2eWLXT53l58nTQXvSN3b@trWD6CB@MR@fzQV5Dnt@2IaiSwS0ojxBblEgWFpIlFkxkzwA@@dWhTyw6llJNL/MmMYlCm9xruUKaYkgcuab00csuYsp9SIUYdwa7Mhl/gX5KxhM1OC5GgsbMaFuYZkwlnKRsMJhLdEAiDQTCSSSKhR246AcIIEWVPcuKIqipJsYRRX8QIgYmoDqrBBs064MA034S3niLEt6mht3Q5LQozLUUeaqsRE6E1Ic6GBwO1SO7tEq8CFXdIEshWsVqSi1hyPwxyRHGOPJBgeB@27SF3RcBxib4gGolngdpb4sPJoboY782HJVUlg/gA "Jelly – Try It Online")
Very slow, works on \$O(2^{n!})\$ complexity, where \$n\$ is the length of the array. Times out for anything with \$n \ge 8\$ on TIO.
This feels too long, especially the `Œ!ŒṖ€Ẏ` bit to generate all possible partitions.
This outputs all possible solutions, but the TIO link (the `ÇḢ` bit in the Footer) limits it to just one
## How it works
```
Œ!ŒṖ€Ẏ§E$ƇLÐṀ - Main link. Takes a list L on the left
Œ! - All permutations of L
ŒṖ€ - Get all partitions of each permutation
Ẏ - Drop these down into a single list of 2d lists
$Ƈ - Keep those for which the following is true:
§ - Sums of each sublist
E - Are all equal
LÐṀ - Get those with a maximal length
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
œ€.œ€`éR.ΔOË
```
[Try it online!](https://tio.run/##yy9OTMpM/V9WeXjD4b1BhsZZQfZKCrp2Ckr2lf@PTn7UtEYPTCYcXhmkd26K/@Hu/7U6/6OjLXUUTHUUDHUUjHQUgGyjWB2FaEOwgDFYxlxHwQQkBpE2A8sAhS2gSo3ATGOYJJA0BgkDVZgAlYKYxmAVhmABI6guqEqIDEjAAmyRBcQCqLnmYC2mUOOMYGaYQAUg0mZQE03A0mYQR0ANMEM43QjhXLCZsQA "05AB1E – Try It Online")
```
œ # all permutations of the input
€.œ # for €ach permutation, get each partition
€` # flatten by one level to get a list of many partitions
é # sort by length (number of sublists in a partition)
R # reverse, longest are now at the front
.Δ # find the first partition where ...
OË # ... each sublist sums to the same value
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
∧≜S&p~c.+ᵛS∧
```
[Try it online!](https://tio.run/##RY@hDsIwEIZf5TKBoZCs7bph4CEmlwmYALEEglkIATFBmCNY8FjMDG/TvkhprzcwzeX7v97frvbLanOot2tua93fj00EkzlEzcJc3qZt9ac76f5mzfVlumc@2p2r6Vj3j9wBa4tixiBhEDPgDNzMSwZFjEBgkjKQnoVYYeJwRirHUQyhO4XHzpBO9aNAI0bA6RaZIfFAohFwUBNSM3xCFqqpMQ0GFfHhiiQQYkULfqv9dlqgSFb4iBBnQ21KEv9/EdvKLw "Brachylog – Try It Online")
Even less efficient than caird's Jelly solution, as it recomputes every partition of every permutation for each sum it tries.
```
~c. Output a partition of
&p a permutation of the input
+ᵛ in which every sublist has the same sum,
∧≜S S∧ which is as small as possible.
```
[Answer]
# JavaScript (ES6), 124 bytes
```
f=(a,n=1)=>(g=(a,q=[],b=[],s=n)=>s?a.some((x,i)=>g(a.filter(_=>i--),q,[...b,x],s-x)):!a[Q=[...q,b],0]||g(a,Q))(a)?Q:f(a,n+1)
```
[Try it online!](https://tio.run/##bVJNjtMwGN3PKT4qodiq65kmmTQtSruCBQtQ1WWIkNs6JSiTtHEYdcRwAyQ2LOEenGcuwBGK/xLaZKrItfPe@973Peczu2diU2X7elSUW346pRFipIjGOJqjndofojgha7WIqJBvxYJRUd5xhI4kk@cdYjTN8ppX6GM0z0YjTA4kppSuyVFqRkeMZy9YvIzUuwNZJ@QmeXyUKrLEGDG8WM5SZTkc41PFD1@yiiMnFQ6mFWfbN1nOVw/FBt1gWperusqKHcJU7POsRoMPxQDTtKxes80nJCCaw9crgBgYAX7c803Nt5BABMIKrmE4msPwGtM7tkf8nuX4lRRUXGpBdqFPoq7k6e3q/TsqtF@WPiBJ0eCmLESZc5qXOzR4KUA/A9KlM0xUHWKK9ao1zWFYgPP3z4@nXz/l6sAMnKff3x3p9A2f4imBWwJjAi4BuXcTsD85A8QaTgjEZ4TkSp3k42nphIDfERlY6zyFyv@JkpkKgUEJhK2dkSlYcYP/nqE1dPXWa/Ry9TpKiyldaAlSJ118adf2B5eNahtNkFxPe4y1wu0n4bWY9dCN2WaMNOkZBKoPSZ9ajTbydSWjNCVvjZ3RtPDYZje1BCkNdd6hgft2CrZOgTVzzQ2pSJ9LwLUKTTCBuU1Xft/AwlbhW4UxCM4zO1c0BoEdoh1QRdBX@PYzsBw7RNDppzOEDiqwN@I1BmGT7iQ5v5EG9m1WmmBs3M4QFzaKbhfDfibWi6Z0qP8A "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
a, // a[] = input list
n = 1 // n = target sum, starting with 1
) => ( //
g = ( // g is a recursive function taking:
a, // the original a[] or a subset of it
q = [], // q[] = list of sublists
b = [], // b[] = current sublist
s = n // s = n minus the sum of the terms in b[]
) => //
s ? // if s is not equal to 0:
a.some((x, i) => // for each value x at index i in a[]:
g( // do a recursive call to g:
a.filter(_ => i--), // remove the i-th element from a[]
q, // pass q[] unchanged
[...b, x], // append x to b[]
s - x // subtract x from s
) // end of recursive call
) // end of some()
: // else:
!a[ Q = [...q, b], // Q[] = copy of q[] with b[] appended
0 // test whether a[] is empty
] || // if it's not:
g(a, Q) // recursive call to g with q[] = Q[]
)(a) ? // initial call to g; if a solution is found:
Q // return it
: // else:
f(a, n + 1) // try again with n + 1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~110 109~~ 107 bytes
```
->l,*r{1.step.find{|x|l.permutation.find{|c|w=-1;r=c.chunk{|z|(w+=z)/x}.map &:last;r.all?{|v|v.sum==x}}};r}
```
[Try it online!](https://tio.run/##TYxLDoIwFEXnrqIj46fUFPFLqgshDCpCJBZsSgtI27VXUjVh9u459z6hbm9XEBdcGFwJjVEjc46Ksr5r0xuGeC4qJaksX/WPZqYjAY4FyVD2UPVTm8EsujUZlpveoopyMD8z2shYIMrYVZvWtKhRFSG9tTYW1nFQJMkJgh0EGIIQgvEO03TmOfZw6@0BgujPv7W9t6M6TiahfzKN0dhJU/cB "Ruby – Try It Online")
### How:
* Starting with x=1, check if we can split the list into chunks whose sum is x.
* Do the same check with every possible permutation of the list.
* If not, increase x and try again.
* The trick is here: `c.chunk{|z|(w+=z)/x}`. This function splits an array into smaller
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 145 bytes
```
(l=Length@#;Catch[Do[If[SameQ@@Total/@(t=TakeList[p,i]),Throw@t],{d,Reverse@Divisors@Total@#},{i,IntegerPartitions[l,{d}]},{p,Permutations@#}]])&
```
[Try it online!](https://tio.run/##TctBS8NAEAXgu78iUJAWBsRoqyKBAXsp9BBtbssehjppBpNs2Z22h5DfHpctFW/z5n2vI224I5U9TXUxzdtiy/1BG5y9f5DuG7N2ZlObHXX8iVg5pfYB51pU9MNbCWqOIHYBVePdBdXC8A1ffGYfGNdyluB8uK5wNsIgsOmVD@xL8ioqrg@mjZvRxvIIJfvupJT@0Vu7uJ9KL71ijcMzZI@QrSB7S0eMS8jy8e4PxOrpZl5v4OUfyNN2lcwymXycfgE "Wolfram Language (Mathematica) – Try It Online")
Rough compromise between speed/memory optimization and code-golf.
The following facts are used:
* Array can only be splitted by the number of parts that are dividing its sum
* The lengths of parts of any split must be integer partition of length of array
Of course, one can optimize the search much better (for example, the dividers of the sum of the array must be less than its length), but it lengthens the code. On the other hand, I don’t want to take away given optimization, because it reduces runtime significantly.
[Answer]
# [Scala](https://www.scala-lang.org/), 773 bytes
\$\text{773 bytes, it can be golfed much more.}\$
Golfed version. [Try it online!](https://tio.run/##pZJta9swFIW/51ecjzIzgmTdmyFl@9DBYC/QMhiEMFRFSbTKspGU0Wb1b091pSRzWpoWajBY9z73XJ9jeymM2Oi6bVyApwMX1jZBBN1YHoQ2TsnBoLn8o2TAN6Et/g2AmZqjjgcm3MJX@OScuJlcBKftYlpU@Gl1wDiRQBurwVg213b2i33VPrAPJd6UGJYYlYjPo6IoHkOHiXudBt6VODmCZrG3aSDS748Lj9L2J4iTqJSJbkOec9fEbgViJl9sIMM/Wsprkkr7@nS6zeDjLsccXBI5V5JdV4jck@MALeStcvUqfxjPZWNM/CKftfNhCwFSeAXCoOf7Yr7@CgO5XNkrH0UJ4fPGzM71YhmSWa7qNtz0lhf3BLbqbF1CSFlgfHqvDVrKYo9rf0ZiuL0llC@VmHG/qvEKa5ziukjJsXWBqiLggY4yadG2neZ3bPojDwa6g1O2GL05YQz7ndaOx3Fnj@r6705RDHK1FkEuD7O8aGrFCCG/vUD29WekeCy3lyf27Ky6XQRd3@D3xiqy9v@XjDuHGSWQ7n0v1rtNt7kD)
```
def findX(list: List[Int]): Option[List[List[Int]]] = {
@tailrec
def findXRec(x: Int): Option[List[List[Int]]] = {
list.permutations.collectFirst {
case perm if {
val chunks = perm.foldRight(List.empty[List[Int]]) {
case (z, acc) =>
if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
else (z :: acc.head) :: acc.tail
}
chunks.forall(_.sum == x)
} =>
perm
} match {
case Some(perm) => {
Some(perm.foldRight(List.empty[List[Int]]) { case (z, acc) =>
if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
else (z :: acc.head) :: acc.tail
})
}
case None => findXRec(x + 1)
}
}
findXRec(1)
}
```
Ungolfed version. [Try it online!](https://tio.run/##1ZNfa9swFMXf/SnOo8Q8gbN2fwwp3cMGg7YbLYNBCEOVlUSbLBtJ2dqs@eyZJKeeHVjb1z7YWPf@7rm6R5YTXPPdTtVtYz1cXDFuTOO5V41hnittpciy5vqHFB7nXBn8yYBKLlCHBeF26Uq8t5bfzq68VWY5pyW@GuUxTSTQhqjXhiyUqb6RM@U8eZfjOEeRY5IjfE8opf9Di8S9SgVvchw9gHZir1NBoN8@LDxJ3R8hjoJSR2yz/dgdoANQImKzT8bHmT@30bJZCvXx@by34fTezLjohS6lIDclAvsECeAX12ilrdfdAbmQijthw9gADY@qvnDrVcwEeMgx0WgdTvWjss73HQDBnUwg1GIQjooWv4PIy2IU1BCrtfnp9vJs0ejqUi1XPrnIZN3628E4dKS5b0c2ObgQFNOTURJxDyRkmHIfohDu7iLIVpJXzK1rvMAGJ7ih6SzIhqIsI3CgInVqsk@m6nsy/eQDfDv47gYLE1muNfmeGk6noVvPbMOO09jZuPrA@Zp7sTr0@KqpJYm1cezHne7xZ@/wwL6xIxeNkdGLf1cjdC/oyNvu3RNFdzm32W73Fw)
```
import scala.annotation.tailrec
object Main {
def main(args: Array[String]): Unit = {
println(findX(List(9, 5, 1, 2, 9, 2)))
println(findX(List(1, 1, 3, 5, 7, 4)))
println(findX(List(2, 9, 6, 1, 5, 8, 2)))
println(findX(List(2, 2, 2)))
println(findX(List(2, 4, 5)))
}
def findX(list: List[Int]): Option[List[List[Int]]] = {
@tailrec
def findXRec(x: Int): Option[List[List[Int]]] = {
val permutations = list.permutations
val validPartition = permutations.collectFirst {
case perm if {
var w = -1
val chunks = perm.foldRight(List.empty[List[Int]]) {
case (z, acc) =>
if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
else (z :: acc.head) :: acc.tail
}
chunks.forall(_.sum == x)
} => perm
}
validPartition match {
case Some(perm) => {
var w = -1
Some(perm.foldRight(List.empty[List[Int]]) {
case (z, acc) =>
if (acc.isEmpty || acc.head.sum + z > x) List(z) :: acc
else (z :: acc.head) :: acc.tail
})
}
case None => findXRec(x + 1)
}
}
findXRec(1)
}
}
```
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes
```
O:ᵐ∑≡$Ðaṁl
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6Fpv9rR5unfCoY-KjzoUqhyckPtzZmLOkOCm5GCq_4BajdLSljoKpjoKhjoKRjgKQbRTLFW0I5huDJcx1FEyAQhBJM7AEUNQCotAIzDKGyQFJY6AoUN4EqBDIMgbLG4L5RhAtUGUQCSDfBCwPEYUoNIUotADbbQGxFGKXOUQeYoURTL0JhA-RNINohpsKMhii2Qyi0gxsOUTSAmafOUSJEdxXYGsggQQA)
```
O:ᵐ∑≡$Ðaṁl
O Non-deterministically choose a set partition of the input
: Duplicate
ᵐ∑ Sum each
≡ Check if all sums are equal, and get the equal value
$Ð Pair the sum with the partition
a Get all possible values
ṁ Minimum (by the sum)
l Take the last element (the partition)
```
[Answer]
# [Julia 1.7](https://julialang.org) + Combinatorics, 74 bytes
```
using Combinatorics
~x=argmin(p->keys(sum.(p)∪0)=>sum.(p),partitions(x))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=jVTLbttGFF20K37FdQwEJDyiTUmRZaYS-li1RYACCbohuBgyY2sockRwhoXdxF73H7rJJpt8R36iWeZLeudBipRUoIQgkXPPuefcMyP-_bFoS04_fPn28znUtFFc8Z2QwAX8tKsyLqjaNTyX3jlslKplfHl5x9WmzcJ8V13-ormvqNpcjsBhUXqeVE2bK3jN1G9923dvvot_yLBCc_U7yxH96AFeMo7feEy89X6kkoUlE3dq49dxPCIHsAIhmdq79DtkKIPAclmpHmp2kmsF37mfDojUx0dv0BO9jC1q7qiZLwPvthW5fgCjyhVrqDoha6YT2GDg1Kz1DAL-n6zZSf9noWZTAiIgsBNs_zyJcEUQiHBEHdH_UybghGQSpfiBNVzB8-fQMNU2wtpi92oYpzaHtDAMD4SOgEcREaAEMmOzsrI9uaJbppmYmkG5ur4Uq2qMJpG84iVtNOAqgNtdA1tcvoqrtIfqRY6LUSz6NX3Vrdyc-bpRQhOeXkQpToA3exE9Sd-FlxjXmX_GJTLUAzEWLLbD8VtwVdzml-ACAz-R2Np3p4YGiVZyT1mQpN0Wvdx30lOj5WEAlLjxUYUmCEzhDBG9Qbd2gYNaU6VkfbHQoYwSKfQSHpAYP9EoF10oitESTYoihdUKMnPz_j1kDaPbk0EhduBCXxU2xBPpIzkN4AJ8A7HdBml3m1dc4E5NogMD23Q0gr4yu1j9hw0TR8fpSt2W6FSJT0lGBOZqDu3HVt1Olv_8et5KLu4OXmFP9yva3FUcT_pkvWUPuCNtFfp18PWvT1fBau2eyOBlcB8EruXWHkF8L2Jqb0uu_6J2bkpytMj-oGXov2KKhsjHf6Yv65Irn5Nnk_WzILDYuuFClcKnq_UTtUvfUykZnpRcp_lE91N8-PJNntwQeIEHiwC-CvB-mnbZTNYAiSnj2UsGgNTTT_iZGeo1gfkByZYNb6ar-HutabbDwlYJLHs5S9NljV3sNZdOcGpuZx0fv2cHTFfTvKUDIA9V5ijX-4OxUSNjAIidGY3IMKbHScz6mtMwxpwZS02PBBbaB8JvHMcIzU0ny7QtX1g5y-nLkcvuxgGQujR5L235WE6XndLCiU3tDulITyUwdQwDsIFNO1fzYwFXdoy5Y1iBxTCzIaMTWLgh-gF1BMeMuTsGDuOGWBz4ORjCBLVwOzLrBJZdutfpcEe68txlZQBWZnowxEhGw92XRZ-IdWTKhGr_bP8C)
`argmin(f, itr)` needs julia 1.7 or later
] |
[Question]
[
*(Inspired by [this challenge](https://codegolf.stackexchange.com/q/102496/42963))*
Given two input strings, one of which is exactly one character longer than the other, arrange the strings into ASCII art as if they are two halves of a zipper that is only halfway zippered. The longer word forms the bottom of the zipper, and is the first and last character of the combined zippered portion. Since that paragraph is hard to understand, take a look at some examples:
```
zippered
paragraph
z
i
p
p
gerraepdh
a
r
a
p
```
Note how `paragraph` (the longer word) forms the bottom zipper, and the `g r a p h` portion encapsulates the `e r e d` portion of `zippered`, and the `z i p p` and `p a r a` portions are offset from each other.
## Input
* Two ASCII strings [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), with one guaranteed to be even in length and the other exactly one character longer.
* Neither string will contain whitespace, but may contain any other printable ASCII value.
* You can take the input in either order. Please state in your submission the input order.
## Output
The resulting ASCII art representation of the zippered words, as described above, again in any convenient format.
## Rules
* Leading or trailing newlines or whitespace are all optional, so long as the 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 other people can try out your code!
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
## Examples
```
ppcg
tests
p
p
sctgs
e
t
string
strings
s
t
r
iinnggs
r
t
s
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~31~~ 28 bytes
```
N®¬£ç iXYm½*Ul
uUo mw
y c ·y
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=Tq6so+cgaVhZbb0qVWwKdVVvIG13CnkgYyC3eQ==&input=InBwY2ciCiJ0ZXN0cyI=) Takes the shorter string first.
### Explanation
```
N®¬£ç iXYm½*Ul First line: Set U to the result.
N® Map each item (there's exactly 2 of them) in the input to
¬ the item split into chars,
£ with each item X and index Y mapped to
ç the first input filled with spaces,
iX with X inserted at index
Ym½*Ul min(Y, 0.5 * U.length).
At the end each input is an array like
["p ", " p ", " c ", " g "]
["t ", " e ", " s ", " t ", " s "]
uUo mw Second line: Set V to the result (though that's not important).
Uo Pop the last item (the array representing the second string) from U.
m Map each item by
w reversing.
u Push the result to the beginning of U.
At the end we have e.g.
[" t", " e ", " s ", " t ", " s "]
["p ", " p ", " c ", " g "]
y c ·y Last line: Output the result of this line.
y Transpose: map [[A,B,C,...],[a,b,c,...]] to [[A,a],[B,b],[C,c],...].
c Flatten into one array. [A,a,B,b,C,c,...]
· Join on newlines. Now we have the output transposed.
y Transpose rows with columns.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 31 bytes
```
→F²«FLθ«§θκ→¿‹κ÷Lθ²¿ι↑↓»J⁰LθAηθ
```
[Try it online!](https://tio.run/##VY5BCsIwEEXX6SlmmUAK0qWuCt1UFET0AKFNm9CapEmsovTsMa1CcTd//rzHVILZSrM@hKMeOd6eZSs82SWNtoAzAu8ELeOBq9YLPJBlhU5WKo9zX6qaP/FAoSMRQuhfgpBsZtQ53FEolS/kKGu@yihkJBrnK0ngC18NAd47/ouFfqhZNSVof7@Zi8YbCus3scmdk63CgsIQ4xTCSxrDLa8TwyxrLTMipGNIXf8B "Charcoal – Try It Online") Link is to verbose version of code. Takes the shorter string first. Edit: Saved 2 bytes by tweaking the midpoint detection. Explanation:
```
→F²«
```
Loop over each string in turn.
```
FLθ«
```
Loop over each character of the string in turn.
```
§θκ→
```
Print the character and move an extra square to the right.
```
¿‹κ÷Lθ²¿ι↑↓»
```
For the first half of the string, also move the cursor down or up as appropriate.
```
J⁰LθAηθ
```
After printing the first string, jump to the second string's starting point, and replace the first string with the second, so that it gets printed for the second loop. (The code runs on both loops, but the second time it's a no-op.)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 35 bytes
```
AQj.t.e+*d+lG*<klH*^_1k/h-lGk2b.iHG
```
[Try it online!](http://pyth.herokuapp.com/?code=AQj.t.e%2B%2ad%2BlG%2a%3CklH%2a%5E_1k%2Fh-lGk2b.iHG&input=%22zippered%22%2C%22paragraph%22&debug=0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 byte thanks to Erik the Outgolfer (use repeat, `¡`, to replace if, `?`, and a passed else clause `¹`)
```
JCḂ¡€ṚH
żµL⁶ẋ;ЀFṙ"ÇZṙÇṀ$Y
```
A full program that prints the result with leading white-space, as allowed in the question (or a dyadic link returning a list of characters).
**[Try it online!](https://tio.run/##y0rNyan8/9/L@eGOpkMLHzWtebhzlgfX0T2Htvo8atz2cFe39eEJQFG3hztnKh1ujwJSh9sf7mxQifz//79SQWJRYnpRYkGG0n@lqsyCgtSi1BQlAA "Jelly – Try It Online")**
### How?
```
JCḂ¡€ṚH - Link 1, get rotations: list p e.g.: ["a1","b2","c3","d4","e5","f6","g"]
J - range of length of p [ 1, 2, 3, 4, 5, 6, 7]
€ - for €ach:
¡ - repeat link:
Ḃ - ...# of times: modulo 2 1 0 1 0 1 0 1
C - ...link: complement (1-x) 0 2 -2 4 -4 6 -6
Ṛ - reverse [-6, 6,-4, 4,-2, 2, 0]
H - halve [-3, 3,-2, 2,-1, 1, 0]
żµL⁶ẋ;ЀFṙ"ÇZṙÇṀ$Y - Main link: longer (odd length); shorter (even length)
- e.g.: "abcdefg", "123456"
ż - zip them together ["a1","b2","c3","d4","e5","f6","g"]
µ - monadic chain separation, call that p
L - length of p 7
⁶ - literal space character ' '
ẋ - repeat " "
F - flatten p "a1b2c3d4e5f"
Ѐ - map with:
; - concatenation [" a"," 1"," b"," 2"," c"," 3"," d"," 4"," e"," 5"," f"," 6"," g"]
Ç - call last link (1) as a monad with argument p
" - zip with (no action on left by trailing values of right):
ṙ - rotate left by [" a "," 1 "," b "," 2 ","c "," 3 "," d"," 4"," e"," 5"," f"," 6"," g"]
Z - transpose [" c "," b ","a "," "," 1 "," 2 "," 3 "," d4e5f6g"]
$ - last two links as a monad:
Ç - call last link (1) as a monad with argument p
Ṁ - maximum 3
ṙ - rotate left by [" "," 1 "," 2 "," 3 "," d4e5f6g"," c "," b ","a "]
Y - join with newlines ''' \n
1 \n
2 \n
3 \n
d4e5f6g\n
c \n
b \n
a '''
- as full program: implicit print
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~128~~ 119 bytes
```
f=lambda a,b,n=0:n/2<len(a)and' '*-~n+a[0]+'\n'+f(a[1:],b[1:],n+2)+'\n'+' '*n+b[0]or' '*n+''.join(sum(zip(b,a+' '),()))
```
[Try it online!](https://tio.run/##JcrBDoIwEATQX@G2u3ZV7JHIlyCHbQCpgW1T8aAHf72CXCaTmRffyxjU5jzUk8yuk0LYsdZlpWd7nXpFIdEOCjgcv2qkKVsDNwUzoDSXqmX3TzWW9n2TatzqQto7wOkRvOLzNePHR3QsmyJGIsoxeV2KAWG9Yp/6DhiiJLkniSNQ/gE "Python 2 – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~47~~ ~~38~~ ~~30~~ ~~27~~ ~~26~~ 25 bytes
Finally beat the current Jelly answer \o/
Takes input with the longer word on top
Explanation coming, don't think there's much more to golf.
```
òGxplòxãòd|>HÏpd|>GGÏphl
```
[Try it online!](https://tio.run/##K/v///Am9wr@gpzDmyoOLz68KaXGzuNwfwGQcncH0hk5//8XJBYlphclFmRwVWUWFKQWpaYAAA "V – Try It Online")
### Explanation
```
ò ò ' <M-r>ecursively
|abc
def
Gx ' (G)oto the last line and (x) the first character
abc
|ef
' <C-O> Go back to the previous location
|abc
ef
p ' (p)aste the character cut
a|dbc
ef
l ' move one character right
ad|bc
ef
```
```
x ' (x) the last extraneous character from the previous loop
ã ' <M-c>enter the cursor
ò ' <M-r>ecursively
d| ' (d)elete to the first co(|)umn
>H ' (>) Indent every line from here to (H)ome (first line)
' this leaves the cursor on the first line
Ïp ' <M-O>n a newline above this (the first) (p)aste the deleted section
' this leaves the cursor on the last character
d| ' (d)elete to the first co(|)umn
>G ' (>) Indent every line from here to the end (G)
' unfortunately the cursor stays on the first line
G ' (G)oto the last line
Ïp ' <M-O>n a newline above this (the last) (p)aste the deleted section
hl ' move left and then right (break the loop at the end)
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 79 bytes
```
ãl}dÍ./ &
XòYf D"0Pr -Y;D"0pr +òGï"1pÓ./&ò
}dGÓ/&ò
{jpògJòÓó
|DÇ./d
MÙ"-pBr
```
[Try it online!](https://tio.run/##K/v///DiHLHalMO9evoKalwRhzdFpim4KBkEFCnoRloDGQVFCtqHN7kfXq9kWHB4sp6@2uFNXPxADe6HJ4PZ1VkFhzelex3edHjy4c1cNS6H2/X0U7h8D89U0i1wKlL4/78qs6AgtSg1hasgsSgxvSixIAMA "V – Try It Online")
The following should be read with plenty of sarcasm and *air-quotes*.
>
> Here's an answer in my *golfing-language* that's *good* at *short* answers to *string-based and ASCII-art challenges*.
>
>
>
Why do I keep doing this to myself?
Hexdump:
```
00000000: e36c 167d 64cd 2e2f 2026 0a58 f259 6620 .l.}d../ &.X.Yf
00000010: 4422 3050 7220 2d59 3b44 2230 7072 202b D"0Pr -Y;D"0pr +
00000020: f247 ef22 3170 d32e 2f26 f20a 0f16 7d64 .G."1p../&....}d
00000030: 47d3 2f26 f20a 7b6a 70f2 674a f2d3 f30a G./&..{jp.gJ....
00000040: 7c44 c72e 2f64 0a4d d922 2d70 4272 20 |D../d.M."-pBr
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 bytes
```
HĊ©«Rµ®Ḥ_,Ṗ
ZLÇṬ€a"¥"o⁶ZẎz⁶Y
```
[Try it online!](https://tio.run/##AVQAq/9qZWxsef//SMSKwqnCq1LCtcKu4bikXyzhuZYKWkzDh@G5rOKCrGEiwqUib@KBtlrhuo564oG2Wf///1sncGFyYWdyYXBoJywgJ3ppcHBlcmVkJ10 "Jelly – Try It Online")
Woo Jelly is actually competing in a [string](/questions/tagged/string "show questions tagged 'string'") *and* [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge! \o/
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~26~~ 23 bytes
```
øS2ä`JIθ«¸«vyNúr})2äR˜»
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8I5go8NLErw8z@04tPoQEJdV@h3eVVSrCRQNOj3n0O7//6syCwpSi1JTuAoSixLTixILMgA "05AB1E – Try It Online")
**Explanation**
With example input = `ppcg, tests`
```
ø # zip the input strings
# STACK: ['tp', 'ep', 'sc', 'tg']
S # split to a list of characters
# STACK: ['t', 'p', 'e', 'p', 's', 'c', 't', 'g'
2ä # divide the list into 2 parts
` # push them as separate to stack
# STACK: ['t', 'p', 'e', 'p'], ['s', 'c', 't', 'g']
J # join the second part to a single string
Iθ« # append the tail of the second input
¸« # concatenate the 2 lists
# STACK: ['t', 'p', 'e', 'p', 'sctgs']
v # for each y,N (element, index) in the list
yNú # prepend N spaces to y
r # reverse the stack
}) # end loop and wrap the stack in a list
# STACK: [' sctgs', ' e', 't', ' p', ' p']
2ä # split the list into 2 parts
R # reverse the list
# STACK: [[' p', ' p'], [' sctgs', ' e', 't']]
˜» # flatten the list and join on newlines
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 163 bytes
```
(l,s)=>{var o="";int i=0,k=s.Length;for(;i<k;)o+=i<k/2?s[i++]+"\n"+"".PadLeft(i):l[i]+""+s[i++];o+=l[i]+"\n";for(i=k/2;i>0;)o+="".PadLeft(--i)+l[i]+"\n";return o;}
```
[Try it online!](https://tio.run/##VYyxTsMwFEV3f4X1JltOQsWI6zAgMRUJiYGhMFiJ6z412MHPqQRRvj1Y7QBMVzo653ZUdzG5dSIMnr98UXYfmnWDJeKfM6NsM3b8HLHnTxaDkDN7nEK3pZxKUPH/23JvVjFUJE07n23i0QBoDJmj2VQnQ83OBZ@P@hCT0Lg9aRmVKXtze097VOpdwVsABdA8237nDlmgvBv2WDioq6FLcSXFvByhKb3GdnN5@9PWNUr16yaXpxR41Muq2UMMFAfXvCbMTngBo03WJzseoYJvHEeXXA9SarYs6w8 "C# (.NET Core) – Try It Online")
Probably a lot of golfing to do here, but here's an initial non-LINQ attempt. Lambda function that takes the longer word first, and returns a string with the ouput.
[Answer]
# Java 8, 216 bytes
A curried lambda: takes `String` and returns a lambda from `String` to `String`. The parameter to the outer lambda is the shorter string.
Not being able to index into `String`s with array syntax is...unfortunate.
```
s->t->{int l=s.length(),i=l/2;String o="",p=o,n="\n";for(;i<l;p+=" ")o=o+t.charAt(i)+s.charAt(i++);o=p+o+t.charAt(i)+n;for(;i-->0;)o=p.substring(l-i--)+s.charAt(i/2)+n+o+p.substring(l-i)+t.charAt(i/2)+n;return o;}
```
## Ungolfed lambda
```
s ->
t -> {
int
l = s.length(),
i = l / 2
;
String
o = "",
p = o,
n = "\n"
;
for (; i < l; p += " ")
o = o + t.charAt(i) + s.charAt(i++);
o = p + o + t.charAt(i) + n;
for (; i-- > 0; )
o =
p.substring(l-i--)
+ s.charAt(i / 2)
+ n
+ o
+ p.substring(l-i)
+ t.charAt(i / 2)
+ n
;
return o;
}
```
## Explanation
`l` is the length of the shorter input and `i` is a multipurpose index, initialized to refer to the first character of the second half of the shorter input. `o` accumulates the result, `p` ultimately stores spaces for padding, and `n` is an alias for `"\n"`.
The first loop interleaves the second halves of the two strings (excluding the last character of the longer input) and builds `p` to the proper amount of padding for the middle line.
The next line completes the middle line of output.
I would like to apologize to James Gosling for the second loop. It adds the lines above and below the middle line from the inside out. Entering the loop, `i` is `l - 1`, so one character of padding is prepended along with the last character of the first half of the shorter string. `i` is decremented so that the next padding (appended to the result) is a character shorter. By integer division, the same position character of the longer string is appended. This repeats, and the completed result is returned.
## Cool stuff
Line 13 used to be
```
o+=t.charAt(i)+""+s.charAt(i++);
```
because without the empty string, `+` added the character values together and appended a numeric string. By expanding the compound assignment, the concatenation of `o` and `t.charAt(i)` is evaluated first, which yields the desired result without need for the empty string, saving 2 bytes. This is the first time I've seen a compound assignment behave differently from its expansion.
[Answer]
# Javascript (ES6), ~~140 137~~ 133 bytes
```
A=(a,b,c=0)=>a[c/2]?` `[d=`repeat`](c+1)+a[0]+`
`+A(a.slice(1),b.slice(1),c+2)+`
`+` `[d](c)+b[0]:` `[d](c)+[...a].map((e,f)=>e+b[f])
```
Quite sure this can be golfed further
[Answer]
# Mathematica, 174 bytes
```
(a=(c=Characters)@#;b=c@#2;T=Table;Column[Join[T[T[" ",i]<>a[[i]],{i,g=Length@a/2}],{T[" ",g+1]<>Riffle[b[[-g-1;;]],a[[-g;;]]]},Reverse@T[T[" ",i]<>b[[i+1]],{i,0,g-1}]]])&
```
**Input**
>
> ["zippered", "paragraph"]
>
>
>
[Answer]
## [TXR Lisp](http://nongnu.org/txr), 126 bytes
```
(defun f(a b :(n 0))(if(<(/ n 2)(length a))` @{""n}@[a 0]\n@(f(cdr a)(cdr b)(+ n 2))\n@{""n}@[b 0]``@{""n}@{(zip b`@a `)""}`))
```
[Answer]
# PHP, ~~149~~ 129 bytes
```
for($r=" ";$x+1<$w=2*$e=strlen($argv[2]);++$x&1||$r[++$i*$w-1]="
")$r[$w*($x&1?$y-1:$e-$y+=$y<$e/2)+$x]=$argv[2-$x%2][$i];echo$r;
```
Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/acf3039720d1e5304b6a880c9b86d8790e617bbb).
[Answer]
# [Perl 5](https://www.perl.org/), 163 bytes
```
@a=map{$s=.5*length;[/./g]}<>;say(($"x(2*$_)).$a[0][$_])for 0..$s-1;print$"x(2*$s);print$a[0][$_].$a[1][$_]for$s..@{$a[1]};print$/.($"x(1+2*$s)).$a[1][$s]while$s--
```
[Try it online!](https://tio.run/##NY1NCoMwEIX3PUUpszAWx6Tgylq8QE8gQQJNNWB1SIT@iFdvaoPu5j2@7w1p22Xel6p4KJrAFZjFne6bsc2rFNNGzudL7tQ7iuDwik4x1IwhqIrLCmrJ7oPdc0RwicjJmn5cKcfWuJF/R4RrUcAhllNo5pVLMTwQxyCzDXfy2ZpOL/uJ96SsaqyidvcxRNrq23eg0Qy988k1Qy74Dw "Perl 5 – Try It Online")
Takes the longer string first.
] |
[Question]
[
We don't have enough (semi-)easy challenges for beginners. More and more of the easy ones are already taken. So I tried to come up with something that might be achievable by beginners, but that isn't a duplicate.
### Input:
A single string separated with your OS new-line (i.e. `\r\n`),
or an array with multiple strings.
### Output - *The Stairs*:
Remove all non-alphabetic and non-numeric symbols. So all that's left is `[A-Za-z0-9]`. And then 'build a stairs'; basically ordering them on length with the smallest at top and widest at the bottom.
### Challenge rules:
1. When two strings are of equal length, we merge them with each other as one big string (the order doesn't matter, so it could be from first to last or last to first, whichever of the two you prefer).
2. The rule above can stack when the merged strings are of equal length again (see test case 2).
### General rules:
* The input is STDIN and contains only ASCII characters. And the output is STDOUT.
* The case of the output must be the same as the input.
* ~~Each submission must be a full program able to compile and run, so not just a method/function.~~ EDIT: I'm rather new, so perhaps it's indeed better to use the [default](http://meta.codegolf.stackexchange.com/a/2422/34531) from now on, even though I prefer a full program myself. Sorry for everyone that has already posted a full program. Feel free to edit, and I'll try to not change the post mid-challenge next time.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. I probably accept the shortest answer in a year from now.
Don't let code-golf answers discourage you from posting golfed non-codegolf languages like C# and alike! Try to come up with the shortest answer for any programming language.
* Feel free to use newer languages than this question.
---
### Test cases:
***Input 1:***
```
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do
```
***Output 1:***
```
Okthatwilldo
Thisisasampletext
Blablablasomemoretext
Thewoodmaybeofexcellentquality
thatyouwillhavetousetobuildstairs
orprettycrappyalmostfallingapartandfilledwithtermites
```
---
***Input 2:***
```
A
small
one
that
contains
equal
length
strings
for
the
special
rule
```
***Output 2:***
```
A Or alternatively: A
length length
oneforthe theforone
smallequal equalsmall
stringsspecial specialstrings
thatrulecontains containsrulethat
```
***Steps explained of 2:***
*First order on length:*
```
A
one
for
the
that
rule
small
equal
length
strings
special
contains
```
*First merge:*
```
A
oneforthe
thatrule
smallequal
length
stringsspecial
contains
```
*Second order on length:*
```
A
length
thatrule
contains
oneforthe
smallequal
stringsspecial
```
*Second merge:*
```
A
length
thatrulecontains
oneforthe
smallequal
stringsspecial
```
*Third order on length:*
```
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains
```
---
***Input 3:***
```
Test,
test.
This
is
a
test.
```
***Output 3:***
```
a Or alternatively: a
is is
TesttestThistest testThistestTest
```
---
***Input 4:***
```
a
bc
d!
123
```
***Output 4:***
```
123 Or alternatively: 123
adbc dabc
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), 11 bytes
```
ωȯmΣġLÖLmf□
```
[Try it online!](https://tio.run/##yygtzv7//3znifW55xYfWehzeJpPbtqjaQv///8freSopKNUnJuYkwOk8/NSgWRJRmIJkErOzytJzMwrBjJTC0sTQfI5qXnpJRkgDSVFmXnpIKm0/CKwFpDG4oLU5EywwqLSnFSlWAA "Husk – Try It Online")
Husk is younger than this challenge (which makes no difference officially, but still).
## Explanation
```
ωȯmΣġLÖLmf□ Implicit input (list of strings), say ["a","bc","d!","123"]
mf□ Keep only alphanumeric chars of each: ["a","bc","d","123"]
ωȯ Repeat until fixed point is reached:
ÖL Sort by length: ["a","d","bc","123"]
ġL Group by length: [["a","d"],["bc"],["123"]]
mΣ Concatenate each group: ["ad","bc","123"]
Final result ["123","adbc"], print implicitly separated by newlines.
```
[Answer]
# Python 3, 264 Bytes
I'm not good at code golf so I'm confident this won't be the best Python 3 answer. This uses recursion and an ordered dict with all the words for each length.
```
from collections import*
def f(i):
d = defaultdict(list)
for l in i: x = "".join(c for c in l if c.isalnum());d[len(x)].append(x)
n = (sorted(["".join(d[z]) for z in d.keys()], key=len))
if n == i:return "\n".join(n)
return f(n)
print(f(eval(input())))
```
Takes input from stdin as a list, for example, test it with this list:
```
['A', 'small', 'one', 'that', 'contains', 'equal', 'length', 'strings', 'for', 'the', 'special', 'rule']
```
Will output:
```
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains
```
[Answer]
# Retina, ~~69~~ 63 bytes
```
[^\w¶]|_
{`\b((.)+)¶((?.)+)\b(?(2)(?!))
$1$3
O$`(.)+
$#1$*
```
[Try it online!](http://retina.tryitonline.net/#code=W15cd8K2XXxfCgp7YFxiKCguKSspwrYoKD88LTI-LikrKVxiKD8oMikoPyEpKQokMSQzCk8kYCguKSsKJCMxJCo&input=QQpvbmUKZm9yCnRoZQp0aGF0CnJ1bGUKc21hbGwKZXF1YWwKbGVuZ3RoCnN0cmluZ3MKc3BlY2lhbApjb250YWlucw)
[Answer]
# Oracle SQL 11.2, 346 bytes
The lines in the input string are separated by '¤'.
That way it is not necessary to create a table to use as the input.
```
This is a sample text,¤that you will have to use to build stairs.¤The wood may be of excellent quality,¤or pretty crappy almost falling apart and filled with termites.¤Bla bla bla - some more text¤Ok, that will do
A¤small¤one¤that¤contains¤equal¤length¤strings¤for¤the¤special¤rule
Test,¤test.¤This¤is¤a¤test.¤
```
Query :
```
WITH v AS(SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))),r(s,i,l)AS(SELECT s,1,1 FROM v UNION ALL SELECT LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s)),ROW_NUMBER()OVER(PARTITION BY LENGTH(s)ORDER BY s),l+1 FROM r WHERE l<LENGTH(:1)AND i=1)SELECT s FROM r WHERE l=LENGTH(:1);
```
Un-golfed
```
WITH v AS
(
-- Splits on ¤ and keeps only alphanum characters
SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))
)
-- Recursive view
-- s : string
-- i : index of the string in case of duplicates
-- l : exit condition
,r(s,i,l)AS
(
-- Start with every element of the input
SELECT s,1,1 FROM v
UNION ALL
SELECT -- Concatenate elements of the same lengths
LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s))
-- Index of elements of the same length (listagg with over generates duplicates)
,ROW_NUMBER()OVER(PARTITION BY LENGTH(s) ORDER BY s)
-- exit condition
,l+1 FROM r WHERE l<LENGTH(:1) AND i=1
)
-- Keep only the elements from the last iteration (automaticaly sorted on my system)
SELECT s FROM r WHERE l=LENGTH(:1)
```
[Answer]
# [J](http://jsoftware.com/), 48 bytes
```
[:(/:#&>)[:(#&>,&.>//.])^:_(#~e.&AlphaNum_j_)&.>
```
[Try it online!](https://tio.run/##JYzBCoMwEETv@xVLBTVgY@kxrYIUeio99FpaCbIaJSbWxGt/PQ30MMzAG94UdjzrsRKYYYEHFDF7jpfH7RqeIi9FktYsjlhFyuuy5C/2Fm2efImnjV6UvG9zO7UswsAAHFYc8/OJt0f210EDbpZagzUEXkkPnTVejsYBfTapQZMZvALn19EMDnq7xhuBW6gbI143TRDN1CmLPbrwAw "J – Try It Online")
## ungolfed
```
[: (/: #&>) [: (#&> ,&.>//. ])^:_ (#~e.&AlphaNum_j_)&.>
```
## explanation
* `(#~e.&AlphaNum_j_)&.>` remove non alphanum
* `(#&> ,&.>//. ])` combine same length items
* `^:_` keep combining until it stops changing
* `(/: #&>)` sort by length
[Answer]
## Haskell, 129 bytes
```
import Data.List
import Data.Char
l=length
print.(foldl(const.map concat.groupBy((.l).(==).l).sortOn l)=<<(filter isAlphaNum<$>))
```
Accepts and prints an array of strings. If the result can be returned from the function (in contrast to printed to stdout), you can omit the `print.` and save 6 bytes.
How it works (note, I use `x` for the input parameter which of course does not appear in the pointfree version above):
```
( )=<<( ) -- (f =<< g) x is f (g x) x, so we fold over x with a
-- starting value of:
filter isAlphaNum<$>x -- keep only alphanumeric chars in every line of x
-- during folding, I ignore the the elements of x.
-- However folding stops the repeatedly applied function
-- after (length x) steps, which is enough for combining
-- lines of equal length
const -- ignore elements from x, deal only with start value
sortOn l -- sort lines from shortest to longest
groupBy((.l).(==).l) -- group lines of equal length
map concat -- concatenate each group
print -- print result after (length x) iterations
```
[Answer]
# Python 3, ~~184~~ 180 bytes
```
def f(x):l=len;m=filter;y=sorted([''.join(m(str.isalnum,i))for i in x],key=l);*z,=m(l,[''.join(i for i in y if-~j==l(i))for j in range(l(y[-1]))]);y==z and+print(*z,sep='\n')or f(z)
```
A function that takes input, by argument, as a list of strings and prints the result to STDOUT. Execution raises an error (due to the use of the + operator before the print statement), but not before the output has been printed.
**How it works**
```
def f(x): Function with input of list of strings
l=len;m=filter Redefine much-used functions: len gives the length
of an object and filter chooses those items from an
iterable for which a function is true
[''.join(m(str.isalnum,i))for i in x] Strip to leave only alphanumeric characters...
y=sorted(...,key=l) ...and sort by length, into y
''.join(i for i in y if-~j==l(i)) Concatenate equal length strings...
[...for j in range(l(y[-1]))] ...for all possible string lengths...
*z,=(m(l,...)) ...and remove empty strings by filtering by length
(the empty string has length 0, and is thus false),
into z
y==z and+print(*z,sep='\n')... If no change after concatenation, no more equal
length strings exist, so print result to STDOUT...
...or f(z) ...else pass new list to function
```
[Try it on Ideone](https://ideone.com/vD0bGs)
[Answer]
# [jq](https://stedolan.github.io/jq/), 78 bytes
Expects "an array with multiple strings."
```
def g:group_by(length);map(scan("\\w+"))|g|until(all(length<2);map(add)|g)[][]
```
[Try it online!](https://tio.run/##NYzBDsIgDEDv@4qFE0S9eFQvfse2mLoxhmGFQYkx2beLM7BTX9PX91pSGuRYq4vyNrrH88ONREWTuM7geOgBOWvb94EJsao1ImnDwZhi3c7Zg2HYzqLpmi6lpqprdmfH/wjzJme0KDPQBJSpt0igMeRNLhGKm@slQV6jKs5o/R4pteBkr/c/H41kVVd9rSNtMaST/wE "jq – Try It Online")
[Answer]
# Javascript ~~198~~ ~~188~~ ~~186~~ 179 bytes
This is my second longest golfed javascript program
```
s=>s.replace(/[^\w]|_/g,``,l=0).split(/\s/g).sort(g=(a,b)=>a[m=`length`]-b[m]).reduce((a,b,c)=>a+(a.split(/\s/g)[c-1][m]<b[m]?`
`:` `)+b).replace(/ /g,``).split`
`.sort(g).join`
`
```
Probably can be golfed further
[Answer]
# [Perl 5](https://www.perl.org/), 112 bytes
```
@F=<>;while($n-@F){$n=@F;%k=();s/[^a-z0-9]//gi,$k{y///c}.=$_ for@F;@F=values%k}say $k{$_}for sort{$a<=>$b}keys%k
```
[Try it online!](https://tio.run/##JYyxCoMwFEV3v8LhCQrG2MGhaMTJrZtbaSUtqYaIEV/aYiW/3jRQuFy4nMNdxDoVzjUtq@ryPcpJxDCTpk12mFnTlpFicVIiPV85@eTkeKF0kCmofaOU3m3GoA8fevWmv3jx6SkwUhb5FnoHeutZiHo1O/CK1XCzSmzecK4TaNLA@M6CbpQY@PD//urFSD2jI6ciyw/5Dw "Perl 5 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY
```
[Try it online!](https://tio.run/##y0rNyan8/z/tUdOawzPCH@6cdmiJD5B9ZMHD3d2PGnc83NUH5B3aeniCT@T///@j1R3VdRTUi3MTc3JAjPy8VBBVkpFYAqKT8/NKEjPzikHs1MLSRLCanNS89JIMsLaSosy8dLBsWn4RRCNYf3FBanImRHVRaU6qeiwA "Jelly – Try It Online")
Not sure why `Ẏf¥€ØWṖ¤L€ĠịµÐLY` doesn't work...
Explanation:
```
f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY Full program
µÐL Execute the following until we get a result a second time
¤ The following as a nilad
ØW [A-Za-z0-9_]
Ṗ Remove last element (_)
f€ Filter the left argument (current result) with the above nilad
€ Left map
L Length
Ġ Group indices of same values, sort values
⁸ Left argument
ị Index on ^^ and ^
€ Left map
Ẏ Concatenate elements
Y Join on newlines (full program will display correctly)
```
[Answer]
# Pyth, 22 bytes
```
jlDusM.glkG@Ls++GrG1UT
```
[Try it here.](http://pyth.herokuapp.com/?code=jlDusM.glkG%40Ls%2B%2BGrG1UT&input=%5B%27A%27%2C+%27small%27%2C+%27one%27%2C+%27that%27%2C+%27contains%27%2C+%27equal%27%2C+%27length%27%2C+%27strings%27%2C+%27for%27%2C+%27the%27%2C+%27special%27%2C+%27rule%27%5D&debug=0)
Explanation:
```
jlDusM.glkG@Ls++GrG1UT
j join on newlines
lD sort by length
u run until duplicate result, return result (argument G, iteration number H)
sM map concatenate elements
.g group elements by function (argument k)
l length
k k
G G
@L left map filter on presence (extra argument first)
s concatenate elements
+ concatenate two items
+ concatenate two items
G G (default = lowercase alphabet)
r 1 to uppercase
G G
U unary range [0..n)
T T (default = 10)
```
[Answer]
# Pyth, 39 bytes
Back to golfing !
There is the program :
~~```
=Qm:d"[\W_]"kQKYLmsd.glkolNb;WnKQ=KQ=yQ;jQ
```~~
```
=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j
```
[Test it here !](https://pyth.herokuapp.com/?code=%3DQm%3Ad%22%5B%5CW_%5D%22kQLmsd.glkolNb%3BWnYQ%3DYQ%3DyQ%3Bj&input=%5B%27A%27%2C+%27small%27%2C+%27one%27%2C+%27that%27%2C+%27contains%27%2C+%27equal%27%2C+%27length%27%2C+%27strings%27%2C+%27for%27%2C+%27the%27%2C+%27special%27%2C+%27rule%27%5D%0A&debug=0)
# Explanations
```
=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j (Implicit) Assign evaluated imput to Q (In this case, an array)
=Q Reassign a value to Q
m Q map a function over Q
:d"[\W_]"k Replace any special character with an empty string
L ; Declare a function y(b)
olNb Sort b by length
.glk Group strings of same length in arrays
msd Concat each inner array
WnYQ ; While Y != Q (previous array is not equal to current array)
=YQ Assign the current array to Y (Y=Q)
=yQ Assign y(Q) to Q (Q=yQ). Here, the assigned variable name is implicit
j Display the resulting array
```
[Answer]
# Java 8, 268 bytes
A void lambda accepting a mutable `List<String>` (i.e. implements `add` and `remove`; e.g. `ArrayList`). Output is printed to standard out, delimited by newline, with a trailing newline. Cast to `Consumer<List<String>>`.
```
l->{int i=0,z;while(i<l.size())l.set(i,l.get(i++).replaceAll("\\W| ",""));while(l.size()>0){l.sort((s,t)->s.length()-t.length());String s=l.remove(0);for(i=0,z=s.length();l.size()>0&&l.get(0).length()==z;i++)s+=l.remove(0);if(i<1)System.out.println(s);else l.add(s);}}
```
[Try It Online](https://tio.run/##hVRNb9swDD0nv4LwoZBRW8iucxKg23XDDg2ww7qDYjOxWlnyJDqpm@W3Z7SdJW3XZoYNfVCPenwkfa82KnU12vvi4VA3S6NzyI0KAb4qbWE3HtVebxQhBFLExnsGyIa0kavG5qSdlZ@dDU2Ffnq2fdGBprfktV3P58AuLN2S0j5XAWF2MOl8x1ugZ5PkKduW2qDQUyODfkIRxzxBEjoxct2N19ex9FgbleONMSK6u/v@G6IkiuL4iP2LnE/iHc@dJyFCQnE6D9KgXVMp4pRO0zgbqEGYGfZcuQ2KSZytnBc9o9kZlZ1dX10NfCbxyTqbPWUdvXD9wpFecTQf4ts2EFbSNSR7BYwVIc7QsARGqqLoVvv9YZSN/1F5upg/U/rGe9X2kvI2udNSLH78BM13hLjL1MgjNd6@BgYZyKOqxHBS5s4YzEmcjw12zmNvcD5IcscF51e8QeTjR4tb1nE82nfkh7o5ct84XUDF1SMGlZmj8usjxZelIFWeY03ieUzsGE7A3RjeeaJFqQPwqyCoqjYIhI@URMn7CCoVQesa2GpjoFQbxjhoQj8sG22KLgTN4V/ysigRts51IbawRHArwMccWS0u6F@NMpraizSc54ZAohZyr@q6BWUqFwhWypiuKFWtPIGyBayYJxZMl0qOzlecwMvcPhkFy@OXQnAVQuX8IM0l3LeHBHp1emUK98bZfZ/t0Rs1HaVpGrHxNeL/qY5uIFQcNTiLw/25swywAbBTEoY@46x05RCAG5SPcZPUmGs2@8ZgJEPNkosI@HcwFOT@8Ac)
This ended up being much longer than I expected. As Kevin observed, it's more complicated than it seems at first glance.
## Ungolfed lambda
```
l -> {
int i = 0, z;
while (i < l.size())
l.set(i, l.get(i++).replaceAll("\\W| ", ""));
while (l.size() > 0) {
l.sort((s, t) -> s.length() - t.length());
String s = l.remove(0);
for (
i = 0, z = s.length();
l.size() > 0 && l.get(0).length() == z;
i++
)
s += l.remove(0);
if (i < 1)
System.out.println(s);
else
l.add(s);
}
}
```
First, I reduce the input in place to letters and numbers. I then process the inputs in groups by length. I append items to the first in the list until the next length is reached, removing them as I go. If only the first element was used, that will be the only string of that length, so it's printed. Otherwise, the joined string is added to the list for another iteration. I sort the list by length each iteration before use.
I started off with a lovely solution that used a priority queue to keep track of the intermediate strings. Unfortunately, `java.util.PriorityQueue<String>` is quite long (and using the raw type was longer), so it had to go.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a1 [`-h`](https://codegolf.meta.stackexchange.com/a/14339/58974), 11 bytes
Input & output as arrays of strings.
```
£=mk\W üÊmq
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a1&code=oz1ta1xXIPzKbXE=&input=WyJhIgoiYmMiCiJkISIKIjEyMyJdCi1oUg==)
```
£=mk\L üÊmq
:Implicit input of string array U
£ :Map
m : Map U
k : Remove
\W : /[^A-Z0-9]/gi
ü : Sort & partition by
Ê : Length
m : Map
q : Join
= : Reassign to U for next iteration
:Implicit output of last element
```
[Answer]
# JavaScript, 119 bytes
I feel like this should be much shorter ...
Includes 2 leading newlines in the output.
```
f=s=>s==(s.replace(/[^\w\n]|_/g,t=``).split`
`.sort((x,y)=>x[l=`length`]-y[l]).map(x=>t+=s==(s=x[l])?x:`
`+x),t)?t:f(t)
```
[Try it online](https://tio.run/##PVHNjtsgEL7PU0xvRut41fa2Elm1L9BLbklaiD2O2WKgzHhjS333FDtt0QAaBr6f4c2@W26zS7ILsaP7vdes96x1xU2m5G1L1fPx@@l2CuffP56vtWhjVMPJOzFgGo5ZqmquF6X389Fr4ylcZTDn3XL0Z9WMNlWz3suT3jD1vJ6@zi/l7dOsalGv8tJXou5tDBw9NT5eqyOAOQyOsYRFtmPyhEKz1CCDFVzihDfnPQ72vRQiTrxtl8n5Dlmsy9zAYSC8xdjhaBe8EMYeaW7JF4WCvyZbHCw1xIwpk8iCbbYpLWj9GFmwt967cEWbbBa0ocO@MFJXiGUoYvLohArLV2/x8nfukONIOMb8kAvffta4Kd7UdtHUxdkX4LGAQwy02YFivUgODLSqgkcHgSUXfoY@5nKNgBO1rpTz5GnDORCvDSnr6tUxlLCPfKtbuLTQfYCPnz6DATj/@4u@mlVTwMdKqeYtumBO4RR2/8eaGXX/Aw)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 85 bytes
```
{.&([o] {my@a;@a[+.comb]~=$_ for $_;@a.grep(~*)}xx$_).sort(+*.comb)}o*.map:{S:g/\W//}
```
[Try it online!](https://tio.run/##HY1LCoMwFAD37xRZiPiBuOtCsdgzdNGFFUnlGQP5NYmgiF7dSrczA2PRydupVhKPpCbnRuOkNR3Z1NqwqmFtTgejPt1RRz0ZjSNRf1HKHdrkyNJ9WaI@pd64kOTZP013k1HFbLk9S168X0WxnxWMiRQafXq/U8/W8wFeMSnBaIQwsQCD0YEJ7QG/M5MgUfMwgQ9OaO7hGl8Zgrc4iEu7WeIP "Perl 6 – Try It Online")
Input and outputs as lists of strings.
[Answer]
# Pyth, 21 bytes
```
jusM.glkG:R"[^\w\d]"k
```
Input is a list of strings. Try it online [here](https://pyth.herokuapp.com/?code=jusM.glkG%3AR%22%5B%5E%5Cw%5Cd%5D%22k&input=%5B%22A%22%2C%22small%22%2C%22one%22%2C%22that%22%2C%22contains%22%2C%22equal%22%2C%22length%22%2C%22strings%22%2C%22for%22%2C%22the%22%2C%22special%22%2C%22rule%22%5D&debug=0), or verify all the test cases [here](https://pyth.herokuapp.com/?code=jusM.glkG%3AR%22%5B%5E%5Cw%5Cd%5D%22k&test_suite=1&test_suite_input=%5B%22This%20is%20a%20sample%20text%2C%22%2C%22that%20you%20will%20have%20to%20use%20to%20build%20stairs.%22%2C%22The%20wood%20may%20be%20of%20excellent%20quality%2C%22%2C%22or%20pretty%20crappy%20almost%20falling%20apart%20and%20filled%20with%20termites.%22%2C%22Bla%20bla%20bla%20-%20some%20more%20text%22%2C%22Ok%2C%20that%20will%20do%22%5D%0A%5B%22A%22%2C%22small%22%2C%22one%22%2C%22that%22%2C%22contains%22%2C%22equal%22%2C%22length%22%2C%22strings%22%2C%22for%22%2C%22the%22%2C%22special%22%2C%22rule%22%5D%0A%5B%22Test%2C%22%2C%22test.%22%2C%22This%22%2C%22is%22%2C%22a%22%2C%22test.%22%5D%0A%5B%22a%22%2C%22bc%22%2C%22d%21%22%2C%22123%22%5D&debug=0).
```
jusM.glkG:R"[^\w\d]"kQ Implicit: Q=eval(input()), k=""
Trailing Q inferred
R Q For each string in Q...
: "[^\w\d]" ... replace non-alphanumerics...
k ... with k (empty string)
u Repeat the following until a fixed point occurs, current as G:
.g G Group the elements of G...
lk ... by length
Groups ordered by the result of the inner function, i.e. length
This means that, in the final iteration, this acts as a sort by length
sM Concatenate each group back into a string
j Join the resulting list on newlines, implicit print
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes
```
krv↔⁽LġṠÞṡ)Ẋ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJhaiIsIiIsImtyduKGlOKBvUzEoeG5oMOe4bmhKeG6iiIsIiIsIkFcbnNtYWxsITBcbm9uZVxudGhhdCxcbmNvbnRhaW5zXG5lcXVhbFxubGVuZ3RoXG5zdHJpbmdzXG5mb3JcbnRoZVxuc3BlY2lhbFxucnVsZSJd)
I/O as lists of lines
```
)Ẋ # Repeat until no change...
v # To each...
↔ # Keep only characters from...
kr # Alphanumeric chars
ġ # Group by...
⁽L # Length
Ṡ # Concatenate each
Þṡ # Sort by length
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~95~~ 93 bytes
```
f=->a{b=a.map{_1.gsub /\W|_/,""}.group_by(&s=:size).map{_2*""}.sort_by &s
b[a.size-1]?a:f[b]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BbsIwEEX3c4ooiwhQY0RXKFKKOAWLNArjyE4sObbx2IsUOAkbFvRQvU0TAev3pPf_7eEjH-_33xhkvv2rZZl_4ZmXyAZ052bDOoo8WX8fLs36I02vrPM2uoaPi4zKgtSPWD7Nz9VMyfowwSQj4BWymeebeoeFrHh9fUWOLgZKZJXugQbUGqwREHoM0FoTUBkCcYqoQQvThR4oeGU6Amn9pAkgJ1o1YR-1SJlWRtC8YZEVbW8Ht6yfnfepfw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εžKÃ}»Δ¶¡é.γg}J»
```
Input as a list of strings.
[Try it online](https://tio.run/##yy9OTMpM/f//3Naj@7wPN9ce2n1uyqFthxYeXql3bnN6rdeh3f//Rys5KukoFecm5uQA6fy8VCBZkpFYAqSS8/NKEjPzioHM1MLSRJB8TmpeekkGSENJUWZeOkgqLb8IrAWksbggNTkTrLCoNCdVTykWAA) or [verify all test cases](https://tio.run/##PVCxTsMwEP2VI3OoBHwAAjHBwNKtynBJLo2FHQf70jZDJn6BH2BkRnSpxJCKtb8Uzk6FZN@z/e7uvbP1mCuaNv1DOp2@f3@ejm/DeDi9j/vx4/i5OH2th8fxMA3puL@dVqtkWSsPshA8mlYTMO04TdKEa2TobQdbpTXUuBHKQucj5J3SJXhG5fxCkpc1wdbaEgz2kBPYCmhXkNbUMLx2qBX3oal10Dpi7qFw2LY9oDbWM1SotWrWgC06BmxKqESVShHnWiw5o5ii0r1GyM/7Erw1BMa62bbQzy8pROfRdWmTLIVVcieMN6IRLDR0nk6gsI3M0Hg5UrApKJbXXIcCdmIpUJV1sSQU@pYKFRNdp2kx91@Sn/9McP4OFepiwP/3mBqueSGhvJBwdX2TZNkf).
Could have been 14 bytes with `εžKÃ}Δé.γg}J}»` if `Δ` would work with a list of strings as well..
**Explanation:**
```
ε } # Map the (implicit) input-list of strings:
žjà # Leave only the letters and digits of each string
# i.e. ["a","bc","d!","123"] → ["a","bc","d","123"]
» # Join the list by newlines to a single string
# i.e. ["a","bc","d","123"] → "a\nbc\nd\n123"
Δ # Loop until the string no longer changes:
¶¡ # Split by newlines
# i.e. "a\nbc\nd\n123" → ["a","bc","d","123"]
.γ } # Group the strings by:
g # Their length
# i.e. ["a","bc","d","123"] → [["a,"d"],["bc"],["123"]]
J # Join each group-list to a single string
# i.e. [["a,"d"],["bc"],["123"]] → ["ad","bc","123"]
» # Join this list by newlines again
# i.e. ["ad","bc","123"] → "ad\nbc\n123"
# (and the result is output implicitly after the loop)
# i.e. "123\nadbc"
```
[Answer]
## Powershell, Windows 10, 63 bytes
So input...
```
$n = @"
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do
"@
```
and code...
```
((($n -Split '\n').Replace(" ","")) -Replace '[\W]','')|Sort *h
```
That covers input/output 1, working on 2 and 3...
] |
[Question]
[
The problem is as follows.
**Input:** An integer `n`
**Output:** The smallest prime bigger than `n`.
The challenge is to give the fastest code possible to do this. I will test the code on values starting at size roughly `10^8` `10^200` and doubling in size until it takes more than one minute 10 seconds on my computer.
**The winning code** will find the next prime for the largest input size.
By way of comparison, a simple sieve written in python is able to find the next prime bigger than `10^8` in about `20` seconds.
The requirement that I can test it on my 4GB RAM ubuntu computer is strict. All code must be free (in both senses) and if it uses libraries they must also be free and easily installable. Any false primes reported will immediately disqualify the submission.
I will award separate commendations for the winners in each programming language too if the code is entirely written in that language without the use of external libraries. I will also keep a running table of the fastest times as the competition goes on so people can see how they are doing.
**Table so far**
* **Python.** An astonishing `357` digit prime `343239883006530485749095039954069660863471765007165270469723172959277159169882802606127982033072727748864815569574042901856099399985832190628701414555752857600000000000000000000000000000000000000002872284792758930912601189043411951050852357613658978971208596097634095500808832510259693761982135208603287199546795000697807728609476163156438356035166156820611` was the final number under 10 seconds using the code supplied by `primo`. Will anyone beat this first entry?
[Answer]
## Python ~451 digits
This is part of the library I wrote for a [semiprime factorization problem](https://codegolf.stackexchange.com/a/9088), with unnecessary functions removed. It uses the [Baillie-PSW primality test](http://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test), which is technically a probabilistic test, but to date, there are no known pseudoprimes – and there's even a cash reward if you're able to find one (or for supplying a proof that none exist).
**Edit**: I hadn't realized that Python has built-in modular exponentiation. Replacing my own for the built-in results in a performance boost of about 33%.
my\_math.py
```
# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
return pow(a, (m-1) >> 1, m)
# strong probable prime
def is_sprp(n, b=2):
d = n-1
s = 0
while d&1 == 0:
s += 1
d >>= 1
x = pow(b, d, n)
if x == 1 or x == n-1:
return True
for r in range(1, s):
x = (x * x)%n
if x == 1:
return False
elif x == n-1:
return True
return False
# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
P = 1
Q = (1-D) >> 2
# n+1 = 2**r*s where s is odd
s = n+1
r = 0
while s&1 == 0:
r += 1
s >>= 1
# calculate the bit reversal of (odd) s
# e.g. 19 (10011) <=> 25 (11001)
t = 0
while s > 0:
if s&1:
t += 1
s -= 1
else:
t <<= 1
s >>= 1
# use the same bit reversal process to calculate the sth Lucas number
# keep track of q = Q**n as we go
U = 0
V = 2
q = 1
# mod_inv(2, n)
inv_2 = (n+1) >> 1
while t > 0:
if t&1 == 1:
# U, V of n+1
U, V = ((U + V) * inv_2)%n, ((D*U + V) * inv_2)%n
q = (q * Q)%n
t -= 1
else:
# U, V of n*2
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
t >>= 1
# double s until we have the 2**r*sth Lucas number
while r > 0:
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
r -= 1
# primality check
# if n is prime, n divides the n+1st Lucas number, given the assumptions
return U == 0
# primes less than 212
small_primes = set([
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97,101,103,107,109,113,
127,131,137,139,149,151,157,163,167,173,
179,181,191,193,197,199,211])
# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
1, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97,101,103,107,109,113,121,127,131,
137,139,143,149,151,157,163,167,169,173,
179,181,187,191,193,197,199,209]
# distances between sieve values
offsets = [
10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]
max_int = 2147483647
# an 'almost certain' primality check
def is_prime(n):
if n < 212:
return n in small_primes
for p in small_primes:
if n%p == 0:
return False
# if n is a 32-bit integer, perform full trial division
if n <= max_int:
i = 211
while i*i < n:
for o in offsets:
i += o
if n%i == 0:
return False
return True
# Baillie-PSW
# this is technically a probabalistic test, but there are no known pseudoprimes
if not is_sprp(n): return False
a = 5
s = 2
while legendre(a, n) != n-1:
s = -s
a = s-a
return is_lucas_prp(n, a)
# next prime strictly larger than n
def next_prime(n):
if n < 2:
return 2
# first odd larger than n
n = (n + 1) | 1
if n < 212:
while True:
if n in small_primes:
return n
n += 2
# find our position in the sieve rotation via binary search
x = int(n%210)
s = 0
e = 47
m = 24
while m != e:
if indices[m] < x:
s = m
m = (s + e + 1) >> 1
else:
e = m
m = (s + e) >> 1
i = int(n + (indices[m] - x))
# adjust offsets
offs = offsets[m:]+offsets[:m]
while True:
for o in offs:
if is_prime(i):
return i
i += o
```
A sample test script:
```
from time import clock
from my_math import *
n = i = 317**79
while True:
i *= 317
time1 = clock()
n, o = next_prime(i), n
span = clock()-time1
if span > 10:
break
print(len(str(n)), span)
print(o)
```
A factor of 317 was chosen, because it's approximately the square root of `10000`, adding roughly 2.5 digits per iteration (and because doubling was too slow to sit through). Output shows the current number of digits, and the time taken.
Sample results:
```
201 0.13121248650317288
203 0.059535499623555505
206 0.9157767258129175
208 0.2583420518529589
211 0.15367400046653978
213 0.32343915218274955
216 1.3962866788935466
218 0.5986165839513125
221 0.973842206202185
223 2.346910291671148
...
428 0.932809896229827
431 4.345940056627313
433 9.511724255457068
436 6.089835998709333
438 1.3793498894412721
441 4.290633027381972
443 3.5102506044762833
446 3.1629148397352083
448 3.364759208223404
451 7.34668009481652
1551197868099891386459896063244381932060770425565921999885096817830297496627504652115239001983985153119775350914638552307445919773021758654815641382344720913548160379485681746575245251059529720935264144339378936233043585239478807971817857394193701584822359805681429741446927344534491412763713568490429195862973508863067230162660278070962484418979417980291904500349345162151774412157280412235743457342694749679453616265540134456421369622519723266737913
```
All code is now python 3 compatible.
[Answer]
## C++ with GMP: 567 digits
Uses the Miller-Rabin implementation in GMP. It might return a false positive, but good luck actually hitting one with probability 2^-200.
```
#include <gmp.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
double time() {
struct timeval t;
gettimeofday(&t, NULL);
return t.tv_usec * 1e-6 + t.tv_sec;
}
int main(int argc, char *argv[]) {
mpz_t n, m;
mpz_init_set_ui(n, 10);
mpz_pow_ui(n, n, 200);
mpz_init(m);
for (int i = 0; true; i++, mpz_mul_ui(n, n, 2)) {
double start = time();
for (mpz_add_ui(m, n, 1); !mpz_millerrabin(m, 100); mpz_add_ui(m, m, 2)) ;
double t = time() - start;
gmp_printf("%d %Zd %f\n", i, m, t);
if (t > 10.0) break;
}
}
```
Finds the prime `10^200 * 2^1216 + 361` (567 digits) before running over time on my slow laptop.
[Answer]
# Perl with GMP module, 1300 digits
Using my module [Math::Prime::Util](https://metacpan.org/pod/Math::Prime::Util) and its [GMP back end](https://metacpan.org/pod/Math::Prime::Util::GMP). The exact crossover point will depend on your computer and whether you have the latest GMP library. All code is free (the modules are on github and CPAN, and GMP is freely available). I've run them on AWS's Ubuntu as well as a desktop Ubuntu (and Fedora, and AIX, and NetBSD, etc.).
The core code is in C and C+GMP. next\_prime from MPU sees the number is too large and forwards it to the GMP back end (or pure Perl code if the back end isn't installed). That stringiifies and converts to a mpz, and will convert the result back into the input object type or Math::BigInt. next\_prime itself does:
* a mod 30 wheel
* keeps track of the remainder mod 23# so it can do native modulos for primes up to 23
* probable prime test on things that pass these.
The probable prime test is:
* check for tiny divisors using mpz\_gcd\_ui (in 64-bit two of these check up to 101)
* check for small divisors using singly-calculated large primorials. This is either primes up to 10k or 40k depending on the input size.
* for values larger than 2^1600, performs further trial division using a treesieve. This could be done more efficiently.
* finally, ES BPSW is done (Miller-Rabin test with base 2 followed by an [extra strong Lucas test](https://oeis.org/A217719)).
Everything prior to the ES BPSW is just optimization, which of course we want for next\_prime. next\_prime is also implemented in Perl using the Math::BigInt module (in core with optional Pari and GMP back ends). That does AES BPSW (like Pari) but isn't as optimized.
I have thought about the merits of a partial-sieve-based version, using a range of, for instance, 2 merits. I'm just not sure if this would really be better, as most of the time we'd be doing unnecessary sieving as the gap was small, and sometimes for a large gap we'd have to repeat it multiple times.
The library implements ECPP (including certificates) so we could run a proof on the result, but 1200 digits is really too large for the tiny default set of included polynomials (there is a method for downloading larger sets -- proofs would take a bit under 15 minutes which is a bit faster than Pari's APR-CL but a bit slower than WraithX's mpz\_aprcl). One downside of ECPP vs. APR-CL is that it has more time variance so there is a good chance of it exceeding 10 seconds on some number before the average time gets there. With a proof I think we're limited to something in the 400 digit range unless we allow multi-threaded software.
```
#!/usr/bin/env perl
use warnings;
use strict;
use Math::Prime::Util ":all";
use Math::Prime::Util::GMP; # Barf if the backend isn't installed
use Time::HiRes qw(gettimeofday tv_interval);
use Math::GMP;
my $n = Math::GMP->new(10) ** 200;
while (1) {
my $start = [gettimeofday];
my $np = next_prime($n);
my $sec = tv_interval($start);
my $len = length($n);
die "next_prime $len = +",$np-$n," in $sec seconds\n" if $sec > 10;
warn " next_prime $len = +",$np-$n," in $sec seconds\n";
$n *= 10;
}
```
I decided to try with the same sequence used by primo. It got to 1191 digits, as that is where we hit a gap of 18138. I also tested primo's code using the latest my\_math.py. It gets to 630 digits with the 10^e sequence and 641 with his sequence. Very impressive for compact all-Python code without lots of pretests.
[Answer]
# [pari/gp](http://pari.math.u-bordeaux.fr/), 703 digits
[Try it online!](https://tio.run/##TYzBCgIhFEX3fsXDNs7ggNJiqKG@oF2tAwNzpMYRRyiIvt3eczaBwuXcd080yXculhLgAB7/VvfXfjcw9mGv0T@t0JIBNm2tBszZT1bjpbOZomgI0jzYd46JkK9sJkZhiSb8D6BbJdSR/A6inhxBq1YrpSTckjUPtGCNypAFP9ng8rgHLmFzzkmERlK@oKhCMiCZFo4zfF@2DmfMpfwA)
```
n = i = 317^79;
{
while(1,
i *= 317;
time1 = gettime();
n = nextprime(i);
o = n;
span = gettime() - time1;
if (span > 10*1000, break);
print("Length: ", #Str(n), ", Time: ", span, "ms");
);
}
print(o);
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/2403/edit)
This is a nice exercise for becoming more fluent in that programming language you've been meaning to learn, but have only tinkered with lightly. This involves working with objects, using or simulating closures, and stretching the type system.
Your task is to write code to manage lazy lists, then use it to implement this algorithm for generating Fibonacci numbers:
*Code samples are in Haskell*
```
let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
in take 40 fibs
```
Result:
```
[0,1,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]
```
Your lazy list implementation should meet these guidelines:
* A List node is one of three things:
+ Nil - Empty list.
`[]`
+ Cons - A single item, paired with a List of the remaining items:
`1 : [2,3,4,5]`
(`:` is the cons operator in Haskell)
+ Thunk - A deferred computation that produces a List node when needed.
* It supports the following operations:
+ nil - Construct an empty list.
+ cons - Construct a cons cell.
+ thunk - Construct a Thunk, given a function that takes no arguments and returns a Nil or Cons.
+ force - Given a List node:
- If it's a Nil or Cons, simply return it.
- If it's a Thunk, call its function to get a Nil or Cons. Replace the thunk with that Nil or Cons, and return it.
**Note:** Replacing the thunk with its forced value is an important part of the [definition of "lazy"](http://en.wikipedia.org/wiki/Lazy_evaluation). If this step is skipped, the Fibonacci algorithm above will be too slow.
+ empty - See if a List node is Nil (after forcing it).
+ head (a.k.a. "car") - Get the first item of a list (or throw a fit if it's Nil).
+ tail (a.k.a. "cdr") - Get the elements after the head of a list (or throw a fit if it's Nil).
+ zipWith - Given a binary function (e.g. `(+)`) and two (possibly infinite) lists, apply the function to corresponding items of the lists. Example:
`zipWith (+) [1,2,3] [1,1,10] == [2,3,13]`
+ take - Given a number N and a (possibly infinite) list, grab the first N items of the list.
+ print - Print all the items in a list. This should work incrementally when given a long or infinite list.
* `fibs` uses itself in its own definition. Setting up lazy recursion is a tad tricky; you'll need to do something like this:
+ Allocate a thunk for `fibs`. Leave it in a dummy state for now.
+ Define the thunk function, which depends on a reference to `fibs`.
+ Update the thunk with its function.You may want to hide this plumbing by defining a function `fix` which calls a List-returning function with its own return value. Consider taking a short nap so this idea can set in.
* Polymorphism (the ability to work with lists of any type of item) is not required, but see if you can find a way to do it that's idiomatic in your language.
* Don't worry about memory management. Even languages with garbage collection have a tendency to carry around objects you'll never use again (e.g. on the call stack), so don't be surprised if your program leaks memory while traversing an infinite list.
Feel free to deviate slightly from these guidelines to accommodate the particulars of your language, or to explore alternative approaches to lazy lists.
Rules:
* Pick a language you don't know well. I can't "require" this, hence the "honor-system" tag. However, voters can check your history to see what languages you've been posting in.
* Don't use your language's built-in lazy list support to do everything. Post something substantial or at least interesting.
+ Haskell is pretty much out. That is, unless you do something like this:
```
data List a = IORef (ListNode a)
data ListNode a = Nil | Cons !a !(List a) | Thunk !(IO (ListNode a))
```
Note: Haskell's non-strict evaluation isn't off-limits, but your lazy list implementation shouldn't derive its capability directly from there. In fact, it'd be interesting to see an efficient, purely functional solution that doesn't require laziness.
+ Python:
- Don't use itertools.
- Generators are fine, but you use them, you'll have to find some way to memoize forced values.
[Answer]
## PostScript
I've [played with PostScript before](https://stackoverflow.com/questions/1078770/array-searching-code-challenge/1079109#1079109), but I wouldn't say I know it particularly well (in fact, my guess is that you can count the number of people in the world that really know PostScript using one hand).
I deviated from your spec in that the function that's used to create a thunk is allowed to return another thunk; `force` will keep evaluating until the result is a `nil` or a `cons`.
The lists are implemented as dictionaries:
```
<< /type /nil >>
<< /type /cons
/head someValue
/tail someList >>
<< /type /thunk
/func evaluationFunction >>
<< /type /dataThunk
/func evaluationFunction
/data someValueToBePassedToTheFunction >>
```
The code follows. Note that we're overwriting some builtin operators (in particular `print`; I haven't checked if there are more); in real world use, this would have to be watched out for. Of course there will be no real world use, so that's fine.
The comments before the procedures are to be read as
```
% before2 before1 before0 <| procedure |> after1 after0
```
i.e. showing the expected stack contents before the call and the resulting stack contents after the call. The comments within the procedures show the content of the stack after the particular line has been executed.
```
% Helper procedure that creates a dictionary with the top two elements as keys
% and the next two elements as values.
%
% value1 value2 key1 key2 <| _twodict |> << /key1 /value1 /key2 /value2 >>
/_twodict {
<< 5 1 roll % << value1 value2 key1 key2
4 2 roll % << key1 key2 value1 value2
3 2 roll % << key1 value1 value2 key2
exch >>
} def
/nil {
<< /type /nil >>
} def
% item list <| cons |> consCell
/cons {
/head /tail _twodict
dup /type /cons put
} def
% constructs a thunk from the function, which will be called with no
% arguments to produce the actual list node. It is legal for the function
% to return another thunk.
%
% func <| thunk |> lazyList
/thunk {
/thunk /func /type _twodict
} def
% A dataThunk is like a regular thunk, except that there's an additional
% data object that will be passed to the evaluation function
%
% dataObject func <| dataThunk |> lazyList
/dataThunk {
/data /func _twodict
dup /type /dataThunk put
} def
% lazyList <| force |> consOrNil
/force {
dup /type get dup
/thunk eq
{
pop
dup /func get exec exch copy
force
dup /func undef
}
{
/dataThunk eq
{
dup dup /data get exch
/func get exec exch copy
force
dup dup /func undef /data undef
} if
} ifelse
} def
/empty {
force
/type get
/nil eq
} def
/head {
force /head get
} def
/tail {
force /tail get
} def
/print {
dup empty not
{
dup
head ==
tail
print
}
{
pop
} ifelse
} def
% sourceList n <| take |> resultingList
/take {
/source /n _twodict
{
dup /source get exch % source data
/n get 1 sub dup % source n-1 n-1
-1 eq
{
pop pop nil
}
{ % source n-1
exch % n-1 source
dup head % n-1 source head
3 1 roll % head n-1 source
tail
exch take % head rest
cons
} ifelse
}
dataThunk
} def
% sourceList1 sourceList2 func <| zipWith |> resultList
/zipWith {
3 1 roll
2 array astore % func [L1 L2]
/func /sources _twodict
{
dup /sources get aload pop % data L1 L2
2 copy empty exch empty or
{
pop pop pop nil
}
{
dup head exch tail % data L1 H2 T2
3 2 roll
dup head exch tail % data H2 T2 H1 T1
exch % data H2 T2 T1 H1
4 3 roll % data T2 T1 H1 H2
5 4 roll /func get % T2 T1 H1 H2 func
dup 4 1 roll % T2 T1 func H1 H2 func
exec % T2 T1 func NEWHEAD
4 2 roll % func NEWHEAD T2 T1
exch 4 3 roll % NEWHEAD T1 T2 func
zipWith cons
} ifelse
}
dataThunk
} def
```
Load this into Ghostscript, ignoring the displayed page -- we're only working with the interpreter. Here's the Fibonacci algorithm:
```
[balpha@localhost lazylist]$ gs lazylist.ps
GPL Ghostscript 8.71 (2010-02-10)
Copyright (C) 2010 Artifex Software, Inc. All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
GS> **/fibs 0 1 { fibs fibs tail { add } zipWith } thunk cons cons def**
GS> **fibs 40 take print**
0
1
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
GS>
```
Two additional interesting functions:
```
% creates an infinite list that starts with the given value, incrementing
% by one for each additional element
%
% startValue <| count |> lazyList
/count {
{
dup
1 add count
cons
}
dataThunk
} def
% apply the given function to each element of the source list, creating
% a (lazy) list that contains the corresponding results
%
% sourceList function <| map |> resultList
/map {
/source /func _twodict
{
dup /func get exch
/source get % func source
dup empty not
{
dup head % func source head
2 index % func source head func
exec 3 1 roll % newHead func source
tail exch map cons
}
{
pop pop nil
} ifelse
}
dataThunk
} def
```
Start counting at 5, multiply each element of the resulting list with 3, and display the first ten values:
```
GS> 5 count { 3 mul } map 10 take print
15
18
21
24
27
30
33
36
39
42
```
Regarding polymorphism: Even though PostScript is strongly typed, it allows arbitrary types as dictionary values, so you can throw in anything you like:
```
GS> 1337 [ 42 3.14 ] << /key /value >> (Hello world) 3 count
GS<5> cons cons cons cons 10 take print
1337
[42 3.14]
-dict-
(Hello world)
3
4
5
6
7
8
GS>
```
Note that type errors, e.g. from trying to add strings to numbers, will only happen at evaluation time:
```
GS> (some string) (another string) nil cons cons
GS<1> 13 27 nil cons cons
GS<2> { add } zipWith % no error yet
GS<1> print
Error: /typecheck in --add--
```
[Answer]
## C
I am a total beginner in C, this code is actually the first real thing I coded in C. It compiles without any warnings and runs fine on my system.
### How to build
First, get the tarball from my [server](http://fuz.su/%7Efuz/src/lazy-list.tar.bz2). It includes a makefile, so just run `make` to build it and then `make run` to run it. The program then prints a list of the first 93 fibonacci numbers. (After number 94, an unsigned 64 bit integer overflows)
### Explanation
The programs core is the file `lazy-list.c`. In the corresponding header file, I define a struct `list`, that is our lazy list. It looks like this:
```
enum cell_kind {
NIL,
CONS,
THUNK
};
typedef enum cell_kind cell_kind;
typedef long int content_t;
struct list {
cell_kind kind;
union {
struct {
content_t* head;
struct list* tail;
} cons;
struct {
struct list* (*thunk)(void*);
/* If you want to give arguments to the thunk, put them in here */
void* args;
} thunk;
} content;
};
```
The member `kind` is kind of a tag. It marks, whether we reched the lists end (`NIL`), a cell that is already evaluated (`CONS`) or a thunk (`THUNK`). Then, there follows a union. It is
* either an already evaluated cell with a value and a tail
* or a thunk, featuring a function-pointer and a struct, that may contain some arguments to the function, if needed.
The content of the union is asserted by the tag. If the tag is `NIL`, the content of the union is undefined.
By defining the helper functions mentioned in the specification above, one can usually abstract the lists definition from it's usage, eg. you can simply call `nil()` to get an empty list instead of creating one by yourself.
The three most interesting functions are `zipWith`, `take` and `fibonaccis`. But I don't want to explain `take`, since it is very similar to `zipWith`. All functions, that operate lazily, have three components:
* A wrapper, that creates a thunk
* A worker, that performs the calculations for one cell
* A struct, that keeps the arguments
In case of `zipWith`, these are `zipWith`, `__zipWith` and `__zipArgs`. I just show them here without any further explanation, there function should be quite clear:
```
struct __zipArgs {
content_t* (*f)(content_t*,content_t*);
list* listA;
list* listB;
};
static list* __zipWith(void* args_) {
struct __zipArgs* args = args_;
list* listA = args->listA;
list* listB = args->listB;
list* listC;
content_t* (*f)(content_t*,content_t*) = args->f;
content_t* headA = head(listA);
content_t* headB = head(listB);
content_t* headC;
if (NULL == headA || NULL == headB) {
free(args);
return nil();
} else {
headC = f(headA, headB);
args->listA = tail(listA);
args->listB = tail(listB);
listC = thunk(__zipWith,args);
return cons(headC,listC);
}
}
list* zipWith(content_t* (*f)(content_t*,content_t*),list* listA, list* listB) {
struct __zipArgs* args = malloc(sizeof(struct __zipArgs));
args->f = f;
args->listA = listA;
args->listB = listB;
return thunk(__zipWith,args);
}
```
The other interesting function is `fibonaccis()`. The problem is, that we need to pass a pointer of the first and second cell to the thunk of the third, but in order to create those cells we also need a pointer to the thunk. To solve that problem, I filled the pointer to the thunk with a `NULL` first and changed it into the thunk, after it was created. Here is the listening:
```
static content_t* __add(content_t* a,content_t* b) {
content_t* result = malloc(sizeof(content_t));
*result = *a + *b;
return result;
}
list* fibonaccis() {
static content_t one_ = 1;
static content_t zero_ = 0;
list* one = cons(&one_,NULL);
list* two = cons(&zero_,one);
list* core = zipWith(__add,one,two);
one->content.cons.tail = core;
return two;
```
### Possible improvements
* My solution does not use polymorphism. Although possibly possible, my C skills are not sufficient to know how to use it. Instead, I used a type `content_t`, that one can change to whatever fits.
* One could extract the thunk out of the list's defintion and using it only abstractly, but doing so would make the code more complicated.
* One could improve the parts of my code that aren't good C.
[Answer]
## C++
This is the largest thing I've ever written in C++. I normally use Objective-C.
It's polymorphic but it doesn't free anything ever.
My `main` function (and the `add` function to `ZipWith`)ended up looking like this:
```
int add(int a, int b) {return a + b;}
int main(int argc, char **argv) {
int numFib = 15; // amount of fibonacci numbers we'll print
if (argc == 2) {
numFib = atoi(argv[1]);
}
// list that starts off 1, 1...
LazyList<int> fibo = LazyList<int>(new Cons<int>(1,
new LazyList<int>(new Cons<int>(1))));
// zip the list with its own tail
LazyList<int> *fiboZip = LazyList<int>::ZipWith(add, &fibo, fibo.Tail());
// connect the begin list to the zipped list
fibo.Tail() -> ConnectToList(fiboZip);
// print fibonacci numbers
int *fibonums = fibo.Take(numFib);
for (int i=0; i<numFib; i++) cout << fibonums[i] << " ";
cout<<endl;
return 0;
}
```
This gives
```
./lazylist-fibo 20
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
```
The classes work like this:
```
make a thunk: LazyList<T>(new Thunk<T>( function, *args ))
make empty list: LazyList<T>(new Nil<T>())
make cons: LazyList<T>(new Cons<T>( car, *cdr ))
list empty: list.Empty()
list's head: list.Head()
list's tail: list.Tail()
zipWith: LazyList<T>::ZipWith(function, a, b)
take: list.Take(n)
print: list.Print()
```
Full source: [here](https://gist.github.com/1547644). It's a mess, mainly because it's in one big file.
Edit: changed the link (the old one was dead).
[Answer]
## Python
Doesn't use generators to implement the list, just to implement the `__iter__` method for use with `for`.
```
class Node(object):
def __init__(self, head, tail):
self.__head__ = head
self.__tail__ = tail
def force(self):
return self
def empty(self):
return False
def head(self):
return self.__head__
def tail(self):
return self.__tail__
def zip_with(self, func, other):
def gen_func():
if other.empty():
return other
return Node(func(self.head(), other.head()), self.tail().zip_with(func, other.tail()))
return Thunk(gen_func)
def __iter__(self):
while not self.empty():
yield self.head()
self = self.tail()
def append(self, other):
while not self.tail().empty():
self = self.tail()
self.__tail__ = other
def take(self, n):
if n == 0:
return NullNode()
else:
return Node(self.__head__, self.__tail__.take(n - 1))
def _print(self):
for item in self:
print item
class NullNode(Node):
def __init__(self):
pass
def empty(self):
return True
def head(self):
raise TypeError("cannot get head of nil")
def tail(self):
raise TypeError("cannot get tail of nil")
def zip_with(self, func, other):
return self
def append(self, other):
raise TypeError("cannot append to nil")
def take(self, n):
return self
class Thunk(Node):
def __init__(self, func):
self.func = func
def force(self):
node = self.func()
self.__class__ = node.__class__
if not node.empty():
self.__head__ = node.head()
self.__tail__ = node.tail()
return self
def empty(self):
return self.force().empty()
def head(self):
return self.force().head()
def tail(self):
return self.force().tail()
def take(self, n):
return self.force().take(n)
```
The Fibonacci list is created like this:
```
>>> from lazylist import *
>>> fib = Node(0, Node(1, NullNode()))
>>> fib.append(fib.zip_with(lambda a, b: a + b, fib.tail()))
>>>
```
[Answer]
## Ruby
My first Ruby program. We represent all nodes as arrays, where the array length determines the type:
```
0: empty list
1: thunk (call the single element to get the cons cell)
2: cons cell (1st is head, 2nd is tail)
```
The code is then pretty straightforward, with a hack to reset the thunk function to set up the recursive fib.
```
def nil_()
return Array[]
end
def cons(a, b)
return Array[a, b]
end
def thunk(f)
return Array[f]
end
def force(x)
if x.size == 1
r = x[0].call
if r.size == 2
x[0] = r[0]
x.push(r[1])
else
x.pop()
end
end
end
def empty(x)
force(x)
return x.size == 0
end
def head(x)
force(x)
return x[0]
end
def tail(x)
force(x)
return x[1]
end
def zipWith(f, a, b)
return thunk(lambda {
if empty(a) or empty(b)
return nil_()
else
return cons(f.call(head(a), head(b)), zipWith(f, tail(a), tail(b)))
end
})
end
def take(n, x)
if n == 0
return nil_()
else
return cons(head(x), take(n - 1, tail(x)))
end
end
def print(x)
while not empty(x)
puts x[0]
x = x[1]
end
end
def add(x, y)
return x + y
end
T=thunk(nil) # dummy thunk function
fibs=cons(0, cons(1, T))
T[0]=zipWith(method(:add), fibs, tail(fibs))[0] # overwrite thunk function
print(take(40, fibs))
```
[Answer]
## Google Go
A relatively new language, and I learned it by `CTRL+F`ing the [Spec](http://golang.org/doc/go_spec.html).
```
package main
import "fmt"
type List struct {
isNil, isCons, isThunk bool
head *interface { }
tail *List
thunk (func() List)
}
func Nil() List {
return List { true, false, false, nil, nil, Nil }
}
func Cons(a interface { }, b List) List {
return List { false, true, false, &a, &b, Nil }
}
func Thunk(f(func() List)) List {
return List { false, false, true, nil, nil, f }
}
func Force(x List) List {
if x.isNil { return Nil()
} else if x.isCons { return Cons(*x.head, *x.tail) }
return Force(x.thunk())
}
func Empty(x List) bool {
return Force(x).isNil;
}
func Head(x List) interface { } {
y := Force(x)
if y.isNil { panic("No head for empty lists.") }
return *y.head
}
func Tail(x List) List {
y := Force(x)
if y.isNil { panic("No tail for empty lists.") }
return *y.tail
}
func Take(n int, x List) List {
if (n == 0) { return Nil() }
return Thunk(func() List {
y := Force(x)
return Cons(*y.head, Take(n - 1, *y.tail))
})
}
func Wrap(x List) List {
return Thunk(func() List {
return x
})
}
func ZipWith(f(func(interface { }, interface { }) interface { }), a List, b List) List {
return Thunk(func() List {
x, y := Force(a), Force(b)
if x.isNil || y.isNil {
return Nil()
}
return Cons(f(*x.head, *y.head), ZipWith(f, *x.tail, *y.tail))
});
}
func FromArray(a []interface { }) List {
l := Nil()
for i := len(a) - 1; i > -1; i -- {
l = Cons(a[i], l)
}
return l
}
func Print(x List) {
fmt.Print("[")
Print1(x)
fmt.Print("]")
}
func Print1(x List) {
y := Force(x)
if y.isCons {
fmt.Print(Head(y))
z := Force(Tail(y))
if z.isCons { fmt.Print(", ") }
Print1(z)
}
}
func Plus(a interface { }, b interface { }) interface { } {
return a.(int) + b.(int)
}
func Fibs() List {
return Thunk(func() List {
return Cons(0, Cons(1, Thunk(func() List {
return ZipWith(Plus, Thunk(Fibs), Tail(Thunk(Fibs)))
})))
})
}
func Fibs0() List {
// alternative method, working
return Cons(0, Cons(1, Fibs1(0, 1)))
}
func Fibs1(a int, b int) List {
c := a + b
return Cons(c, Thunk(func() List { return Fibs1(b, c) }))
}
func CountUp(x int, k int) List {
return Cons(x, Thunk(func() List {
return CountUp(x + k, k)
}))
}
func main() {
//a := []interface{} { 0, 1, 2, 3 }
//l, s := FromArray(a), FromArray(a)
Print(Take(40, Fibs()))
}
```
The problem was fixed, by dealing with thunk-within-a-thunks.
However, it seems the online compiler cannot take 40 elements, maybe because of memory. I will test it on my Linux later.
```
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368runtime: address space conflict: map() =
throw: runtime: address space conflict
panic during panic
```
I tested the code with the [online compiler](http://golang.org/), because I can't install Go on Windows easily.
[Answer]
# [Crystal](http://crystal-lang.org/)
Despite following the GitHub repository, I've never actually *used* Crystal until now. Crystal is a statically-typed Ruby variant with full type inference. Even though there's already a Ruby answer, Crystal's static typing led me to using polymorphism, rather than an array, to represent the nodes. Because Crystal does not allow modification of `self`, I created a wrapper class, named `Node`, that would wrap everything else and manage the thunks.
Along with the classes, I created the constructor functions `lnil`, `cons`, and `thunk`. I've never quite used Ruby for more than a 20-line script before, either, so the block stuff threw me off quite a bit.
I based the `fib` function off the [Go answer](https://codegolf.stackexchange.com/a/2416/21009).
```
class InvalidNodeException < Exception
end
abstract class LazyValue
end
class LNil < LazyValue
def empty?
true
end
def force!
self
end
def head
raise InvalidNodeException.new "cannot get head of LNil"
end
def tail
raise InvalidNodeException.new "cannot get tail of Nil"
end
def take(n)
Node.new self
end
end
class Cons < LazyValue
def initialize(@car, @cdr)
end
def empty?
false
end
def force!
@cdr.force!
self
end
def head
@car
end
def tail
@cdr
end
def take(n)
Node.new n > 0 ? Cons.new @car, @cdr.take n-1 : LNil.new
end
end
class Thunk < LazyValue
def initialize(&@func : (-> Node))
end
def empty?
raise Exception.new "should not be here!"
end
def force!
@func.call()
end
def head
self.force!.head
end
def tail
self.force!.tail
end
def take(n)
self.force!.take n
end
end
class Node
def initialize(@value = LNil.new)
end
def empty?
self.force!
@value.empty?
end
def force!
@value = @value.force!
self
end
def head
self.force!
@value.head
end
def tail
self.force!
@value.tail
end
def take(n)
self.force!
return @value.take n
end
def print
cur = self
while !cur.empty?
puts cur.head
cur = cur.tail
end
end
end
def lnil
Node.new LNil.new
end
def cons(x, r)
Node.new Cons.new x, r
end
def thunk(&f : (-> Node))
Node.new Thunk.new &f
end
def inf(st=0)
# a helper to make an infinite list
f = ->() { lnil }
f = ->() { st += 1; cons st, thunk &f }
thunk { cons st, thunk &f }
end
def zipwith(a, b, &f : Int32, Int32 -> Int32)
thunk { a.empty? || b.empty? ? lnil :
cons f.call(a.head, b.head), zipwith a.tail, b.tail, &f }
end
def fibs
# based on the Go answer
fibs2 = ->(a : Int32, b : Int32) { lnil }
fibs2 = ->(a : Int32, b : Int32) { cons a+b, thunk { fibs2.call b, a+b } }
cons 0, cons 1, thunk { fibs2.call 0, 1 }
end
fibs.take(40).print
zipwith(inf, (cons 1, cons 2, cons 3, lnil), &->(a : Int32, b : Int32){ a+b }).print
```
[Answer]
I bent the rules a little because there isn’t yet a .NET solution here – or more generally an OOP solution except for the one in Python which uses inheritance, but it’s different enough from my solution to make both interesting (in particular since Python allows to modify the `self` instance, making the thunk implementation straightforward).
So this is **C#**. Full disclosure: I’m nowhere near a beginner in C# but I haven’t touched the language in a while since I currently have no use for it at the job.
The salient points:
* All classes (`Nil`, `Cons`, `Thunk`) derive from a common abstract base class, `List`.
* The `Thunk` class uses the [Envelope-Letter](http://en.wikibooks.org/wiki/More_C++_Idioms/Envelope_Letter) pattern. This essentially emulates the `self.__class__ = node.__class__` assignment in the Python source, since the `this` reference cannot be modified in C#.
* `IsEmpty`, `Head` and `Tail` are properties.
* *All* appropriate functions are implemented recursively and lazily (except for `Print`, which can’t be lazy) by returning thunks. For example, this is `Nil<T>.ZipWith`:
```
public override List<T> ZipWith(Func<T, T, T> func, List<T> other) {
return Nil();
}
```
… and this is `Cons<T>.ZipWith`:
```
public override List<T> ZipWith(Func<T, T, T> func, List<T> other) {
return Thunk(() => {
if (other.IsEmpty)
return Nil();
return Cons(func(Head, other.Head), Tail.ZipWith(func, other.Tail));
});
}
```
Unfortunately, C# has no multiple dispatch, otherwise I could also get rid of the `if` statement. Alas, no dice.
Now, I’m not really happy with my implementation. I’m happy so far because all of the above is totally straightforward. *But*. I feel that the definition of `Fib` is needlessly complicated since I need to wrap the arguments into thunks to make it work:
```
List<int> fib = null;
fib = List.Cons(0, List.Cons(1,
List.ZipWith(
(a, b) => a + b,
List.Thunk(() => fib),
List.Thunk(() => fib.Tail))));
```
(Here, `List.Cons`, `List.Thunk` and `List.ZipWith` are convenience wrappers.)
I would like to understand why the following much easier definition isn’t working:
```
List<int> fib = List.Cons(0, List.Cons(1, List.Nil<int>()));
fib = fib.Concat(fib.ZipWith((a, b) => a + b, fib.Tail));
```
given an appropriate definition of `Concat`, of course. This is essentially what the Python code does – but it’s not working (= throwing a fit).
/EDIT: Joey has pointed out the obvious flaw in this solution. However, replacing the second line with a thunk also yields an error (Mono segfaults; I’m suspecting a stack overflow which Mono doesn’t handle well):
```
fib = List.Thunk(() => fib.Concat(fib.ZipWith((a, b) => a + b, fib.Tail)));
```
The full source code can be found [as a gist on GitHub](https://gist.github.com/1000783).
[Answer]
## Pico
for the record, this solution uses a translation of scheme's delay force as defined in [srfi-45](http://srfi.schemers.org/srfi-45/). and builds lazy lists on top of that.
```
{
` scheme's srfi-45 begins here `
_lazy_::"lazy";
_eager_::"eager";
lazy(exp())::[[_lazy_, exp]];
eager(exp)::[[_eager_, exp]];
delay(exp())::lazy(eager(exp()));
force(promise)::
{ content:promise[1];
if(content[1]~_eager_,
content[2],
if(content[1]~_lazy_,
{ promise_:content[2]();
content:promise[1];
if(content[1]~_lazy_,
{ content_:promise_[1];
content[1]:=content_[1];
content[2]:=content_[2];
promise_[1]:=content });
force(promise) })) };
` scheme's srfi-45 ends here `
nil:delay([]);
is_nil(s):size(force(s))=0;
cons(a(),b()):delay([a(),b()]);
head(s):force(s)[1];
tail(s):force(s)[2];
zipWith(f,a,b):
lazy(if(is_nil(a)|is_nil(b),
nil,
cons(f(head(a),head(b)), zipWith(f,tail(a),tail(b)))));
fibs:void;
fibs:=cons(0, cons(1, zipWith(+,fibs,tail(fibs))));
take(c,s):
lazy(if((c=0)|(is_nil(s)),
nil,
cons(head(s),take(c-1,tail(s)))));
print(s):
{ comma(s):
if(is_nil(s),
void,
{ display(head(s));
if(!(is_nil(tail(s))), display(","));
comma(tail(s)) });
display("[");
comma(s);
display("]");
void };
print(take(40,fibs))
}
```
the output looks like this: (but depending on how `tpico` is patched it might have more double quotes in it. `display` normally prints strings with quotes. i.e. all appearances of `[`,`,`,`]` would have quotes around them like `"["`.)
```
[0,1,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]<void>
```
due to the limits of the integer datatype in tpico this fails at computing the 45th (or 46th offset) Fibonacci number.
note that tpico 2.0pl11 is broken in that `begin(a,b)` (which is commonly written as `{a;b}`) and the `if` function are not tail recursive. not to mention that it took me 5 years to figure out why `begin` wasn't tail recursive. also at that time i wrote the translation of srfi-45 in Pico. it turned out to be that `begin` was waiting for the value of `b` before returning when it didn't need to wait. and once i got that i was also able to fix `if` as it had the same problem. and there was this other error that made the meta level constructor `make` inoperative.
Pico lets a function control if its arguments are evaluated before the function is called or just packaged as thunks. for this code, i can ellipsis over the oddities of *call by function*.
Pico has no type inference. i thought about this for a while but i ran to a problem due to the oddities of *call by function*. i came up with the statement that *types must encode the existence of bound variable names*. but i was mainly thinking of how to adapt Hindley-Milner type inference to a subset of Pico without mutation. the main idea was that *the type checker returns multiple possible schemes if there are more than one possible binding* and *the type check succeeds if there is at least one possible type scheme*. a possible scheme is one that no type assignment conflicts.
] |
[Question]
[
Given a positive integer `n`, do the following (and output every stage):
1. start with a list containing `n` copies of `n`.
2. do the following `n` times:
3. at the `i`th step, gradually decrement the `i`th entry of the list until it reaches `i`
So, for example, if the given `n` is `4`, then you start with `[4,4,4,4]`, and then at the first step you have `[3,4,4,4]`, `[2,4,4,4]`, `[1,4,4,4]`. At the second step, you have `[1,3,4,4]`, `[1,2,4,4]`. At the third step you have `[1,2,3,4]`. Nothing is done on the fourth step.
So your output is `[[4,4,4,4],[3,4,4,4],[2,4,4,4],[1,4,4,4],[1,3,4,4],[1,2,4,4],[1,2,3,4]]`.
---
Any reasonable input/output format is permitted.
---
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): the answer with the smallest byte-count wins.
---
[Python implementation for checking purposes](https://tio.run/##XY3BCsIwEETP6VestwRRKHoS8iUhSKEbu2C3IY1Yvz7uigfxOPOGN/lVp4VPrY2YIFl2l87MOIOHwJCWAlcghjLwDQXGzhRcFYbtQzelso9CNNPvWlTmOdEddREows4D7Xutzbc5eOg1ivU45Iw82n@z08/6KOLFteVCXG2yZ@faGw).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly)
```
r€⁸Œp»\QṚ
```
**[Try it online!](https://tio.run/##ARwA4/9qZWxsef//cuKCrOKBuMWScMK7XFHhuZr///81 "Jelly – Try It Online")**
### How?
```
r€⁸Œp»\QṚ - Link: integer, N e.g. 4
€ - for €ach of implicit range of N (i.e. for i in [1,2,3,...N])
⁸ - with the chain's left argument, N on the right:
r - inclusive range (for i<=N this yields [i, i+1, ..., N]
- ...leaving us with a list of lists like the post-fixes of [1,2,3,....,N]
- e.g. [[1,2,3,4],[2,3,4],[3,4],[4]]
Œp - Cartesian product* of these N lists
- e.g. [[1,2,3,4],[1,2,4,4],[1,3,3,4],[1,3,4,4],[1,4,3,4],[1,4,4,4],[2,2,3,4],[2,2,4,4],[2,3,3,4],[2,3,4,4],[2,4,3,4],[2,4,4,4],[3,2,3,4],[3,2,4,4],[3,3,3,4],[3,3,4,4],[3,4,3,4],[3,4,4,4],[4,2,3,4],[4,2,4,4],[4,3,3,4],[4,3,4,4],[4,4,3,4],[4,4,4,4]]
\ - cumulative reduce with:
» - maximum (vectorises)
- e.g. [[1,2,3,4],[1,2,4,4],[1,3,4,4],[1,3,4,4],[1,4,4,4],[1,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[2,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[3,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4],[4,4,4,4]]
Q - de-duplicate e.g. [[1,2,3,4],[1,2,4,4],[1,3,4,4],[1,4,4,4],[2,4,4,4],[3,4,4,4],[4,4,4,4]]
Ṛ - reverse e.g. [[4,4,4,4],[3,4,4,4],[2,4,4,4],[1,4,4,4],[1,3,4,4],[1,2,4,4],[1,2,3,4]]
```
\* It may be easier to see what's going on with the Cartesian product used above with a different input:
```
the Cartesian product of [[0,1,2],[3,4],[5]]
is [[0,3,5],[0,4,5],[1,3,5],[1,4,5],[2,3,5],[2,4,5]]
```
[Answer]
# [R](https://www.r-project.org/), ~~83~~ ~~82~~ 74 bytes
```
N=rep(n<-scan(),n);while({print(N);any(K<-N>1:n)})N[x]=N[x<-which(K)[1]]-1
```
[Try it online!](https://tio.run/##K/r/38@2KLVAI89Gtzg5MU9DUydP07o8IzMnVaO6oCgzr0TDT9M6Ma9Sw9tG18/O0CpPs1bTL7oi1hZI2OgCFSZnaHhrRhvGxuoa/jf9DwA "R – Try It Online")
Instead of a double for-loop, a `while` loop is sufficient here: we find the first index where the list is greater than the index, and decrement there.
`K` has `TRUE` wherever `N[i]>i`, `which(K)` returns the true indices, and we take the first with `[1]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
R‘®¦<³S©$пṚ
```
[Try it online!](https://tio.run/##ASEA3v9qZWxsef//UuKAmMKuwqY8wrNTwqkkw5DCv@G5mv///zQ "Jelly – Try It Online")
[Answer]
# JavaScript (ES6), 75 bytes
```
f=(n,a=Array(n).fill(n))=>[[...a],...a.some(v=>v>++j,j=0)?f(a[j-1]--,a):[]]
```
[Try it online!](https://tio.run/##FcVRCsMgDADQ6yRUwwb9GsSxc4gfodVRcWZoEXZ6t/28l2VI39rxPm3VPc6ZGKoRfrQmH6hI6SjlN7LznogkmL/U9RVhsBtuWbLJfMF7AvHZXoO1RvDmQ5ib1q4lUtEnJFgR5xc "JavaScript (Node.js) – Try It Online")
[Answer]
# APL+WIN, 54 bytes
Prompts for screen input of integer
```
((⍴m)⍴n)-+⍀m←0⍪(-0,+\⌽⍳n-1)⊖((+/+/m),n)↑m←⊖(⍳n)∘.>⍳n←⎕
```
Outputs a matrix with each row representing the result of each step e.g. for 4:
```
4 4 4 4
3 4 4 4
2 4 4 4
1 4 4 4
1 3 4 4
1 2 4 4
1 2 3 4
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
x`’Jḟḣ1Ʋ¦ÐĿ
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//eGDigJlK4bif4bijMcaywqbDkMS/////NA "Jelly – Try It Online")
### How it works
```
x`’Jḟḣ1Ʋ¦ÐĿ Main link. Argument: n
x` Repeat self; yield an array of n copies of n.
ÐĿ While the results are unique, repeatedly call the link to the left.
Return the array of all unique results, including the initial value.
’ ¦ Decrement the return value at all indices specified by the chain
in between.
Ʋ Combine the four links to the left into a monadic chain.
J Indices; yield [1, ..., n].
ḟ Filterfalse; remove all indices that belong to the return value.
ḣ1 Head 1; truncate the result to length 1.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 91 bytes
```
n=int(input())
x=[n]*n;print(x)
for i in range(n):
for j in[0]*(n-i-1):x[i]-=1;print(x)
```
[Try it online!](https://tio.run/##Pcu9CoAgFIbh3atw9AhC0WZ4JeLQ0M9p@BQxsKs3XXrHB970litiaQ2OURQjPUURieo8gsaa8uBK4ohZsmTIvOHcFcgK2Rt8d/ZT0AqGzUy2eg7Gzf/b2gc "Python 3 – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 135 bytes
```
a->{int r[]=new int[a],i=0;java.util.Arrays x=null;x.fill(r,a);for(r[0]++;i<a;r[i++]++)for(;--r[i]>i;System.out.print(x.toString(r)));}
```
[Try it online!](https://tio.run/##jY8xbsMwDEX3nIKjBMdChqYdVAfoAZolo6CBdexCriIblJw4MHx2l3Yzdcr2yf9JPjZ4xbztqtCcf@bSY4zwiS6MGwAXUkU1lhUcx2vrzkCCW4BST@zGhMmVcIQABcyYH8bFJGOLUN2WWYN264qdbviC6pPz6oMI7xGGIvTe60HVzntBW15YtyTI7GyWafeOmozLMi7k0td5zrU9OH26x1RdVNsn1RFfEINK7Smx/BYkJXPNmsm6/ssz2QNwJb/wS@IvaSzK5TuAoEi8SL3q/6t9EA9nSe2fSr0@lXpb9bSZ5l8 "Java (OpenJDK 8) – Try It Online")
**Explanation:**
```
int r[]=new int[a],i=0; //Initialize array and loop counter
java.util.Arrays x=null; //reduces the number of of “Arrays” needed from 3 to 1
x.fill(r,a); //Sets each value in array length n to int n
for(r[0]++;i<a;r[i++]++) //Increment everything!
for(;--r[i]>i; //If decremented array element is larger than element number:
System.out.print(x.toString(r)));} //Print the array
```
**Credit:**
-8 bytes thanks to [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)!
-16 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
-1 byte thanks to [Okx](https://codegolf.stackexchange.com/users/26600/okx)!
[Answer]
# Haskell, ~~69 67 65~~ 63 bytes
Recursive definition:
```
f 0=[[]]
f a=map(:(a<$[2..a]))[a,a-1..2]++[1:map(+1)x|x<-f$a-1]
```
Thanks to Laikoni for 2 bytes!
[Answer]
## PHP, 153 Bytes
[Try it online!](https://tio.run/##bczBCgIhEAbge09RyxyUbZft0MmVHqRiEVM0ZBzcImLx2U3vwfDD/Px85KjMF6pp36hfPuLeMkC@gZIqJfVdrA@BTUfAelxAks814mJQx4dhoPjY3bATQHISH@dD7WhugK@OugLdDxKoPzWxfcNQjfE/kk1YzVbXvcjZaBchibwrlp25KD8)
**Code**
```
function f($n){
$a=array_fill(0,$n,$n);$r=json_encode($a)."\n";$p=0;while($p<$n)
{if($a[$p]!=$p+1){$a[$p]--;$r.=json_encode($a)."\n";}else{$p++;}}echo$r;}
```
*Gonna try to lower the bytes, or finish the recursive function*
**Explanation**
```
function f($n){
$a=array_fill(0,$n,$n); #start with $nlength array filled with $n
$r=json_encode($a)."\n"; #pushed to the string to output
$p=0; #first position
while($p<$n){ #on position $n ($n-1) we do nothing
if($a[$p]!=$p+1){ #comparing the position+1 to the value
$a[$p]--; #it gets decreased by 1
$r.= json_encode($a)."\n"; #and pushed
} else {
$p++; #when position+1 = the value,
} #position is changed ++
}
echo $r;
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~80~~ 76 bytes
```
i=input();l=[i]*i;print l
for x in range(i):
while l[x]>x+1:l[x]-=1;print l
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9M2M6@gtERD0zrHNjozVivTuqAoM69EIYcrLb9IoUIhM0@hKDEvPVUjU9OKS6E8IzMnVSEnuiLWrkLb0ArE0LU1hGn5/98EAA "Python 2 – Try It Online")
Bit wasteful having two `print` statements but I can't think of a better way at the moment.
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
-2 bytes thanks to @LeakyNun
-2 bytes thanks to @JonathanFrech
```
i=I=input()
l=[I]*I
exec"exec'print l;l[-i]-=1;'*max(~-i,2);i-=1;"*~-I
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PW0zYzr6C0REOTK8c22jNWy5MrtSI1WQlEqBcUZeaVKORY50TrZsbq2hpaq2vlJlZo1Olm6hhpWmeCRJS06nQ9//83AwA "Python 2 – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 112 bytes
```
n->{var s="";for(int i=1,k=n,j;i<=n;k=--k>i?k:n-++i+i)for(j=0;j++<n;)s+=(j<i?j:j>i?n:k)+(j<n?",":";");return s;}
```
[Try it online!](https://tio.run/##dc7BaoQwEAbgu08x5GQaDS0UCsbordBDT3tse0hdLRN1lCQKy@Kz22zXaw/DMMw/zGfNanJ77ncc58kFsHGWS8BBdgs1ASeSDyppBuM9vBukawLggwnYwBuF1yNTnoJD@qmgAw075dV1NQ68Zkx1k0uRAqB@ynpNmVVYalK9zvO@wrovKBcCBfJb0OpHZYUoSXEvdGpLrG1hY4yKnos4U80yVjDFuHJtWByBV9uuImpevoeIOmzrhGcYoze9yz6@DL/RAeIb@ANRpD6r2EoNL7ELweEeAThdfGhHOS1BzvE8DJR20szzcEmJS9fOg2naNDIy9kmMc/X/3bHbkltt@y8 "Java (JDK 10) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~17~~ 15 bytes
```
+/\@,(#=)@i.&.-
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/7X1Yxx0NJRtNR0y9dT0dP9rcinpKaingRSoK@go1FoppBVzcaUmZ@QrpCmY/AcA "J – Try It Online")
## Explanation
```
+/\@,(#=)@i.&.- Input: n
- Negate n
i. Reverse of range [0, n)
= Identity matrix of order n
# Copy each row by the reverse range
- Negate
, Prepend n
+/\ Cumulative sum of rows
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 49 bytes
```
.+
*
_
$`_,$=
.{*\`_+,(_+)
$.1
0`(\b(_+),\2)_
$1
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS4srnkslIV5HxVaBS69aKyYhXltHI15bk0tFz5DLIEEjJgnE04kx0gSqA2ox/Q8A "Retina – Try It Online") Explanation:
```
.+
*
```
Convert the input to unary.
```
_
$`_,$=
```
Create a list of n copies of `i,n` where `i` is the index of the copy.
```
.
```
Don't print anything (when the loop finishes).
```
{
```
Loop until the pattern does not change.
```
*\`_+,(_+)
$.1
```
Temporarily delete the `i`s and convert the `n`s to decimal and output.
```
0`(\b(_+),\2)_
$1
```
Take the first list entry whose value exceeds its index and decrement it.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~70~~ ~~67~~ 65 bytes
```
def f(n):
k=0;a=[n]*n
while k<n-1:print(a);k+=a[k]==k+1;a[k]-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI0/Tiksh29bAOtE2Oi9WK49LoTwjMydVIdsmT9fQqqAoM69EI1HTOlvbNjE6O9bWNlvb0BrE0rU1/J@mYaL5HwA "Python 3 – Try It Online")
* (67) Converting to function: -3 bytes
* (65) Removing unneeded parentheses: -2 bytes
**Ungolfed version:**
```
def f(n):
k = 0
a = [n] * n # create n-item list with all n's
while k < n - 1: # iterate through columns 0..n-1
print(a) # print whole list
if a[k] == k + 1: # move to the next column when current item reaches k+1
k += 1
a[k] -= 1 # decrement current item
```
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~131~~ 141 bytes
```
i,j,k,m[99];p(){for(k=0;m[k];printf("%d ",m[k++]));puts("");}f(n){for(j=k=m[n]=0;k<n;m[k++]=n);p();for(;j<n;j++)for(i=1;i++<n-j;m[j]--,p());}
```
[Try it online!](https://tio.run/##TY7BboMwEETP9VesqCrZMTSkt8i4P4I4UDCJ7bAgbNRIEd9O141UdU@7ozcz2xXdrcXL/mqxu629gSrE3k7v10/2X1osXkjbbe5yn4/1@dyomYvHMC3c61KNtSeBqDjw7K2HjBgvZSOEmtcYeJYJtQ0cnw6nvR5rbMjoK1RPVKNIkSoBypHspBTpsPqkrJQVFo5Q1xRFThzl7VQHY2uRC3iwdNxBQ6kYS7a0n0pFWqXhIy2URxwM/C4Ug7@/XmiOB/j9HoKZ26WNdkL4MvHbGIRoQoSuDSbA4cg2xhYT1wVT0bb/AA "C (clang) – Try It Online")
This will work for all `n` upto 99. TIO truncates output. It can support arbitrarily larger `n` by changing size of array `m` as memory permits.
---
Following is limited to n=1..9 but is significantly shorter
# [C (clang)](http://clang.llvm.org/), ~~89~~ 92 bytes
```
i,j;char m[12];f(n){j=!puts(memset(m,n+48,n));for(;j<n;j++)for(i=1;i++<n-j;m[j]--,puts(m));}
```
[Try it online!](https://tio.run/##TY2xbsMwDETn6iuYdJEiu6mLDilo90eCDKpDJxIi2pBkNEDgb3eldikX8h7ujn3d3wxf1mfL/W0@E7Qxne34cv0U/1GwfMlstZXD/moC@GPzdsJBsnq4bjPNKUpPPlKSvmL9fqhYKRzGING1jE5rVYTtGrRat1w79Ed3quvqL5rNy2o5gTeWpYKHKOIOHbyiECVa7gYzajv4yDs3ZhcM8q5QwG/LdqvwKc9@B1Mo@UiTCSbZkeGL0jcRQ6KYoDeRIuz2YhEiUJoDlzfL@gM "C (clang) – Try It Online")
Updated: Modified to avoid dependence on static initialization
[Answer]
## Clojure, 132 bytes
```
#(loop[R[(vec(repeat % %))]j(- % 2)i 0](if(> i j)R(recur(conj R(update(last R)i dec))(if(= i j)(- % 2)(dec j))(if(= i j)(inc i)i))))
```
I was hoping this to be shorter...
Less stateful but longer at **141** bytes:
```
#(apply map list(for[i(range %)](concat(repeat(nth(cons 0(reductions +(reverse(range %))))i)%)(range % i -1)(if(>(dec %)i)(repeat(inc i))))))
```
[Answer]
# Python 3, 101 bytes
```
def f(n):
p=print;m=[n for_ in range(n)];p(m)
for i in range(n):
while m[i]>1+i:m[i]-=1;p(m)
```
I could probably golf more with the print, but I'm away from my computer and am not entirely sure of python 2's rules on setting a variable to print. I'll update later when I get to a computer or if someone clarifies in the comments.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~34~~ 32 bytes
```
{{x[y]-:1;x}\(,x#x),,/(|!x)#'!x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nqrq6IroyVtfK0LqiNkZDp0K5QlNHR1@jRrFCU1ldsaL2f5qCyX8A "K (ngn/k) – Try It Online")
] |
[Question]
[
Say I have a list such as `[3, 0, 4, 2, 1]`, and I use selection sort to sort it, I could visualize it like this:
```
3,0,4,2,1
|-|
0,3,4,2,1
|-----|
0,1,4,2,3
|-|
0,1,2,4,3
|-|
0,1,2,3,4
```
This challenge is about visualizing sorting like this.
## Input
Your input will be a list of positive integers, in any format you like.
## Task
Your submission should sort the input list by only swapping two elements at a time, and at each swap, the submission should display the list, and a character under each of the elements being swapped. If a number that was swapped has more than one digit, the character can be anywhere underneath it. At the end, the submission should display the sorted list.
## Other rules
* The sorting must use fewer swaps than n4, where n is the length of the list.
* The sorting doesn't have to be deterministic.
* The characters under the swapped can be any char except space.
[Answer]
# Perl, 62 bytes
Includes +3 for `-p`
Give input as a single line of numbers on STDIN:
```
perl -M5.010 visisort.pl <<< "3 0 4 2 1"
```
Repeatedly swaps the first inversion. Swap complexity is `O(n^2)`, time complexity is `O(n^3)`. Uses the numbers being swapped as mark:
```
3 0 4 2 1
3 0
0 3 4 2 1
4 2
0 3 2 4 1
3 2
0 2 3 4 1
4 1
0 2 3 1 4
3 1
0 2 1 3 4
2 1
0 1 2 3 4
```
`visisort.pl`:
```
#!/usr/bin/perl -p
$&>$'&&say$_.$"x"@-".!s/(\S+) \G(\S+)/$2 $1/.$&while/\S+ /g
```
The program also supports negative values and floating point numbers
If you insist on a connecting character the code becomes 66 bytes:
```
#!/usr/bin/perl -p
$&>$'&&say$_.$"x"@-".!s/(\S+) \G(\S+)/$2 $1/.$1.-$2while/\S+ /g
```
But now it doesn't support negative numbers and 0 anymore (but the program only has to support positive integers anyways. The `0` in the example is a mistake)
[Answer]
## JavaScript (ES6), 158 bytes
```
a=>{for(;;){console.log(``+a);i=a.findIndex((e,i)=>e<a[i-1]);if(i<0)break;console.log(` `.repeat(`${a.slice(0,i)}`.length-1)+`|-|`);t=a[i];a[i]=a[--i];a[i]=t}}
```
Bubble sort. Sample output:
```
3,0,4,2,1
|-|
0,3,4,2,1
|-|
0,3,2,4,1
|-|
0,2,3,4,1
|-|
0,2,3,1,4
|-|
0,2,1,3,4
|-|
0,1,2,3,4
```
[Answer]
# PHP, 248 Bytes
Bubblesort boring wins
```
<?for($c=count($a=$_GET[a]);$c--;){for($s=$i=0;$i<$c;){$l=strlen($j=join(",",$a));if($a[$i]>$a[$i+1]){$t=$a[$i];$a[$i]=$a[$i+1];$a[$i+1]=$t;$m=" ";$m[$s]=I;$m[$s+strlen($a[$i].$a[$i+1])]=X;echo"$j\n$m\n";}$s+=strlen($a[$i++])+1;}}echo join(",",$a);
```
PHP, 266 Bytes a way with array\_slice and min
modified output `I X` instead of `*~~*`
```
<?for($c=count($a=$_GET[a]);$i<$c;){$j=join(",",$s=($d=array_slice)($a,$i));$x=array_search($m=min($s),$s);echo($o=join(",",$a));$a[$x+$i]=$a[$i];$a[$i]=$m;if($i++!=$c-1){$t=" ";$t[$z=($f=strlen)($o)-($l=$f($j))]=I;$t[$l+$z-$f(join(",",$d($s,$x)))]=X;echo"\n$t\n";}}
```
282 Bytes
```
<?for($c=count($a=$_GET[a]);$i<$c;){$j=join(",",$s=($d=array_slice)($a,$i));$x=array_search($m=min($s),$s);echo($o=join(",",$a));$a[$x+$i]=$a[$i];$a[$i]=$m;if($i++!=$c-1)echo"\n".str_repeat(" ",($f=strlen)($o)-($l=$f($j))).($x?str_pad("*",$l-$f(join(",",$d($s,$x))),"~"):"")."*\n";}
```
## How it works
Looks for the minimum in an array and take this on first position
Look for the minimum without first position .... and so on
If a value is double the first value will be swap
## Output Example
```
31,7,0,5,5,5,753,5,99,4,333,5,2,1001,35,1,67
*~~~~*
0,7,31,5,5,5,753,5,99,4,333,5,2,1001,35,1,67
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
0,1,31,5,5,5,753,5,99,4,333,5,2,1001,35,7,67
*~~~~~~~~~~~~~~~~~~~~~~~~~*
0,1,2,5,5,5,753,5,99,4,333,5,31,1001,35,7,67
*~~~~~~~~~~~~~~*
0,1,2,4,5,5,753,5,99,5,333,5,31,1001,35,7,67
*
0,1,2,4,5,5,753,5,99,5,333,5,31,1001,35,7,67
*
0,1,2,4,5,5,753,5,99,5,333,5,31,1001,35,7,67
*~~~*
0,1,2,4,5,5,5,753,99,5,333,5,31,1001,35,7,67
*~~~~~~*
0,1,2,4,5,5,5,5,99,753,333,5,31,1001,35,7,67
*~~~~~~~~~~*
0,1,2,4,5,5,5,5,5,753,333,99,31,1001,35,7,67
*~~~~~~~~~~~~~~~~~~~~~*
0,1,2,4,5,5,5,5,5,7,333,99,31,1001,35,753,67
*~~~~~~*
0,1,2,4,5,5,5,5,5,7,31,99,333,1001,35,753,67
*~~~~~~~~~~~*
0,1,2,4,5,5,5,5,5,7,31,35,333,1001,99,753,67
*~~~~~~~~~~~~~~~*
0,1,2,4,5,5,5,5,5,7,31,35,67,1001,99,753,333
*~~~~*
0,1,2,4,5,5,5,5,5,7,31,35,67,99,1001,753,333
*~~~~~~~~*
0,1,2,4,5,5,5,5,5,7,31,35,67,99,333,753,1001
*
0,1,2,4,5,5,5,5,5,7,31,35,67,99,333,753,1001
```
[Answer]
## Haskell, ~~165~~ ~~164~~ 162 bytes
```
s%c=drop 2$show s>>c
p#x|(h,t:s)<-span(/=minimum x)x=id=<<[show$p++x,"\n ",[' '|p>[]],p%" ","|",h%"-",['|'|h>[]],"\n",(p++[t])#(drop 1h++take 1h++s)]|1<2=""
([]#)
```
This visualizes selection sort. Usage example:
```
*Main> putStr $ ([]#) [31,7,0,5,5,5,753,5,99,4,333,5,2,1001,35,1,67]
[31,7,0,5,5,5,753,5,99,4,333,5,2,1001,35,1,67]
|----|
[0,7,31,5,5,5,753,5,99,4,333,5,2,1001,35,1,67]
|-------------------------------------|
[0,1,31,5,5,5,753,5,99,4,333,5,2,1001,35,7,67]
|-------------------------|
[0,1,2,5,5,5,753,5,99,4,333,5,31,1001,35,7,67]
|--------------|
[0,1,2,4,5,5,753,5,99,5,333,5,31,1001,35,7,67]
|
[0,1,2,4,5,5,753,5,99,5,333,5,31,1001,35,7,67]
|
[0,1,2,4,5,5,753,5,99,5,333,5,31,1001,35,7,67]
|---|
[0,1,2,4,5,5,5,753,99,5,333,5,31,1001,35,7,67]
|------|
[0,1,2,4,5,5,5,5,99,753,333,5,31,1001,35,7,67]
|----------|
[0,1,2,4,5,5,5,5,5,753,333,99,31,1001,35,7,67]
|---------------------|
[0,1,2,4,5,5,5,5,5,7,333,99,31,1001,35,753,67]
|------|
[0,1,2,4,5,5,5,5,5,7,31,99,333,1001,35,753,67]
|-----------|
[0,1,2,4,5,5,5,5,5,7,31,35,333,1001,99,753,67]
|---------------|
[0,1,2,4,5,5,5,5,5,7,31,35,67,1001,99,753,333]
|----|
[0,1,2,4,5,5,5,5,5,7,31,35,67,99,1001,753,333]
|--------|
[0,1,2,4,5,5,5,5,5,7,31,35,67,99,333,753,1001]
|
[0,1,2,4,5,5,5,5,5,7,31,35,67,99,333,753,1001]
|
```
How it works:
`s % c` is a helper function that makes `length (show s) - 2` copies of character `c`. It's used for spacing before both `|`, one time with `c == ' '` and one time with `c == '-'`.
The main function `#` takes a list `p` which is the sorted part of the list and `x` which is the yet to sort part. The pattern match `(h,t:s)<-span(/=minimum x)x` splits the list `x` at its minimum element and binds `h` to the part before the minimum, `t` to the minimum itself and `s` to the part after the minimum. The rest is formatting two lines: 1) the list at its current state (`p++x`) and 2) the `|----|` part followed by a recursive call of `#` with `t` appended to `p` and the head of `h` inserted between the tail of `h` and `s`.
PS: works also with negativ and/or floating point numbers:
```
*Main> putStr $ ([]#) [-3,-1,4e33,-7.3]
[-3.0,-1.0,4.0e33,-7.3]
|----------------|
[-7.3,-1.0,4.0e33,-3.0]
|-----------|
[-7.3,-3.0,4.0e33,-1.0]
|------|
[-7.3,-3.0,-1.0,4.0e33]
|
```
Edit: @BlackCap saved 2 bytes. Thanks!
[Answer]
# Python 2, 267 bytes
It works with decimals and negative numbers as well.
```
p=1
while p!=len(a):
q=p-1;k=a[p:];m=min(k);n=k.index(m)+p;b=map(str,a)
if a[q]>m:print','.join(b)+'\n'+''.join(' '*len(i)for i in b[:q])+' '*q+'*'+'-'*(len(b[n])+n-q-2)+''.join('-'*len(i)for i in b[q:n])+'*';a[q],a[n]=[a[n],a[q]]
p+=1
print','.join(map(str,a))
```
Example:
```
7,2,64,-106,52.7,-542.25,54,209,0,-1,200.005,200,3,6,1,0,335,-500,3.1,-0.002
*----------------------*
-542.25,2,64,-106,52.7,7,54,209,0,-1,200.005,200,3,6,1,0,335,-500,3.1,-0.002
*-------------------------------------------------------*
-542.25,-500,64,-106,52.7,7,54,209,0,-1,200.005,200,3,6,1,0,335,2,3.1,-0.002
*-----*
-542.25,-500,-106,64,52.7,7,54,209,0,-1,200.005,200,3,6,1,0,335,2,3.1,-0.002
*-------------------*
-542.25,-500,-106,-1,52.7,7,54,209,0,64,200.005,200,3,6,1,0,335,2,3.1,-0.002
*-----------------------------------------------------*
-542.25,-500,-106,-1,-0.002,7,54,209,0,64,200.005,200,3,6,1,0,335,2,3.1,52.7
*--------*
-542.25,-500,-106,-1,-0.002,0,54,209,7,64,200.005,200,3,6,1,0,335,2,3.1,52.7
*-----------------------------*
-542.25,-500,-106,-1,-0.002,0,0,209,7,64,200.005,200,3,6,1,54,335,2,3.1,52.7
*------------------------*
-542.25,-500,-106,-1,-0.002,0,0,1,7,64,200.005,200,3,6,209,54,335,2,3.1,52.7
*-------------------------------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,64,200.005,200,3,6,209,54,335,7,3.1,52.7
*--------------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,200.005,200,64,6,209,54,335,7,3.1,52.7
*-------------------------------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,200,64,6,209,54,335,7,200.005,52.7
*------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,64,200,209,54,335,7,200.005,52.7
*-----------------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,7,200,209,54,335,64,200.005,52.7
*----------------------------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,7,52.7,209,54,335,64,200.005,200
*----*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,7,52.7,54,209,335,64,200.005,200
*--------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,7,52.7,54,64,335,209,200.005,200
*-----------------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,7,52.7,54,64,200,209,200.005,335
*---------*
-542.25,-500,-106,-1,-0.002,0,0,1,2,3,3.1,6,7,52.7,54,64,200,200.005,209,335
```
[Answer]
# JavaScript (ES6), 147 ~~155~~
Using n\*n compares, but (I believe) the minimum number of swaps. And the swap positions are more variable compared to the boring bubble sort.
```
l=>l.reduce((z,v,i)=>l.map((n,j)=>s+=`${j>i?n<l[i]?l[p=j,t=s,i]=n:0:u=s,n},`.length,s=p=0)|p?z+`
${l[p]=v,' '.repeat(u)}^${Array(t-u)}^
`+l:z,''+l)
```
*Less golfed* and hopefully more understandable
```
l=>
l.reduce( (z,v,i) => // update z for each list element v at position i
( // begin outer loop body
// loop to find the least value that is to be placed at pos i
l.map( (n,j) => // for each list element n at position j
( // begin inner loop body
j > i ? // check if at position after i
n < l[i] && // check if lower value
(
p = j, // remember position in p
l[i] = n, // store value in l[i] (could change later)
t = s // in t, string length of list elements up element preciding j
)
: // else, position up to i
u = s, // in u, string length of list elements up element preciding i
s += `${n},`.length, // string length of list elements up to this point (value length + comma)
) // end inner loop body
, s = p = 0 // init s and p at start of inner loop
),
p ? (// if found a lower value, complete the swap and update output
l[p] = v, // complete swap, l[i] was assigned before
z + '\n' + ' '.repeat(u) + // spaces to align
'^' + // left marker
Array(t-u) + // swap highlight, using sequence of commas
'^\n' + // right marker, newline
l + // list values after the swap, newline
)
: z // else output is unchanged
) // end outer loop body
, ''+l // init string output at start of outer loop
) // output is the result of reduce
```
**Test**
```
f=
l=>l.reduce((z,v,i)=>l.map((n,j)=>s+=`${j>i?n<l[i]?l[p=j,t=s,i]=n:0:u=s,n},`.length,s=p=0)|p?z+`
${l[p]=v,' '.repeat(u)}^${Array(t-u)}^
`+l:z,''+l)
function sort()
{
var list=I.value.match(/-?[\d.]+/g).map(x=>+x)
O.textContent = f(list)
}
sort()
```
```
#I { width:80% }
```
```
<input id=I value='3, 0, 4, 2, 1'>
<button onclick='sort()'>Sort</button>
<pre id=O></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes
```
I;0CMḢ;L‘ṬCœṗ¹UF©µÐĿ,n+32Ọ$¥¥2\;/®ṭG
```
[Try it online!](https://tio.run/nexus/jelly#AUsAtP//STswQ03huKI7TOKAmOG5rEPFk@G5l8K5VUbCqcK1w5DEvyxuKzMy4buMJMKlwqUyXDsvwq7hua1H////WzIsMSwxMCw4LDQsNl0 "Jelly – TIO Nexus")
## Explanation
```
I;0CMḢ;L‘ṬCœṗ¹UF©µÐĿ,n+32Ọ$¥¥2\;/®ṭG
µÐĿ Repeat until we see a previously seen value:
I;0 Take differences of adjacent inputs, and 0
CM Find the indices (M) of the smallest (C)
œṗ Split {the input} into pieces
‘Ṭ that end
;L C everywhere except
Ḣ the first of the chosen deltas
¹ Resolve parser ambiguity
U Reverse each piece
F Concatenate the pieces back into a list
© Store the value in a register
Then, on the accumulated list of results:
2\ Look at each consecutive pair of results
, ¥ ;/ and return the first element, followed by
+32Ọ$ the character with code 32 plus
n ¥ 1 (if unequal), 0 (if equal)
®ṭ Append the value of the register
G Output in grid form
```
The example shown in the TIO link is a particularly hard one for this program; the `;0` near the start is necessary to ensure that the loop ends just at the point where the input becomes sorted. This normally isn't necessary (because it will end after one more iteration), but if the last swap is of the first two elements (as seen here), the one-more-iteration won't happen and makes it impossible to finish the list consistently. As such, we need to ensure we don't swap anything on the last loop iteration.
[Answer]
# Java 7, ~~256 241~~ 282 Bytes
*Thanks to @Geobits and @Axelh for saving 15 bytes*
```
void f(int[]a){int m,i,j,l=a.length;for(i=0;i<l;j=a[i],a[i]=a[m],a[m]=j,i++){for(int k:a)System.out.print(k+" ");System.out.println();for(j=i+1,m=i;j<l;m=a[j]<a[m]?j:m,j++);for(j=0;j<=m&i!=l-1;j++)System.out.print(j==i|j==m?a[j]+" ":" ");System.out.println();}}
```
# Ungolfed
```
void f(int[]a){
int m,i,j,l=a.length;
for(i=0;i<l;j=a[i],a[i]=a[m],a[m]=j,i++){
for(int k:a)
System.out.print(k+" ");
System.out.println();
for(j=i+1,m=i;j<l;m=a[j]<a[m]?j:m,j++);
for(j=0;j<=m&i!=l-1;j++)
System.out.print(j==i|j==m?a[j]+" ":" ");
System.out.println();
}
}
```
### output
```
3 0 1 4 2
3 0
0 3 1 4 2
3 1
0 1 3 4 2
3 2
0 1 2 4 3
4 3
0 1 2 3 4
```
[Answer]
# [J](http://jsoftware.com/), ~~66~~ 65 bytes
```
[:(>@,@(2({.;'^ '{~=/)\])@,{:)@":]C.~a:,[:<"1\@;({.,.}.)&.>@C.@/:
```
[Try it online!](https://tio.run/##bYyxCsJAEET7fMWSwr2Du42XXLUxYeHAyso2iSBiEBs/4DC/fi6IncU0783Ms9SEKwwMCA72wBpPkM6nY5nYjOLEtCZTjxfAvA2NnRcrLrOVmpdE25XdxIc6zNJrzdGb7I5GSSQNF1tV99vjBSt0@huhhfAF6L3HnwvKO4h/TFSum/IB "J – Try It Online")
] |
[Question]
[
In this challenge, you will write a program which outputs a program which is the **double** the length of the original program. The outputted program should output a new program a program double *its* length.
## Examples
If my program is `a`:
```
< a
> aa
< aa
> aaaa
< aaaa
> aaaaaaaa
```
## Rules
* No quine built-ins
* The original program must be at least one byte
* The sequence should theoretically work infinitely
* Your program is not allowed to read from anything (file, stdio)
Your score is the size of the original program.
[Answer]
## CJam, 10 bytes
```
{"_~"+_}_~
```
[Test it here.](http://cjam.aditsu.net/#code=%7B%22_~%22%2B_%7D_~)
### Explanation
```
{"_~" e# Generalised quine framework, leaves the block and the string "_~"
e# on the stack.
+ e# Prepend the block to the string.
_ e# Duplicate the resulting array.
}_~
```
[Answer]
## JavaScript, ~~62~~ ~~61~~ 37 bytes
Thanks to @Doᴡɴɢᴏᴀᴛ for the help!
---
*Original [37 bytes]:*
```
f=_=>'f='+'_'.repeat((10+f).length)+f
```
*Child [74 bytes]:*
```
f=______________________________________=>'f='+'_'.repeat((10+f).length)+f
```
*Grandchild [148 bytes]:*
```
f=________________________________________________________________________________________________________________=>'f='+'_'.repeat((10+f).length)+f
```
---
**Alternate (with printing to console, and as a full program):**
*Original [61 bytes]:*
```
f=_=>console.log(`f=${'_'.repeat((0+f).length+5)+f};f()`);f()
```
*Child [122 bytes]:*
```
f=______________________________________________________________=>console.log(`f=${'_'.repeat((0+f).length+5)+f};f()`);f()
```
*Grandchild [244 bytes]:*
```
f=________________________________________________________________________________________________________________________________________________________________________________________=>console.log(`f=${'_'.repeat((0+f).length+5)+f};f()`);f()
```
---
**How it works!**
**1.** `f=_=>` Define function f as `console.log(...)`
**2.** `;f()` Run function f.
**3.** *(in function f)*
* `console.log(...)` Print the following:
+ `f=` literal text "f="
+ `${'_'.repeat((0+f).length+5)` "\_" repeated for the length of f, altered to account for characters not included in the stringification of f
+ `+f}` The stringification of function f
+ `;f()` literal text ";f()"
**Notes**
* `console.log` is necessary instead of `alert` because `alert` doesn't seem to play well with really long strings (at least on my machine/browser configuration)
* The `_`'s are inserted into the name of the (unused) parameter of function f, to ensure that they are included in the stringification of f.
* Main improvement (aside from getting rid of the `console.log`) of the first solution over the second: adding `10` to the function instead of `0` to cast it to string makes it one byte longer, eliminating the need to add 1 to the length afterwards, saving a byte.
[Answer]
## [Minkolang 0.15](https://github.com/elendiastarman/Minkolang), ~~19~~ 14 bytes
```
"66*2-rIDdr$O.
```
[Original](http://play.starmaninnovations.com/minkolang/?code=%2266*2-rIDdr%24O%2E), [child](http://play.starmaninnovations.com/minkolang/?code=%2266*2-rIDdr%24O%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E), [grandchild](http://play.starmaninnovations.com/minkolang/?code=%2266*2-rIDdr%24O%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E%2E).
### Explanation
```
"66*2- $O. Standard quine formulation
r Reverse stack
I Push length of stack
D Pop n and duplicate top of stack n times
d Duplicate top of stack
r Reverse stack
```
What the bit in between `r`s does is duplicate the ending period enough times to fulfill the doubling criterion. `.` is the "stop program" character, so the many periods at the end do nothing except be there.
[Answer]
# CJam, 12 bytes
```
{"_~"1$1$}_~
```
When run, this will print
```
{"_~"1$1$}_~{"_~"1$1$}_~
```
which, in turn, will print
```
{"_~"1$1$}_~{"_~"1$1$}_~{"_~"1$1$}_~{"_~"1$1$}_~
```
and so on.
[Try it online!](http://cjam.tryitonline.net/#code=eyJffiIxJDEkfV9-&input=)
[Answer]
# Python 3, 51 bytes
```
x=r"print('x=r\"'+x+'\"'+';exec(x*2)');";exec(x*2)
```
This includes a trailing newline.
Which outputs:
```
x=r"print('x=r\"'+x+'\"'+';exec(x*2)');";exec(x*2)
x=r"print('x=r\"'+x+'\"'+';exec(x*2)');";exec(x*2)
```
[Answer]
# GolfScript, 11 bytes
```
{: ".~"]}.~
```
[Try it online!](http://golfscript.tryitonline.net/#code=ezogIi5-Il19Ln4&input=)
### How the source code works
```
{: ".~"]}.~
{ } Define and push a code block.
.~ Push a copy and execute it.
: Save the code block in the space character.
Every subsequent space will now execute the code block.
".~" Push that string.
] Wrap the entire stack in an array.
```
If the above source code is executed once, the stack will end up as
```
["" {: ".~"]} ".~"]
```
where the empty string at the beginning corresponds to the initial state of the stack (empty input).
Two copies of the source code would leave a final state of
```
[["" {: ".~"]} ".~"] {: ".~"]} ".~"]
```
and so on.
### What happens next
After executing the source code, the interpreter does the following:
1. It wraps the entire stack in an array, and pushes that array on the stack.
For a single copy of the source code, the stack now contains
```
["" {: ".~"]} ".~"] [["" {: ".~"]} ".~"]]
```
2. It executed `puts` with the intention of printing the wrapped stack, followed by a linefeed.
`puts` is defined as `{print n print}`, so it does the following.
1. `print` prints the wrapped up copy of the stack without inspecting it (i.e., without converting it to its string representation). This sends
```
{: ".~"]}.~
```
to STDOUT and pops the stack copy from the top of the stack.
The stack now contains
```
["" {: ".~"]} ".~"]
```
2. executes the code block we defined previously.
`:` begins by saving `["" {: ".~"]} ".~"]` in the space character, then `".~"` pushes itself and `]` wraps the stack in an array.
3. `n` pushes a string consisting of a single linefeed.
The stack now contains
```
[["" {: ".~"]} ".~"] ".~"] "\n"
```
4. is executed once more. However, it was redefined when we called it for the first time and now contains an array, not a code block.
In fact, it pushes `["" {: ".~"]} ".~"]`, leaving the stack as
```
[["" {: ".~"]} ".~"] ".~"] "\n" ["" {: ".~"]} ".~"]
```
5. Finally, `print` prints the topmost stack item without inspecting it, sending
```
{: ".~"]}.~
```
to STDOUT.
[Answer]
# ùîºùïäùïÑùïöùïü, 26 chars / 36 bytes
```
⟮ô`\u27ee⦃ᶈ0}\u27ef
`ď2)⟯
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&code=%E2%9F%AE%C3%B4%60%5Cu27ee%E2%A6%83%E1%B6%880%7D%5Cu27ef%0A%60%C4%8F2%29%E2%9F%AF%0A)`
Note that there is a trailing newline.
# Explanation
Standard quine: `⟮ⒸⅩ222+ᶈ0`
Modifications:
* Use `ô` function to output the quines all results instead last result (as done using implicit output)
* Use `\u27ee⦃ᶈ0}\u27ef\n` and close copy block to prevent conflicts with later copy blocks.
* Use `ď2` to repeat string twice.
] |
[Question]
[
You should write a program or function which receives a string representing a chessboard with only pawns as input and outputs or returns whether any capture is possible on the board.
Input is in a [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation)-like notation describing positions of white and black pawns with no other pieces present. You should decide if there is a pawn which can capture an enemy one.
>
> Each rank is described, starting with rank 8 and ending with rank 1; within each rank, the contents of each square are described from file "a" through file "h". Each pawn is identified by a single letter (white pawn = "P", black pawn = "p", ). Empty squares are noted using digits 1 through 8 (the number of empty squares), and "/" separates ranks. *(partially taken from Wikipedia)*
>
>
>
For example
```
8/pppppppp/8/8/4P3/8/PPPP1PPP/8
```
describes the board
```
--------
pppppppp
P
PPPP PPP
--------
```
A white pawn can capture a black one if the black one is positioned diagonally up from it (black is up-left or up-right) and a black pawn can capture a white one if the white one is diagonally below from it (white is down-left or down-right). No other capture move ([en passant](https://en.wikipedia.org/wiki/En_passant)) should be considered.
## Input
* A [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation)-like string consisting of the characters `12345678pP/`.
* The input describes the pawns of a valid chess game position. This means (among other more complex constraints) there will be at most 8 pawns for each side and no pawns on ranks 1 and 8.
## Output
* If there is a possible capture for either side you should output a [truthy](http://meta.codegolf.stackexchange.com/a/2194/7311) value and a [falsy](http://meta.codegolf.stackexchange.com/a/2194/7311) value otherwise.
## Examples
Inputs with **truthy** output (one per line)
```
8/7p/6P1/8/8/8/8/8
8/8/p7/1P6/3P3p/8/8/8
8/2P5/8/4P1p1/2p2P2/3p4/3p1P2/8
8/P7/8/5P2/2pp4/3P2p1/3pP3/8
8/P7/p7/p1P1P3/1P3p2/8/1p6/8
8/4p1P1/2P2P1P/2p1pPpp/8/6P1/pP1p4/8
```
Inputs with **falsy** output (one per line)
```
8/8/8/8/8/8/8/8
8/7P/6p1/8/8/8/8/8
8/7p/7P/8/8/8/8/8
8/pppppppp/8/8/8/8/PPPPPPPP/8
8/p7/8/1p6/5P2/8/8/8
8/p7/P7/2P1p1p1/2p5/8/PP6/8
```
This is code golf so the shortest entry wins.
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~33~~ 29 bytes
```
T`d`w
)`\d
$0.
_
p.{7}(..)?P
```
To run the code from a single file, use the `-s` flag.
Should be easily beatable by something like Perl where the expansion of digits into strings of spaces (or other characters) doesn't take up 17 bytes.
The output is positive (truthy) if there is a possible capture and zero (falsy) if there isn't.
## Explanation
```
T`d`w
)`\d
$0.
```
This is a loop of two stages. The first one is a transliteration stage which decrements each digit, and turns zeroes to underscores. Why? Because `d` and `w` expand to the following two lines:
```
0123456789
_0123456789AB...YZab...yz
```
If the target set of a transliteration stage is longer than the source set, the extraneous characters are ignored, hence the decrementing behaviour (honestly, it was just luck that I decided to put the underscore in front of the digits when expanding the `w` character class).
Then the second stage is a replacement, which appends a `.` to each digit. That means that for each digit `n`, `n` periods are added before that digit is turned into an underscore.
```
_
<empty>
```
This just gets rid of the underscores.
```
p.{7}(..)?P
```
Finally, we find the matches. Since we're ignoring en passant, captures are only possible if there is a `p` and then a `P` diagonally below it. In the linear string, this simply means that there must be 7 or 9 characters between the two pawns. This matched with `.{7}(..)?` (i.e. match 7 characters and then, optionally, match another two).
Such a match stage returns the number of matches it found.
[Answer]
# Pyth, 25 bytes
```
/smC,>JsXz`M9*LN9dJ,8T"Pp
```
[Test suite](https://pyth.herokuapp.com/?code=%2FsmC%2C%3EJsXz%60M9%2aLN9dJ%2C8T%22Pp&test_suite=1&test_suite_input=8%2F7p%2F6P1%2F8%2F8%2F8%2F8%2F8%0A8%2F8%2Fp7%2F1P6%2F3P3p%2F8%2F8%2F8%0A8%2F2P5%2F8%2F4P1p1%2F2p2P2%2F3p4%2F3p1P2%2F8%0A8%2FP7%2F8%2F5P2%2F2pp4%2F3P2p1%2F3pP3%2F8%0A8%2FP7%2Fp7%2Fp1P1P3%2F1P3p2%2F8%2F1p6%2F8%0A8%2F4p1P1%2F2P2P1P%2F2p1pPpp%2F8%2F6P1%2FpP1p4%2F8%0A8%2F8%2F8%2F8%2F8%2F8%2F8%2F8%0A8%2F7P%2F6p1%2F8%2F8%2F8%2F8%2F8%0A8%2F7p%2F7P%2F8%2F8%2F8%2F8%2F8%0A8%2Fpppppppp%2F8%2F8%2F8%2F8%2FPPPPPPPP%2F8%0A8%2Fp7%2F8%2F1p6%2F5P2%2F8%2F8%2F8%0A8%2Fp7%2FP7%2F2P1p1p1%2F2p5%2F8%2FPP6%2F8&debug=0)
Steps:
Transform the input by replacing the digits with the equivalent number of quote marks (`N`). This is saved in `J`. We then slice off the first 8 or 10 characters, and zip the result with the original. Any capturing pair will be transformed into `"Pp"`, so we then find the count of that string in the resultant list. This is the output.
As a bonus, this actually counts the number of captures possible in the input.
[Answer]
# Javascript, 272 characters
```
function h(t){b=[[]];for(i=-1;i++<7;){c=0;b.push(l=[]);for(j=-1;j++<7;){o=t.split('/')[i][j];switch(o){case'P':l[c++]=-1;break;case'p':l[c++]=1;break;default:c+=parseInt(o);}}}b.push([]);for(i=1;i<9;i++)for(j=0;j<8;j++)if((p=b[i][j])&&(b[i+p][j-1]||b[i+p][j+1]))return 1;}
```
There's probably a lot of room for improvement.
[Answer]
# Ruby, ~~145 123~~ 46 bytes
```
->b{b.gsub(/\d/){|x|?.*x.to_i}=~/p.{7}(..)?P/}
```
I don't know why I didn't think about this in the first place. It's much shorter and also pretty readable.
Here's the test: <http://ideone.com/Gzav8N>
---
The old approach:
```
->b{l={}
r=p
b.split(?/).map{|s|c={}
i=0
s.chars.map{|x|n=x.to_i;c[i]=x;i+=n<1?1:n;x==?P&&r||=l[i-2]==?p||l[i]==?p}
l=c}
r}
```
Online test: <http://ideone.com/9L01lf>, version before golfing: <http://ideone.com/CSmqlW>
A history of modifications is available [here](https://github.com/wolfascu/codegolf/commits/master/59147-capture-on-the-pawn-chessboard/59147-capture-on-the-pawn-chessboard-golfed.rb).
[Answer]
## ES6, 64 bytes
An appropriate byte count, if it lasts!
```
f=s=>/p.{7}(..)?P/.test(s.replace(/\d/g,n=>" ".slice(-n)))
```
I actually thought of this solution without reading the other answers first, but I won't mind if you don't believe me.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 21 bytes
```
`p.{7}(..)?P`NaRXDsX_
```
[Verify all test cases!](https://tio.run/##VU8xDsIwDNx5RUcYiJWkbbqxsIIspm4tE2JBJxirvj2cS1vRRI6cO599xhN5yD3ckMa9c4eT9tf7rT1/2i6Phfu4rrgUj9xIgtTqpVnuzl4k8VpL1IgVDVoxK9XDS0DQIBElwzMzXhPpip8AwzWwLkLjQrInaz0BBqgRj3oiS8PZP5Cl2kNhY80WOK6cTTUbk0mlxtY3VyH6j2A@K6jz@bFpNmGuV0kys8HWnBatJhWN5uP79QU "Pip – Try It Online")
### Explanation
Same regex-based solution as most of the other answers.
```
`p.{7}(..)?P`NaRXDsX_
a 1st command-line argument
R Replace
XD regex matching a digit
sX_ with space repeated that many times
N Count occurrences of
` ` this regex:
p A black pawn
.{7} followed by any 7 characters
(..)? optionally followed by 2 more characters
P followed by a white pawn
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 bytes
```
'p.{7}(..)?P'{≢⍺ ⎕S⍬⊢⍵}('\d'⎕R{' '⍴⍨⍎⍵.Match})⍞
```
I wanted to make a matrix based matching solution for this, but Martin Ender's Regex ended up being simpler.
[Try it online!](https://tio.run/##XVC7TsQwEOzzFel8VxDLzsPp6OiQVkBJE3E6rojECo4iilLzkHwdJRRUFJTQ8Dn7I2EcfHCcLUv2zOzujBtuDxZd015djnJ/txwVZ70bZlk2PyTVy8Or@K9UNk@n4t/lEa/PYabOFwrQSa9SJf5D/Jv4DZjsuFlfrIa5@JfQbBT/nJ5d365XXbJMau1YV2R0vd0TWGt22lClc8p5B7dU4l6QYaMtW7I65wLH4PajIAdBiaflwJCFMmfK/2h0ht4AwmHUacNVpIvAYIoFjw6GicP4YJAxtIAsCf6Pmvami07rPe@OdMX7gZAS@H@M4/qFKa4t76K3EGenzIUUNvzB9AvlVBkSfAM "APL (Dyalog Unicode) – Try It Online")
## Explanation
```
'p.{7}(..)?P'{≢⍺ ⎕S⍬⊢⍵}('\d'⎕R{' '⍴⍨⍎⍵.Match})⍞
⍞ String input
⎕R Perform Regex replacement
'\d' match all digits
{' '⍴⍨⍎⍵.Match} Execute match(convert to number), replace with that many spaces
{≢⍺ ⎕S⍬⊢⍵} Tally number of matches of left argument in right
'p.{7}(..)?P' Match two opposite colored pawns 7-9 spaces apart
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~55~~ 51 bytes
```
t=>/p.{7}(..)?P/.test(t.replace(/\d/g,i=>'1e'+i-1))
```
[Try it online!](https://tio.run/##VVDbboMwDH3vjzSoaywnQJAm2C/4A/ZQlKYVEypWQXuZ9u3MZpStiRw55/hy7I/2sx3jvePpeBvOab7U81Q3wPYrfBtrszcCO6VxMpO9J@7bmAy8n@H60tXNHtP@0B0xy@bX066CwFASQvW4O305AFIJnjxvqKNCvJyQERw7cuA5F0PxlKcgdCEfx4qTkzjP5B@k1JRYFECMJQeQy4XMFZf6TljJRibWtiqLpV2@iqqeRAaCkp91yyiC/kd4PRtI6/llwypCVW8pQcU6HXMZtFiyVOjpb5n2IMuMdROH2zj0yfbD1VxMzGSpPw "JavaScript (Node.js) – Try It Online")
Replace numbers with spaces, then
```
12345678/
P1234567
p P1234
56789p
P1234567p ; attempt to make P and p not in neighbor line
P1 ; and fail
23456789p
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Adaptation of [Neil's solution](https://codegolf.stackexchange.com/a/69469/58974).
```
r\dȰçÃè/p{7ç.}(..)?P
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clxkyLDnw%2bgvcHs35y59KC4uKT9QLw&footer=VmdX%2biBtKyIgPT4gIiApKyEhVQ&input=WwoiOC83cC82UDEvOC84LzgvOC84IgoiOC84L3A3LzFQNi8zUDNwLzgvOC84IgoiOC8yUDUvOC80UDFwMS8ycDJQMi8zcDQvM3AxUDIvOCIKIjgvUDcvOC81UDIvMnBwNC8zUDJwMS8zcFAzLzgiCiI4L1A3L3A3L3AxUDFQMy8xUDNwMi84LzFwNi84IgoiOC80cDFQMS8yUDJQMVAvMnAxcFBwcC84LzZQMS9wUDFwNC84IgoiOC84LzgvOC84LzgvOC84IgoiOC83UC82cDEvOC84LzgvOC84IgoiOC83cC83UC84LzgvOC84LzgiCiI4L3BwcHBwcHBwLzgvOC84LzgvUFBQUFBQUFAvOCIKIjgvcDcvOC8xcDYvNVAyLzgvOC84IgoiOC9wNy9QNy8yUDFwMXAxLzJwNS84L1BQNi84IgpdLW1S) (Includes all test cases)
[Answer]
# Perl 5, 30 bytes
29, plus 1 for `-pe` instead of `-e`
```
s/\d/1x$&/ge;$_=/p.{7}(..)?P/
```
A Perl copy of [w0lf's Ruby answer](/a/59155).
[Answer]
# PHP, ~~94~~ ~~87~~ 80 bytes
```
for(;$i++<8;)$t[$i]=$s.=" ";echo preg_match("#p.{7}(..)?P#",strtr($argv[1],$t));
```
That loop+`strtr` is a lot shorter than `preg_replace_callback` with `str_pad`.
[Answer]
## Jelly, 88 84 79 72 69 65 64 63 60 bytes
Definitely room for improvement.
```
ØDṖḊ
”_x
e1£¬
1£iЀ2Ŀ€
x"3Ŀ€;"ÇFṣ”/
w€⁾pPn0
5ĿUŒDÇ
5ĿŒD6ĿoÇS
```
] |
[Question]
[
Given an ordered list of numbers (possibly with leading zeros), arrange the numbers vertically, then let all zeros drop all the way to the bottom and all overhangs drop to the bottom-most open slot. Output the resulting integers, removing leading zeros.
### Worked Example
Say we were given the following as input:
```
['0000312941295', '239124000124581598', '32852353800451258', '10235923505185190', '1491359102149']
```
First we arrange it vertically:
```
0000312941295
239124000124581598
32852353800451258
10235923505185190
1491359102149
```
Then, column by column, drop the zeros "through" the other numbers so they rest on the bottom and "push" the other numbers up. This would result in the first couple steps being as follows:
```
2000312941295
339124000124581598
12852353800451258
10235923505185190
0491359102149
^
2300312941295
329124000124581598
14852353800451258
10235923505185190
0091359102149
^
2390312941295
328124000124581598
14252353800451258
10935923505185190
0001359102149
^
...
2391312941295
328524538124581598
14232323525451258
10915991001185190
0000350000049
^
```
Next, drop all overhangs as if gravity is pulling them down like sand.
```
2391312941295
3285245381245 1598
14232323525458258
10915991001181190
00003500000495
^
2391312941295
3285245381245 598
14232323525458158
10915991001181290
000035000004951
^
...
2391312941295
3285245381245
14232323525458159
10915991001181258
000035000004951908
^
```
Finally, output these numbers, removing leading zeros. For our worked example, output:
```
[2391312941295, 3285245381245, 14232323525458159, 10915991001181258, 35000004951908]
```
For another example, suppose input of `[1234000,12345678,1234,12340608,12341234]`.
```
1234000
12345678
1234
12340608
12341234
```
Drop the zeros:
```
1234
12345678
1234163
12340208
12340004
```
Drop the remaining overhanging digits:
```
1234
1234567
12341638
12340208
12340004
```
Output is `[1234, 1234567, 12341638, 12340208, 12340004]`.
### Rules
* The input *may* contain leading zeros. The output *must not* contain leading zeros.
* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
Z¬Þ€UZṚḌ
```
[Try it online!](https://tio.run/##y0rNyan8/z/q0JrD8x41rQmNerhz1sMdPf///4@ONtCBQGMdQx0jHUsdEyhtGqujEG0EFLYEC5hAlUHYpjoWQJYpUM4CpMwYKGgB5IKUmwKxBVgpSBlIuSlEkSFQCKLAEkobgBVYgElLHQOIIhOwhRBlEC1gsdhYAA "Jelly – Try It Online")
### How it works
```
Z¬Þ€UZṚḌ Main link. Argument: M (2D array / matrix)
Z Zip; transpose M by reading columns as rows.
¬Þ€ Sort each row of the transpose by logical NOT, pushing 0's to the end.
U Upend; reverse all sorted rows of the transpose.
Z Zip again, restoring rows from columns. Overhangs rise to the top.
Ṛ Reverse the order of the rows.
Ḍ Decimal; convert the rows from base 10 to integer.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
ζεð†R0†R}øï
```
[Try it online!](https://tio.run/##HcmxDUJBDAPQVeiuoYiTs5SsQYsoQGIMJEZhA2hA9Nf/IVjk8P@RbFkvxvMF1zmXz/Ier9/9cbC1buM7nnMem@kCXl1h2@@aR8G7VM0EK1cNT3ow0qwTzg1holKMSKJsw16Q6qfVTn8 "05AB1E – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 12 bytes
```
md↔TmoÖ±miT↔
```
[Try it online!](https://tio.run/##Fcm9DcJQDATgXV5N4Z93kr1HOpSOAoSeKFBWyAQoe2QFsgmLmIuls86f78v7WTVuv/UzjdexfffxmHhU1bUJx9WyM2iXZp5qnciNUGQQ3QLm8BDpUMNpKpRkBBrQlNN6KpEvtjb/AQ "Husk – Try It Online")
### Explanation
```
md↔Tm(Ö±mi)T↔ -- input as list of strings, example: ["103","32","258"]
↔ -- reverse: ["258","32","103"]
T -- transpose: ["231","520","83"]
m( ) -- with each line do (example with "520")
mi -- | convert each char to digit: [5,2,0]
Ö± -- | sort by signum (stable): [0,5,2]
-- : [[2,3,1],[0,5,2],[8,3]]
T -- transpose: [[2,0,8],[3,5,3],[1,2]]
↔ -- reverse: [[1,2],[3,5,3],[2,0,8]]%
md -- convert each to integer: [12,353,208]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 118 bytes
```
lambda l:[int(''.join(z))for z in zip(*map(lambda*a:['']*a.count(None)+[e for e in a if'0'<e]+['0']*a.count('0'),*l))]
```
[Try it online!](https://tio.run/##RZFNcoMwDIX3OYV3xsTNyH@pnSk9Qi/gekEbmNIhwCRk0VyeSiZpYYweH5KeRkw/89c46KWt3pe@Pn0ca9YfYjfMBee777EbipsQ7XhmN9YN7NZNRXmqp2JNLetD5DyV9e5zvGLJ2zg0YhsbRgUNFdSsaznwlyZtI8b/VHwRsuyFSMvcXOZLFTcRM/AySgeLx3HJuDZBaYsUn84rFzxRo73TxhkPYJ3SLkMFiAIecMo7FSBDGxRS/IaKJxmp4Z@DZLmTxU7UXzJltaHbabfaIYKAETuAUp68sMjRnGADufiUJI2utKE5uczK7Z/9Xd4D7OFBMsVZKKLBmr4KtTd@VaDhodAqpU3a0FZpWfLcXK79TPvNuztMZ/xhbKVV1RZEhcyp/OmVyztZfgE "Python 2 – Try It Online")
### Ungolfed version
```
def f(list_):
max_len = max(len(x) for x in list_)
transposed_list = zip(*[list(row)+(max_len-len(row))*[None] for row in list_])
weighted_list = [['']*column.count(None)+[cell for cell in column if cell != '0' and cell != None]+['0']*column.count('0') for column in transposed_list]
return [int(''.join(row)) for row in zip(*weighted_list)]
```
The first two lines are equivalent to `map(lambda*a...)`, the default behaviour if for `map` to fill with `None`s if one list is shorter than the other.
`e>'0'` is equivalent to `cell != '0' and cell != None`, because if it is any digit (1~9) it will have a higher codepoint, and (any) string is higher than `None`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 104 bytes
```
->a{a.map{|x|x.ljust(99).chars}.transpose.map{|x|x.sort_by{|x|x<?1?x:?!}}.transpose.map{|x|x.join.to_i}}
```
[Try it online!](https://tio.run/##bY/dasMgFIDv8xSOXmSDVDzqAR3r8iAhFDtamtIlQQ2ktHn27Ghhu5ni3@fxfEc/HW7rabduP93d8W833h/zY@bXyxTiq7Vv/OvsfFh49K4P4xCOfzFh8HF/uOXDRw31/F6/LP9GXoau53HYd8uydv04RbZjTSmoKZBW08CyYqVUFqQmSjMaQGsSVdKgVKiMEBpBYoYgCFkaAsEgWJGhtkCU7mhXtoU/humaXKcmW9tiZE9WbJok@7VXLFs0WZK7YqClSp3yP0shJCytOTuYVAc9wvQHoW2qwLTrDw "Ruby – Try It Online")
## Explanation
```
->a{
a.map{|x|x.ljust(99).chars} # Fill spaces to make this rectangular
.transpose.map{|x|
x.sort_by{|x|x<?1?x:?!} # Treat all chars but " 1" as ! (see ascii table)
}.transpose.map{|x|x.join.to_i} # Convert back to numbers
# note: if no leading 0s, eval x*'' , doesn't work here
}
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
iRT_C_M!DMC
```
[Try it online!](https://tio.run/##Lc0xDoAgDAXQq@j@B1SalFlXF@PWEFbdHFw8PZaWEGj5fYTne69a7@Msa9nHbV9rFQnwtWDCjITYK2UMMmucLIideU9g7UhnnCGLZqy3pkk3m2yqaWpmkEkjB6nXYIDtTAiOov3nzJ9YlvMP "Pyth – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~95~~ 92 bytes
```
m(+`^((.)*)(.+)(¶(?<-2>.)*)(?(2)_)$
$1$4$3
+`^((.)*)0(.*¶(?>(?<-2>.)*))([^0])
$1$4${3}0
^0+
```
[Try it online!](https://tio.run/##RYo9CgJBDEb7nGOKZBeX/ExgBmT3IOKqhYWFFmK3eC0P4MXGqKCBL3x5edfj7XQ5tHbGfj8jDtQRDj3h84HTeqXjB0yotKMESVJOBj@Tceje4vh3CTczb@mrLnZnmLmH1jjGRGuOOKhV0RwothfxWsC0uJpbYc4u6gWE464RdikulUFylUDxiPYC "Retina 0.8.2 – Try It Online") Explanation: The first stage drops the overhanging digits as this makes it easier (edit: even easier for a 3-byte saving) for the second stage to drop the zeros. The third stage then removes leading zeros.
[Answer]
# [Perl 5](https://www.perl.org/), -p0 77 bytes
Old style counting: 79 bytes (`+2` for `p0`)
Give input as lines on STDIN without final newline (otherwise everything is seen as overhang and the final newline rises to the top as the input string crashes down). E.g.:
```
0000312941295
239124000124581598
32852353800451258
10235923505185190
1491359102149
```
It was a bit tricky to get the overhang dropping and the `0` dropping into one regex
```
#!/usr/bin/perl -p0
s/^.{@{+}}\K((0)|.+$)(.*
.{@{+}})((?(2)[1-9]|$))/$4$3$1/m while/|/g;s/^0+//mg
```
[Try it online!](https://tio.run/##LYy7CsMwDEV3f0UGD3ZDbMm2wCZDu/cT@thCGsiLpqVDkl@vq6EXjpCO4M7Ns6f8XpqCDIKBOi/2btbTWu779awU6M2UUitzEH@rlToqpy9YpdsmtbYySC/RDsXn0fWN3WxbcweU1g5tzsDx6FJgSDif0AVWPCkipSi8i@Q8@QgQCB1FgcB3YoAwEiYQGBKy4gdv32l@ddO45GqGHw "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function taking a character matrix as argument and returning a list of numbers.
```
⍎⍤1∘⍉' 0'(∩∘⊃,~,∩∘⊃∘⌽)⍤1⍨⍉
```
[Try it online!](https://tio.run/##PY3BSgMxEIbvPsXcYqFCJsnU5C32FZZtdxmou2V3Ebx4EUoVU9pDwYs3D/oQvkxeZJ3UamBm/nz/z0y5Wd8sH8p110xpfyqKtD1YBym@Q9FzO8KmX1U8cNeC4IGblmuuSjGW3PA4wNjlyP1KyFCxjOxD3fV35TjVsi3FfYofmHZvKT4r0Oo67b7y7@Vp/jj/17m/fs/O0fgp0WmqIW2PSsuzaIKTIgXK2IDGCZROHil4gdZ4Mpas19oRGsoMtZAgpQk9YdCZuYACxRKlrn4voLF5X7ZF0eLWX@Rl6IX@I2f6Aw "APL (Dyalog Unicode) – Try It Online")
`⍉` transpose the input (as we need to work on the columns)
`' 0'(`…`)⍤1⍨` apply the following tacit function to each row (sub-array of tensor rank 1) with `' 0'` as *right* argument (`⍨` swaps the arguments) :
`∩` intersection of the row and
`∘` and
`⊃` the first of `' 0'`
(i.e. `row∩' '`; all the spaces from each row)
`,` followed by…
`~` the set difference
(i.e. `row~' 0'`; the row but without spaces and zeros)
`,` followed by…
`∩` intersection of the row and
`∘` and
`⊃` the first
`∘` of
`⌽` the reversed `' 0'`
(i.e. `row∩'0'`; all the zeros from each row)
`⍎⍤1` evaluate each row (sub-array of tensor rank 1)
`∘` of
`⍉` the transpose of that (i.e. each column; the now modified input rows)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 203 bytes
```
->a{t=->b{b[0].zip(*b[1..-1])}
m=a.map{|s|s.size}.max
a.map!{|s|(s+" "*m)[0...m].chars}
a=t[a].map{|c|c.size.times{|i|" 0"[c[i]]&&(c.slice!(i)==?0?c.push(?0):c.unshift(" "))}
c}
t[a].map{|r|r.join.to_i}}
```
[Try it online!](https://tio.run/##RY//aoMwEID/9ylSB1W7NiQxgWRg@yAhDA1KM2orRmGr@uzuYmFLyK/vuPsu/Vj9rE2xns7lNBSnczVVmhj8dF16qDTF@ERNtkRtUeK27KbZzx5796wXeH5HG9wFmvr3GMWHNtMEY9wabK9l75eoLAZdmleune2WiwfX1n6a3RwjEmurnTH7fQrBm7P1LnVZUVzIxeJu9Nf0QrIPi8e7v7pmSEGSQT92if7r9nOPvx7ujofHp1uW1d27cUAF0gmBkVOmOCyRHFHCckUZBwq7kFQoGWjOpGC5yCUhXFAmNkgJIAWLCCoFVWSDXFGgEINbYqK@9uMtuBq9WU3UoReL3nSQ/dmPaLNwsAT3EVHO8jCh/qsVQETBuVWnMvQBSSL8gXAVOpBm/QU "Ruby – Try It Online")
A lambda accepting an array of strings and returning an array of ints. I feel like I'm missing something; this feels enormous :/
```
->a{
t = -> b { b[0].zip(*b[1..-1]) } # t is a lambda that transposes 2D arrays
m = a.map{ |s| s.size }.max # m is the maximum input string length
a.map!{ |s| (s+" "*m)[0...m].chars } # Right-pad every string to the same length
a = t[a].map{ |c| # Transpose a, and for every row (column)
c.size.times{ |i| # For every character in the column
" 0"[c[i]] && ( # If the character is 0 or space
c.slice!(i) == ?0 ? # Remove it from the column, and if it was 0,
c.push(?0) : # Push a 0 to the end (bottom) of the column, else
c.unshift(" ") # Add a space to the top of the column
)
}
c
}
t[a].map{ |r| r.join.to_i } # Transpose a back, and parse each row to int
}
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~24~~ ~~23~~ 22 bytes
```
⍎⍤1⍉{⍵[⍒⌈9÷⍨⎕d⍳⍵]}⍤1⍉⎕
```
[Try it online!](https://tio.run/##NY3PisIwEIfvfQpvPRVmkowmz7J4KJaKULDoSZa9Lf5BU1TwDTx4F/EB9k3mRbq/ag1M8s03vyR5XWXFKq/m02xS5cvlbNJqc5nNdX0k3f@CywWYjR@927pGa12i203Zamw0Xlnj7lvj40vjWQ/b8PfUeEO00HiHHv/0GagW19oy0fUpJSzLJjiUpIPU2MDGQWIXzxI8pDVejBXriZywkc4xwQQUCXvhQJ1zgSExAqVJlrz/YGO7F7sASIYj32N/0JA@5mX/AQ "APL (Dyalog Classic) – Try It Online")
based on Adam's solution
] |
[Question]
[
Your task: make a hexagonal triangle with side length `n`, where `n` is a positive whole number or 0.
First, let me define a hexagon:
```
/ \
| |
\ /
```
(Amazing ASCII art, right?)
Hexagons can be linked together by sharing sides:
```
/ \ / \
| | |
\ / \ /
/ \
| |
/ \ /
| |
\ /
```
A hexagonal triangle is the following:
```
/ \
| |
/ \ / \
| | |
\ / \ /
```
That hexagonal triangle has a side length of 2-- 2 hexagons are required to make one side. A hexagonal triangle with side-length 1 is just a single hexagon, and a hexagon with side-length 0 is empty.
More formally, a hexagonal triangle is a triangle made of hexagons linked by their sides. The top hexagon links to the two below it on its bottom two sides. The triangle in the bottom left links to the one to its right and top-right, and the one in the bottom right links to the ones on its left and upper left. There are hexagons *in between* the corner ones, connected by their opposite sides, and their number is `n-2`. The triangles are **not** filled.
More examples:
```
Side length 3:
/ \
| |
/ \ / \
| | |
/ \ / \ / \
| | | |
\ / \ / \ /
Side length 4:
/ \
| |
/ \ / \
| | |
/ \ / \ / \
| | | |
/ \ / \ / \ / \
| | | | |
\ / \ / \ / \ /
(This triangle isn't really filled, the borders make it look like there is a hexagon in the middle, but there is not.)
Side length 5:
/ \
| |
/ \ / \
| | |
/ \ / \ / \
| | | |
/ \ / \ / \
| | | |
/ \ / \ / \ / \ / \
| | | | | |
\ / \ / \ / \ / \ /
Side length 6:
/ \
| |
/ \ / \
| | |
/ \ / \ / \
| | | |
/ \ / \ / \
| | | |
/ \ / \ / \
| | | |
/ \ / \ / \ / \ / \ / \
| | | | | | |
\ / \ / \ / \ / \ / \ /
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~62~~ ~~43~~ 39 bytes
```
NβF³«F⁻β‹ι²« / \¶| |¶ \ /Mײι↑¿⁻¹ιM⁶←
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9nnXnNr3fs@zQ5kOrgdSjxt3nNj1q2Hlu56FNh1Yr6CvEHNpWo6CgUHNom0KMgv77PWsPTz@06dzOR20TD@0HKj4EVAkUfNS47VHbhP//TQE "Charcoal – Try It Online") Edit: Saved some bytes thanks to @ASCII-only (not sure exactly how many as I also saved another ~~6~~ 10 bytes but then needed to spend 4 bytes on a bugfix). Now using nested loops, which is what this should have been all along.
[Answer]
# Python 2, ~~184~~ ~~177~~ ~~174~~ 164 bytes
```
n=input();p='| |';e=' \\ /'
for i in range(n):k=' '*(4*i-5);w=' '*~(i-n);print w+[' / \\'*-~i+'\n'+w+p[:4]*i+p,' /'+e+k[3:]+e+' \\\n'+w+p+k+p][2<i<n-1]
print e*n
```
[Try it Online!](https://tio.run/nexus/python2#LY07DsIwEET7nGK7tb1YIRCafE5iu6AwaBVpsaKgNFGuHhZBNXqa0ZtDRpbyXozty4gbAGzY5xEhRqixerxmYGCB@S7PbMR2k3boTOvY32y/Kinuhr2oYWZZYKWAUKsAnd@ZMArSSiV0bXJM5aQlUqYpXLuk@b36T2iiksJl4EF8k6qfLjs5jub8AQ)
*-7 bytes thanks to Ørjan Johansen*
[Answer]
## JavaScript (ES6), 243 bytes
```
f=n=>(n=n*2-2,a=[...Array(n+3)].map(_=>Array(n*2+5).fill` `),g=(y,x)=>(a[y+1][x]=a[y+1][x+4]=`|`,a[y][x+1]=a[y+2][x+3]=`/`,a[y][x+3]=a[y+2][x+1]=`\\`),[...Array(n+!n)].map((_,i)=>i%2||(g(n,i*2),g(i,i=n-i),g(i,n+i))),a.map(a=>a.join``).join`
`)
```
```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```
[Answer]
## JavaScript (ES6), ~~133~~ ~~129~~ ~~128~~ 126 bytes
Builds the output character by character with two *for* loops.
```
n=>{for(s='',y=n*2,n*=4;~y--;s+=`
`)for(x=n;~x--;)s+=' \\ /|'[x>y-2&x<n-y&(k=x+y&3,x>n-y-6|x<y+4|y<2)?y&1?k:k+1&4:0];return s}
```
### How it works
In the outer loop, ***y*** iterates from ***n\*2-1*** to ***-1***. In the inner loop, ***x*** iterates from ***n\*4-1*** to ***-1***. We set ***k = (x+y) & 3***, which is the underlying pattern that is used to generate the hexagons.
Below is the resulting grid for ***n = 4***:
```
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 -1
+---------------------------------------------------
7 | 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2
6 | 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1
5 | 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0
4 | 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3
3 | 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2
2 | 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1
1 | 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0
0 | 3 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3
-1 | 2 1 0 3 2 1 0 3 2 1 0 3 2 1 0 3 2
```
On even rows, a cell is filled with a pipe character when ***k = 3***, and a space otherwise. The pipe is the 5th character in our reference string `" \ /|"`, so the correct index is given by ***(k+1) & 4***.
On odd rows, each cell is filled directly with the corresponding character in the reference string:
* ***k = 0*** → space
* ***k = 1*** → "\"
* ***k = 2*** → space
* ***k = 3*** → "/"
Below is our updated example (spaces replaced with dots):
```
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 -1
+---------------------------------------------------
7 | . \ . / . \ . / . \ . / . \ . / .
6 | . . | . . . | . . . | . . . | . .
5 | . / . \ . / . \ . / . \ . / . \ .
4 | | . . . | . . . | . . . | . . . |
3 | . \ . / . \ . / . \ . / . \ . / .
2 | . . | . . . | . . . | . . . | . .
1 | . / . \ . / . \ . / . \ . / . \ .
0 | | . . . | . . . | . . . | . . . |
-1 | . \ . / . \ . / . \ . / . \ . / .
```
In the following formulas, we define ***N = n\*4*** for readability (although the same variable is used in the code).
The triangle shape is obtained by testing:
* ***x > y - 2*** → removes the right corner
* AND ***x < N - y*** → removes the left corner
And the inner part is removed by testing:
* ***x > N - y - 6*** → keeps only the left edge
* OR ***x < y + 4*** → keeps only the right edge
* OR ***y < 2*** → keeps only the bottom edge
### Demo
```
let f =
n=>{for(s='',y=n*2,n*=4;~y--;s+=`
`)for(x=n;~x--;)s+=' \\ /|'[x>y-2&x<n-y&(k=x+y&3,x>n-y-6|x<y+4|y<2)?y&1?k:k+1&4:0];return s}
console.log(f(3))
console.log(f(4))
console.log(f(5))
console.log(f(6))
console.log(f(7))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~62~~ 61 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
### *Currently containing six sixes.*
```
_‘<×⁸>6
Rµ‘⁾| ẋ⁾/\ẋ⁸¤ż;/K€µ⁶ðMṀ_6r6ẋð¦"Jç¥
ḤḶUẋ@€⁶;"ǵ-ịṙ6ṭ⁸Y
```
**[Try it online!](https://tio.run/nexus/jelly#@x//qGGGzeHpjxp32JlxBR3aCuQ@atxXo/BwVzeQ1o8B0zsOLTm6x1rf@1HTGqCKxm2HN/g@3NkQb1ZkBpQ@vOHQMiWvw8sPLeV6uGPJwx3bQoGCDkClQIXWSofbD23Vfbi7@@HOmWYPd64FmhX5//9/MwA)**
### How?
```
_‘<×⁸>6 - Link 1, should we eat the praline? row number, triangle size
_ - row number minus triangle size
‘ - plus one
< - less than triangle size? (1 if one of the last rows else 0)
×⁸ - multiply by row number (row number or 0)
>6 - greater than 6? (row number if between row 6 and last two rows)
Rµ‘⁾| ẋ⁾/\ẋ⁸¤ż;/K€µ⁶ðMṀ_6r6ẋð¦"Jç¥ - Link 2, build a solid triangle: triangle size
(except the very bottom row)
R - range: [1,2,...,size]
µ - monadic chain separation, call that r
‘ - increment: [2,3,...,size+1]
⁾| <space - literal "| "
ẋ - repeat: ["| | ","| | | ",...]
¤ - nilad followed by link(s) as a nilad:
⁾/\ - literal "/\"
⁸ - link's left argument, r
ẋ - repeat (vectorises): ["/\","/\/\",...]
ż - zip the two repeated lists together: [["/\","| | "],["/\/\","| | | "],...]
;/ - reduce by concatenation: ["/\","| | ","/\/\","| | | ",...]
K€ - join with spaces for €ach: ["/ \","| | ","/ \ / \","| | | ",...]
µ - monadic chain separation call that s
¥ - last two links a a dyad:
J - range(length(s))
ç - call the last (1) link as a dyad (left = result of J, right = size)
" - zip with: (call those d)
ð ð¦ - apply to indexes:
⁶ - a literal space character
M - indexes of maximal elements in an element of s (a row)
Ṁ - maximum (this is the rightmost non-space index, MṀ working like length ignoring trailing spaces)
_6 - subtract 6 (6 indexes back from the right)
r6 - range from there to 6, i.e [l-6,l-7,...,6]
ẋ - repeat d times (1 or 0), thus applying to the middle rows but not the bottom and top ones.
ḤḶUẋ@€⁶;"ǵ-ịṙ6ṭ⁸Y - Main link: triangle size
Ḥ - double(size)
Ḷ - unlength: [0,1,2,...,double(size)-1]
U - upend: [double(size)-1,...,2,1,0]
⁶ - literal space character
ẋ@€ - repeat for €ach with reversed arguments [" ... ",...," "," ",""]
Ç - call the last link (2) as a monad(size)
;" - zip with concatenation (zips the leading spaces with the solid triangle body)
µ - monadic chain separation, call that t
-ị - index -1 (last but one row of t)
ṙ6 - rotate left by 6 (any number congruent to 2 mod 4 would do)
ṭ⁸ - tack to t (add this new row on)
Y - join all the rows by new lines
- implicit print
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 82 bytes
```
jb+Rt_.rd"/\\"_.e<s[dd*dkb*dyQ)hyQ*,"| |""/ \\ /"tQ*Q" / \\"+*Q"| "\|*Q" \\ /"
```
[Try it online!](http://pyth.herokuapp.com/?code=jb%2BRt_.rd%22%2F%5C%5C%22_.e%3Cs%5Bdd%2adkb%2adyQ%29hyQ%2a%2C%22%7C+++%7C%22%22%2F+%5C%5C+%2F%22tQ%2aQ%22+%2F+%5C%5C%22%2B%2aQ%22%7C+++%22%5C%7C%2aQ%22+%5C%5C+%2F%22&input=6&debug=0)
[Answer]
## Mathematica, 155 bytes
```
""<>Table[If[i+j<d||i-j>d+1||i+j>d+5&&i-j<d-3&&j<d-1," ",Switch[Mod[i+d+{j,-j},4],{1,3},"/",{3,1},"\\",{1,1},"|",_," "]],{j,(d=2#)+1},{i,4#+1}]~Riffle~"\n"&
```
with `\n` replaced with a newline.
More readable:
```
"" <> Table[
If[i+j < d || i-j > d+1 ||
i+j > d+5 && i-j < d-3 && j < d-1, " ",
Switch[Mod[i+d+{j,-j}, 4], {1, 3}, "/", {3, 1},
"\\", {1, 1}, "|", _, " "]], {j, (d=2#)+1}, {i, 4#+1}]~
Riffle~"\n" &
```
Creates an array of characters, indexed by *i* from 1 to 4 *n* + 1 horizontally and *j* from 1 to 2 *n* + 1 vertically. First, `Switch[Mod[i+d+{j,-j},4],{1,3},"/",{3,1},"\\",{1,1},"|",_," "]` fills in a hexagonal grid:
```
\ / \ / \ / \ /
| | | |
/ \ / \ / \ / \
| | | | |
\ / \ / \ / \ /
| | | |
/ \ / \ / \ / \
| | | | |
\ / \ / \ / \ /
```
then `If[i+j<d||i-j>d+1||i+j>d+5&&i-j<d-3&&j<d-1," ",...]` replaces this with `" "` outside the unfilled triangle.
] |
[Question]
[
In a chatroom with a few people, a topic came up between me and them about how many possible strings a regex could match.
Your task is to build a program that can answer that question.
Your program will accept, as input, any regular expression as defined in [this document](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html) as an "extended regular expression", such as:
```
^[A-Za-z0-9]{8}$
```
and output the total number of possible strings that match that expression, outputting `infinity` if there are infinitely many:
```
218340105584896
```
Your program may also output `too many` if there are more than 263-1 possible strings that match the regex; however, it must not output `infinity` unless there are actually infinitely many strings.
The shortest program to do the above wins.
[Answer]
# Python 3370
I got this to be about as functional as I could, and even got alternation to work (with correct double-count checking!). As far as I know this works for everything except lookarounds (because that would be crazy).
For anyone writing their own solution feel free to use/improve my methods as much as you like.
Code:
```
R=range;L=len;E=enumerate;I=int;F="Infinity";S=sum;H=chr;D=ord;J=lambda l:''.join(l);U=lambda s:J([H(i)if H(i) not in s else''for i in R(1,128)]);s=' \n\t';c=J((H(i)if H(i)not in s else'')for i in R(1,32));d,l,u=[J(H(i)for i in R(*n))for n in [[48,59],[97,123],[65,91]]];p='`~!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?';Y={'\\s':s,'\\S':c+s+p+u+l+d,'\\d':d,'\\D':U(d),'\\w':u+l+'_','\\W':U(u+l+'_'),'[:alnum:]':u+l+d,'[:alpha:]':u+l,'[:ascii:]':U(''),'[:blank:]':' \t','[:cntrl:]':c,'[:digit:]':d,'[:graph:]':p+d+l+u,'[:lower:]':l,'[:print:]':p+d+l+u+s,'[:punct:]':p,'[:space:]':s,'[:upper:]':u,'[:word:]':l+u+'_','[:xdigit:]':d+'ABCDEF'};C=lambda l,n:[d+[l[i]]for i in R(L(l))for d in C(l[i+1:],n-1)]if n>0 else[[]];O=lambda x:S([all((c in s)for s in [(e[1]if any(e[1] not in Y for e in x)else Y[e[1]])if e[0]=='e'else(e[1]if e[0]=='t'else((Y[e[1]]if e[1]in Y else B(e[1]))if e[0]=='['else''))for e in x])for c in Y['[:ascii:]']])
def X(r):
x=[];l=0;c=''
for h in r:
l+=I(h in'([')-I(h in')]')
if l<1 and'|'==h:x+=[c];c=''
else:c+=h
x+=[c]
if L(x)>1:
o=0;m=[];u=[]
for e in x:
p,b=X(e)
if p==F:return F,[]
o+=p;m+=[('(',b)];u+=[b]
return o-S([(-1)**(i%2)*T(s) for i in R(2,L(u)+1)for s in C(u,i)]),[('|',m)]
u=[];o=[];m=[];w=1
while r!='':
h=r[0];z=0
if h in'([{':
l=1;i=1
while l>0:k=r[i];l+=(k==h)-(k=={'(':')','[':']','{':'}'}[h]);i+=1
u+=[(h,r[1:i-1])];z=i
elif h=='\\':u+=[('e','\\'+eval("'\\%s'"%r[1]))]if r[1]in'nt'else[('e','\\'+r[1])];z=2
elif h in ['*','+','?']:u+=[('{',h)];z=1
elif h in'^$':return 0
elif h=='.':u+=[('[','[:ascii:]')];z=1
else:u+=[('t',h)];z=1
r=r[z:]
for t,g in u:
if t=='(':p,b=X(g);o+=[p];m+=[('(',b)]
elif t=='e':o+=[L(Y[g])]if g in Y else[1]
elif t=='[':o+=[N(g)]
elif t=='{':
n=o[-1]
try:o[-1]=S([n**r for r in Q(g)])
except:return F,[]
elif t=='t':o+=[1]
if t!='(':m+=[(t,g)]
for c in o:
if c==F:return F,[]
w*=c
return w,m
def N(s):
if s in Y:return L(Y[s])
if(s[0],s[-1])==('[',']'):return 1
n=(s[0]=='^');a=0
if n:s=s[1:]
while s!='':
if L(s)>=3 and s[1]=='-':a+=D(s[2])-D(s[0])+1;s=s[3:];continue
a+=1;s=s[1:]
return 256*n+(-1)**n*a
def Q(s):
if s=='?':return[0,1]
if s[0]in'*+':return None
if ','in s:
l,h=s.split(',')
return None if h==''else R(I(l),I(h)+1)
return[I(s)]
def B(s):
n=(s[0]=='^')
if n:s=s[1:]
a='';w=''
while s!='':
h=s[0]
if 3<=L(s)and'-'==s[1]:
for i in R(D(s[0]),D(s[2])+1):a+=H(i)
s=s[3:];continue
a+=h;s=s[1:]
return J([c*(c not in a)for c in Y['[:ascii:]']])if n else a
def T(x):
if all(e==[] for e in x):return 1
for i,e in E(x):
if L(e)>=2 and e[1][0]=='{':return S([T([[e[0]]*n+e[2:]]+x[:i]+x[i+1:])for n in Q(e[1][1])])
if L(e)>=1:
if e[0][0] == '(':return T([e[0][1]+e[1:]]+x[:i]+x[i+1:])
if e[0][0]== '|':
t=S(T([[s]+e[1:]]+x[:i]+x[i+1:])for s in e[0][1])
u=[[s]for s in e[0][1]]
return t-S((-1)**(j%2)*T(b)for j in R(2,L(u)+1)for b in C(u,j))
if any(e==[]for e in x):return 0
return O([e[0]for e in x])*T([e[1:]for e in x])
r=raw_input();e=[];l=0;c=''
for h in r:
l+=I(h in'([')-I(h in')]')
if l<1 and'|'==h:e+=[c];c=''
else:c+=h
e+=[c];o=[];x=[]
for f in e:
if '^'!=f[0]or'$'!=f[-1]:print F;quit()
n,m=X(f[1:-1])
if n==F:print F;quit()
o+=[n];x+=[m]
print S(o)-S([(-1)**(i%2)*T(s) for i in R(2,L(x)+1)for s in C(x,i)])
```
Ungolfed:
```
controlchars = ''
for i in range(1,32):
if chr(i) not in '\t\n':
controlchars += chr(i)
CLASSES={
'\\s':' \t\n',
'\\S':controlchars+'!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'\\d':'0123456789',
'\\D':controlchars+'\n\t !"#$%&\'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'\\w':'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_',
'\\W':controlchars+'\n\t !"#$%&\'()*+,-./:;<=>?@[\\]^`{|}~',
'[:alnum:]':'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
'[:alpha:]':'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'[:ascii:]':controlchars+'\n\t !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'[:blank:]':' \t',
'[:cntrl:]':controlchars,
'[:digit:]':'0123456789',
'[:graph:]':'!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'[:lower:]':'abcdefghijklmnopqrstuvwxyz',
'[:print:]':'\n\t !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
'[:punct:]':'`~!@#$%^&*()-_=+[{]}\\|;:\'",<.>/?',
'[:space:]':' \t\n',
'[:upper:]':'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'[:word:]':'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_',
'[:xdigit:]':'0123456789ABCDEF'
}
DELIMIT = {
'(':')',
')':'(',
'[':']',
']':'[',
'{':'}',
'}':'{'
}
def combos(lst,num):
if num == 0:
return [[]]
combs = []
for i in range(len(lst)):
for c in combos(lst[i+1:],num-1):
combs.append([lst[i]]+c)
return combs
def count_regex(regex):
exprs = []
level = 0
current = ''
for char in regex:
if char in '([':
level += 1
if char in ')]':
level -= 1
if char == '|' and level == 0:
exprs.append(current)
current = ''
else:
current += char
exprs.append(current)
comps = []
expanded = []
for e in exprs:
if (e[0] != '^' or e[-1] != '$'):
return 'Infinity'
num,member = count_expr(e[1:-1])
if num == 'Infinity':
return 'Infinity'
comps.append(num)
expanded.append(member)
total = sum(comps)
for i in range(2,len(expanded)+1):
for subset in combos(expanded,i):
if i % 2 == 0:
total -= count_doubles(subset)
else:
total += count_doubles(subset)
return total
def count_expr(expr):
exprs = []
level = 0
current = ''
for char in expr:
if char in '([':
level += 1
if char in ')]':
level -= 1
if char == '|' and level == 0:
exprs.append(current)
current = ''
else:
current += char
exprs.append(current)
if len(exprs) != 1:
comps = 0
members = []
sub = []
for e in exprs:
comp,memb = count_expr(e)
if comp == 'Infinity':
return 'Infinity',[]
comps += comp
members.append(('(',memb))
sub.append(memb)
for i in range(2,len(sub)+1):
for subset in combos(sub,i):
if i % 2 == 0:
comps -= count_doubles(subset)
else:
comps += count_doubles(subset)
return comps,[('|',members)]
sub = []
while expr != '':
char = expr[0]
if char in ['(','[','{']:
level = 1
i = 1
while level > 0:
nchar = expr[i]
if nchar == char: level += 1
if nchar == DELIMIT[char]: level -= 1
i += 1
sub.append((char,expr[1:i-1]))
expr = expr[i:]
elif char == '\\':
if expr[1] == 'n':
sub.append(('e','\\'+'\n'))
expr = expr[2:]
elif expr[1] == 't':
sub.append(('e','\\'+'\t'))
expr = expr[2:]
else:
sub.append(('e','\\'+expr[1]))
expr = expr[2:]
elif char in ['*','+','?']:
sub.append(('{',char))
expr = expr[1:]
else:
if char in '^$':
return 0
if char == '.':
sub.append(('[','[:ascii:]'))
expr = expr[1:]
else:
sub.append(('t',char))
expr = expr[1:]
components = []
members = []
for t,string in sub:
if t == '(':
comp,memb = count_expr(string)
components.append(comp)
members.append(('(',memb))
elif t == 'e':
if string in CLASSES:
components.append(len(CLASSES[string]))
else:
components.append(1)
elif t == '[':
components.append(count_class(string))
elif t == '{':
num = components[-1]
try:
components[-1] = sum([num**r for r in count_quantifier(string)])
except TypeError:
return 'Infinity',[]
elif t == 't':
components.append(1)
if t != '(':
members.append((t,string))
total = 1
for c in components:
if c == 'Infinity':
return 'Infinity',[]
total *= c
return total,members
def count_class(string):
if string in CLASSES:
return len(CLASSES[string])
if string[0] == '[' and string[-1] == ']':
return 1
negate = (string[0] == '^')
if negate: string = string[1:]
avail_count = 0
while string != '':
char = string[0]
if len(string) >= 3:
if string[1] == '-':
first,last = string[0],string[2]
avail_count += ord(last)-ord(first)+1
string = string[3:]
continue
avail_count += 1
string = string[1:]
if negate:
return 256-avail-count
return avail_count
def count_quantifier(string):
if string == '?':
return [0,1]
if string[0] in '*+':
return None
if ',' in string:
low,high = string.split(',')
if high == '':
return None
return range(int(low),int(high)+1)
return [int(string)]
def bracket_string(string):
negate = (string[0] == '^')
if negate: string = string[1:]
avail = ''
while string != '':
char = string[0]
if len(string) >= 3:
if string[1] == '-':
first,last = string[0],string[2]
for i in range(ord(first),ord(last)+1):
avail += chr(i)
string = string[3:]
continue
avail += char
string = string[1:]
if negate:
new = ''
for c in CLASSES['[:ascii:]']:
if c not in avail:
new += c
return new
return avail
def overlap(es):
chars=['' for i in range(len(es))]
for i,e in enumerate(es):
if e[0] == 'e':
if any(e[1] not in CLASSES for e in es):
chars[i] = e[1]
else:
chars[i] = CLASSES[e[1]]
for i,e in enumerate(es):
if e[0] == 't':
chars[i] = e[1]
for i,e in enumerate(es):
if e[0] == '[':
if e[1] in CLASSES:
chars[i] = CLASSES[e[1]]
else:
chars[i] = bracket_string(e[1])
total = 0
for c in CLASSES['[:ascii:]']:
has = True
for chs in chars:
if c not in chs:
has = False
break
if has:
total += 1
return total
def count_doubles(exprs):
if all(e==[] for e in exprs):
return 1
for i,expr in enumerate(exprs):
if len(expr) >= 2 and expr[1][0] == '{':
rng = count_quantifier(expr[1][1])
total = 0
for n in rng:
total += count_doubles([ [expr[0]]*n+expr[2:] ] + exprs[:i] + exprs[i+1:])
return total
for i,expr in enumerate(exprs):
if len(expr) >= 1 and expr[0][0] == '(':
return count_doubles([ expr[0][1]+expr[1:] ] + exprs[:i] + exprs[i+1:] )
if any(e==[] for e in exprs):
return 0
for i,expr in enumerate(exprs):
if expr[0][0] == '|':
total = 0
subs = []
for sub_expr in expr[0][1]:
subs.append([sub_expr])
total += count_doubles([ [sub_expr]+expr[1:] ] + exprs[:i] + exprs[i+1:])
for j in range(2,len(subs)+1):
for subset in combos(subs,j):
if j % 2 == 0:
total -= count_doubles(subset)
else:
total += count_doubles(subset)
return total
over = overlap([e[0] for e in exprs])
if over == 0:
return 0
return over * count_doubles([e[1:] for e in exprs])
reg = raw_input('Regex: ')
print count_regex(reg)
```
Here are some relevant test cases I have confirmed:
```
Regex: ^[A-Za-z0-9]{8}$
218340105584896
Regex: ^([a-b]*)$
Infinity
Regex: ^([0-9]|[a-e])([a-e]|[A-E])$|^[a-f]{2}$
161
Regex: ^[a-z]{2}$|^[0-9]?[a-z]{2,3}$|^a[a-z]?$
200773
Regex: ^([a-z]|[a-e]|[A-E]|[3-4]|[D-G])$
35
Regex: ^\(.)\(.)\2\1$
16129*
Regex: ^(a)\1?$
2
Regex: ^[[:space:]]$|^\t$
3
```
\*This is actually different in the golfed and ungolfed due to a one character difference in what is defined as valid ascii. I believe the golfed is the more correct one.
To confirm its accuracy further tests could be done, please let me know of any errors (I honestly would not be surprised if there were quite a few).
] |
[Question]
[
A superpowerset (analogous to [superpermutation](https://en.wikipedia.org/wiki/Superpermutation)) on \$n\$ symbols is a string over the alphabet \$\{1,2,...,n\}\$ such that every subset of \$\{1,2,...,n\}\$ appears as a substring (in some order). For instance, `12342413` is a superpowerset on four symbols because it contains `1`, `2`, `3`, `4`, `12`, `13`, `41`, `23`, `24`, `34`, `123`, `241`, `413`, `234`, `1234`.
The lengths of the shortest such strings and some examples are given in this sequence: [A348574](https://oeis.org/A348574)
## The Challenge
Given a string composed of \$n\$ unique symbols (and, optionally, \$n\$), output whether it is a superpowerset on \$n\$ symbols.
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins.
* Assume only valid input will be given.
* Assume \$n\$ is greater than \$0\$
* Input and output can assume whatever form is most convenient, e.g. the series of symbols can be a string, a list, an integer, a set of n bitmasks, etc, so long as it is indicated in the answer. Additionally, anything may be used as a symbol provided it is distinct from all the other symbols.
## Test Cases
```
In: 1234
Out: False
In: 1
Out: True
In: 11111111
Out: True
In: 123
Out: False
In: 1234512413
Out: False
In: 12342413
Out: True
In: 123424133333333
Out: True
In: 1234567214573126431523674256147325716357
Out: True
In: 122331
Out: False
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ŒPḊfƑɓẆṢ€
```
A dyadic Link accepting the alphabet size, `N`, on the left and the candidate string, `S`, on the right as a list of integers that yields `1` if the string is a superpowerset of that alphabet size.
**[Try it online!](https://tio.run/##y0rNyan8///opICHO7rSjk08OfnhrraHOxc9alrz//9/k//RhjpGOsY6JkDSRMdQxzgWAA "Jelly – Try It Online")**
### How?
```
ŒPḊfƑɓẆṢ€ - Link: integer, N; list of integers, S
ŒP - powerset of [1..N]
Ḋ - dequeue - removes the empty list
ɓ - new chain with swapped arguments:
Ẇ - all sublists of S
Ṣ€ - sort each
Ƒ - is the dequeued powerset invariant under:
f - filter keep the sorted sublists
```
[Answer]
# [Python](https://www.python.org), 90 bytes
```
lambda i,n:f(*i)+2>>2**n
f=lambda a,*i,k=0:1<<(l:=k|1<<a-1)|(i>()and(l>k)*f(*i,k=l)|f(*i))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XU9RasMwDP3vKfQTLGcOzI4HJdQ-yNiPS5vOxHFD7MIGucl-AmO7yE6x28xJnZ89kPQkPUno43t4j69XP39e1MvXLbbV_vfZmf54MmCZb1osLX0QWouy9LtW5ZZhpWWdemz44YCuUd2UiKk4ndBqpMaf0OmOlst40jk6rYtovvDTXkeI5xDBeiBc1JIwwhfLWKio714-cSH5lvyjGeuoEHUtpRBS8tQgzQ4S_K0_nscACpwNEXszoPWRrdcpXSXDmCpICr4PUGkoAoECcBEwuGBewKA3b1tC6fbKPN_jHw)
Takes a list of integers `i` and the integer `n` as arguments. Uses bitmasks to avoid lengthy *frozensets*.
Using one less layer of bitmasks might be a bit clearer, but [costs a byte](https://ato.pxeger.com/run?1=XU9LasMwEN3nFLMxkhwZIlmFYCJfJMlCIXYqLCvGUqCl7UmyMZT2Ij1Fb1NZVjZ9MN_3Zoa5fw-v_vlqp8-LPHzdfFtsf_dG9aezAk1tZRqL3_IW55p8kDWra7tqZeIVzTXt5Kbam0p272y3UwWjOdag7BmbuiNxMEgMWccV5JhO_LTXEXzjPGgLiPFSIIrYbAlzysvFiyfGBXsU_9KEOMp5WQrBuRAsEKhaQYC99admdCDBaOdxrwasrafxOiFRMoyhg1HGtg6KGjKHIAM8CyhccFpAoVcvj4IELK9M0xL_AA).
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ ~~10~~ ~~8~~ 7 bytes
*Edit: -2 bytes after inspiration from caird coinheringaahing, and then -1 byte by stealing the I/O idea from [emanresu A's answer](https://codegolf.stackexchange.com/a/242529/95126)*
```
-ṁPQ¹Ṗu
```
[Try it online!](https://tio.run/##yygtzv7/X/fhzsaAwEM7H@6cVvr///9oQx0jHWMdEyBpomOoYxwLAA "Husk – Try It Online")
Outputs a list of an empty list (`[[]]`) if a superpowerset, or a list containing nonempty lists otherwise.
```
u # Get uniqe elements of input,
Ṗ # and get all subsequences
- # now remove from this
ṁP # all permutations of
Q¹ # all contiguous sublists of the input.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ŒPŒ!ẇ€SɗƇƑ
```
[Try it online!](https://tio.run/##y0rNyan8///opICjkxQf7mp/1LQm@OT0Y@3HJv4/vNyl9tBSpaOTHu6cARSO/P/fREfB9L@hkbGJkYmhsY4CiGVqCGIDAA "Jelly – Try It Online")
Takes \$n\$ on the left, and a list of integers up to \$n\$ on the right
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes
```
Length[{}⋃Union/@Subsequences@#]==2^#2&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yc1L70kI7q69lF3c2heZn6evkNwaVJxamFpal5yarGDcqytrVGcspHa/4CizLySaGVdu7RoZR3fxAqgVKxaXXByYl5dNVe1oY6RjrGOSa0OkAkmdFAgRAioBM7QMdEx1QGxTIAkijBuIVSIapSZjjmQbQhmmwPFQDJmQB6IZQpWBVIBMgqkFqQOpMoIrNoQKGIMYtVy1f4HAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
ÞSvs?Uṗ$F
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnlN2cz9V4bmXJEYiLCIiLCJbMSwyLDMsNCwyLDQsMSwzXSJd)
Returns a list containing the empty list (`⟨ ⟨ ⟩ ⟩`) for truthy and a list containing nonempty lists for falsy.
```
ÞS # Sublists...
vs # Sort each
$F # Remove from...
ṗ # Powerset of...
?U # Unique symbols of input
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 84 bytes
```
And@@(Subsequences@s~ContainsAny~Permutations@#&/@Subsets@Union[s=IntegerDigits@#])&
```
[Try it online!](https://tio.run/##VYo9C8IwFEX/ilAQhUJ5@ZwKr@jiVhAncYg11Ax9xSYdROxfj9F28cCFey@nM@FuOxNcY2JbxopuiJvjePX2MVpqrEc/7XoKxpGv6DnVdujGkPyePGbrAn9u8HiidJ19eaBgWzvsXevSm12261gPjsKqwLbAFzAucshhIU/7GyGBCZjrX1mYHaUZCKk5MCU4SMaVFkwqEJozqUFxqd8xfgA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~83~~ 76 bytes
```
->l,n{!(z=*1..n).uniq{|w|[*z.combination(w)]-l.each_cons(w).map(&:sort)}[1]}
```
[Try it online!](https://tio.run/##VY7ZCoMwFER/pX0pKjFws0LB/ohIUbsFNLEuaDV@u41oHzowcIa5cKfuss/yiJbwUiA9Hb0xCgBj7eNOq/dkexsHI85NmSmdtspor/eTsMD3NH9dc6Mbl3GZVt7p3Ji69ecYknmpDjEQyhAg2IVcXs04EAYb/sGu7UZIAoxLCkQwCpxQIRnhApikhEsQlMtk/TrZwT7iAd/UU7UN@oGrBrfiCw "Ruby – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 98 bytes
```
lambda i,s:len(f(i))>>s
f=lambda i,*t:i and{1,len(i)>len({*i})or frozenset(i),*f(*t,i[1:],i[:-1])}
```
[Try it online!](https://tio.run/##bU/LTsMwELz7K6yc7Mig5tEDRu4RqadeuIUcDHXKSo4d2S6iVP0KDlz6df2R4IRAK5WVdi3NzI5nu114tabooe2sC9jvPIp961Vw6mXrPFijoYVA7qaiCG3EU69l@7yWGJjnWhnSEKB0sfCoEX9MGjhgadb7jA0SoIvh2adwoNbhxtkPZeI/kWBpQ9LAoMp4HSe/yWp6uIwEWOAZsnE@SO0VaqKBxmDwmDWswXCEocG6mtVCJMuEgyBpKzui3qRmuip5HXUOOkIpowgrfVavEm7FoCO6mvN6ZL3iTmwIsFa@D6fddw5MIMnp@HU6fiaVFcLFqMzRfmk4zvKiRKtt4FM@NII/yKPb/gJTXeF5cb0cHedZXmb/U2fi0j7Pi6Is86utbw "Python 3 – Try It Online")
Takes a list of numbers and the number of symbols.
In python, you can't have a set of sets, instead you have to use the immutable frozenset. The algorithm is quite simple, just check every substring. To do that, you can use the vararg-sublist trick, where f is called for every sublist of the input in length order. The recursion is stopped when we encounter the empty list. This means that if this is really a superpowerset, then the resulting set will contain \$2^s\$ elements (every subset, except the empty set plus a 1). We can then use a bitshift to check for that condition.
It's possible to replace `frozenset(i)` with `(*{*i},)` for -5 bytes, but I'm not sure if the order of the set expansion is well defined.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 74 bytes
```
[ dup members all-subsets rest swap all-subseqs [ natural-sort ] map ⊂ ]
```
[Try it online!](https://tio.run/##hZA9TgMxEIX7PcW7ACttfiU4AKKhQVRRCq8zgMWu17HHIlHkhpJjcpFlbCTCkgKPZH3z5s0U70lpHvz4@HB3f3uNV/KWOgTiIN8@ktX0i2o6sFciDJ6NfUav@KWO1uhhR9@NHvrWWCUnjQ5wnpiPzhvLuKmqUwV5JzSYYY4F0k9/pmmlyUb6s78stJD/cvafPq3LyyushZvCa9HyZCVdpmVxZUe@l73Zl12z4m5EmRdKVRo32EWHnvqWfIDquqsQ25Kwp8AIb8qd1X3ABpJf9EoUiRlbCdbh8@Md2zFTPX4B "Factor – Try It Online")
*"Is the power set of the input's alphabet a subset of the sorted sub-sequences of the input?"*
[Answer]
# JavaScript (ES10), 86 bytes
*Saved 14 bytes thanks to @tsh!*
Expects an array of symbols. Returns \$0\$ or \$1\$.
```
a=>(g=a=>new Set(a).size)(a.flatMap(x=>p=[...p,y=1<<x].map(v=>v&y?0:v|y),p=[0]))>>g(a)
```
[Try it online!](https://tio.run/##jY3NCoJAFEb3PUW4iBmwwTu/EM70BK1ahouhRjFMJcU0encbwWVK3@Iu7jnfvXfb2eb6zOt2X1Y3N6Z6tNqgTPtZutf27FpkMWnyt8PIkrSw7cnWqNem1hdCSB0OGuK4T8jDrzttut1wjA7dZ8ChN6IEY2Myf2K8VmVTFY4UVYZSNHUDoIwH3tj8YotgziKnbAVxAZTDqvEPn7P6SCoKXCgGVHIGgjKpOBUSuGJUKJBMqKk/fgE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
â à eÈá d@øX
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=4iDgIGXI4SBkQPhY&input=WyIxMjM0IiwKIjEiLAoiMTExMTExMTEiLAoiMTIzIiwKIjEyMzQ1MTI0MTMiLAoiMTIzNDI0MTMzMzMzMzMzIiwKIjEyMzQyNDEzIl0tbQ)
```
â - unique elements
à - combinations
eÈ - all?
á * permutations of that combination
d@ * any?
øX in input U
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 53 bytes
```
W⁻⪪θ¹υ⊞υ⌊ι≔⟦⟧ηFLθFE⊕ι✂θκ⊕ιF⬤κ⁼¹№κλ⊞ηΣX²Eκ⌕υμ¬⁻…¹X²Lυη
```
[Try it online!](https://tio.run/##VY89a8MwEIb3/oobT6AOdrJ1CqWFQlNMM5YOwlGtI2cp1kfy85WTSQsdT@@Hnnd0Jo7BcK1XR2wB9@RLwsOZKeOioVMailIwlOSwaBCZ5jIjKfX0sEuJJo9f3xqcnD8hAr5bP2WHi2TWe2/O@ObHaGfrsz1KUMOBabSt/aThv6Z@YztmFPVlKYYTdhqeQ/G5PfFqWnmcVAnLEK42Yi9w8pc4XskfG@vcnMI1RJLoR8j3cZ/GT7Z1/gXv0DJUtSkSqrXrN9t@223q44Vv "Charcoal – Try It Online") Link is to verbose version of code. Takes a string as input and outputs a Charcoal boolean, i.e. `-` for a superpowerset, nothing if not. Explanation:
```
W⁻⪪θ¹υ⊞υ⌊ι
```
Get the unique elements of the input.
```
≔⟦⟧η
```
Start collecting integers representing sets of unique elements.
```
FLθFE⊕ι✂θκ⊕ι
```
For each substring, ...
```
F⬤κ⁼¹№κλ
```
... if this substring only contains unique elements, then ...
```
⊞ηΣX²Eκ⌕υμ
```
... collect a bitmask of the unique elements.
```
¬⁻…¹X²Lυη
```
Check that all possible bitmasks were collected.
34 bytes for a specific input format:
```
FLηFE⊕ι✂ηκ⊕ιF⬤κ⁼¹№κλ⊞ηΣX²κ¬⁻…¹X²θη
```
[Try it online!](https://tio.run/##VY7BCsIwDIbvPkWOKVTQ6c2TiAfByXDHsUOZdS12retaffyaDhS8hCTfl590SvjOCZPS3XnAs7R9UKgYg3kuxRNPtvNykDbIG2rGoTa6k6g4PDj8M/Y92xuDRI9jFGbCNYeDizbklZmlKk4qJ9RxwMq9pceC4ojsFpXXZF5cwFLbOOFV2F7miJ83MnpCZTmlZsuhWXEgTmQzN1RpU7RtWr7MBw "Charcoal – Try It Online") Link is to verbose version of code. Uses the same algorithm, but takes an integer `n` and a list of integers less than `n` as input.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~8~~ 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
êæIŒ€{K
```
Only takes the string as input. Outputs `[""]` for truthy, and a list with additional items as falsey, which is allowed because of the flexible rule "*output can assume whatever form is most convenient. ... Additionally, anything may be used as a symbol provided it is distinct from all the other symbols.*" (taken from [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/242529/52210)).
If a truthy/falsey value was mandatory, a trailing `g` (length) could be added, because only `1` is [truthy](https://codegolf.meta.stackexchange.com/a/2194/52210) in 05AB1E.
[Try it online](https://tio.run/##yy9OTMpM/f//8KrDyzyPTnrUtKba@/9/QyNjEyMTQ2MA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w6sOL6s8OulR05pq7/8u9umZSgoaJUWlJRmVmkqHVwM5aYk5xalATq3O/2hDI2MTHUMdQyjQAfJB2MTU0MjEEMJEYUABRI2ZuZGhiam5saGRmYmxoamRsZm5iZGpmaGJubGRqbmhmbGpeSwA).
**Explanation:**
```
ê # Sorted uniquify the digits in the (implicit) input
æ # Pop and push its powerset list
I # Push the input
Œ # Pop and push its substrings
€{ # Sort each substring
K # Remove those from the powerset-list
# (after which the result is output implicitly)
```
] |
[Question]
[
In some parts of the world, phone numbers are fixed-length, apparently. That sounds boring, though.
For this challenge, your task is to take the digits of a what is presumed to be a valid phone number, and format it based on some simplified rules around what a phone number looks like.
### Input format
Your input will consist of nothing except the digits `0` through `9`, and the input will contain between five and ten of them (both inclusive). Every input *will* be a valid phone number, according to the following simplified rules:
* A full phone number consists of eight to ten digits and can be divided into an optional area code of two to four digits (the first of which is `0`), and a mandatory subscriber number of five to eight digits (the first of which is *not* `0`)
* When calling someone from a landline phone who has the same area code as you, you do not need to dial the area code. Thus, your program must be able to handle inputs consisting only of a subscriber number with no area code.
* The subscriber number consists of 5 to 8 digits, and the first one isn't `0`.
* The area code, if present, begins with `0`, and has 2 to 4 digits. For this challenge's purposes, the length depends on the second digit:
+ The second digit of the area code will never be `0`.
+ If the second digit is `8`, the entire area code will be 2 digits long (so the entire area code will be `08`)
+ If the second digit is `1`, `2`, `3`, `4`, or `7`, the area code will be 3 digits long.
+ If the second digit is `5`, `6`, or `9`, the area code will be 4 digits long.
* *However*, for some inputs, the above cutoff point would cause the subscriber number to be too short or begin with a `0`. Since we know the input is a valid phone number (because I say so) we have to conclude that the length of the area code is different from the above. If the length listed above does not work, you should pick a length which works, preferring 3-digit codes over 4-digit codes, and preferring either of those to 2-digit codes. You will not need to handle inputs like `0801234`, which are invalid for all those cutoff points.
### Output format
Your output should be the area code, followed by a dash (only if an area code is present), followed by the subscriber number which should be grouped in one of the following manners (with the groups separated by a single space):
```
xxx xxx xx
xxx xx xx
xx xx xx
xxx xx
```
That means numbers *with* area codes specified will have one of the following formats:
```
0x-xxx xxx xx
0x-xxx xx xx
0x-xx xx xx
0xx-xxx xx xx
0xx-xx xx xx
0xx-xxx xx
0xxx-xx xx xx
0xxx-xxx xx
```
## Test cases
All numbers were randomly generated, and some of them could potentially be in use, so while I don't expect any of them to belong to anyone in particular, please don't try to call them.
```
27983516 -> 279 835 16 # No area code, 8 digits
6278304 -> 627 83 04 # No area code, 7 digits
627830 -> 62 78 30 # No area code, 6 digits
11865 -> 118 65 # No area code, 5 digits
067934821 -> 0679-348 21 # Simple 4+5
0927586130 -> 0927-58 61 30 # Simple 4+6
0374821096 -> 037-482 10 96 # Simple 3+7
042807961 -> 042-80 79 61 # Simple 3+6
04629873 -> 046-298 73 # Simple 3+5
0897106384 -> 08-971 063 84 # Simple 2+8
081859302 -> 08-185 93 02 # Simple 2+7
08379451 -> 08-37 94 51 # Simple 2+6
0480936572 -> 0480-93 65 72 # Area code couldn't be 048 to prevent subscriber number starting with 0
0957024168 -> 095-702 41 68 # Area code couldn't be 0957 for the same reason
06057291 -> 060-572 91 # Area code couldn't be 0605 because of subscriber number's length
04809714 -> 04-80 97 14 # Area code could neither be 048 nor 0480 didn't help
080062517 -> 0800-625 17 # Area code could neither be 08 nor 080
09106574 -> 09-10 65 74 # Area code had to be shortened twice from 0910 because shortening it to 091 didn't work
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest code in each language wins.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~78~~ 73 bytes
```
(0(8|[569].?.?|..?0?)(?=[^0]....))?(...?)?(...?)(..)$
$1$#1*-$3$#3* $4 $5
```
Inspired by both [*@mazzy*'s PowerShell answer](https://codegolf.stackexchange.com/a/195790/52210) and [*@NahuelFouilleul*'s Perl 5 answer](https://codegolf.stackexchange.com/a/195791/52210), so make sure to upvote them both as well!
-5 bytes thanks to *@Neil*.
[Try it online.](https://tio.run/##NU27SkNBEO33KwJZYW/AZd6PQrb0I0JECwsbC7HMv1/nQpxizuE8Zn4@f7@@P3B/Gq/v@4AR96ta3uaa6z7ngrWN9XJ9g9us2bY1CtY/1N5669jPeHnu3M98OXU5dd138gxWtGbkwSAPbIhh2sA8WYKwQZJrGJYF7IcEaQ2EAjytfDHKcG4Q6QjGIUUxNBmoGHuKHrGAZFMvLdWBBC3qDZSSD9vxqAIYKXrF6pq6/AE)
**Explanation:**
Match the digit groups like this:
```
( )? # An optional group 1, which consists of:
0 # A leading 0
( | | ) # followed by either (ignored inner group 2):
8 # A single 8
|[569] # or one of 569,
.?.? # with one or two optional chars
|. # or any character,
.? # with one optional character,
0? # and an optional trailing 0
(?= ) # followed by an uncaptured inner group with:
[^0] # A character which is NOT a 0
.... # followed by any four characters
( )? # An optional group 3, which consists of:
.. # Two characters,
.? # followed by an optional character
( ) # A mandatory group 4,
...? # which is similar as group 3
( ) # Followed by a mandatory group 5
$ # (at the end of the string), which consists of:
.. # Any two characters
```
Then replace it with:
```
$1 # The content of group 1 (possibly empty)
$#1* # If group 1 isn't empty:
- # A "-"
$3 # The content of group 3 (possibly empty)
$#3* # If group 3 isn't empty:
<sp> # A " "
$4 # The content of group 4
<sp> # A " "
$5 # The content of group 5
```
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), ~~92~~, 84 bytes
```
s/(0(8|[569].?.?|..?0?)(?=.{5})(?!0))?(...?)?(...?)(..)$/$1-$3 $4 $5/;s/^\D*|-\K //g
```
[Try it online!](https://tio.run/##PU3LSsRAELzPV0TIIREy0z0z/UJkLt78BFdvIguLG8zeNv66sQOrl66iqrpqfv860bYtaYBB1xdie40ttjXGBm0c2mO80rfjHYxjG6LLf@B37FOPU1@6vnY9pYclvR2e7tfp8Nyl9LFtWUwLIQfOogXqDQOiMgVgsVI1YwDLQsroFpDsEhgHqFlBjN2vnE2lBFATBC5anaKSFcjOililPaZghUlcMxLIFVl9xjuz3WzB/RWAM6F4zNt8MUD5n/05z5fj@XPZptP8Cw "Perl 5 – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~135~~ ~~127~~ ~~118~~ ~~107~~ 105 bytes
*-1 byte thanks @Kevin Cruijssen*
```
$args-replace'(0(8|[569].?.?|..?0?)(?=[^0].{4}))?(...?)?(...?)(..)$','$1-$3 $4 $5'-replace'^\D+|(?<=\D) '
```
[Try it online!](https://tio.run/##bZPLbttADEX3/goimFYS6hE4b7KooS6y7g/khTSZNAu3ce0ELWD7211KsR42qoUEHR2RnDuY1cufvN485@XyoJ5gAduDul//2Oh1Xi3vH3JRYkm7qxD5pm7qZlfXDTZV2SyubvGm3vp9VTVlLbR/yL1SxbxQRisHyoMKxVDs9vry065sviyuLysoDvvZ7Gs5A7nmZWETkwsmFt07QAtACAiqeinaRA5953SSAJFA0JnzrhwdSASCBsUYiuFodIoAEDIIGBM7T9YUR6EFWggIGi22KVA0XbfOEqCDlDIn7TCkthZy7D0BmiwYBJ6sDt2555L2//G8JUwcx@m81YQggcXpeD5apuSGRAVoISBolIiTwejI9z1JCwFBQH7qGQrs0A49SQsBlvDtVHOJfTBjT9IuAXsIJ5MRsosh2b6pAC2lYoA0rcYhofUm0hBw0ELAGxA22S5J1PKka0QtBPi8aTJ@EkcbGicwJ@tEjDaYNK4TUQsBQZPBJDPZxLEWa9mkdvy2VgU7@ADbzlar55df@dvbz@9yzuag8t9VfnjNj3LW1N27sc6bt@WrgI9yBE/87vuFKo@Kzr@H/6vP/Y8Xs/3hHw "PowerShell – Try It Online")
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 554 bytes
```
#it's the source patterns
s=r'''xxx xxx xx
xxx xx xx
xx xx xx
xxx xx
0x-xxx xxx xx
0x-xxx xx xx
0x-xx xx xx
0xx-xxx xx xx
0xx-xx xx xx
0xx-xxx xx
0xxx-xx xx xx
0xxx-xxx xx'''.split('\n')
import re
#now we make pattern matchers for each of them,
#assuming 0 does not start a short number (^) or the first group after '-'
m=[re.compile('^'+
re.sub(r'(^)?(\-)?(x+)',
lambda m:
(lambda x:
[r'(\d{%d})'%x,r'([1-9]\d{%d})'%(x-1)]
[(m.group(2)!=None)or(m.group(1)!=None)])
(len(m.group(3))),i)
.replace(' ','')
+'$')
for i in s]
f=lambda i:(lambda k,v:re.sub('x+','%s',k)%v)(*(
#then we sort matching patterns by
#first character in ['','8','12347','569'][len(first_group)]
#and by len(first_group)
#and take the last elem. It will be with key (True,n) or
#(False,max(n)) if n is the first group's length
sorted(
[(k,v.groups()) for j,k in zip(m,s) if (v:=j.match(i))],
key=lambda x:((g:=x[1][0])[0] in ['','8','12347','569'][len(g)],
len(g)) )[-1]))
```
[Try it online!](https://tio.run/##hVXbjuI4EH3PV9Sqt2V7SJCdq4PEjPYH5mUfQ0ZKg4EMuckJ3Zm9fHtPObeGZVeLCHYdn1M@djmm@dGd68qTjX5/b7eaENL3PYyPNTZjD24hi/fODW@JlmDp34/865Dp3g/MI@hm3TZF3lGyqwiz8rKpdQdaWeU20Wq9r8smLxQl38gKw/b6QjWh39gXunPwp18xYhdZ@XLIoNzQqddvEiTtDn8@H/5m5Lm3MUqEE6cLRHtHsNRKaLk@6fraUJf9sv1aV4rVesHEjKWMFqpacI8xZudsrVVTZHv0BsQmhK3Ir4Qdaw055BW0qXXcTn7yxdnFft1MyyD9CmXPLbEv7PmV0U@0xZWrA00ossapWsoYmJTf7YtJ@kfe0NJuGeRHoK@b7fd1mXX7M80ZS@2L@rFdNoDS02bbJyJNeMrwMeqE4IQSH@F6foRtEMYkTczSTqgfW8YSR6SMvffDUXGjWHqBCAE/zmcAjAEBGBF4gq81ZFplsK8PygYJh/yUd60VupH0uA@zDmPUwYQ86KJ7HdzoIJIwIw@6cNYJIcMAPnQYwwI86oJZx8Mo9nzpiklnYgcBGBDU/Y4nslDgrwKLx24UyFAYNwMXYyfAecRg8IZrNsfiQWQS8zic6Bg70gXBwUAL3VtFFvddyaM4XGz4riM54GYP0A03RG7oxjLyYOGGDgIwIrdctCzjSPDQk/7ElQ4CuEoPDLRw3ZVErpBB7HEXFi4CEGPVXLjjol/pRbEfCPjgehHEPgT32@YOfiWPvTCI3Nmv5A5mxfIY6Al@m@uCP9fiUJEOXpShQVdDo9WrqjrAV6bd6/xFaaiupWnaLtNdXp3gLe/OwLE8QcRdX4RyLk/gIAC@AAP95zwoG96x7qygzUqFl0/W1hUeDayYG3@sMeSOWcSI/DPfkg5V2O6za6ugPj76Ji3gm3bqzuPGRML/KKSpeRzBCD0YhkrhSjHRtDsVmjY58CwPs59V0WBlOA/dQERLZTh3EIAB@Z@kU05pNhOPDR7YxVvs4Lk1JXvwds4OplCob8/mBqsUxm/5XsFR1yWYTMuGjAxtqpZ3RoWjs/23Wl/wxrH64eIf/xQ02bWf6JcNfnfO7jP7y3SeGEOU4BUMy3Xb3/6LpFaDU3Q0Kwp6xMtxu81Gpp3Z@4GN99tP "Python 3.8 (pre-release) – Try It Online")
I see it can be shortened by `sum(len(j)-1 for i in s for j in re.findall('x+',i))==50` bytes by replacing 'x' repeating n times by n, but I just wanted to demonstrate the approach.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 246 bytes
```
s=>{int a=s[1]-'0',b=0,c=s.Length,d,e;bool f=s[4]==48,g=s[2]==48;var h="";if(s[0]==48){b=a==8?2:a<5|a==7?3:f?3:4;b=s[3]==48?!g&c-b<6?2:f?3:4:g?3:b;h+=s.Substring(0,b)+"-";}for(d=b;d<c-1;d+=e)h+=$"{s.Substring(d,e=c-b==6?2:c-d<5?2:3)} ";return h;}
```
[Try it online!](https://tio.run/##dVA7b8IwEN77K9KoKolIqvPbxjFsndg6dEAMcd5SFaQkdKH8dmrCUhUz2He673GfXYxpMXaX92NfZOM0dH2T3Mo6qANzGc361PVTkJtxh/bpAhaJNZAUZnzbVn0ztUmZVNoeDl9B7Sh0bwyVSeNaPLf6Ox@C1oSh7upo3ME8jE/W5MbIDV7lGftxrdiQVe0O1dZJyczaPDevRWoz7mgztmrcbXW7dMs/jvYWM4LExsswDfW5PgxRaawusyJFulyaKnbcl/D0l@7iGudqzNW2SMuMuUricxDqoZqOQx@0@nzRT59DN1Xbrq@iOgqxUJIwxMM4/odwLCQB@gi4nyMkObsfAxeKUImRB1JYMMmRzw2IuIpAeaIBxRKE4j5LyrGSgngQqQQCTiT1YUgyRQD7ICIUZd5VEhThTPhUignAFHHp@xBwGvXIUSBvQACOGRK@Ve5VTMyiyy8 "C# (Visual C# Interactive Compiler) – Try It Online")
```
int a = s[1]-'0' //int value of second char
b = 0, //area code length
c = s.Length, //length of the input
d, //for loop iterator
e; //length of the current number group
bool f = s[4]==48, //5th digit is 0
g = s[2]==48; //3rd digit is 0
var h=""; //output string
if(s[0]==48) //starts with 0 / is area code
{
b=a==8?2:a<5|a==7?3:f?3:4; //set area code length from subscriber number
b=s[3]==48?g&c-b<6?2:f?3:4:!g?3:b; //modify area code length according to special 0's
h+=s.Substring(0,b)+"-"; //append area code to output
}
for(d=b;d<c-1;d+=e) //iterate the non area code numbers
{
h+=$"{s.Substring(d,e=c-b==6?2:c-d<5?2:3)} "; //append number group of 'e' length
}
return h;
```
[Answer]
# [Python 3](https://docs.python.org/3/), 128 bytes
```
lambda x:re.sub(r'^\D+|(?<=\D) ','',re.sub(r'(0(8|[569].?.?|..?0?)(?=[^0].{4}))?(...?)?(...?)(..)$',r'\1-\3 \4 \5',x))
import re
```
[Try it online!](https://tio.run/##PYvNCoJAFEb3PcUsgnsv2TDmTxrJbHwLr4KikpA/TAZG9uyTm9p8B87hm17zbRw82yZs72Vf1aVYLqaRj2eFBgpODyvqa8IpCXAAnH9ChdGaBWGcSy31KqVWmlAnWaFy@fY/RBrlZn/YlvbbH9g9sifYFxyAsxDtun4azSxMYyfTDTO2CCo@nYModD0FRPYL "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~284~~ 267 bytes
```
(n,B=I=>+n[I]&&n.length-I>4,A=a=>a.includes(n[1]),b=B(0),L=A('8')?2:A('569')?4:3)=>(b?'':n.slice(0,B(L)?L:L=L>3?B(3)?3:2:L>2?B(4)?4:2:B(4)?4:3))+(b?'':'-')+n.slice(b?0:L).replace(/./g,(e,i,T,U=e+' ')=>T[5]?T[6]?T[7]?i==2|i==5?U:e:i==2|i==4?U:e:i==1|i==3?U:e:i==2?U:e)
```
[Try it online!](https://tio.run/##TVJNb5tAEL3zK@YUWJnF@/1BtaC4p0gcnV5cSyHOJnVLsRWcSpX6390hwTgcYN57vDczq/3Z/mmH3ev@eKL94Smen8M56/NVuAvVot/cbW9u@qKL/cvpB72rVH4b2lC1xb7fdW9Pccj6Dd@S/DGsMkbyJtxmqUtJLUostPFYqlKSUGWPdZqWfTF0@13MWL7KGlI3ZROaStarTJJalqJsKoFAjSZRToUkZPHhTmlKFpeIx5qVDSle47FrES6L5UuexXyfr/P7EBcppNh1vdHber0x48tu630I4h@@dH1fxvKC1AXxEclZGwty3h364QSnOJy@tkMcIMCDsN5JzQ3gQysAxIAEcJMYYZ1kCi4SYpSAqUmBTwpYB5IlnDuj4SogBqMTZqyXygk@0SOmSIDgCfPCamf4mPeuIaYabXwMZNKOPubNpEpLkQDOwJuEKeGY9WbOVYI6BriCwWBlhHdWwiwaigRYmTDnLWdGOjVJjiKBY0lwClXutJdMwKwiAR5XFyhK65XmcBWlBa9Ajx0d89JoKy4dHaNowyOx6PTaMqG4cZdFNUUCFAfj8IgY@vw11zA6Bvkp1nJ1XWRc0lvg46yMGaG5ncdhjCIB3GJD3FHbq89TPLZxGPVQDMduf8rS731KviQf9@JX/Put7d7e78V8R4rf7TGLHYQKYje5lrDAvMWSTNZDF4vu8JLNAZ9Mz/jdsC3Bf8//AQ "JavaScript (Node.js) – Try It Online")
**No regex** except for the basic `/./g`, and that's the way I want it to be.
] |
[Question]
[
Create a program that outputs itself.
However, if the source code is repeated n times *(meaning to concatenate a copy of the source code to the end n-1 times)*, then there should be 1/n probability outputting the original source code, a 1/n probability of outputting the source code repeated twice, a 1/n probability of outputting the source code repeated three times, ..., and a 1/n probability of outputting the source code n times.
For example, if your program is `foobar`, then it should always output exactly `foobar`.
However, if you run `foobarfoobarfoobarfoobar`, then there should be a ¼ chance each of outputting `foobar`, `foobarfoobar`, `foobarfoobarfoobar` and `foobarfoobarfoobarfoobar`.
* The distribution of each possible output should be equal
* In addition to standard I/O methods applying and standard loopholes forbidden, standard quine rules apply (can't access its own source, etc.)
* This is code golf so shortest answer in bytes wins
[Answer]
# [Perl 5](https://www.perl.org/), ~~82~~ 80 bytes
```
$s=q($s=q(%s);printf"$s\n+1#",$s for 0..rand);printf"$s\n+1#",$s for 0..rand
+1#
```
[Try it online!](https://tio.run/##K0gtyjH9/1@l2LZQA0yoFmtaFxRl5pWkKakUx@RpGyor6agUK6TlFykY6OkVJealEJLnAor9/w8A "Perl 5 – Try It Online") or [Test suite](https://tio.run/##K0gtyjH9/18lOT8lVcFWQcUxyD0s2iC2AsIwjLXmKijKzCtRUFIAAteK1OTSksy8dKuYPLCOmDyQcFBqcWlOCVBMyZortSwxRwEsZ/0faGyxbaEGmFAt1rQGm5SmpFIck6dtqKyko1KskJZfpGCgp1eUmJdCSJ4LKPbfCAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 22 bytes
```
“Ṿ;ẋŻɼLX¤¤µ”Ṿ;ẋŻɼLX¤¤µ
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO/dZP9zVfXT3yT0@EYeWAOHWRw1zsYj@/w8A "Jelly – Try It Online")
[Try it x4!](https://tio.run/##y0rNyan8//9Rw5yHO/dZP9zVfXT3yT0@EYeWAOHWRw1zsYoOvNr//wE)
```
“Ṿ;ẋŻɼLX¤¤µ”Ṿ;ẋŻɼLX¤¤µ
“Ṿ;ẋŻɼLX¤¤µ” String literal: Ṿ;ẋŻɼLX¤¤µ
Ṿ Uneval. Return “Ṿ;ẋŻɼLX¤¤µ” (with quotes)
; Append the initial string. Yields the source code.
ɼ Apply the preceding link to the register and store the
result in the register.
Ż Prepend 0.
Each time Żɼ is used when the source code is repeated
the register's length increases by one.
We can't use ‘ because it closes string literals.
L Length. Returns the number of times the source code has
been repeated up till now.
X Random element. If ɼ results in n, X returns a random
integer between 1 and n.
¤ Combines ŻɼLX as a nilad.
ẋ Repeat the source code a random number of times between
1 and n.
¤ Close everything from the initial string literal as a
nilad.
µ Start a new monadic chain. The register gets updated
once for time the code is repeated but only the final
repetition will result in output.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 32 bytes
```
"34çìDJ¼32ôн¾L×Ω"34çìDJ¼32ôн¾L×Ω
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fydjk8PLDa1y8Du0xNjq85cLeQ/t8Dk8/txKX@P//AA "05AB1E – Try It Online")
**Explanation**
```
"34çìDJ¼32ôн¾L×Ω" # push this string
34ç # push a "-character
ì # prepend it to the string
DJ # duplicate and join the copy to the string
¼ # increment the counter
32ô # split the string into pieces of size 32
н # take the first one
¾L× # repeat it for each in [1 ... counter]
Ω # pick one at random
```
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 21 bytes
```
:QoaonC|P\Sx*F2ssS"
0
```
[Try it online!](https://tio.run/##S8/PScsszvj/3yowPzE/z7kmICa4QsvNqLg4WInL4P9/AA "Gol><> – Try It Online")
### Explanation:
```
:Q | If the top of stack is 0, skip to next |
Top of stack is implicitly 0
P Increment top of stack
\ Redirect pointer down]
0:QoaonC|P\Sx*F2ssS" Increment for each copy of the source code
0:QoaonC|P\Sx*F2ssS"
\ Redirect back to the right
Sx* Multiply the number of copies of the source code by a random number between 0 and 1
F Repeat that many times
2ss Push a double quote
S" Print the source code minus the quote, newline and 0
:Q If top of stack is not 0
oaonC Print the quote, a newline and a 0 to complete the source code and continue the loop
\Sx* Error on the * for some reason
```
[Answer]
# [Alice](https://github.com/m-ender/alice), 35 bytes
```
"d3a*h-&;adddd12h&}Uh*t&w.odt,k@
!
```
[Try it online!](https://tio.run/##S8zJTE79/18pxThRK0NXzToxBQgMjTLUakMztErUyvXyU0p0sh24FBT//wcA "Alice – Try It Online")
### Explanation
```
"
```
Like in many quines in 2D languages, this starts with a `"` that wraps around to itself and pushes the entire first line except the `"` itself.
```
d3a*h-&;
```
Adding one or more additional copies of the source code will place some implicit spaces at the end of the string literal. To make this actually a quine, we truncate the stack at 31 characters.
```
addd
```
Push a newline, then the stack height three times. The values pushed as the stack height are 32 (the space in the second line), 33 (the `!` in the second line), and 34 (the initial `"`).
```
d
```
Push the stack height again, this time as the length of the original source code (35).
```
1
```
Initialize a counter at 1. This will count the number of times the source code is repeated.
```
2h&}
```
Turn right three times in place (i.e., turn left). Each additional repetition of the source code will contribute an `h` in the same column as this `}`, thus incrementing the counter. When the IP returns to the `}`, turn right again to continue in the same direction.
```
Uh
```
Take a uniform random number from 0 to n-1, then add 1 to get the number of times to output the original source.
```
*t&w
```
Multiply by the previously pushed stack height (code length), then repeat the following that many times by pushing a return address that many times minus one.
```
.o
```
Output the top of the stack without destroying it.
```
dt,
```
Move the bottom stack entry to the top.
```
k@
```
Repeat, then terminate after the loop is finished.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 62 bytes
```
(f=a=>b=>b?f(a+.5):`(f=${f})(1)`.repeat(1+Math.random()*a))(1)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@cn1ecn5Oql5OfrvFfI8020dYuCYjs0zQStfVMNa0SgGIq1Wm1mhqGmgl6RakFqYklGobavoklGXpFiXkp@bkamlqJmiDp/xqamv8B "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 58 bytes
```
≔´θ´⎚´×´⊕´‽´L´⊞´O´υ´ω´⁺´⪫´⁺´´´≔´θ´´´´´θθ⎚×⊕‽L⊞Oυω⁺⪫⁺´≔θ´´θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R55RDW87tOLTlUd@sQ1sOTwcyuqYCiYa9h7a837MGxJ0HYq0/tOV8KxB3AkUadwGJVauhLBCEmwKD53ac2wE08fB0oGlAs4AmAc0BmnK@9XwnUBdQN8SUzikQXed2/P8PAA "Charcoal – Try It Online") No verbose version because the deverbosifier currently chokes on `"´"`. Mostly based on the Charcoal quine from [Golf you a quine for great good!](https://codegolf.stackexchange.com/questions/69). Explanation:
```
≔´θ´⎚´×´⊕´‽´L´⊞´O´υ´ω´⁺´⪫´⁺´´´≔´θ´´´´´θθ
```
Assign the literal string `θ⎚×⊕‽L⊞Oυω⁺⪫⁺´≔θ´´θ` to `θ`.
```
⎚
```
Clear any previous output, so that only the last output takes effect.
```
×⊕‽L⊞Oυω
```
Push the empty string to the predefined array. This makes the array length equal to the number of repetitions processed so far, so take its length, take a random number the implicit exclusive range, add 1, and repeat the following string that many times.
```
⁺⪫⁺´≔θ´´θ
```
Prepend the literal string `≔` to `θ`, then insert literal `´`s between each character, then suffix another copy of `θ`.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~118~~ 116 bytes
```
for i in(1,c:=0):
exec(s:="from random import*;c+=i or print('for i in(1,c:=0):\\n exec(s:=%r)#'%s*randint(1,c))")#
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFTITNPw1An2crWQNOKSyG1IjVZo9jKVimtKD9XoSgxLwVIZeYW5BeVaFkna9tmKgD1FBRl5pVoqGNoj4nJgxugWqSprK5arAUyAqQaqEZTU0lT@f9/AA "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
## Introduction
You may know and love your normal unit circle. But mathematicans are crazy and thus they have abstracted the concept to any point that satisfies `x*x+y*y=1`. Because Cryptographers1 are also weird, they *love* finite fields and *sometimes* finite rings (it is not like they have much choice though), so let's combine this!
## The Challenge
### Input
A positive integer larger than one in your favorite encoding. Let's call this number n.
### Output
You will output the "picture" (which consists of n times n characters) of the unit circle modulo the input integer as ASCII-Art using "X" (upper-case latin X) and " " (a space). Trailing spaces and newlines are allowed.
### More Details
You have to span a coordinate system from bottom-left to top-right. Whenever a point fulfills the circle equation, place an X at the position, otherwise place a space.
The condition for a point to be considered part of the circle border is:
`mod(x*x+y*y,n)==1`.
Here a quick illustration of the coordinate-system:
```
(0,4)(1,4)(2,4)(3,4)(4,4)
(0,3)(1,3)(2,3)(3,3)(4,3)
(0,2)(1,2)(2,2)(3,2)(4,2)
(0,1)(1,1)(2,1)(3,1)(4,1)
(0,0)(1,0)(2,0)(3,0)(4,0)
```
If it helps you, you may also invert the direction of any of the axes, but the examples assume this orientation.
## Who wins?
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in byte wins! [Only the default I/O methods are allowed](https://codegolf.meta.stackexchange.com/q/2447/55329) and all standard loopholes are banned.
## Examples
Input: 2
```
X
X
```
Input: 3
```
X
X
XX
```
Input: 5
```
X
X
X X
```
Input: 7
```
X
X X
X X
X
X X
```
Input: 11
```
X
XX
X X
X X
XX
X
X X
```
Input: 42
```
X
X X
X X
X X
X X
X
X X X X
X X X X
X
X X
X X
X X
X X
X
X X X X
X
X X
X X
X X
X X
X
X X X X
X X X X
X
X X
X X
X X
X X
X
X X X X
```
---
1 I suggest you take a look at my profile if you're wondering here.
[Answer]
# Bash + GNU Utilities, 59
```
x={0..$[$1-1]}d*
eval echo $x$x+$1%1-0r^56*32+P|dc|fold -$1
```
Input `n` given as a command-line parameter. The y-axis is inverted.
[Try it online](https://tio.run/nexus/bash#@19hW22gp6cSrWKoaxhbm6LFlVqWmKOQmpyRr6BSoVKhrWKoaqhrUBRnaqZlbKQdUJOSXJOWn5OioKti@P//fxMjAA).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~45~~ 44 bytes
```
@(n)[(mod((x=(0:n-1).^2)+x',n)==1)*56+32,'']
```
[Try it online!](https://tio.run/nexus/octave#@@@gkacZrZGbn6KhUWGrYWCVp2uoqRdnpKldoa6Tp2lra6ipZWqmbWyko64e@z8xr1jD0FDzPwA "Octave – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 68 bytes
```
f n|r<-[0..n-1]=unlines[[last$' ':['X'|mod(x*x+y*y)n==1]|y<-r]|x<-r]
```
[Try it online!](https://tio.run/nexus/haskell#@5@mkFdTZKMbbaCnl6drGGtbmpeTmZdaHB2dk1hcoqKuoG4VrR6hXpObn6JRoVWhXalVqZlna2sYW1Npo1sUW1MBIv/nJmbmKdgqFKUmpvjkKdjZ2SoUlJYElxQp6Cmk/TcxAgA "Haskell – TIO Nexus") The y-axis is flipped. Usage: `f 42` returns a newline delimited string.
This is a nested list comprehension where both `x` and `y` are drawn from the range `[0..n-1]`. `last$' ':['X'|mod(x*x+y*y)n==1]` is a shorter form of `if mod(x*x+y*y)n==1 then 'X' else ' '`. The list comprehension evaluates to a list of strings which is turned into a single newline separated string by `unlines`.
[Answer]
## Mathematica, 56 48 bytes
*Edit: Thanks to Greg Martin and Martin Ender for saving 8 bytes.*
```
Grid@Array[If[Mod[#^2+#2^2,x]==1,X]&,{x=#,#},0]&
```
## Original solution:
```
Grid@Table[If[Tr[{i-1,j-1}^2]~Mod~#==1,X,],{i,#},{j,#}]&
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 23 bytes
```
ri:X,2f#_ff{+X%(S'X?}N*
```
[Try it online!](https://tio.run/nexus/cjam#@1@UaRWhY5SmHJ@WVq0doaoRrB5hX@un9f@/iREA "CJam – TIO Nexus")
```
ri:X e# Read input, convert to integer, store in X.
, e# Turn into range [0 1 ... X-1].
2f# e# Square each value in the range.
_ff{ e# 2D map over all pairs from that list.
+ e# Add the two values in the current pair.
X% e# Take the sum modulo X.
( e# Decrement, so that x^2+y^2==1 becomes 0 (falsy) and everything
e# else becomes truthy.
S'X? e# Select space of 'X' accordingly.
}
N* e# Join rows with linefeeds.
```
[Answer]
## JavaScript (ES6), 81 bytes
```
f=
n=>[...Array(n)].map((_,x,a)=>a.map((_,y)=>(x*x+y*y)%n-1?` `:`X`).join``).join`
`
```
```
<input type=number oninput=o.textContent=f(+this.value)><pre id=o>
```
The Y-axis is the reverse of the OP.
[Answer]
# [Röda](https://github.com/fergusq/roda), 74 bytes
```
f n{seq n-1,0|{|y|seq 0,n-1|{|x|["X"]if[(x^2+y^2)%n=1]else[" "]}_;["
"]}_}
```
[Try it online!](https://tio.run/nexus/roda#@5@mkFddnFqokKdrqGNQU11TWQPiGegA@UBeRU20UoRSbGZatEZFnJF2ZZyRpmqerWFsak5xarSSglJsbbx1tBIXiK79n5uYmadQzcWZpmBixFX7HwA "Röda – TIO Nexus")
Ungolfed:
```
function f(n) {
seq(n-1, 0) | for y do
seq(0, n-1) | for x do
if [ (x^2 + y^2) % n = 1 ] do
push("X")
else
push(" ")
done
done
print("")
done
}
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~87~~ 83 bytes
```
lambda n:"\n".join("".join(" X"[(y*y+x*x)%n==1]for x in range(n))for y in range(n))
```
[Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqiQZ6UUk6ekl5WfmaehBKMVIpSiNSq1KrUrtCo0VfNsbQ1j0/KLFCoUMvMUihLz0lM18jQ1QSKVKCL/QUKZIKFoIx0FYx0FUx0Fcx0FQ0MdBROjWCsuhYKizLwSjUxNGCsNyIZzNP8DAA "Python 3 – TIO Nexus")
The y-axis is inverted
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~14~~ 13 bytes
```
R²+þ`%=1ị⁾X Y
```
The x-axis is inverted.
[Try it online!](https://tio.run/nexus/jelly#@x90aJP24X0JqraGD3d3P2rcF6EQ@f//fxMjAA "Jelly – TIO Nexus")
### How it works
```
R²+þ`%=1ị⁾X Y Main link. Argument: n
R Range; yield [1, ..., n].
² Square; yield [1², ..., n²].
+þ` Self table addition; compute x+y for all x and y in [1², ..., n²],
grouping by the values of y.
% Take all sums modulo n.
=1 Compare them with 1, yielding 1 or 0.
ị⁾X Index into "X ".
Y Separate by linefeeds.
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 79 bytes
```
?dsRsQ[88P]sl[32P]sH[0sM[lM2^lR2^+lQ%d1=l1!=HlM1+dsMlQ>c]dscx10PlR1-dsR0<S]dsSx
```
The `y`-axis is inverted whereas the `x`-axis is not.
[Try it online!](https://tio.run/nexus/dc#@2@fUhxUHBhtYREQW5wTbWwEpDyiDYp9o3N8jeJygozitHMCVVMMbXMMFW09cnwNtVOKfXMC7ZJjU4qTKwwNAnKCDHWBRhjYBANFgiv@/zcxAgA "dc – TIO Nexus")
[Answer]
# [Python 3](https://docs.python.org/3/), (102 98 95 bytes)
### y-axis inverted
```
n=int(input());r=range(n);p=print
for i in r:
for j in r:p(end=' 'if(i*i+j*j)%n-1else'X')
p()
```
[Try it online!](https://tio.run/nexus/python3#JckxCoAwDADAva/IIk0UB8VJ6T9cBVtJkRiivr8qjscVCSwXsuh9IdFkwRbZIgpNGtTec@kwYGABGx18yD8Uo6zBg@eEXHOT60yVtF3cz@hnTw4UqZShdw8 "Python 3 – TIO Nexus")
* saved 4 bytes: omitted variable c in c=' 'if(i*i+j*j)%n-1else'X'
* saved 3 bytes: Thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs) (modified print statement)
[Answer]
## [Lithp](https://github.com/andrakis/node-lithp), 125 bytes
```
#N::((join(map(seq(- N 1)0)(scope #Y::((join(map(seq 0(- N 1))(scope #X::
((?(== 1(@(+(* X X)(* Y Y))N))"X" " "))))""))))"\n")
```
Linebreak for readability.
[Try it online!](https://andrakis.github.io/ide2/index.html?code=JSBBbiBlbnRyeSBmb3IgYSBDb2RlZ29sZiBjaGFsbGVuZ2U6CiUgaHR0cDovL2NvZGVnb2xmLnN0YWNrZXhjaGFuZ2UuY29tL3F1ZXN0aW9ucy8xMTQ4NDcvZHJhdy1tZS10aGUtd2VpcmQtdW5pdC1jaXJjbGUKJSBGb3IgYmVzdCByZXN1bHRzLCBleHBhbmQgdGhlIG91dHB1dCB3aW5kb3cgYmVsb3cuCigKICAgIChpbXBvcnQgbGlzdHMpCiAgICAlIFVuZ29sZmVkOgogICAgKGRlZiBmICNOIDo6ICgKICAgICAgICAoam9pbiAobWFwIChzZXEgKC0gTiAxKSAwKSAoc2NvcGUgI1kgOjogKAogICAgICAgICAgICAoam9pbiAobWFwIChzZXEgMCAoLSBOIDEpKSAoc2NvcGUgI1ggOjogKAogICAgICAgICAgICAgICAgKD8gKD09IDEgKEAgKCsgKCogWCBYKSAoKiBZIFkpKSBOKSkgIlgiICIgIikKICAgICAgICAgICAgKSkpICIiKQogICAgICAgICkpKSAiXG4iKQogICAgKSkKICAgICUgR29sZmVkOgogICAgKGRlZiBmICNOOjooKGpvaW4obWFwKHNlcSgtIE4gMSkwKShzY29wZSAjWTo6KChqb2luKG1hcChzZXEgMCgtIE4gMSkpKHNjb3BlICNYOjooKD8oPT0gMShAKCsoKiBYIFgpKCogWSBZKSlOKSkiWCIgIiAiKSkpKSIiKSkpKSJcbiIpKSkKICAgIAogICAgJSBUZXN0czoKICAgIChlYWNoIChzZXEgMiAzMCkgKHNjb3BlICNOIDo6ICgKICAgICAgICAocHJpbnQgIkZvciBOPSIgTiAiOlxuIiAoZiBOKSkKICAgICkpKQogICAgKHByaW50IChmIDQwKSkKKQ==)
Not the shortest. I think I need some sort of shorthand module. See the Try it Online link for further explanation, ungolfed version, and some tests. For best results, expand the output window to see more.
[Answer]
# [Python 3](https://docs.python.org/3/), 82 bytes
```
f=lambda n,k=0:k<n>f(n,k+1)!=print(''.join(' X'[(k*k+j*j)%n==1]for j in range(n)))
```
[Try it online!](https://tio.run/nexus/python3#DcZBDkAwEADAr6yDdFdFECex3iERhwqVtixp/L/MaZLl01zrZkDKwHUfBhkt/tcNZfxEJy8qVfnbCSqY1IyhCNoXnnJhbhZ7R/DgBKKRY0chomSxayl9 "Python 3 – TIO Nexus")
[Answer]
# [GNU APL](https://www.gnu.org/software/apl/), 41 chars, 59 bytes
Reads an integer and displays the circle.
```
N←⎕◊⌽{(⍵+1)⊃' ' 'X'}¨{1=(N|(+/⍵*2))}¨⍳N N
```
### Ungolfed
```
N←⎕
⌽ ⍝ flip the X axis so 0,0 is bottom left
{
(⍵+1) ⊃ ' ' 'X' ⍝ substitute space for 0, X for 1
} ¨ {
1=(N|(+/⍵*2)) ⍝ mod(x*x+y*y, 1)==1
} ¨ ⍳N N ⍝ generate an NxN grid of coordinates
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 13 bytes
```
:qU&+G\1=88*c
```
Origin is at top left. So the output is flipped upside down compared with the examples in the challenge.
Try at [MATL online!](https://matl.io/?code=%3AqU%26%2BG%5C1%3D88%2ac&inputs=11&version=19.9.0)
### Explanation
```
: % Input n implicitly. Push [1 2 ... n]
q % Subtract one (element-wise)
U % Square (element-wise)
&+ % Matrix of pairwise sums
G % Push n
\ % Modulo
1= % Equal to 1? (element-wise)
88* % Multiply by 88 (ASCII code of 'X')
c % Convert to char. Char 0 will be displayed as a space
% Display implicitly
```
[Answer]
# Haskell, 115 bytes
```
n#(a,b)|mod(a*a+b*b)n==1='X'|1>0=' '
m n=map(n#)<$>zipWith(zipWith(,))(replicate n[0..n-1])(replicate n<$>[0..n-1])
```
The y axis is inverted.
[Try it online!](https://tio.run/nexus/haskell#VctBCsJADEDRvacItDBJraXj2vQaCuIiowUDJg5lVtK7j24UXH148Ks3KH2i1Z43lE62qUvkzJHDKaxxGjlA2Bg4m2T0hg7t9NJ81HLHb3siXOb80KuUGfw8DoPv4uUPP9vPq4k6MORFvUALBvv6Bg "Haskell – TIO Nexus")
All those parentheses are kind of annoying me...
## Explanation
```
n#(a,b)|mod(a*a+b*b)n==1='X'|1>0=' '
n#(a,b) --Operator #, takes a number n and a tuple (a,b)
|mod(a*a+b*b)n==1 --Test if the mod equals 1
='X' --If so, return 'X'
|1>0=' ' --Otherwise, return ' '
m n=map(n#)<$>zipWith(zipWith(,))(replicate n[0..n-1])(replicate n<$>[0..n-1])
m n= --Make a new function m with argument n
(replicate n[0..n-1]) --Make a list of [[0,1,2,3..n-1],[0,1,2,3..n-1],(n times)]
(replicate n<$>[0..n-1]) --Make a list of [[0,0,0(n times)],[1,1,1(n times)]..[n-1,n-1,n-1(n times)]
zipWith(zipWith(,)) --Combine them into a list of list of tuples
map(n#)<$> --Apply the # operator to every tuple in the list with the argument n
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
' x'{~1=[|+/~@:*:@i.
```
[Try it online!](https://tio.run/nexus/j#@59ma6WuUKFeXWdoG12jrV/nYKVl5ZCp9z81OSNfIU3BxIgrtSKzRMHgPwA "J – TIO Nexus")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 34 bytes
```
~:c,{.*}%:a{:b;a{b+c%1=' x'=}%}%n*
```
[Try it online!](https://tio.run/nexus/golfscript#@19nlaxTradVq2qVWG2VZJ1YnaSdrGpoq65QoW5bq1qrmqf1/7@JEQA "GolfScript – TIO Nexus")
I really don't like using variables...
] |
[Question]
[
Create a basic calculator for Roman numerals.
### Requirements
* Supports `+`,`-`,`*`,`/`
* Input and output should expect only one subtractor prefix per symbol (i.e. 3 can't be `IIV` because there are two `I`'s before `V`)
* Handling of the subtraction principle in input and output must at minimum support modern standard conventions, in which only powers of ten are subtracted from larger numbers (e.g. `I`,`X`,`C` are required subtractors but not `V`,`L`,`D`) and subtraction is never done from a number more than 10x the subtractor (e.g. `IX` must be supported but `IC` is not required).
* Input and output should be left to right in order of value, starting with the largest (i.e. 19 = `XIX` not `IXX`, 10 is larger than 9)
* Left to right, no operator precedence, as if you were using a hand calculator.
* Supports whole positive numbers input/output between 1-4999 (no need for V̅)
* No libraries that do roman numeral conversion for you
### For you to decide
* Case sensitivity
* Spaces or no spaces on input
* What happens if you get a decimal output. Truncate, no answer, error, etc..
* What to do for output that you can't handle. Negatives or numbers to large to be printed.
* Whether to support a more liberal use of the subtraction principle than the minimum requirement.
### Extra Credit
* **-50** - Handle up to 99999 or larger. Symbols **must** include a [vinculum](http://en.wikipedia.org/wiki/Vinculum_(symbol)#Roman_numerals)
Sample input/output
```
XIX + LXXX (19+80)
XCIX
XCIX + I / L * D + IV (99+1/50*500+4)
MIV
```
The shortest code wins.
[Answer]
# JavaScript (ES6), 238
```
c=s=>{X={M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1}
n=eval('W='+s.replace(/[\w]+/g,n=>(o=0,n.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,d=>o+=X[d]),
o+';W=W')));o='';for(i in X)while(n>=X[i])o+=i,n-=X[i];return o}
```
Usage:
```
c("XIX + LXXX")
> "XCIX"
c('XCIX + I / L * D + IV')
> "MIV"
```
Annotated version:
```
/**
* Process basic calculation for roman numerals.
*
* @param {String} s The calculation to perform
* @return {String} The result in roman numerals
*/
c = s => {
// Create a lookup table.
X = {
M: 1e3, CM: 900, D: 500, CD: 400, C: 100, XC: 90,
L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1
};
// Do the calculation.
//
// The evaluated string is instrumented to as below:
// 99+1/50*500+4 -> W=99;W=W+1;W=W/50;W=W*500;W=W+4;W=W
// -> 1004
n = eval('W=' + s.replace(
// Match all roman numerals.
/[\w]+/g,
// Convert the roman number into an integer.
n => (
o = 0,
n.replace(
/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g,
d => o += X[d]
),
// Instrument number to operate left-side operations.
o + ';W=W'
)
));
// Convert the result into roman numerals.
o = '';
for (i in X)
while (n >= X[i])
o += i,
n -= X[i];
// Return calculation result.
return o
}
```
[Answer]
## T-SQL, 1974 - 50 = 1924 bytes
I know that golfing in SQL is equivalent to playing 18 holes with nothing but a sand wedge, but I relished the challenge of this one, and I think I managed to do a few interesting things methodologically.
This does support the vinculum for both input and output. I adopted the convention of using a trailing tilde to represent it , so V~ is 5000, X~ is 10000, etc. It should also handle outputs up to 399,999 according to standard modern Roman numeral usage. After that, it will do partially non-standard Roman encoding of anything in INT's supported range.
Because it's all integer math, any non-integer results are implicitly rounded.
```
DECLARE @i VARCHAR(MAX)
SET @i='I+V*IV+IX*MXLVII+X~C~DCCVI'
SELECT @i
DECLARE @t TABLE(i INT IDENTITY,n VARCHAR(4),v INT)
DECLARE @u TABLE(n VARCHAR(50),v INT)
DECLARE @o TABLE(n INT IDENTITY,v CHAR(1))
DECLARE @r TABLE(n INT IDENTITY,v INT,r VARCHAR(MAX))
DECLARE @s TABLE(v INT,s VARCHAR(MAX))
DECLARE @p INT,@x VARCHAR(4000)='SELECT ',@j INT=1,@m INT,@y INT,@z VARCHAR(2),@q VARCHAR(50)='+-/*~]%'
INSERT @t(n,v) VALUES('i',1),('iv',4),('v',5),('ix',9),('x',10),('xl',50),('l',50),('xc',90),('c',100),('cd',400),('d',500),('cm',900),('m',1000),('mv~',4000),('v~',5000),('mx~',9000),('x~',10000),('x~l~',40000),('l~',50000),('x~c~',90000),('c~',100000)
INSERT @u VALUES('%i[^i'+@q,-2),('%v[^vi'+@q,-10),('%x[^xvi'+@q,-20),('%l[^lxvi'+@q,-100),('%c[^clxvi'+@q,-200),('%d[^dclxvi'+@q,-1000),('%mx~%',-2010),('%x~l~%',-20060),('%x~c~%',-20110)
WHILE PATINDEX('%[+-/*]%', @i)!=0
BEGIN
SET @p=PATINDEX('%[+-/*]%', @i)
INSERT @o(v) SELECT SUBSTRING(@i,@p,1)
INSERT @r(r) SELECT SUBSTRING(@i,1,@p-1)
SET @i=STUFF(@i,1,@p,'')
END
INSERT @r(r) SELECT @i
UPDATE r SET v=COALESCE(q.v,0) FROM @r r LEFT JOIN (SELECT r.r,SUM(u.v)v FROM @u u JOIN @r r ON r.r LIKE u.n GROUP BY r.r)q ON q.r=r.r
UPDATE r SET v=r.v+q.v FROM @r r JOIN (SELECT r.n,r.r,SUM((LEN(r.r)-LEN(REPLACE(r.r,t.n,REPLICATE(' ',LEN(t.n)-1))))*t.v) v FROM @r r JOIN @t t ON CHARINDEX(t.n,r.r) != 0 AND (LEN(t.n)=1 OR (LEN(t.n)=2 AND RIGHT(t.n,1)='~')) GROUP BY r.n,r.r) q ON q.r=r.r AND q.n = r.n
SELECT @m=MAX(n) FROM @o
SELECT @x=@x+REPLICATE('(',@m)+CAST(v AS VARCHAR) FROM @r WHERE n=1
WHILE @j<=@m
BEGIN
SELECT @x=@x+o.v+CAST(r.v AS VARCHAR)+')'
FROM @o o JOIN @r r ON r.n=o.n+1 WHERE o.n=@j
SET @j=@j+1
END
INSERT @s(v,s) EXEC(@x+',''''')
UPDATE @s SET s=s+CAST(v AS VARCHAR(MAX))+' = '
SET @j=21
WHILE @j>0
BEGIN
SELECT @y=v,@z=n FROM @t WHERE i = @j
WHILE @y<=(SELECT v FROM @s)
BEGIN
UPDATE @s SET v=v-@y,s=s+@z
END
SET @j=@j-1
END
SELECT @x+' = '+UPPER(s) FROM @s
```
I'm still tinkering with a set-based solution to replace some of the WHILE looping that might whittle down the byte count and be a more elegant example of idiomatic SQL. There are also some bytes to be gained by reducing use of table aliases to a bare minimum. But as it's essentially un-winnable in this language, I'm mostly just here to show off my Don Quixote outfit. :)
SELECT @i at the top repeats the input:
```
I+V*IV+IX*MXLVII+X~C~DCCVI
```
And the SELECT at the end returns:
```
SELECT (((((1+5)*4)+9)*1047)+90706) = 125257 = C~X~X~V~CCLVII
```
And you can test it yourself at [this SQLFiddle](http://sqlfiddle.com/#!6/d41d8/15047)
And I will be returning to add some commentary on how it works, because why post an obviously losing answer if you're not going to exploit it for educational value?
[Answer]
# [APL (Dyalog Unicode 18.0)](https://www.dyalog.com/), 187 − 50 = 137 [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 using stdin/stdout. Requires 0-based indexing and space(s) between symbols and numbers.
```
d←,∘⌊⍨'IVXLCD'
'[a-z]'⎕R('\u&',⎕UCS 773)⊢d[∊(2×⌽⍳≢r)+{⍵=⍛⌽⍺0/⍨⍺×⍛⍮⍵-1}⌿0 5⊤1+⍎¨r←⍕⍎∊'\w+'⎕R{⍕(×\1,11⍴5 2)[d⍳⍵.Match](⊣+.ׯ1*2</,)0}'(.)\pM'⎕R'\l1'⌽'-' '\*' '/' '\S+'⎕S'-⍨' '×' '÷⍨' '&'⊢⍞]
```
[Try it online!](https://tio.run/##VVBNa8JAEL3nV2wvbmISNRbx0p7iZSFeKg0LxoM00hakBrH0C4@2NrjSi6RQ6MH24Kk9tFIolIK5@ivmj6STiJoOw@7bNy9vZtL02rp71Wx3jvXWZa915rbcCMaT0w7cPhQkGN55kYtQg@EjjHwQM8psbpkVKtF6U79uUBQfyNQ5z1AN4aFZI@XyrgL@1K3D0JeLYQCjHxAfcD/tKuoNiPk@iKeE@y7k0RBv1CAl3rCoG30Y/RZICfxXQwUxXsy62B/EBDEaUudCTXqi00QOA8fQDAPEZ4kUlbob9xHzXLXZOzppyOC/qLkwWLwb2eJeXlMKfSrnFMerJgbUaRsU56A6JdTJ4pGPQS2xr1E93pXQMIiPr9UjQ3EvEM@NCH9MRJLwJM44UYnFOZc2lJlwjOSJRbKkEmN7W@WcMaQttv2CLQerjKVrnK6i3ty8Y1PzH1NZDsx1WssBT6W9tltlxcSIp@U2w9j2SNlvIccVWDKtnZLaZOcP "APL (Dyalog Unicode) – Try It Online")
* Full support for [vinculum](https://en.wikipedia.org/wiki/Roman_numerals#Vinculum), so 1000 is written as `I̅` (`M` is a modern addition)
* Handles all positive results until 899999
* Allows non-standard input, including, e.g. purely additive notation and too large/small subtractors
* Includes support for factorial ! (and actually a bunch of other operations)
[Answer]
# Javascript - ~~482~~ 476 characters
```
String.prototype.m=String.prototype.replace;eval("function r(a){return a>999?'Mk1e3j899?'CMk900j499?'Dk500j399?'CDk400j99?'Ck100j89?'XCk90j49?'Lk50j39?'XLk40j9?'Xk10j8?'IX':a>4?'Vk5j3?'IV':a>0?'Ik1):''}".m(/k/g,"'+r(a-").m(/j/g,"):a>"));s=prompt();h=s.match(/\w+/gi);for(k in h)s=s.m(h[k],eval(eval("'0'+h[k].m(/IVu4pIXu9pXLu40pXCu90pCDu400pCMu900pMu1000pDu500pCu100pLu50pXu10pVu5pIu1')".m(/u/g,"/g,'+").m(/p/g,"').m(/")))+")");for(k in h)s="("+s;alert(r(Math.floor(eval(s))))
```
The sample input/output works:
```
XIX + LXXX -> XCIX
XCIX + I / L * D + IV -> MIV
```
It badly handles large numbers too:
```
MMM+MMM -> MMMMMM
M*C -> MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
```
And it accepts, but does not requires, spaces too.
But, since I was golfing it has some problems:
* It does not validates if the input is well-formed. If the input is not well-formed, the behaviour is undefined (and in practice it is very bizarre and strange).
* It truncates fraction numbers on output (but it is able to do intermediate calculations with them).
* It really abuses the eval function.
* It does not attempt to handle negative numbers.
* It is case-sensitive.
This alternative version handles numbers over 5000 upto 99999, but it has ~~600~~ ~~598~~ 584 characters:
```
String.prototype.m=String.prototype.replace;eval("function r(a){return a>8zz?'XqCqk9e4j4zz?'Lqk5e4j3zz?'XqLqk4e4jzz?'Xqk1e4j89z?'IqXqk9e3j49z?'Vqk5e3j9z?'Mk1e3j8z?'CMk900j4z?'Dk500j3z?'CDk400jz?'Ck100j89?'XCk90j49?'Lk50j39?'XLk40j9?'Xk10j8?'IX':a>4?'Vk5j3?'IV':a>0?'Ik1):''}".m(/k/g,"'+r(a-").m(/j/g,"):a>").m(/q/g,"\u0305").m(/z/g,"99"));s=prompt();h=s.match(/\w+/gi);for(k in h)s=s.m(h[k],eval(eval("'0'+h[k].m(/IVu4pIXu9pXLu40pXCu90pCDu400pCMu900pMu1000pDu500pCu100pLu50pXu10pVu5pIu1')".m(/u/g,"/g,'+").m(/p/g,"').m(/")))+")");for(k in h)s="("+s;console.log(r(Math.floor(eval(s))))
```
[Answer]
## Javascript ~~479~~ ~~361~~ ~~348~~ ~~278~~ 253
303 characters - 50 for supporting numbers up to 1 million, complete with vinculum support:
```
function p(s){s=s[r](/(^|[*\/+-])/g,"0;s$1=");for(i in v){f=R("\\b"+i);while(f.test(s))s=s[r](f,v[i]+"+")}eval(s+"0");h="";for(i in v)while(s>=v[i]){h+=i;s-=v[i]}return h}v={M̅:1e6,D̅:5e5,C̅:1e5,L̅:5e4,X̅:1e4,V̅:5e3,M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};r="replace";R=RegExp
```
Usage: `p(text)`, e.g., `p('XIX + LXXX')` returns `XCIX`.
Code with explanatory comments:
```
// Array mapping characters to values
v={M¯:1e6,D¯:5e5,C¯:1e5,L¯:5e4,X¯:1e4,V¯:5e3,M:1e3,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};
// Shortcut for String.replace
r='replace';
R=RegExp;
// The heart of the program
function p(s) {
// Replace operators with ";s+=", ";s-=", and so on
s=s[r](/(^|[*\/+-])/g,'0;s$1=');
// Loop over the character map and replace all letters with numbers
for(i in v){
f=R('\\b'+i);
while(f.test(s))
s=s[r](f, v[i]+'+')
}
eval(s+'0');
// Set up our return string
h='';
// Replace digits with characters
for(i in v)
while(s>=v[i]) {
h+=i;
s-=v[i];
}
return h;
}
```
This works for the given samples and for all others I have tried. Examples:
```
XIX + LXXX = XCIX
XCIX + I / L * D + IV = MIV
XL + IX/VII + II * XIX = CLXXI
CD + C + XL + X + I = DLI
M̅ + I = M̅I
MMMM + M = V̅
```
[Answer]
## Ruby 2.1, 353 (and *many* other iterations), 295 - 50 = 245
The vinculum handling adds ~23 characters.
This handles "IL" or "VM" in the input, and fails without error on negatives (goes to high ints) or decimals (truncates), or any spaces. Now also handles a negative first number (though if the total is negative, it still fails poorly). Also fails poorly if you start with \* or / or if the result is 4 million or larger.
Uses Object#send for "hand-calculator" functionality.
```
m=%w{I V X L C D M V̅ X̅ L̅ C̅ D̅ M̅};n=m.zip((0..12).map{|v|(v%2*4+1)*10**(v/2)}).to_h
d=0
gets.scan(/([-+*\/])?([A-Z̅]+)/){|o,l|f=t=0
l.scan(/.̅?/){t-=2*f if f<v=n[$&]
t+=f=v}
d=d.send o||:+,t}
7.downto(1){|v|z=10**v
y=(d%z)*10/z
q,w,e=m[v*2-2,3]
$><<(y>8?q+e : y<4?q*y : y<5?q+w : w+q*(y-5))}
```
Ungolfed:
```
m=%w{I V X L C D M V̅ X̅ L̅ C̅ D̅ M̅} # roman numerals
n=m.zip((0..12).map{|v|(v%2*4+1)*10**(v/2)}).to_h # map symbols to values
d=0
gets. # get input and...
scan(/([-+*\/])?([A-Z̅]+)/) { |l,o| # for each optional operator plus number
f=t=0
l.scan(/.̅?/){ # read the number in one letter at a time
t -= 2 * f if f < (v=n[$&]) # if the number's greater than the prev, subtract the prev twice since you already added it
t += (f = v) # add this, and set prev to this number
}
d = d.send((o || :+), t) # now that we've built our number, "o" it to the running total (default to +)
}
7.upto(1) { |v| # We now print the output string from left to right
z = 10**v # z = [10, 100, 1000, etc.]
y = (d%z)*10/z # if d is 167 and z is 100, y = 67/10 = 6
q,w,e = m[v*2-2,3] # q,w,e = X, L, C
$><< ( # print:
y>8 ? q+e : # if y==9, XC
y<4 ? q*y : # if y<4, X*y
y>3 ? q+w : # if y==4, XL
q*(y-5) # else, L + X*(y-5)
)
}
```
[Answer]
# Python 2 - ~~427~~ ~~418~~ ~~404~~ ~~401~~ ~~396~~ ~~395~~ 392 characters
Reads from standard input. It only handles uppercase (could make it case-insensitive at the cost of 8 extra characters) and requires spaces. Does no validation--I haven't tested to see how it breaks in various cases. It does, however, handle numbers like VC = 95.
```
N=['?M','DC','LX','VI'];t=0;o='+'
for q in raw_input().split():
if q in"+-*/":o=q;continue
n=s=0;X=1
for l in q:
x=''.join(N).find(l);v=(5-x%2*4)*10**(3-x/2)
if X<x:n+=s;s=v;X=x
elif X>x:n+=v-s;s=0
else:n+=v+s;s=0
exec"t"+o+"=n+s"
r=t/1000*'M'
for p,d in enumerate("%04d"%(t%1e3)):
i="49".find(d);g=N[p]
if i<0:
if'4'<d:r+=g[0]
r+=int(d)%5*g[1]
else:r+=g[1]+N[p-i][i]
print r
```
And the ungolfed version:
```
# Numerals grouped by powers of 10
N = ['?M','DC','LX','VI']
# Start with zero plus whatever the first number is
t = 0
o = '+'
for q in raw_input().split():
if q in "+-*/":
# An operator; store it and skip to the next entry
o = q
continue
# n holds the converted Roman numeral, s is a temp storage variable
n = s = 0
# X stores our current index moving left-to-right in the string '?MDCLXVI'
X = 1
for l in q:
# x is the index of the current letter in '?MDCLXVI'
x = ''.join(N).find(l)
# Calculate the value of this letter based on x
v = (5 - x%2 * 4) * 10 ** (3 - x/2)
if X < x:
# We're moving forward in the list, e.g. CX
n += s # Add in any previously-stored value
s = v # Store this value in case we have something like CXL
X = x # Advance the index
elif X > x:
# Moving backward, e.g. XC
n += v - s # Add the current value and subtract the stored one
s=0
else:
# Same index as before, e.g. XX
n += v + s # Add the current value and any stored one
s = 0
# Update total using operator and value (including leftover stored value
# if any)
exec "t" + o + "=n+s"
# Now convert the answer back to Roman numerals
# Special-case the thousands digit
r = t / 1000 * 'M'
# Loop over the number mod 1000, padded with zeroes to four digits (to make
# the indices come out right)
for p, d in enumerate("%04d" % (t % 1e3)):
i = "49".find(d)
g = N[p]
if i < 0:
# i == -1, thus d isn't '4' or '9'
if '4' < d:
# >= 5, so add the 5's letter
r += g[0]
# ... plus (digit % 5) copies of the 1's letter
r += int(d) % 5 * g[1]
else:
# If it's a 4 or 9, add the 1's letter plus the appropriate
# larger-valued letter
r += g[1] + N[p-i][i]
print r
```
I have a feeling Perl would have been better, but I don't know enough of it. For a first stab at code golf, though, I feel pretty good about this.
[Answer]
# PHP — ~~549~~ ~~525~~ ~~524~~ 520 bytes
Nothing too innovative: normalizes the operators to ensure left to right precedence, converts Roman to decimal, runs `eval` on the statement, e.g. *XCIX + I / L \* D + IV* is converted to something like *return (((((+90 +9) + (+1)) / (+50)) \* (+500)) + (+4));*, then converts decimal back to Roman.
* final results are truncated
* answers less than 1 come back blank
* results are undefined if given incorrect input
```
$f='str_replace';$g='str_split';$c=array('M'=>1e3,'CM'=>900,'D'=>500,'CD'=>400,'C'=>100,'XC'=>90,'L'=>50,'XL'=>40,'X'=>10,'IX'=>9,'V'=>5,'IV'=>4,'I'=>1);$j='['.$f(array('+','-','*','/'),array('])+[','])-[','])*[','])/['), $argv[1]).'])';$j=str_repeat('(',substr_count($j,')')).$j;$j=$f('[','(',$j);$j=$f(']',')',$j);foreach($g('IVIXXLXCCDCM',2)as$w)$j=$f($w,'+'.$c[$w],$j);foreach($g('IVXLCDM')as$w)$j=$f($w,'+'.$c[$w],$j);$k=eval('return '.$j.';');$l='';foreach($c as$a=>$b){while($k>=$b){$l.=$a;$k-=$b;}}print$l."\n";
```
e.g.
```
$ php roman.php 'XCIX + I / L * D + IV' — test case
MIV — 1004
$ php roman.php 'XXXII * LIX' — 32 × 59
MDCCCLXXXVIII — 1888
```
[Answer]
# Python - 446 bytes
This could be improved considerably. I felt I had to take the first swing using Python. It does 3 things on the first pass
1. tokenizes the numbers and operators
2. evaluates the numbers, and enlarges the symbol table `x` to include all possible combinations encountered (even if they are not used). For example, while `XIX` is being lexed, the partial values of `"X":10`, `"XI":11` and `"XIX":19` are added to the symbol table
3. inserts nested parens to enforce left-to-right evaluation
At the end, it calls `eval` on the original string (except with added parens) and gives it the symbol table.
Then I just pasted in a known solution to convert integer to Roman, since I had worked on this long enough... please feel free to improve so that I learn something new :)
```
m=zip((1000,900,500,400,100,90,50,40,10,9,5,4,1),
('M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'))
def doit(s):
x={'M':1e3,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1};y=[];z='';a='0';s='+'+s
for c in s.upper():
if c in x:
z+=c;y.append(x[c])
if len(y)>1and y[-1]>y[-2]:y[-2]*=-1
x[z]=sum(y)
elif c in"+/*-":a='('+a+z+')'+c;y=[];z=''
a+=z;i=eval(a,x);r = ''
for n,c in m:d=int(i/n);r+=c*d;i-=n*d
return r
print doit("XIX + LXXX")
print doit("XCIX + I / L * D + IV")
```
[Answer]
## MATLAB - 543 bytes
I tried not to look at others' answers before working on my own, although my approach ended up similar regardless. I use a regular expression to match word characters (the numbers) or operators, which splits up the input into a cell array alternating between numbers and operators. I then replace the roman numerals in every other cell with itself and a plus sign, using order of precedence on the groups to ensure proper grouping. I define variables with the same name as each split group and use an eval statement on the split roman numeral to convert it to a value with a closing parenthese. I then concatenate the whole list of values and operators with proper opening parentheses to ensure strict left-to-right order of operations. I then deconstruct the resulting number digit-by-digit and convert it to the proper roman numeral based on its "power".
```
function n=m(I)
e=regexp(I,'\w+|[\+\-\*\/]','match');CM=900;XC=90;IX=9;CD=400;XL=40;IV=4;M=1e3;D=500;C=100;L=50;X=10;V=5;I=1;e(1:2:end)=cellfun(@(x) [num2str(evalin('caller',[x '0'])) ')'],regexprep(e(1:2:end),'CM|XC|IX|CD|XL|IV|.?','$0+'),'un',0);S=num2str(eval(strcat(repmat('(',1,(length(e)+1)/2),e{:})));n='';I='IXCM';V='VLD ';l=length(S);for i=1:l
p=l-i+1;a=eval(S(i));if p>3
n=repmat('M',1,a);continue
end
b=a>4;switch a
case 4
n=[n I(p) V(p)];case 9
n=[n I(p:p+1)];otherwise
n=[n repmat(V(p),1,b) repmat(I(p),1,a-5*b)];end
end
```
ungolfed:
```
function n=m(I)
e=regexp(I,'\w+|[\+\-\*\/]','match'); % match roman numerals or operators
CM=900;XC=90;IX=9; % nines
CD=400;XL=40;IV=4; % fours
M=1e3;D=500;C=100; % single character numbers (ones and fives)
L=50;X=10;V=5;I=1;
e(1:2:end)=cellfun(@(x) [num2str(evalin('caller',[x '0'])) ')'],... % Evaluate each group and add a parenthesis
regexprep(e(1:2:end),'CM|XC|IX|CD|XL|IV|.?','$0+'),'un',0); % replace each group or single digit with itself and a +
S=num2str(eval(strcat(repmat('(',1,(length(e)+1)/2),e{:}))); % concatenate the split string and evaluate with proper parentheses for left-to-right Order of Operations
n=''; % initialize output
I='IXCM'; % Define ones and fives
V='VLD ';
l=length(S);
for i=1:l
p=l-i+1;
a=eval(S(i));
if p>3 % if the number has 4 or more digits, just add a bunch of Ms
n=repmat('M',1,a);
continue
end
b=a>4;
switch a
case 4
n=[n I(p) V(p)]; % If the digit is 4, add the proper 1 and 5
case 9
n=[n I(p:p+1)]; % If the digit is 9, add the correct 9 group
otherwise
n=[n repmat(V(p),1,b) repmat(I(p),1,a-5*b)]; % Add a 5 if the digit is greater than 4. add 1s for either the digit value (1,2,3) or the value - 5 (6,7,8)
end
end
```
] |
[Question]
[
## Background
Numeric Mahjong is a hypothetical variation of Japanese Mahjong, played with nonnegative integers instead of Mahjong tiles. Given a list of nonnegative integers, it is a *winning hand* if it satisfies the following:
* its length is \$3n+2\$ for some nonnegative integer \$n\$, and
* it can be partitioned into \$n\$ triples and a pair so that
+ each triple consists of three identical numbers \$(x,x,x)\$ or three consecutive numbers \$(x,x+1,x+2)\$, and
+ the pair consists of two identical numbers \$(x,x)\$.
## Challenge
Write a program or function that tests if a given a list of nonnegative integers is a winning hand in Numeric Mahjong. As this is a [self-validating](/questions/tagged/self-validating "show questions tagged 'self-validating'") challenge, **your source code** (when converted to a list of integers) **must be a winning hand.** For example, `print(1)` is not a valid answer even if it implements the task, but the following may be:
```
print(1)###*11ios
```
whose ASCII values in sorted order is `[35, 35, 35, 40, 41, 42, 49, 49, 49, 105, 105, 110, 111, 112, 114, 115, 116]`, which can be partitioned to five triples `[35, 35, 35], [40, 41, 42], [49, 49, 49], [110, 111, 112], [114, 115, 116]` and a pair `[105, 105]`.
When converting the source code to integers, you may choose between
* Unicode codepoints of each char (when the source code is a sequence of Unicode characters),
* one of your language's fixed-width encodings, or
* a raw byte sequence (when the source code has an integral number of bytes).
If there are other sensible conversions, please leave a comment.
For output, you can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
### Truthy
```
[0, 0]
[999, 999, 999, 1234, 1234]
[1, 2, 2, 2, 3]
[1, 4, 7, 2, 5, 5, 5, 8, 3, 6, 9]
[1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
[0, 0, 0, 0, 0, 0, 0, 0]
```
### Falsy
```
[]
[1]
[1, 3, 5, 7, 9]
[1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~47~~ ~~44~~ ~~41~~ 38 bytes
```
≈ì í3√¥ í¬•J>}gy3√¥ í¬•T>SQ}g+3*Ig>Q}ƒáQ,¬•‚Ä∫HUyy
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6ORTk4wPbzk16dBSL7va9EooO8QuOLA2XdtYyzPdLrD2SHugzqGljxp2eYRWVv7/H22oo2Cko2Cso2Cio2AaCwA), or [try all test cases (this code can handle in under a minute)](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRfeWjl/6OTT00yPrzl1KRDS73satMroewQu@DA2nRtY61D69LtAmuPtAfqHFr6qGGXR2hl5f//0dGxOgrRhiDCQEfBAMzRUTDWUTDVUTDXUbCEChjBkDFIwNLSEigFJwyNjE0gJEI10ASgmGlsLAA).
[See the codepoints](https://tio.run/##yy9OTMpM/a/0/@jkU5OMD285NenQUi@72vRKKDvELjiwNl3bWMsz3S6w9kh7oM6hpY8adnmEVlb@Vzq07cKec1uP7jvSVpxdW11Waa@koGunoGQPEqk8vEKn9j8A)
Returns `0` for true and `[]` for false.
## Explanation
The general approach is this: Test for the existence of a permutation such that if we split it to parts of length 3, and then keep all the valid ones and count them, and multiply by 3, we should get 1 plus the length of the original input.
```
œ # all permutations
í # keep those such that:
3ô # split to parts of length 3
í # keep parts where:
¥ # their differences
J # joined to a string
> # plus one
} # (is equal to 1)
g # find the length
y # push the input again
3ô # and split to parts of length 3
í # keep parts such that:
¥ # their differences
T> # 11
S # [1, 1]
Q # [1, 1] is equal to the differences
}
g # take their lengths
+ # sum the lengths of the two types of parts
3* # times 3
I # input
g # length
> # plus one
Q # is equal to the number of valid parts times 3
}
ćQ # test whether the array is empty, by comparing arr[0] == arr[1:]
, # output - this suppresses implicit output, so the rest of the code doesn't matter
¥›HUyy # filler to satisfy the self validation requirement
```
[Answer]
# JavaScript (ES6), ~~ 143 122 ~~ 119 bytes
*-24 bytes thanks to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)!*
Expects an `Uint32Array`. Returns a Boolean value.
```
n=>(q=([v,...f],e)=>6/v?[e,4,4.5].some(t=>q(f.filter(i=>p>t|v+t%1*p-i||0%[p*=2],p=2),t<p?4>t?4:e:1%0)):e>3)(n.sort(),3)
```
[Try it online!](https://tio.run/##nZDNTsMwDMfvfYpo0qRkZKFNsu6LZOLAnmCcSg/RSFlRabs0FE3au5euYaXAjehnK7Id52@/qlpVe5OWdpoXz7rZiiYXEh4FjGpMCElirJGQ4W29iTTmmJNZTKriTUMr5BEmJEkzqw1MhSylPdc3dhxMyml6PvvjqJwIGuNSUITtXbnh0m74Sq@CsY/QSkuGYN72MhYizFCzL/KqyDTJihc4inbm3R5O8QitvcgDIPIx8GN8uS2XSwy@XUAZd96lAwzoFdaH2pJ5F5pdWbRpDMK2y693rINfcdVhR9ti3lf30OGPDld00fyX2Is9khTmQe0PUAEhwXDyLcz1B3hMc8vovTHqBBVqz9rzfuznKY@2KqsGC/rS1ctjne75cL5eq5ts0RGEzhh1FvKL/U9k8wk "JavaScript (Node.js) – Try It Online")
The above function is too slow to validate itself on TIO, so this is using my original answer with an additional optimization:
[Try it online!](https://tio.run/##Xc/PToQwEAbw@z4FbgKZQqlQ0APLlOhh38AT4UCwNRhs@VMxJrw7FuNh4xwnk@/7zXu7tks396ONtXmV@xV3hQImhHqljDHVUIkJQZHer5UseRDUnOb0oWGL@ZBg3a3GlBpUTPWDlTP0KHTIhd36eI2tz0O9bXdRpAn9XQfBBIbKCGyZETeFREwJKJc3WyBkH6T1Okfx0Dvr/xQHeXSQWjpDzm4UE9wCRle/RtZPwzHuty3x6zFE3tAROaG2HKtc2CovZJH6yUEQGQH9J6AZOV9Op87oxQySDeYNrqDll/fSa5vxp3luv@H5UylXdTiPJy77Dw "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 71 bytes
```
oo::{*0-0!=|/{:[&/0=x;1;|/^%x;0;o@@[1_x;!2;-;3!*x]]}'+@[-2*=3+/x;x;1+]}
```
[Try it online!](https://ngn.codeberg.page/k#eJxlUstuhDAMvOcrzGrbSjxEHpAAKRL/QdN2L5V6yhVpd/+9jr2kVNWMrRB7xlZEjNN0LWUji/nWXqf1uZXz5pW/te9Pm5c+LsuqPjZfaN94U5RbCPeXalkbXc6majePzVW4C/E1oTpGSGKZLlqxyhpkEOs4jjX8JqVNxxlrqga90/A3Fh199zsHrNVgUX9UGGK3k1stEfWOWzP1cRAz8Ib/GYRYk5wtDBm7PD2b8dyBqCyH0Ry2S5HX5UX7IN7wpUCCxIyPkSO9BiW8V6AJhs4dODz3hAEMWBhzj0F0hFS1CAeOqgy9OyXw3CNwlQUKmXKtSGbQxj0GsDyZDwhlE41OtB3ysURaoCejz+/zKeLfdKrPMYrXS3GZ/lz9AKoTePc=)
Based on a polynomial-time algorithm with respect to the maximal element, so it can test all test cases and itself in a second.
Let's call `(x,x,x)` an *x-triplet* and `(x,x+1,x+2)` an *x-sequence*.
* Count the occurrence of each number in `[0, 1, 2, ...]` up to the maximal element that appears in the input. Let's call it C.
* For `i` from 0 to the maximum index of C,
+ Construct a copy of C where `i`-th element is subtracted by 2. (i.e., Assume a pair is `(i,i)`.)
+ Repeat until one of the halting condition is met:
- If the remaining array is all zeros, return true.
- If the remaining array contains a negative value, return false.
- Otherwise, pop `x` from the front, and subtract `x%3` from the first two elements. (i.e., Maximally create `j`-triplets and try creating `j`-sequences for the remaining `j`s.)
* If any choice of `i` gives true, return true. Otherwise return false.
If a partition exists and it contains three or more `j`-sequences for some `j`, three copies of `j`-sequences can be replaced with `j`-, `j+1`-, and `j+2`-triplets to get another valid partition. Also, when considering all possible partitions where the minimum value is `j`, choosing to have three `j`-sequences (compared to one `j`-triplet) has the effect of fixing a `j+1`- and `j+2`-triplet from the remaining numbers, leaving a strict subset of choices afterwards. Therefore, it suffices to check if a greedy partitioning (favoring triplets) leads to a valid one.
```
{|/{:[&/0=x;1;|/^%x;0;o@@[1_x;!2;-;3!*x]]}'+@[-2*=3+/x;x;1+]}
+@[-2*=3+/x;x;1+] construct number-count arrays with all choices of pairs
=3+/x identity matrix of size `sum of x + 3`
-2* change 1s on the diagonal to -2
@[ ;x;1+] for each number i in x, add 1 to i-th row of the above
+ transpose
{:[...]}' test if each number-count array is partitionable
&/0=x;1; if all elements are 0, return 1
|/^%x;0; if any element is negative, return 0
(monadic % is square root, which gives 0n for negatives;
monadic ^ is null-check, which gives 1 for 0n)
o@@[1_x;!2;-;3!*x] otherwise, update the array and do recursive call
1_x remove first element k
!2 and update 0th and 1st elements by
- 3!*x subtracting k%3
o@ recursive call
|/ return 1 if any is true
*0-0!= filler that preserves truthiness
oo:: globally assign function to the name oo
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~128~~ ~~125~~ ~~122~~ 95 bytes
```
≔∧θE⌈⁺³θ№θιθFEθ⮌Eθ⁻λ∧⁼κ첫W∧›L鲬‹⌊ι⁰«≔﹪⊟ι³θF²§≔ι±⊕λ⁻§ι±⊕λθ»P↔¬⌈↔ι»W⁰«⊟⊟⌊≡↔⊕¬§﹪﹪⁺⁺⁻⁰³FLLPPWιλθ»
```
[Try it online!](https://tio.run/##dVFLTsMwEL0KB2CRUGiSs1RdJE4RCyQkVl02EqraKMvCtmIBkWiEAlk0v5UP4EP4AjlCGM9YtSlCsl6cmTfvvUnYXfjIHsL7cZTbndzkoh76N5ltZNLyStTy6UXUolHVd2hA4TOjZ9KJDvgy6UUrev7ND0N/VIVVO/SFaKBSyFUjs1Q0Min5AfSH5kOme@hVKAiUHKrw/iXTZ5BLOp6f3kTNu6Ev5XoHQhBorYidMkG1dK9OlsrtK7Rgghc8BwPlkbR4OsWsMHmBp8RzhH1QfRxnM2fps8sLZ@m4Cm8R2Y1CN1QYRgqjien6vrkvAmtqamY1808ljHHKcoyogi4LvEdXyESX2LOYC1RjxlczqYt1N7C6jtGhHUNM4kwtzuQ8v9a8NlPEdDFhwEx@2oWY/3H01tiNMU8wNZnpCwdWHs30zvNTZkLa0ffMLDmSJuWhTTVGFsZGmXbXf40ZpJwaPZPt90bz@Q8 "Charcoal – Try It Online") Uses the Charcoal code page. Add the `-x` argument to show the hex dump which you can compare against the input. Outputs a Charcoal boolean, i.e. `-` for a winning hand, nothing if not. Explanation: Now a port of @Bubbler's algorithm.
```
≔E⁺³⌈θ№θιθ
```
Count the number of times each integer appears in the array, plus some extra dummy values.
```
FEθ⮌Eθ⁻λ∧⁼κ첫
```
Try each integer in case it's the pair.
```
W∧›L鲬‹⌊ι⁰«
```
Repeat until a count becomes negative or the length is reduced to `2`.
```
≔﹪⊟ι³θ
```
Get the number of runs needed to satisfy the next integer.
```
F²§≔ι±⊕λ⁻§ι±⊕λθ
```
Subtract them from the next two integers.
```
»P↔¬⌊↔ι
```
Output a `-` if this reduced all the integers to zero (but not negative).
```
»W⁰«⊟⊟⌊≡↔⊕¬§﹪﹪⁺⁺⁻⁰³FLLPPWιλθ»
```
Filler bytes to satisfy the source layout, wrapped in a `while` loop whose condition is false.
Original verbose code (without padding): [Try it online!](https://tio.run/##hVFda4MwFH22vyKPERxou1WlTzLGKMxR9lr6EDVtw1Jt/eiE0d/uknvTxXWM@XBI7j3n3nNivmd1XjE5DEnTiF1Jk7KgJ4@k7EhT1otDd6Ar2TV05pGT63rkserKVjOEq68ndzHZVjWhWqCqb/zM64Zfr6kolVZ6RI99OnVMNvTdIwelnLrwkc@J87EXkhNY/Vxz1vKavvBy1@6pAKJHXqtWlZqGqoHgSTf8q94x3tOq6GRFV9UR@jPjz3HA4dQlyEvaZVnwngo1l@/UOros85ofeNnygkodC33/S4QFesNl4qSdbMWxFup1kqypZKfo2vb1Fb@LAnIvJpdhWK/9PspVkt4PNG4B8weNAdPIMo3ZzHajyJ55PFLNrdYwf1VYAarRxgwrsIXDOZsCE7YU4YjJYVpu9xomdqEexKOub@dgRgZO/PmIM7v1b2beWxUyA3AY59Y/ZkHmXxyTGroF@Inn1jO@cDzyY5jhrX/0jIgZo9BqcSPORD@Y1GA2wsJOxuzmr@UW0afB0Hr7mWizGe7O8gs "Charcoal – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 122 bytes
```
f=(A,e,k,n)=>1/n&&!{'1,1':1,'0,0':'B\():'|1}[[e-k,k-n]]?!!0:A+A?A.some((C,j)=>f(A.filter(B=>j--),C,...1/n?[]:[e,k])):e==+k
```
[Try it online!](https://tio.run/##jZBRT4MwEMff@RTdHkabHZXChA3TLWxxn8C3rg9kFjdAMDBNjPrZsaMOUV9Mfndp7q53/7sseUmafX18Ojllda/aLW9TjmNQkENJ@JJdlZPJ6M1mwOyIge2Ca0f2eodJZL@zDyGUk0PulFKuRiM3iqfxKqZN9agw3kCmG6Q4pumxOKkar/kycxwCG6CU6sYrISOhB0lCIsX5NG/3VdlUhaJF9YDH4q5@Ph1e5ZjcWMJCSLiAXAnn12KxAPTtmOfPjDdpBsi74PchXRJ2oesLc50GFOguv/75HbMLpjro0C3CvrrHG040mKKz5r/onLRoWtW3yf6AE8SXaLj6FieE6K2tH/fYlWKbFM3gIF86ejl@pzMc7tNrM5vMO1hgzPeMBbOzyf9oaj8B "JavaScript (Node.js) – Try It Online")
Besides tuplets: `&& ++,,-- --..// AABBCC [\] ijjkkl mno rst {|}`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 50 bytes
```
°þþ&&,@ƑƒWß»Ȥ
WÞW+þ@3’œ&ƑƇœ-@€Ʋ€Ẏ$ƬẎŒɠ%¹Ƈɗ€3‘œ&ƑƇ3
```
[Try it online!](https://tio.run/##y0rNyan8///QhsP7Du9TU9NxODbx2KTww/MP7T6xhCv88Lxw7cP7HIwfNcw8OlkNKNV@dLKuw6OmNcc2AYmHu/pUjoHIo5NOLlA9tPNY@8npQGGg6hlQ1cb/D@08PMMr89HGdUAjjnX5H5tof7j94a4dXA937ju0E8S1ftQwR0HXTuFRw1zrw@1cD3dvOTopDGjK4XYgEfn/v5KSUrSBjoJBLFe0paWljgKCMDQyNoGQQDlDHQUjGDKG8IGS5mC@KQxZAOV0FMyA@pF1GIORCQxBlJqBEVC/OUQpHBkhWwRBQBUgF2KiWC4lrAF7aBvlIavEFQ1yGcR1xmA3m8M9BncnxEsWYGRoBsHGRhBsZgLCscAABgA "Jelly – Try It Online")
The main part is a monadic link that takes a list of integers and returns an empty list for false and a list containing one or more items for truthy. To meet the challenge rules, the program includes another link above the main one which is just filler.
Completes all test cases including itself in about 17 seconds on TIO. Full explanation to follow. Note the footer turns the falsy and truthy outcomes to 0 and 1 for more compact printing.
General explanation:
* Remove every possible combination of runs of three (including removing none)
* Check the remaining integers are in groups of length 0 mod 3, except for one that is of length 2 mod 3
## Explanation
```
°þþ&&,@ƑƒWß»Ȥ | Filler to meet challenge requirements
W√û | Sort (technically with order based on that after wrapping each item in a list, but this doesn't affect sort order)
W | Wrap in a list
$Ƭ | Repeat the following until no changes are made, gathering up intermediate results
Ʋ€ | - For each list in the lists of lists (example for e.g. [1, 2, 3, 4, 4])
+þ@3 | - Outer addition using 1, 2, 3 e.g. [[[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [5, 6, 7]]
’ | - Decrease by 1 e.g. [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [4, 5, 6]]
œ&ƑƇ | - Filter, keeping only those lists that were seen in the original list e.g. [[1, 2, 3], [2, 3, 4]]
œ-@€ | - Filter the original list removing each of these in turn [[4, 4], [1, 4]]
Ẏ | - Join inner lists together, leaving one list of lists
Ẏ | Join all gathered intermediate results into one list of lists
ɗ€ | For each list within this list:
Œɠ | - Run lengths
% 3 | - Mod 3
¹Ƈ | - Only keep those non-zero (i.e. those lists that were not a multiple of 3 in length)
‘ | Increase by 1
œ&ƑƇ3 | Only keep those that consist of a single 3
```
Some of the code above (e.g. using `W√û` rather than `·π¢`) would be suboptimal in normal code-golf challenges, but here improve length by reducing the amount of filler required.
The runtime is sufficient to complete all the test cases, but as written becomes very inefficient as the number of runs of three consecutive numbers increases. This can be greatly improved by adding a uniquify step ([TIO](https://tio.run/##y0rNyan8///QBp3D@w7vU1NVdTg28dik8MPzD@0@sSQw8FjXsS6u8MPzwrUP73MwftQw8@hkNaCC9qOTdR0eNa05tglIPNzVB1IHoo9OOrlA9dDOY@0npwMlgOpnQNUb/z@08/AMr8xHG9cBDTnW5X9sov3h9oe7dnA93Lnv0E4Q1/pRwxwFXTuFRw1zrQ@3cz3cveXopDCgKYfbgUTk//9KSkrRBjoKBrFc0ZaWljoKCMLQyNgEQgLlDHUUjGDIGMIHSpqD@aYwZAGU01EwA@pH1mEMRiYwBFFqBkZA/eYQpXBkhGwRBAFVgFyIiWK5lPCF8KFt1AhiJa5okBMhzjQGO94c7kO4gyF@swAjQzMINjaCYDMTEI4FhjQA)), reducing the run time for all test cases and my original code down to ~0.3 seconds total).
[Answer]
# [Raku](https://raku.org/), ~~121~~ 116 bytes
```
{sub k(\u){u{*}~~[.2/.1]||?(u{*}:k).grep:{?grep {u (>)$_&&k u (-)$_},^3+$_,[$_,$_,$_]}}(bag |$_)}#%&//:>>?\`aabeqqss
```
[Try it online!](https://tio.run/##ZY7dboMwDIVfxeoYClsGJWGhMBUehDIGEvSCVqMgLqqQvjrLD7SbJn3HsWzn2F3dn9h8voLdwH7mw1hBiw6jw0f@Im63zCWe6@fTlCJViFvHPfZ1F/NUPcBHQIljFbbdgkzfZCrwJ321CpxJaXIhUFUeYbIKRzw9254XJ0l6@CrLqr5chmH@gKG8wsYq3E4egxzYJ8AbkFYbaL57yLYYtjmGLIoiDI/gExqYqJo@BrJCl4Jsh7rwvrKTTQxMOvz5QzXBipllGmkQLrN3yO9dBjWi7vyP6miDxYVq8/Bxwt3QLN9pfGZEiRELlPL5Bw "Perl 6 – Try It Online")
The inner subroutine name `k` and its argument `u` were somewhat haphazardly chosen to try to produce more triples and runs.
* `bag |$_` converts the argument list into a `Bag` (a set with multiplicity) which is then given to the inner recursive subroutine `k`.
* The subroutine returns true if `u{*} ~~ [.2/.1]`, that is, if the bag contains a single element with multiplicity 2. This is the pair that a winning mah jong hand must contain.
* Otherwise, for the keys ùë• in the bag (`u{*}:k`), return true if the bag is a superset (`u (>) $_`) of either the run ùë•, ùë• + 1, ùë• + 2 (`^3 + $_`) or the triple ùë•, ùë•, ùë• (`[$_, $_, $_]`), and the bag minus those elements (`u (-) $_`) produces a true result when passed to the inner recursive function `k`. (Normally I prefer using the Unicode characters for superset (`‚äÉ`) and set minus (`‚àñ`), which are the same number of bytes as the equivalent plain ASCII operators (`(>)` and `(-)` respectively), but then I'd have to repeat both of them twice in the trailing comment for a substantial byte penalty.)
Of course, the trailing comment `#%&//:>>?\`aabeqqss` makes the overall code snippet into a winning numerical mah jong hand. The function takes an infeasibly long time to validate itself; I constructed the comment by visual inspection of the function's character distribution.
The pair is: `~~`
The runs are: `#$%`, `()*`, `()*`, `+,-`, `123`, `[\]`, `[\]`, `^_` plus a backtick I can't figure out how to escape, `pqr`, `pqr`
The triples are: , , `$$$`, `$$$`, `&&&`, `(((`, `)))`, `,,,`, `...`, `///`, `:::`, `>>>`, `???`, `___`, `___`, `aaa`, `bbb`, `eee`, `ggg`, `kkk`, `sss`, `uuu`, `uuu`, `{{{`, `{{{`, `|||`, `}}}`, `}}}`
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~116~~ 92 bytes
Brute force solution checking all permutations until it finds one that matches. Times out on medium inputs, so verification was done using the program below since it doesn't time out as easily.
Recursive approach saving 24 bytes by G B.
```
e=->a{a[2]?a.permutation.any?{_,o,z,*i=_1;_-o==(o-=z)&&o**2<2&&e[i]}:a!=a|a}#"')).11@@A[]ass
```
[Attempt This Online!](https://ato.pxeger.com/run?1=tVBLTsMwFBTbbLmA-ZmkOFbsAG0pbss5jBW5YGiktI4aFxQan4RNF-VQcBqSuIVKrJFGI83Mex7rvW8Wy0m5Xn8szVPY-7xXLBzKleRUjCTO1WK2NNKkeo7lvBytEqTRG-qkLCGDJNSM-TpkbwGEutOhtxRCxVNhb-QRk5W0J8fnQYAJGY_vuJBFse3Y5KDtcE8aJrGRWVYOfMMTIkJGgyGLIJS40AuD62i0qlRluBKt7_sRxriRZywOXO4rjNUF3aoqradTwRqCOCTWBtZa_qxMgR-mepbjSWlUIbzXaZop0PgeyIHi6kVmp4nw1PzR_XX9dXD4nxfxeIRAJDze7_cR-CVC40vHdUYQoDvETtdht9VXO_TqDIHret9N_IDubzsIV_sX-6vbssZydtz2dJsGd5xv)
## [Ruby](https://www.ruby-lang.org/), 137 bytes
Count the number of occurrences of each element. Then, for each element, removes a pair from the count (if possible), then checks if everything else is sequences or triplets.
```
->a{a.any?{t=a.tally;(t[_1]-=2)>=0&&a.sort.all?{|e|t[e]>=0&&((0...t[e]%=3).all?{(e..e+2).all?{|i|t[i]=t[i]&.-1}})}}}#$&*++3;;??\\__lmtty|
```
[Attempt This Online!](https://ato.pxeger.com/run?1=zVHRboIwFM1e-xWNcwQmNNA61CjyIdiQ4upkQSVStxDgA5bsD_Zilu2jtq9ZaZWZ7AeWnHuT03PvOTfw9rE_JOXxfRV8HsTKGX-9OHNWMcS2ZViJgCHBsqycmiKKPeoE2JoHrmEwVOz2AkkprGpei4hT9W6aLkKopTcBsbRucoT4AJ9YncrplAZtM5DjNY3VNM1137gdDMh0GoaLRRxnGyHK-nTQJoEBfOCiQMv1bpOjpBS8UPkgh4m-D-QHUUiSbh_5Upi9nlXF3mwW40bOrKKEAvC8TjOufABMpSN_YhnsxwDmMLXlTEoB394DHXr8vnr9N98BRK4NXQqiyWRiw9_mYTLUXWqeDfEZRHMpjhS_O2MsNRv6cv9ygygMz9CjvoLcH-nRDvgySIPqC_9CCu22diDKd9SFd146dqzg-boI1uUP26L6r_wA)
] |
[Question]
[
Within the recesses of Unicode characters, there exists a Unicode block of (currently) 63 characters named "Number Forms", which consists of characters that have numerical values such as the roman numeral Ⅻ, vulgar fractions like ⅑ or ↉, or weird ones like ↊ (10) or ↈ (100000).
Your task is to write a program or function that, when given a list of assigned Unicode characters within this block, sorts the list by the numerical values of each character.
A (sortable) list of characters and values can be found on the [Wikipedia Page](https://en.wikipedia.org/wiki/Number_Forms).
To be self contained though, here's a list of the codepoints and their values:
```
Hex Char Value
0x00BC: ¼ = 1/4 or 0.25
0x00BD: ½ = 1/2 or 0.5
0x00BE: ¾ = 3/4 or 0.75
0x2150: ⅐ = 1/7 or 0.142857
0x2151: ⅑ = 1/9 or 0.111111
0x2152: ⅒ = 1/10 or 0.1
0x2153: ⅓ = 1/3 or 0.333333
0x2154: ⅔ = 2/3 or 0.666667
0x2155: ⅕ = 1/5 or 0.2
0x2156: ⅖ = 2/5 or 0.4
0x2157: ⅗ = 3/5 or 0.6
0x2158: ⅘ = 4/5 or 0.8
0x2159: ⅙ = 1/6 or 0.166667
0x215A: ⅚ = 5/6 or 0.833333
0x215B: ⅛ = 1/8 or 0.125
0x215C: ⅜ = 3/8 or 0.375
0x215D: ⅝ = 5/8 or 0.625
0x215E: ⅞ = 7/8 or 0.875
0x215F: ⅟ = 1
0x2160: Ⅰ = 1
0x2161: Ⅱ = 2
0x2162: Ⅲ = 3
0x2163: Ⅳ = 4
0x2164: Ⅴ = 5
0x2165: Ⅵ = 6
0x2166: Ⅶ = 7
0x2167: Ⅷ = 8
0x2168: Ⅸ = 9
0x2169: Ⅹ = 10
0x216A: Ⅺ = 11
0x216B: Ⅻ = 12
0x216C: Ⅼ = 50
0x216D: Ⅽ = 100
0x216E: Ⅾ = 500
0x216F: Ⅿ = 1000
0x2170: ⅰ = 1
0x2171: ⅱ = 2
0x2172: ⅲ = 3
0x2173: ⅳ = 4
0x2174: ⅴ = 5
0x2175: ⅵ = 6
0x2176: ⅶ = 7
0x2177: ⅷ = 8
0x2178: ⅸ = 9
0x2179: ⅹ = 10
0x217A: ⅺ = 11
0x217B: ⅻ = 12
0x217C: ⅼ = 50
0x217D: ⅽ = 100
0x217E: ⅾ = 500
0x217F: ⅿ = 1000
0x2180: ↀ = 1000
0x2181: ↁ = 5000
0x2182: ↂ = 10000
0x2183: Ↄ = 100
0x2184: ↄ = 100
0x2185: ↅ = 6
0x2186: ↆ = 50
0x2187: ↇ = 50000
0x2188: ↈ = 100000
0x2189: ↉ = 0
0x218A: ↊ = 10
0x218B: ↋ = 11
```
### Test cases:
```
['½','ↆ','ↂ','⅒','Ⅽ','⅑','ⅷ'] -> ['⅒','⅑','½','ⅷ','ↆ','Ⅽ','ↂ']
['¼','↋','↉','ↅ','⅐','⅟','Ⅻ','ⅺ'] -> ['↉','⅐','¼','⅟','ↅ','↋','ⅺ','Ⅻ']
['¼','½','¾','⅐','⅑','⅒','⅓','⅔','⅕','⅖','⅗','⅘','⅙','⅚','⅛','⅜','⅝','⅞','⅟'] -> ['⅒','⅑','⅛','⅐','⅙','⅕','¼','⅓','⅜','⅖','½','⅗','⅝','⅔','¾','⅘','⅚','⅞','⅟']
'⅞ⅾ↊ↄⅨⅮⅺↁⅸⅰⅩⅱⅶ¾ⅧↅↃ↋ↆ⅔ⅼⅲ⅘⅒ⅽⅦ⅕ⅤⅭⅳↂⅪⅬⅯↇⅠⅷ⅛Ⅵ½ⅵ¼ⅻ⅐Ⅱ⅜⅗⅝⅚Ⅳ⅓ⅴ↉ⅿⅫⅹↀↈ⅙⅑Ⅲ⅖⅟' -> '↉⅒⅑⅛⅐⅙⅕¼⅓⅜⅖½⅗⅝⅔¾⅘⅚⅞⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↄↃⅮⅾⅯⅿↀↁↂↇↈ'
['Ↄ','ↄ','↊','↋'] -> ['↊','↋','ↄ','Ↄ']
```
Note that four of the symbols (the ones used in the last case) are not unicode numbers, though they still have a numerical value, so make sure to check before just posting a built-in.
### Rules:
* If any more characters are assigned to this block in the future, you won't need to update your code to support them.
* Order of characters with identical values doesn't matter.
* [IO is flexible](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422).
+ Output must be as the characters though, not the numerical values
* [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* I'm not banning built-ins that can fetch the numerical value of a character, but I encourage also adding a non-builtin answer if possible.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes for each languages wins! Good luck!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~216~~ 213 bytes
-3 bytes thanks to TFeld
```
lambda l:sorted(l,key='⅒⅑⅐⅙⅕¼⅓⅖½⅗⅔¾⅘⅚⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↃↄ⅛⅜Ⅾⅾ⅝⅞Ⅿⅿↀↁↂↇↈ'.find)
```
[Try it online!](https://tio.run/##TZJLTxpRGIb3/gp2I8mkG3cm/BJkYQNEIh0MzMZdC76nKhuRq3irWqut4qVeUARN5qe8f4TO98akbp6ZkzkzX@Z5zspquFQK5qb51MK0uPjlc3YxUZyvlMphLjtb9JdzqymP2CYaxBaxQ7SjMdEkOtGE6BKt6JXoEX3ikPhB3BBHxC1xTPwlTog74idxT5wSD3QgfhGPxBkxJM6JJ@I38Uy3SfwhRnR14oJ4IS6JMZ0jBsSErka3RuwSe8QVEY/eJw6Ia@KN7ivdN7oq3Xe6de9TvhBkk9MwVwkrqXTaiyae78XfEqtGbIsDsSEOvYwfbx1rU13cEKHHW@KheCGO/r@gAdHrh42ND1OaYktsix2xK/bEHbEv7op74r548D48o4X9fSzMfJxLxsj@3lzeSGdc4NHanJlxE1eXx5YJtTA9dZ0oRluFBpYq1mcNLs1p7NGKDmX81II/WP0XnYUjReiqQF@dmxbZbVgKq/esIOs6NQ0dh47UpWObNTldEzffXWcyM/lSOWG9EoVA18r8TGKlXAjCWVv53kLg@XndJ7VITv8B "Python 3 – Try It Online")
### With built-in that fetch the numerical value, 111 bytes
```
lambda l:sorted(l,key=lambda c:[10,11,100,100,0]['↊↋Ↄↄ'.find(c)]or numeric(c))
from unicodedata import*
```
[Try it online!](https://tio.run/##TZHJbuJgEITvPIVvhsgagXJD4knAB4JtxRqwkTEHblnofyZwCbNkX2bJMpklsySzJhDJj1IvwjQlpHDwZ7fdv6u6ut1LV@NoeRpUatNmvbXi1a1muRMnqe/lm85Tv1eZv22Uq6WiUyo5pWKRV9Gt2jADmCHMJkzffhKEkZdvFNw4saJuy0/ChlaFXJDELasbhY3Y8716WrfCVlsFlqap30k7lWrVzsa2o/8y5MaM8oL8Qo7I37braOs9m4bkFin8vE2ekp/If48HKJBNFhpHCyovyVfka3KH3CX3yH3ygDwkj8hj8mQu7rKATBhMH/IBcq1OYNYhfyDfIFeQ75Bf2QRyqd6ZnSZo1ADkHvJDFdUYZAy5UD@QM80BcqPJQD5CPkO@wjyDvNFM1AzkPNPen5kevtPxIG/VnLpXc@oY8l4nhNxqXJAHDQfyF2YN5rlOpUFA3unAjG620E1m2icH86xdNxfoUmf7ssKI9045Z7WTMErzs8qxa5HtBHwusChM/wM "Python 3 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 57 bytes
```
*.sort: {%(<Ↄ 100 ↄ 100 ↊ 10 ↋ 11>){$_}//.unival}
```
[Try it online!](https://tio.run/##LY3HTgJRAEV/5S1UYDMwGxdG/RWDRhIMMAbUhEwmsd1n29h7b2DvXTGZTzk/Mr6Fq7M5597hwWqpMynXTUfB9Jgk9GpBdaTLhO3pbuyU8XM5g53@57yjw4Lx/d5M2NYXZbPeaKU4li9FUVLL100hnUL7qOVcl6EmukWf2An0ju7RBXpAr3ELNbByJ24Qa9Eq@kaPaBMtox90jtbQKbpBT9hJdImu0R12Bh2iN7SDzmLnvsQu/kKL6Ajtog20h7bRCVpBz9g59Iuu0Ad2HDuLttASOkbr6CDlDQTl/ow3FBQryR8 "Perl 6 – Try It Online")
Just looks up the four exceptional characters in a hash, or falls back to the built-in `unival` method.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~192~~ ~~74~~ ~~63~~ 61 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Σ•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ
,λ₂ϦP(Ì•65в₂+sÇт%k
```
-118 bytes by using characters of 05AB1E's code page only, so we don't need to use UTF-8 encoding.
-11 bytes thanks to *@Adnan*.
-2 bytes thanks to *@Grimy*.
[Try it online](https://tio.run/##MzBNTDJM/f//3OJHDYucji480nho/@GJhxee23ZuyuGph5c9ampVOrTO/fDMR01Nh9Yd2nBs2@G1@UqHlh/efLjf5NCOpCPth6coPmpqPrwzyu3wrsMTDq85uoNL59xuoPLD/YeWBWgc7gEabGZ6YRNQRLv4cPvFJtXs//@j1Q/tVddRf9TWBiabQGTrJDC5FkxOBJPb1WMB) or [verify all test cases](https://tio.run/##TdG9TsJQFAfwnbeQxNRERvEBHDBuzhoGSRyMAwOzCRRaVEwABRHFD0DBD0AERT5UknvAxaTRV@iL1Pbfkp7ll9vT2557/ycc2QrtbBv@wJqhVfVoZWVansTEmLJU1npajvJU02XFK1qrVNRlWbRE@7tHzbBX1KlL6SXRD02SlJvT5TgNNgI0pAw1pn2PTxuZ2yktausLdGT@eNn/2zErixFK/snzu8beT4nqPmNTEp@ST9JVFcqWyjFswix8l4Iec@sHNqXgAVTwOgOv4RMcuh@ggfhiG7OsywnMwTw8hQV4BovwHF7AEryEV05zq@HsCd3UQ5hA5R62nMNZ9RjWfdiGD/AF9txD192bqnGWgMqOjmSUDju0fT2Eq9TY9W5ZuF0W@iNswGfUk1jfOANwL383C1VX3qyl3XvEAi6zkAosKjvCKgv@1Z2lMmbzG6AehftsCPboKmxQTvBOMgkWfEoK/gM).
**Explanation:**
```
Σ # Sort the input by:
•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ
,λ₂ϦP(Ì•65в₂+
# List of ASCII values modulo-100 of the characters we want to sort
sÇ # Get the ASCII value of the current input-character
т% # Take modulo 100 of this ASCII value
k # And get the index in the list of ASCII values, as sorting order
```
So what is `•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ\n,λ₂ϦP(Ì•65в₂+`?
Based on the order of the characters modulo-100 we get the following list:
```
[85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84]
```
These are generated by the following program:
```
"↉⅒⅑⅛⅐⅙⅕¼⅓⅜⅖½⅗⅝⅔¾⅘⅚⅞⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↃↄⅮⅾⅯⅿↀↁↂↇↈ"Çт%
```
[Try it online.](https://tio.run/##Dc1bUoEBGIDhvZjpvi5aEDPto/B@UjcdUFIhOtDBqUKomd8KbOHdyK9nA8/ufja3d5CmGaMsF3IuDTmTulSTpVzKrdSSlVzJnVSSX7mWG7mXprRkKG0ZyYOMpSMT6cqnPMqXgTzJtzzLVF5kJj2ZGyfSlx/jVF5lIW@yNELeZWUUjKJ8yP87kD/j0Dgy8kbJOM6sS5v8TppuAQ)
`•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ\n,λ₂ϦP(Ì•65в₂+` is a shorter variation of this list by taking the [compressed number](https://codegolf.stackexchange.com/a/166851/52210) `1485725021600091112740267145165274006958935956446028449609419704394607952161907963838640094709317691369972842282463`, then converting it to Base-65, and then adding 26 to each.
[Try it online](https://tio.run/##AW4Akf8wNWFiMWX//@KAokLFocSBwr/DkcOhzrbOlMOVw6bigoUiwq5Hw5nigoLCrsKwxrbDrW8iwqfDs8OPNMK4YsSHw5Qh4oKDw7laRsO6w5DDrMW4CizOu@KCgsOPwqZQKMOM4oCiNjXQsuKCgiv//w) and [verify that the lists are the same](https://tio.run/##DY07TkJRAAV7duFLTEy00ERcgIW22tpJYu0W5OG5@EsABRX/oIIfQARFvpLcC5ZEtzAbeb52MpmZj27GFraCwMPso2OUQZcojfIoZ/voBF2hUztAZ@gaZe03OkcX6AbdojtURwX0joqoge5REz2gD/SIPjFCJdRCZfSFnlAbPaMO5gC9oC7mEL2iHqqgPsagKhpgEphdVEPh9w0NMTuYOMbHJDF7nkv@@dMRdorL48Iobocu4wqT1iTrcq6EL8/WVl0e37c1W/9pueq2Z8uu6VKLth0bJV12Cj/hOhsrruvSrjJuR@YmvVB3KVtam3FHYXgp@tsIyWxkPQj@AQ).
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~1~~93 bytes (UTF-8)
```
2{O`.
T`¼-¾⅐-↋\LI ^]Q@TU\\[ZYWSPNK\HFDB?=;975X\VR\OMJG\ECA><:86432\-)#1%0,*&.(!"$/+'`Ro
```
[Try it online!](https://tio.run/##HdBLMkNRFIXhvrlQxURUKQO4Gho6KKWnQ1ibSEckJOIRIS@CxCMJQlTdofwTuc4@Azhnff/eWt1eW1@Zz7KFncVkbmY5wY6wQyw3i/5QH03RC7aPHaBf9IwZ@kFPaIJ6WAF9o0fsGH2hB/SJumiMOmiE2pjQELXQB2qid3SP3tAdekUNNEC3qI5uUA1V0zBbRteokobVc3SFSmnYPUMX6ARdoiI6xfKbydJGlsW3U2c4tevsALO96BlEWNga@c8dF3lTIdaUY1DgVP0/r2zHnabnBqzlvM@L@34cl47jfsttQ1dNIqkRmZXorsXGkidbPh6z5/exXT@xJxRjfiir/wM "Retina – Try It Online") Explanation: Sorts the characters in code point order, then maps between the numeric characters and ASCII characters so that the numeric characters with the lowest value map the the ASCII characters with the lowest code point and vice versa. Then repeats the exercise, so that the characters are now sorted in order of this ASCII mapping, which corresponds to the desired numeric order, before they are transformed back. Edit: Saved 100 (!) bytes by specifying the order of the ASCII characters rather than the numeric characters.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 55 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O%70‘“$Żz*ṀḢD⁹VṢaʠƝ lẹkƝʋ9⁽ƭXmż4#⁺3ç%|ọṢLxƈ⁽}ÞƇ2’Œ?¤iµÞ
```
A monadic link accepting a list of characters which yields a list of characters.
**[Try it online!](https://tio.run/##DcvLLgNxAEbxV5HQjZUgESsbS4md2FpYoPYIyQy@f0sjoW4tbVW16lb30plpK5mms@hbzHmRMevzO6vLyeRmFM0npsawcliFkb63NRo6VtiqzGI7C6FTWRqUg@JQMnSdtaA4yExjd4LG4nq/PTmM7U706ont0DuK4dxGkI7jTq8UpMax8v3sjF9d8Zu9UhRFqIS6mEPMPnpAr8jF2KiF3tEj@kA/fhfVMcLsYTIYg85QG32iHMqiDrpH56iKGugLs4ue0At6w6RQGf2ia1TzY9v049lDx@gWFdAlKqIrdIdO0TfmAP2hZ@RgLEwa5dEJqqALdPMP "Jelly – Try It Online")**
### How?
Much simpler than it looks since `“$Żz*ṀḢD⁹VṢaʠƝ lẹkƝʋ9⁽ƭXmż4#⁺3ç%|ọṢLxƈ⁽}ÞƇ2’` is just a large number in base 250 using Jelly's code-page as the digits, I shall use `“...’` in its place.
```
O%70‘“...’Œ?¤iµÞ - Link: list of characters
Þ - sort by:
µ - the monadic function (i.e. f(character)):
O - get the ordinal value of the character
%70 - modulo by 70 (get the remainder after dividing by 70)
- - giving integers in [0,69] excluding [52,58]
‘ - increment (below code pattern can't have anything but '↉' map to 0)
¤ - nilad followed by link(s) as a nilad:
“...’ - literal 7826363328008670802853323905140295872014816612737076282224746687856347808481112431487214423845098801
Œ? - get the permutation of natural numbers [1,N] with minimal N such
- that this permutation would reside at the given index in a
- sorted list of all permutations of those same numbers
- -> [46,52,53,54,55,56,57,58,61,60,70,59,68,64,49,62,1,65,50,66,2,63,51,67,69,3,4,5,21,6,22,7,23,8,24,9,25,10,26,42,11,27,12,28,13,29,14,30,47,15,31,48,16,32,17,33,43,18,34,40,41,19,35,20,36,37,38,39,44,45]
i - first index of (the ordinal mod 70 plus 1) in that list
```
---
### Aside
Somewhat ironically the nearest to a "use a built-in approach" I could muster was [85 bytes](https://tio.run/##FY45ToJRGEV79@ECjAuws9DCzlhZOURC7O144n04JA44TyCI4oATAv4DaPKIJi7jnY3gs7n5cr/knpOZz2ZXBgNyF6627KOyT2JMB9P2yfaoj/KuvoL5wCTfRR81w9dVfNryyfrYrI9Kv10fN3xsf48xvf7r@ISr/xTC6ZOij6s@3ZoZd9WRyZ8mpuujjk92eHte8PHRokvDTIbcJSb6Lk6HHJoaxsRBBJO6d0wrQMmdLIWVf7ue@5qbc5XQuGAY9Quu5uIx1@6XBkHfbmHz2DXsJnYdW8CuYg02h77QC/pEz6iHnrAWdVEDpegRJegBxegeRegOfaA66qBbrFAb3aAWqqF3dI2aqIreUAW9oitURiV0hk5cQB2gS3TsAu8IXaB9F4iH6BTtonO0h4rYjT8 "Jelly – Try It Online"), this uses a compressed string:
```
from unicodedata import*; copy_to( atoms['
'], numeric( atoms['
'].call()))
```
which is split on newlines and joined with `⁸`s to give the Python code:
```
from unicodedata import*; copy_to( atoms['⁸'], numeric( atoms['⁸'].call()))
```
which is executable within Jelly's interpreter - it will place the Unicode character's numeric value into the left argument nilad, `⁸` for later use.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 72 bytes
```
ñ@`'%!x("y#) z$&*+,<-=.>/?0@1aq2b3c4d5ev6fw7g8hr9iop:j;klmn¡`u bXcuL
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=8UBgHh0nHCUheB8oInkjKSB6JCYqKyw8LT0uPi8/MEAxYXEyYjNjNGQ1ZXY2Znc3Zzhocjlpb3A6ajtrbG1uoWB1IGJYY3VM&input=WyK9IiwiXHUyMTg2IiwiXHUyMTgyIiwiXHUyMTUyIiwiXHUyMTZkIiwiXHUyMTUxIiwiXHUyMTc3Il0=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.5&code=8UBgHh0nHCUheB8oInkjKSB6JCYqKyw8LT0uPi8/MEAxYXEyYjNjNGQ1ZXY2Znc3Zzhocjlpb3A6ajtrbG1uoWB1IGJYY3VM&input=WwpbIr0iLCJcdTIxODYiLCJcdTIxODIiLCJcdTIxNTIiLCJcdTIxNmQiLCJcdTIxNTEiLCJcdTIxNzciXQpbIrwiLCJcdTIxOGIiLCJcdTIxODkiLCJcdTIxODUiLCJcdTIxNTAiLCJcdTIxNWYiLCJcdTIxNmIiLCJcdTIxN2EiXQpbIrwiLCK9IiwiviIsIlx1MjE1MCIsIlx1MjE1MSIsIlx1MjE1MiIsIlx1MjE1MyIsIlx1MjE1NCIsIlx1MjE1NSIsIlx1MjE1NiIsIlx1MjE1NyIsIlx1MjE1OCIsIlx1MjE1OSIsIlx1MjE1YSIsIlx1MjE1YiIsIlx1MjE1YyIsIlx1MjE1ZCIsIlx1MjE1ZSIsIlx1MjE1ZiJdClsiXHUyMTVlIiwiXHUyMTdlIiwiXHUyMThhIiwiXHUyMTg0IiwiXHUyMTY4IiwiXHUyMTZlIiwiXHUyMTdhIiwiXHUyMTgxIiwiXHUyMTc4IiwiXHUyMTcwIiwiXHUyMTY5IiwiXHUyMTcxIiwiXHUyMTc2IiwiviIsIlx1MjE2NyIsIlx1MjE4NSIsIlx1MjE4MyIsIlx1MjE4YiIsIlx1MjE4NiIsIlx1MjE1NCIsIlx1MjE3YyIsIlx1MjE3MiIsIlx1MjE1OCIsIlx1MjE1MiIsIlx1MjE3ZCIsIlx1MjE2NiIsIlx1MjE1NSIsIlx1MjE2NCIsIlx1MjE2ZCIsIlx1MjE3MyIsIlx1MjE4MiIsIlx1MjE2YSIsIlx1MjE2YyIsIlx1MjE2ZiIsIlx1MjE4NyIsIlx1MjE2MCIsIlx1MjE3NyIsIlx1MjE1YiIsIlx1MjE2NSIsIr0iLCJcdTIxNzUiLCK8IiwiXHUyMTdiIiwiXHUyMTUwIiwiXHUyMTYxIiwiXHUyMTVjIiwiXHUyMTU3IiwiXHUyMTVkIiwiXHUyMTVhIiwiXHUyMTYzIiwiXHUyMTUzIiwiXHUyMTc0IiwiXHUyMTg5IiwiXHUyMTdmIiwiXHUyMTZiIiwiXHUyMTc5IiwiXHUyMTgwIiwiXHUyMTg4IiwiXHUyMTU5IiwiXHUyMTUxIiwiXHUyMTYyIiwiXHUyMTU2IiwiXHUyMTVmIl0KWyJcdTIxODMiLCJcdTIxODQiLCJcdTIxOGEiLCJcdTIxOGIiXQpdLW1S)
---
## Explanation
```
ñ@ :Sort by passing each X through a function
`...` : A compressed string, which itself contains a bunch of unprintables (See below for codepoints of original string)
u : Uppercase
b : Index of
Xc : Charcode of X
uL : Mod 100 and get character at that codepoint
```
### Codepoints
```
30,29,39,28,37,33,120,31,40,34,121,35,41,32,122,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,97,113,50,98,51,99,52,100,53,101,118,54,102,119,55,103,56,104,114,57,105,111,112,58,106,59,107,108,109,110,115,116
```
---
## Original Solution, ~~90~~ ~~89~~ 88 bytes
```
ñ!b`(&" )#$*!%'+,-=.>/?0@1a2br3c4d5e6fw7gx8h9:jpq;k<lmÍ/`®iv u nLõd)dÃi6'¼ iA'½ iE'¾
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=8SFiYB8eKB0mIiApIyQqISUnKywtPS4+Lz8wQDFhMmJyM2M0ZDVlNmZ3N2d4OGg5iTpqcHE7azxsbc0vYK5pdiB1IG5M9WQpZMNpNie8IGlBJ70gaUUnvg==&input=WyK9IiwiXHUyMTg2IiwiXHUyMTgyIiwiXHUyMTUyIiwiXHUyMTZkIiwiXHUyMTUxIiwiXHUyMTc3Il0=) or [run all test cases](https://ethproductions.github.io/japt/?v=1.4.6&code=8SFiYB8eKB0mIiApIyQqISUnKywtPS4+Lz8wQDFhMmJyM2M0ZDVlNmZ3N2d4OGg5iTpqcHE7azxsbc0vYK5pdiB1IG5M9WQpZMNpNie8IGlBJ70gaUUnvg==&input=WwpbIr0iLCJcdTIxODYiLCJcdTIxODIiLCJcdTIxNTIiLCJcdTIxNmQiLCJcdTIxNTEiLCJcdTIxNzciXQpbIrwiLCJcdTIxOGIiLCJcdTIxODkiLCJcdTIxODUiLCJcdTIxNTAiLCJcdTIxNWYiLCJcdTIxNmIiLCJcdTIxN2EiXQpbIrwiLCK9IiwiviIsIlx1MjE1MCIsIlx1MjE1MSIsIlx1MjE1MiIsIlx1MjE1MyIsIlx1MjE1NCIsIlx1MjE1NSIsIlx1MjE1NiIsIlx1MjE1NyIsIlx1MjE1OCIsIlx1MjE1OSIsIlx1MjE1YSIsIlx1MjE1YiIsIlx1MjE1YyIsIlx1MjE1ZCIsIlx1MjE1ZSIsIlx1MjE1ZiJdClsiXHUyMTVlIiwiXHUyMTdlIiwiXHUyMThhIiwiXHUyMTg0IiwiXHUyMTY4IiwiXHUyMTZlIiwiXHUyMTdhIiwiXHUyMTgxIiwiXHUyMTc4IiwiXHUyMTcwIiwiXHUyMTY5IiwiXHUyMTcxIiwiXHUyMTc2IiwiviIsIlx1MjE2NyIsIlx1MjE4NSIsIlx1MjE4MyIsIlx1MjE4YiIsIlx1MjE4NiIsIlx1MjE1NCIsIlx1MjE3YyIsIlx1MjE3MiIsIlx1MjE1OCIsIlx1MjE1MiIsIlx1MjE3ZCIsIlx1MjE2NiIsIlx1MjE1NSIsIlx1MjE2NCIsIlx1MjE2ZCIsIlx1MjE3MyIsIlx1MjE4MiIsIlx1MjE2YSIsIlx1MjE2YyIsIlx1MjE2ZiIsIlx1MjE4NyIsIlx1MjE2MCIsIlx1MjE3NyIsIlx1MjE1YiIsIlx1MjE2NSIsIr0iLCJcdTIxNzUiLCK8IiwiXHUyMTdiIiwiXHUyMTUwIiwiXHUyMTYxIiwiXHUyMTVjIiwiXHUyMTU3IiwiXHUyMTVkIiwiXHUyMTVhIiwiXHUyMTYzIiwiXHUyMTUzIiwiXHUyMTc0IiwiXHUyMTg5IiwiXHUyMTdmIiwiXHUyMTZiIiwiXHUyMTc5IiwiXHUyMTgwIiwiXHUyMTg4IiwiXHUyMTU5IiwiXHUyMTUxIiwiXHUyMTYyIiwiXHUyMTU2IiwiXHUyMTVmIl0KWyJcdTIxODMiLCJcdTIxODQiLCJcdTIxOGEiLCJcdTIxOGIiXQpdLW1S)
---
### Explanation
```
`...` :A compressed string, which itself contains a bunch of unprintables (See below for codepoints of original string)
® :Map
iv : Prepend "v"
u : Convert to uppercase
Lõ : Range [1,100]
d : Characters at those codepoints
n ) : Convert from that base to base-10
d : Get the character at that codepoint
à :End map
i6'¼ :Insert "¼" at (0-based) index 6
iA'½ :Insert "½" at index 10
iE'¾ :Insert "¾" at index 14
ñ :Sort the input array
!b : By finding the index of the current element in the string above
```
**Codepoints**
```
31,30,40,29,38,34,32,41,35,36,42,33,37,39,43,44,45,61,46,62,47,63,48,64,49,97,50,98,114,51,99,52,100,53,101,54,102,119,55,103,120,56,104,57,105,115,58,106,112,113,59,107,60,108,109,110,111,116,117
```
[Answer]
# 05AB1E, ~~56~~ ~~53~~ ~~51~~ ~~50~~ ~~49~~ 48 bytes
```
ΣÇ©1ö•Ω‘~Èr–Õî5®Î¼ÓÂ∍_OûR•42в•мjāl†£•₂°*S>ÅΓ®Íè+
```
[Try it online!](https://tio.run/##DYvLLgNhHEffhxVh6xUkPICQWBCJhL1Mh9@/RSoYpe7VcWldRhV16ajk@6ybPsN5kTGrk5Ocs7w6O7cwn2X92Bddc8R3COr9JkF1zZdWCCJf8cm4S/yOS33kQ0rlmUnfncqrsdFBO8cgXfwrLBHUXJwbYehaQ9MTXv0ov8q@MZxl6AL1sC1sAzVQgr6xAvpELdREL6jjeugOE7aObWOGDlCK2qiK9tEPukUVdI2e0CsWonv0iJ6xIqqhD3SKblzevrt87qJddIXO0BE6RycoRhF6wzbRL3pAX1iAldAx2kN1dIgu/wE "05AB1E – Try It Online")
At the core of this solution is a compressed list mapping unicode code points to a sorting key. Characters that correspond to the same number are mapped to the same key, so we only need 40 different keys.
70 is the smallest number by which we can modulo all input codepoints and get distinct results. Since indexing in 05AB1E wraps around, we don’t need to explicitly `70%`, just make sure the list is length 70.
Notice that there are long stretches of consecutive code points with consecutive keys. Thus, encoding (key - codepoint) rather than simply (key) gives long stretches of identical numbers, which can be run-length encoded. However, the range of code points is very large (damn those 0xBC .. 0xBE), which would be an issue. So instead of (key - codepoint), we encode (key - sum\_of\_digits(codepoint)), which unfortunately limits the stretch length to 10, but does quite well at reducing the range of encoded values. (Other functions are of course possible, like codepoint % constant, but sum of digits gives the best results).
Additionally, it turns out rotating the list by 2 plays well with run-length encoding, so we subtract 2 from the codepoint before indexing.
```
•Ω‘~Èr–Õî5®Î¼ÓÂ∍_OûR•42в # compressed list [25, 34, 27, 36, 30, 38, 29, 35, 41, 0, 28, 16, 19, 31, 7, 4, 11, 17, 22, 13, 16, 17, 20, 8, 19, 4, 18, 21]
•мjāl†£• # compressed integer 79980000101007
₂°* # times 10**26
S # split to a list of digits
> # add 1 to each
ÅΓ # run-length decode, using the first list as elements and the second list as lengths
Σ # sort by
Ç©1ö # sum of digits of the codepoint
+ # plus
... è # the element of the run-length decoded list
®Í # with index (codepoint - 2) % 70
```
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 117 bytes
```
a=>a.sort((a,b)=>(g=c=>';<=>GHIJCDEF?@AB/37~15:;8-9+6.24,*)0N(DEH@GMJKLH'[(c.charCodeAt()&127^44)%92%76%60])(a)>g(b))
```
[Try it online!](https://tio.run/##jZFbTxpRFIXf/RV9wTmn4ggUoV5migUKausfMDYZR6QoZQhDTHwxXrrH24tardqbt17UtrZqrwo0mZ@y/whud3wgISG@fE9nrbPXWmPGhGGbhUy@2GrnMyOpwnMrN56arI5qVUPTDdW2CkUhDO@w1HSR1kxNV7q6NT2R7O2LxuKPHkR6HrbdC0/52zu77rd2tITUQNB7V/oGRCyejCSe9PU/TiqDwlTNZ0Yhao2keopCNvsD4afBoPR0BDzhkCfkG5LCkHpaDEtZNa2cbWVTatZKi1ExqLhlxaug4zBnrwlrzG/MVeYfZUiqY1YmJ5Q7ipRNdSYlli8zF5nAwhXmDvML8@I2VnyUW6mxWK257CVznbnBfMXcZG4xt5mvmW@Yb5nvmO9vzmp8CjpzHOUFc@kmYkONqqrX9ggVEpAS4RDhhFKjM4PwF@EHwhHCKcJvt4LwmXqiX8iWFqBICCWEM8pAURHKCJ8oIcIHWgPhnPZBOEb4ivAdnXmEXVqG4iF8dOntL5fEl1QYwh7FpT4oLnWAcECdIfykaRD@0xAI/9CZRmeBeqJqEfapwro@qlc "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# T-SQL, 207 bytes
```
SELECT*FROM t ORDER BY
CHARINDEX(c,N'⅒⅑⅛⅐⅙⅕¼⅓⅜⅖½⅗⅝⅔¾⅘⅚⅞⅟ⅠⅰⅡⅱⅢⅲⅣⅳⅤⅴⅥ
ⅵↅⅦⅶⅧⅷⅨⅸⅩⅹ↊Ⅺⅺ↋ⅫⅻⅬⅼↆⅭⅽↃↄⅮⅾⅯⅿↀↁↂↇↈ'COLLATE Thai_BIN)
```
Return in the middle of the string is for readability only. I think I got the byte count correct (3 of the numeric characters are 1-byte, the remainder are 2-bytes), character count is 148.
I pre-sorted the string in ascending order, leaving out `↉` (which returns 0) as suggested by other answers.
Any binary collation will work, I used `Thai_BIN` since it has the shortest name. (A collation in SQL prescribes how character sorting/comparison is done, I need binary so each character only matches itself.)
[Per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), input is taken via pre-existing table **t** with `NCHAR(1)` field **c**.
If you define the input table itself using a binary collation, you can leave that out to save 16 bytes:
```
CREATE TABLE t(c NCHAR(1) COLLATE Thai_BIN)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 77 bytes
Changes all the characters to letters that represent the numerical values and sorts by that.
```
->a{a.sort_by{|e|e.tr'¼-¾⅐-↋','HLPECBIOGKMQFRDJNSaa-pa-ppqrnnfmstAjk'}}
```
[Try it online!](https://tio.run/##TZDXagJhEIXvfQovAnuT9Q0SSO/90oisQUlVs5qAqJDi/En0RtN7771XNbCPch4km3EQElg@WP4Z5jvHnPDF7EBVv61XG3HDFQmZUa8vFk/4E35X1NSsvG4VQVkdKqNVas3t3Q11tS1dTW0dPY299a2dfYahh/kLj5vBYGAsEq0ZHtGSSTvsDLj9k8aos8Lrsd2aVeBlKCWcKZEWhTfCnPBN8zh4NC9DGeGCkOQ5K9wTXgk//xbkgFX8N5j7d2VJuCxcEa4K14Trwg3hpnBLuC3cEe6Wj3scpR9QESoNlQKdg27ZBGoa9A66B12AHkCvpdrO2B1qltNwdhYA5UGPfJHFQAXQKfuAjrkH0BM3A7oEXYPuoOZA@9wJy4BOLJ59sXj5i@OBDliO7VmOjUFHnBD0zHWBvrkc0AfUFNQ8p@IiQIccuGTvGhg0zAh3xlLSbEqYLjfu@QmFo0OhYMTWg78 "Ruby – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~13~~ 52 bytes
```
*.sort:{%(<Ↄ 99 ↄ 99 ↊ 10 ↋ 11>){$_}//.EVAL}
```
[Try it online!](https://tio.run/##K0gtyjH7n1uplmb7X0uvOL@oxKpaVcPmUVuzgqWlwqO2FgjVpWBoAKS6FQwN7TSrVeJr9fX1XMMcfWr/W3MVJ1YqpCloqB/aq66j/qitDUw2gcjWSWByLZicCCa3q2ta/wcA "Perl 6 – Try It Online")
] |
[Question]
[
The purpose of the challenge is to approximately plot the [attractor](https://en.wikipedia.org/wiki/Attractor) of the [logistic map](https://en.wikipedia.org/wiki/Logistic_map) as a function of its parameter *r* (also called [bifurcation diagram](https://en.wikipedia.org/wiki/Bifurcation_diagram)), or a subregion of it. The appearance of the graph can be seen in the following image from Wikipedia:
[](https://i.stack.imgur.com/IvDrXl.png)
## Background
The **logistic map** is a mathematical function that takes an input *xk* and maps it to an output *xk+1* defined as
*xk+1* = *r* *xk* (1−*xk*)
where *r* is the **parameter** of the map, assumed to lie in the interval [0, 4].
Given *r* in [0,4], and an initial value *x*0 in the interval [0,1], it is interesting to **repeatedly apply** the function for a large number *N* of iterations, producing a final value *xN*. Note that *xN* will necessarily lie in [0,1] too.
As an example, consider *r* = 3.2, *N* = 1000. The initial value *x*0 = 0.01 gives *x*1000 = 0.5130. For *x*0 = 0.02 the result is *x*0 = 0.7995. For *any* other initial values *x*0 the final values *x*1000 are extremely close to either 0.5130 or 0.7995. This is seen in the graph as the height of the two lines at horizontal position *r* = 3.2.
This does *not* mean that for *r* = 3.2 each sequence converges to one of those two values. In fact, for the two initial values considered above, the sequences are (note the oscillating behaviour):
*x*0 = 0.01, ..., *x*1000 = 0.5130, *x*1001 = 0.7995, *x*1002 = 0.5130, ...
*x*0 = 0.02, ..., *x*1000 = 0.7995, *x*1001 = 0.5130, *x*1002 = 0.7995, ...
What *is* true is that for sufficiently large *N*, and for almost all initial values *x*0, the term *xN* will be close to one of the elements of the set {0.5130, 0.7995}. This set is called the **attractor** for this specific *r*.
For other values of the parameter *r* the size of the atractor set, or its elements, will change. The graph plots the elements in the attractor for each *r*.
The attractor for a specific *r* can be **estimated** by
1. testing a wide range of initial values *x*0;
2. letting the system evolve for a large number *N* of iterations; and
3. taking note of the final values *xN* that are obtained.
## The challenge
### Inputs
* ***N***: number of iterations.
* ***r*1**, ***r*2** and ***s***. These define the set *R* of values of *r*, namely *R* = {*r*1, *r*1 + *s*, *r*1 + 2 *s*, ..., *r*2}.
### Procedure
The set *X* of initial values *x*0 is fixed: *X* = {0.01, 0.02, ..., 0,99}. Optionally, 0 and 1 may also be included in *X*.
For each *r* in *R* and each *x*0 in *X*, iterate the logistic map *N* times to produce *xN*. Record the obtained tuples (*r*, *xN*).
### Output
Plot each tuple (*r*, *xN*) as a point in the plane with *r* as horizontal axis and *xN* as vertical axis. Output should be graphic (not ASCII art).
## Additional rules
* The indicated procedure defines the required result, but is not enforced. Any other procedure that procudes the same set of (*r*, *xN*) tuples can be used.
* Input is flexible as usual.
* Floating point errors won't be held against the answerer.
* Graphic output is required, in any of the [accepted formats](https://codegolf.meta.stackexchange.com/q/9093/36398). In particular, output may be displayed on screen, or a graphics file may be produced, or an array of RGB values may be output. If outputting a file or an array, please post an example of what it looks like when displayed.
* Graphics may be vector or raster. For raster graphics, the size of the image should be at least 400×400 pixels.
* Each point should be shown as a single pixel, or as a mark with size of the order of one pixel (otherwise the graph quickly gets cluttered).
* Axis range should be [0,4] for *r* (horizontal axis) and [0,1] for *xN* (vertical axis); or it may be smaller as long as it includes all obtained points.
* Axis scales are arbitrary. In particular, the scale need not be the same for both axes.
* Grid lines, axis labels, colors and similar elements are acceptable, but not required.
* Shortest code in bytes wins.
## Test cases
Click on each image for a high-resolution version.
`N = 1000; r1 = 2.4; r2 = 4; s = 0.001;`
[](https://i.stack.imgur.com/QakwE.png)
`N = 2000; r1 = 3.4; r2 = 3.8; s = 0.0002;`
[](https://i.stack.imgur.com/1QHic.png)
`N = 10000; r1 = 3.56; r2 = 3.59; s = 0.00002;`
[](https://i.stack.imgur.com/TEbWQ.png)
## Acknowledgment
Thanks to [@FryAmTheEggman](https://codegolf.meta.stackexchange.com/users/31625/fryamtheeggman) and [@AndrasDeak](https://codegolf.stackexchange.com/users/45297/andras-deak) for their helpful comments while the challenge was in the sandbox.
[Answer]
# MATL, ~~32~~ ~~30~~ ~~28~~ 27 bytes
*4 bytes saved thanks to @Luis*
```
3$:0:.01:1!i:"tU-y*]'.'3$XG
```
The input format is `r1`, `s`, `r2`, and `N`
Try it at [**MATL Online**](https://matl.io/?code=3%24%3A0%3A.01%3A1%21i%3A%22tU-y%2a%5D%27.%273%24XG&inputs=1%0A.01%0A4%0A1000&version=20.0.0)
[](https://i.stack.imgur.com/AyIge.png)
**Explanation**
```
% Implicitly grab the first three inputs
3$: % Take these three inputs and create the array [r1, r1+s, ...]
0:.01:1 % [0, 0.01, 0.02, ... 1]
! % Transpose this array
i % Implicitly grab the input, N
:" % For each iteration
tU % Duplicate and square the X matrix
- % Subtract from the X matrix (X - X^2) == x * (1 - x)
y % Make a copy of R array
* % Multiply the R array by the (X - X^2) matrix to yield the new X matrix
] % End of for loop
'.' % Push the string literal '.' to the stack (specifies that we want
% dots as markers)
3$XG % Call the 3-input version of PLOT to create the dot plot
```
[Answer]
# Mathematica, 65 bytes
```
Graphics@Table[Point@{r,Nest[r#(1-#)&,x,#]},{x,0,1,.01},{r,##2}]&
```
Pure function taking the arguments N, r1, r2, s in that order. `Nest[r#(1-#)&,x,N]` iterates the logistic function `r#(1-#)&` a total of `N` times starting at `x`; here the first argument to the function (`#`) is the `N` in question; `Point@{r,...}` produces a `Point` that `Graphics` will be happy to plot. `Table[...,{x,0,1,.01},{r,##2}]` creates a whole bunch of these points, with the `x` value running from `0` to `1` in increments of `.01`; the `##2` in `{r,##2}` denotes all of the original function arguments starting from the second one, and so `{r,##2}` expands to `{r,r1,r2,s}` which correctly sets the range and increment for `r`.
Sample output, on the second test case: the input
```
Graphics@Table[Point@{r,Nest[r#(1-#)&,x,#]},{x,0,1,.01},{r,##2}]&[2000,3.4,3.8,0.0002]
```
yields the graphics below.
[](https://i.stack.imgur.com/InJoZ.png)
[Answer]
# Mathematica, 65 bytes
I used some of Greg Martin's tricks and this is my version without using Graphics
```
ListPlot@Table[{r,NestList[#(1-#)r&,.5,#][[-i]]},{i,99},{r,##2}]&
```
**input**
>
> [1000, 2.4, 4, 0.001]
>
>
>
**output**
[](https://i.stack.imgur.com/87MQO.jpg)
**input**
>
> [2000, 3.4, 3.8, 0.0002]
>
>
>
**output**
[](https://i.stack.imgur.com/sQPFM.jpg)
[Answer]
# TI-Basic, [85](https://codegolf.meta.stackexchange.com/questions/1541/how-to-score-ti-basic/4764#4764) bytes
```
Prompt P,Q,S,N
P→Xmin:Q→Xmax
0→Ymin:1→Ymax
For(W,.01,1,.01
For(R,P,Q,S
W→X
For(U,1,N
R*X*(1-X→X
End
Pt-On(R,X
End
End
```
A complete TI-Basic program which takes input in the order `r1,r2,s,N` and then shows the output in real time on the graph screen. Note that this tends to be *incredibly slow*.
Here is an incomplete sample output generated after about 2.5 hours for the input `3,4,0.01,100`:
[](https://i.stack.imgur.com/6y4Ch.png)
[Answer]
# ProcessingJS, ~~125~~ ~~123~~ 120 bytes
Thanks to [Kritixi Lithos](https://codegolf.stackexchange.com/users/41805/kritixi-lithos) for saving 3 bytes.
```
var f(n,q,r,s){size(4e3,1e3);for(i=0;i<1;i+=.01)for(p=q;p<=r;p+=s){x=i;for(j=0;j<n;j++)x*=p-p*x;point(p*1e3,1e3-x*1e3)}}
```
[Try it online!](https://www.openprocessing.org/sketch/435013) Call using `f(N, r_1, r_2, s);`
[Answer]
# [GEL](http://www.jirka.org/genius.html), 158 bytes
```
`(N,r,t,s)=(LinePlotWindow=[r,t,0,1];for i=r to t by s do(p=.;for w=0to 1by 0.01do(x=w;for a=0to N do(x=i*x*(1-x););p=[p;q=[i,x]];);LinePlotDrawPoints(p);););
```
It may not be the shortest, but it draws in real time, although it can be incredibly slow with huge inputs. Anyways, this is an anonymous function which takes input in the format `(N,r1,r2,s)` and outputs the plot in a new window. Note that this *must* be run with the GNOME version of Genius.
[](https://i.stack.imgur.com/SLl6K.png)
[Answer]
# R, ~~159~~ 147 bytes
```
pryr::f({plot(NA,xlim=c(a,b),ylim=0:1);q=function(r,n,x=1:99/100){for(i in 1:n)x=r*x*(1-x);x};for(i in seq(a,b,s))points(rep(i,99),q(i,n),cex=.1)})
```
Which productes the function
```
function (a, b, n, s)
{
plot(NA, xlim = c(a, b), ylim = 0:1)
q = function(r, n, x = 1:99/100) {
for (i in 1:n) x = r * x * (1 - x)
x
}
for (i in seq(a, b, s)) points(rep(i, 99), q(i, n), cex = 0.1)
}
```
`plot(NA,...)` creates an empty canvas that has the correct dimensions. `q` is the function that does the iterating. It takes a value of `r`, and then does `n` iterations for all starting points between `0.01` and `0.99`. It then returns the resulting vector.
The for-loop applies the function `q` to the sequence `a` to `b` with step `s`. Instead of returning the values, it adds them as points to the plot. If the attraction point is one value, all the points would just overlap and show as one point. `cex=.1` is a necessary addition to make the points as small as possible.
[](https://i.stack.imgur.com/k5HfS.png)
] |
[Question]
[
### Challenge
Given a colour raster image\* with the same width and height, output the image transformed under [*Arnold's cat map*](https://en.wikipedia.org/wiki/Arnold%27s_cat_map). (\*details see below)
### Definition
Given the size of the image `N` we assume that the coordinates of a pixel are given as numbers between `0` and `N-1`.
*Arnold's cat map* is then defined as follows:
A pixel at coordinates `[x,y]` is moved to `[(2*x + y) mod N, (x + y) mod N]`.
This is nothing but a linear transform on torus: The yellow, violet and green part get mapped back onto the initial square due to the `mod N`.

This map (let's call it `f`) has following properties:
* It is *bijective*, that means reversible: It is a linear transformation with the matrix `[[2,1],[1,1]]`. Since it has determinant `1` and and it has only integer entries, the inverse also has only integer entries and is given by `[[1,-1],[-1,2]]`, this means it is also bijective on integer coordinates.
* It is a *torsion* element of the group of bijective maps of `N x N` images, that means if you apply it sufficiently many times, you will get the original image back: `f(f(...f(x)...)) = x` The amount of times the map applied to itself results in the identity is guaranteed to be less or equal to `3*N`. In the following you can see the image of a cat after a given number of iterated applications of *Arnold's cat map*, and an animation of what a repeated application looks like:


### Details
* Your program does not necessarily have to deal with images, but 2D-arrays/matrices, strings or similar 2D-structures are acceptable too.
* It does not matter whether your `(0,0)` point is on the bottom left or on the top left. (Or in any other corner, if this is more convenient in your language.) **Please specify what convention you use in your submission.**
### Testcases
In matrix form (`[1,2,3,4]` is the top row, `1` has index `(0,0)`, `2` has index `(1,0)`, `5` has index `(0,1)`)
```
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
maps to:
1 14 11 8
12 5 2 15
3 16 9 6
10 7 4 13
--------------------
1 2 3
4 5 6
7 8 9
map to:
1 8 6
9 4 2
5 3 7
```
As image (bottom left is `(0,0)`):

[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Zṙ"JC$µ2¡
```
[Try it online!](https://tio.run/nexus/jelly#@x/1cOdMJS9nlUNbjQ4t/P//f3S0oY6RjrGOSaxOtKmOmY65jgWQZaljaKBjaKhjaATkGBrrGJroGJrqGJrFxgIA "Jelly – TIO Nexus") The coordinates are as in the answer.
## Explanation
```
µ2¡ Twice:
Z Transpose, then
ṙ" Rotate rows left by
JC$ 0, -1, -2, -3, …, 1-n units.
```
This wrap-shears the matrix in one direction, then the other.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 23 bytes
```
tt&n:qt&+&y\tb+&y\b*+Q(
```
The `(0,0)` point is upper left, as in the examples in the challenge text.
[Try it online!](https://tio.run/nexus/matl#@19SopZnVViipq1WGVOSBCKTtLQDNf7/jzbUMdIx1jGxVjDVMdMx17GwVrDUMTTQMTTUMTSyVjA01jE00TE01TE0iwUA "MATL – TIO Nexus")
### Explanation
A matrix in MATL can be indexed with a single index instead of two. This is called **linear indexing**, and uses **column-major** order. This is illustrated by the following 4×4 matrix, in which the value at each entry coincides with its linear index:
```
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
```
There are two similar approaches to implement the mapping in the challenge:
1. Build an indexing matrix that represents Arnold's **inverse mapping** on linear indices, and use it to **select** the values from the original matrix. For the 4×4 case, the indexing matrix would be
```
1 8 11 14
15 2 5 12
9 16 3 6
7 10 13 4
```
telling that for example the original `5` at *x*=2, *y*=1 goes to *x*=3, *y*=2. This operation is called **reference indexing**: use the indexing matrix to tell which element to pick from the original matrix. This is functon `)`, which takes two inputs (in its default configuration).
2. Build an indexing matrix that represents Arnold's **direct mapping** on linear indices, and use it to **write** the values into the original matrix. For the 4×4 case, the indexing matrix would be
```
1 10 3 12
6 15 8 13
11 4 9 2
16 5 14 7
```
telling that the entry *x*=2, *y*=1 of the new matrix will be overwritten onto the entry with linear index `10`, that is, *x*=3, *y*=2. This is called **assignment indexing**: use the indexing matrix, a data matrix and the original matrix, and write the data onto the original matrix at the specified indices. This is function `(`, which takes three inputs (in its default configuration).
Method 1 is more straightforward, but method 2 turned out to be shorter.
```
tt % Take the input implicitly and push two more copies
&n % Get its size as two (equal) numbers: N, N
:qt % Push range [0 1 ... N-1] twice. This represents the original x values
&+ % Matrix of all pairwise additions. This represents x+y
&y % Push a copy of N onto the top of the stack
\ % Modulo. This is the new y coordinate: y_new
t % Push another copy
b+ % Bubble up the remaining copy of [0 1 ... N-1] and add. This is 2*x+y
&y % Push a copy of N onto the top of the stack
\ % Modulo. This is the new x coordinate: x_new
b*+ % Bubble up the remaining copy of N, multiply, add. This computes
% x_new*N+y_new, which is the linear index for those x_new, y_new
Q % Add 1, because MATL uses 1-based indexing
( % Assigmnent indexing: write the values of the original matrix into
% (another copy of) the original matrix at the entries given by the
% indexing matrix. Implicitly display the result
```
[Answer]
# Mathematica, 44 bytes
```
(n=MapIndexed[RotateLeft[#,1-#2]&,#]&)@*n
```
A port of [Lynn's fantastic algorithm](https://codegolf.stackexchange.com/a/105371/56178). There's an invisible 3-byte character, U+F3C7 in the UTF-8 encoding, before the last `]`; Mathematica renders it as a superscript `T`, and it takes the transpose of a matrix.
# Mathematica, 54 bytes
```
Table[#2[[Mod[2x-y-1,#]+1,Mod[y-x,#]+1]],{x,#},{y,#}]&
```
Unnamed function taking two arguments, a positive integer `#` and a 2D array `#2` of dimensions `#`x`#`, and returning a 2D array of similar shape. As in the given test case, the point with coordinates {0,0} is in the upper left and the x-axis is horizontal. Straightforward implementation using the inverse `[[1,-1],[-1,2]]` mentioned in the question, with a `-1` in the first coordinate to account for the fact that arrays are inherently 1-indexed in Mathematica. If we're not allowed to take the dimension of the matrix as an additional argument, then this solution becomes nine bytes longer (replace the first `#`—not the `#2`—with `a=Length@#` and all the subsequent `#`s with `a`s).
[Answer]
## Python 2, ~~89~~ ~~82~~ ~~77~~ 73 bytes
```
def f(a):exec'a=[l[-i:]+l[:-i]for i,l in enumerate(zip(*a))];'*2;return a
```
Input is a list of lists
The string inside the exec transpose the list of lists and cyclically rotate each list by the line index (0 based - 3rd line is rotated 2 times to the right).
This process is done 2 times to the input.
### +4 bytes that will do the transformation N times
```
def f(a,n):exec'a=[l[-i:]+l[:-i]for i,l in enumerate(zip(*a))];'*2*n;return a
```
[Answer]
## Haskell, 55 bytes
```
m#n|r<-[0..n-1]=[[m!!mod(2*y-x)n!!mod(x-y)n|x<-r]|y<-r]
```
Usage example: `[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] # 4` -> `[[1,14,11,8],[12,5,2,15],[3,16,9,6],[10,7,4,13]]`.
`0,0` is the upper left corner. This uses the inverse transformation.
[Answer]
## Python, 69 bytes
```
lambda M:eval("[r[-i:]+r[:-i]for i,r in enumerate(zip(*"*2+"M))]))]")
```
An improvement on [Rod's transpose-and-shift-twice method](https://codegolf.stackexchange.com/a/105367/20260). Applies the operation `M -> [r[-i:]+r[:-i]for i,r in enumerate(zip(*M))]` twice by creating and evaluating the string
```
[r[-i:]+r[:-i]for i,r in enumerate(zip(*[r[-i:]+r[:-i]for i,r in enumerate(zip(*M))]))]
```
This narrowly beats out a direct transformation (70 bytes), assuming the image is square and its length can be taken as input:
```
lambda M,n:[[M[(2*j-i)%n][(i-j)%n]for i in range(n)]for j in range(n)]
```
[Answer]
# ImageJ macro, 29 bytes
```
v=getPixel((x+y)%w,(2*y+x)%h)
```
* Open image of Lena
* From Process menu select Math / Macro...
[Answer]
# Java, 160
Golfed:
```
int[][]f(int[][]m){int x=0,y,l=m.length,r[][]=new int[l][];for(;x<l;++x)r[x]=new int[l];for(x=0;x<l;++x)for(y=0;y<l;++y)r[(x+y)%l][(2*x+y)%l]=m[y][x];return r;}
```
Ungolfed:
```
int[][] f(int[][] m) {
int x = 0, y, l = m.length, r[][] = new int[l][];
for (; x < l; ++x) {
r[x] = new int[l];
}
for (x = 0; x < l; ++x) {
for (y = 0; y < l; ++y) {
r[(x + y) % l][(2 * x + y) % l] = m[y][x];
}
}
return r;
}
```
] |
[Question]
[
Your task is simple: write a program that will replace random pixels in a black 16px \* 8px rectangle (width by height) with a white pixel.
The holes must be uniformly random, and you should output the 16px by 8 px image with the white pixels inserted.
Replace only 1 pixel per column (16 total replaced pixels)
You don't take any input, and you can't rely on the image being stored elsewhere on the computer.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the program with the shortest bytecount wins!
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ ~~14~~ 13 bytes
```
8tE2$r&S1=3YG
```
Example (with MATL compiler running on MATLAB):
[](https://i.stack.imgur.com/dclQB.png)
Or try it at [**MATL Online!**](https://matl.io/?code=8tE2%24r%26S1%3D3YG&inputs=&version=19.7.0) (If it doesn't run the first time, press "Run" again or refresh the page). Note that the image is scaled by the online interpreter for better visualization.
This is a port of my [Octave / MATLAB answer](https://codegolf.stackexchange.com/a/104464/36398) (see explanation there). Here are the equivalent statements:
```
MATL Octave / MATLAB
---- ---------------
8tE 8,16
2$r rand(...)
&S [~,out]=sort(...)
1= ...==1
3YG imshow(...)
```
[Answer]
# Pyth - ~~16~~ 15 bytes
Outputs image to `o.png`.
```
.wCm.S+255mZ7y8
```
Example image:
[](https://i.stack.imgur.com/ylk3j.png)
[Answer]
# C, ~~85~~ 100 bytes
```
main(c){char a[138]="P5 16 8 1 ";for(srand(time(0)),c=17;--c;a[9+c+(rand()&112)]=1);write(1,a,138);}
```
Writes a [PGM](http://netpbm.sourceforge.net/doc/pgm.html) image file to stdout (call it with `prog >out.pgm`).
**Ungolfed and explained:**
```
main(c) {
// A buffer large enough to contain the whole image,
// pre-filled with the PGM header.
// This is a binary greyscale (P5) image with only two levels (1),
// Because a binary bitmap would require pixel packing.
char a[138] = "P5 16 8 1 ";
// c iterates from 16 to 1 over the columns
for(
srand(time(0)), c = 17;
--c;
// (rand() % 8) * 16 is equivalent to (rand() & 7) << 4
// Since all bits are equally random, this is equivalent
// to rand() & (7 << 4), that is rand() & 112.
// This picks a pixel from the first column, which is then
// offset to the correct column by c - 1 + 10
// (10 is the length of the header).
a[9 + c + (rand() & 112)] = 1
)
; // Empty for body
// Write the whole buffer to stdout
write(1,a,138);
}
```
**Updates:**
* OP has clarified that the output should change with each execution, lost 15 bytes to `srand(time(0))` (`:(`)
[Answer]
## Ruby, 61 bytes
```
puts'P116 8';puts Array.new(16){[*[1]*7,0].shuffle}.transpose
```
This is a full program that outputs the image in netpbm format to stdout.
Sample output:
[](https://i.stack.imgur.com/Jg5My.png)
```
puts'P116 8'; # output the netpbm header (P1 for black and white, 16x8)
puts # then output the data as follows:
Array.new(16){ # make a 16-element array and for each element,
[*[1]*7,0] # generate the array [1,1,1,1,1,1,1,0] (1=black 0=white)
.shuffle} # shuffle the array
.transpose # transpose the rows/columns of the 2d array (so that each column
# has one white pixel)
```
[Answer]
# Octave / MATLAB, ~~48~~ ~~37~~ 35 bytes
```
[~,z]=sort(rand(8,16));imshow(z==1)
```
Example (on Octave):
[](https://i.stack.imgur.com/0B797.png)
### Explanation
```
rand(8,16) % 8×16 matrix of random values with uniform
% distribution in (0,1)
[~,z]=sort( ); % Sort each column, and for each output the
% indices of the sorting. This gives an 8×16
% matrix where each column contains a random
% permutation of the values 1,2,...,8
z==1 % Test equality with 1. This makes all values
% except 1 equal to 0
imshow( ) % Show image, with grey colormap
```
[Answer]
# Processing, ~~74~~ 73 bytes
```
fill(0);rect(0,0,15,7);stroke(-1);for(int i=0;i<16;)point(i++,random(8));
```
Sample output:
[](https://i.stack.imgur.com/U96KB.png)
### Explanation
```
fill(0); //sets the fill colour to black
rect(0,0,15,7); //draws a 16*8 black rectangle
stroke(-1); //set stroke colour to white
for(int i=0;i<16;) // for-loop with 16 iterations
point(i++,random(8)); // draw a point at x-coordinate i and a random y coordinate
// the colour of the point is white since that is the stroke colour
```
[Answer]
# HTML+JavaScript, 148 bytes
```
c=O.getContext`2d`;for(x=16;x--;){r=Math.random()*8|0;for(y=8;y--;)c.fillStyle=y-r?'#000':'#fff',c.fillRect(x,y,1,1)}
```
```
<canvas id=O width=16 height=8>
```
[Answer]
# Befunge, 90 bytes
This generates a PBM file written to stdout.
```
>030#v_\2*>>?1v
:v9\$<^!:-1\<+<
|>p1+:78+`!
>"P",1..8.28*8*v
.1-\88+%9p:!#@_>1-::88+%9g:!!
```
[Try it online!](http://befunge.tryitonline.net/#code=PjAzMCN2X1wyKj4+PzF2Cjp2OVwkPF4hOi0xXDwrPAp8PnAxKzo3OCtgIQo+IlAiLDEuLjguMjgqOCp2Ci4xLVw4OCslOXA6ISNAXz4xLTo6ODgrJTlnOiEh&input=)
**Explanation**
The top three lines make up the random number generator, storing 16 random 3-bit numbers (i.e. in the range 0-7) on the tenth line of the playfield. Line four writes out the PBM header, and the last line then generates the pixels of the image. This is done by counting down the 16 random numbers as the pixels are output - when the number corresponding to a particular column reaches zero we output a 1 rather than a 0.
Sample output (zoomed):

[Answer]
# Mathematica, ~~77~~ 60 bytes
```
Image[{RandomInteger@7+1,#}->1&~Array~16~SparseArray~{8,16}]
```
**Sample Output**
[](https://i.stack.imgur.com/AtiML.png)
**Explanation**
```
{RandomInteger@7+1,#}->1&~Array~16
```
Make replacement rules for each column; replace a randomly selected position with 1.
```
... ~SparseArray~{8,16}
```
Create a `SparseArray` with size 8x16 from the replacement rules. The background is `0` by default. (8x16 because Mathematica counts rows first)
```
Image[ ... ]
```
Convert the `SparseArray` into an `Image` object.
**77 byte version**
```
ReplacePixelValue[Image@(a=Array)[0&~a~16&,8],{#,RandomInteger@7+1}->1&~a~16]
```
[Answer]
# R, 76 bytes
```
a=matrix(0,8,16);for(i in 1:16)a[sample(1:8,1),i]=1;png::writePNG(a,'a.png')
```
Uses package [`png`](https://cran.r-project.org/web/packages/png/index.html) to output to a file.
Example output:
[](https://i.stack.imgur.com/Ce3Z8.png)
[Answer]
# QBasic, 59 bytes
```
RANDOMIZE TIMER
SCREEN 9
FOR x=0TO 15
PSET(x,RND*8-.5)
NEXT
```
Pretty straightforward. The `-.5` is needed because `PSET` with non-integer arguments uses round-to-nearest instead of floor or truncate (and `-.5` is shorter than `INT()`).
The image in question is displayed at the top left corner of the output window. A (cropped) example: [](https://i.stack.imgur.com/Ra4p4.png)
[Answer]
# Java, (*Does it even matter* Bytes, AKA 244 + 18 import = 262)
```
import java.awt.*;static void l(){new Frame(){public void paint(Graphics g){int x=50;int i=16;g.setColor(Color.BLACK);g.fillRect(x,x,16,8);g.setColor(Color.WHITE);for(;i>0;i--){int y=(int)(Math.random()*8);g.drawLine(x+i,x+y,x+i,x+y);setVisible(1>0);}}}.show();}
```
Was wonky because the coordinate system includes the frame window pane... So you need to buffer by at least 26 bytes or nothing shows up, hence the `x=50` bit.
[Answer]
# Postscript (65 bytes)
```
0 0íkà0ícà8íc0 8ícííB1à1íù16{0 randàíj0.5í©ík1 0íÖíß1 0í≠}íÉ
```
Ungolfed version:
```
0 0 moveto
16 0 lineto
16 8 lineto
0 8 lineto
closepath
fill
1 1 1 setrgbcolor
16{0 rand 16 mod 0.5 sub moveto 1 0 rlineto stroke 1 0 translate}repeat
```
[Answer]
# SmileBASIC, 30 bytes
```
FOR I=0TO 15GPSET I,RND(8)NEXT
```
[Answer]
# Chip-8, 12 bytes
```
0xA201 'Load sprite at address 201 (which is the second byte of this instruction)
0xC007 'Set register 0 to a random number from 0 to 7 (rnd & 0x7)
0xD101 'Draw sprite. x = register 1, y = register 0, height = 1
0x7101 'Add 1 to register 1
0x3110 'If register 1 is not 16...
0x1202 'Jump to second instruction
```
Draws the image on the screen.
[Answer]
# Tcl/Tk, 163
Two different approaches render to the same byte extent:
```
grid [canvas .c -w 16 -he 8 -bg #000 -highlightt 0]
.c cr i 8 4 -i [set p [image c photo -w 16 -h 8]]
set x 0
time {$p p #FFF -t $x [expr int(rand()*8)];incr x} 16
```
---
```
grid [canvas .c -w 16 -he 8 -bg #000 -highlightt 0]
.c cr i 8 4 -i [set p [image c photo -w 16 -h 8]]
time {$p p #FFF -t [expr [incr x]-1] [expr int(rand()*8)]} 16
```
[](https://i.stack.imgur.com/VHIRb.png)
[Answer]
**VBA Excel, ~~86~~ 105 bytes**
using immediate window
```
Cells.RowHeight=42:[a1:p8].interior.color=0:for x=0to 15:[a1].offset(rnd*7,x).interior.color=vbwhite:next
```
] |
[Question]
[
# Task description
Sometimes, you really need to fit something you’re writing in a small space. It may be tempting to drop the vowels and wrt lk ths – and failing that, who really needs spaces? Thssprfctlrdbl!†
Write a function or program that removes lowercase vowels `aeiou`, and then spaces, and then *any* characters from an **input string**. Furthermore, each time you remove a character, it must be the **rightmost** character eligible for removal. It must repeat this process until the string is **no longer than some given input length**.
† “This is perfectly readable!” But if you’re reading this footnote, it probably isn’t, really... :)
# Examples
Here, you can see this process applied for successively smaller input sizes:
```
23: Hello, Code Golf World!
22: Hello, Code Golf Wrld!
21: Hello, Code Glf Wrld!
20: Hello, Cod Glf Wrld!
19: Hello, Cd Glf Wrld!
18: Hell, Cd Glf Wrld!
17: Hll, Cd Glf Wrld!
16: Hll, Cd GlfWrld!
15: Hll, CdGlfWrld!
14: Hll,CdGlfWrld!
13: Hll,CdGlfWrld
12: Hll,CdGlfWrl
11: Hll,CdGlfWr
(etc.)
```
After squeezing the string down to 17 characters, we run out of vowels to remove, so the next character we remove is the rightmost space; when we hit 14 characters, we’ve removed all vowels *and* spaces, so we simply start munching the string from right to left.
Here is some ~~pseudocode~~ Python code that solves this challenge:
```
def crunch_string(string, to_length):
while len(string) > to_length:
# Store the best candidate index for deletion here.
best = None
# First, find the rightmost vowel's index.
for i in range(len(string)):
if string[i] in 'aeiou':
best = i
# If there were no vowels, find the rightmost space's index.
if best is None:
for i in range(len(string)):
if string[i] == ' ':
best = i
# If there were no spaces either, use the final index.
if best is None:
best = len(string) - 1
# Remove the selected character from the string.
string = string[:best] + string[best + 1:]
# Return the string once `len(string) <= to_length`.
return string
```
# Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
* The input string will consist of the printable ASCII characters from space (, decimal 32) up to and including tilde (`~`, decimal 126). There will be no uppercase vowels `AEIOU` in the string. In particular, there will be no Unicode, tabs, or newlines involved.
* Call the input string *s*, and the input target length *t*. Then 0 < t ≤ length(*s*) ≤ 10000 is guaranteed. (In particular, the input string will never be empty. If *t* = length(*s*), you should just return the string unmodified.)
# Test cases
```
Input: 50, Duis commodo scelerisque ex, ac consectetur metus rhoncus.
Output: Duis commodo scelerisque ex, ac cnscttr mts rhncs.
Input: 20, Maecenas tincidunt dictum nunc id facilisis.
Output: Mcnstncdntdctmnncdfc
Input: 150, golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf
Output: glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glf glfglfglfglfglfglfglfglfglfglf
```
[Answer]
# Perl, ~~48~~ ~~45~~ 43 bytes
Includes +4 for `-Xlpi` (-X can be left out but leaves ugly warnings on STDERR)
Run with the number after the `-i` option and the input on STDIN (supports multiple lines too). e.g. `perl -Xlpi50 crunch.pl <<< "Duis commodo scelerisque ex, ac consectetur metus rhoncus."`
`crunch.pl`:
```
s/.*\K[aeiou]|.*\K |.$// while pos=-$^I
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 20 bytes
```
t11Y2mEG32=+K#Si:)S)
```
[**Try it online!**](http://matl.tryitonline.net/#code=dDExWTJtRUczMj0rSyNTaTopUyk&input=J0R1aXMgY29tbW9kbyBzY2VsZXJpc3F1ZSBleCwgYWMgY29uc2VjdGV0dXIgbWV0dXMgcmhvbmN1cy4nCjUw)
```
t % implicitly input string. Duplicate
11Y2 % predefined literal 'aeiou'
m % ismember. Gives true for input characters that are vowels
E % multiply by 2
G % push input string again
32 % ASCII for space
= % gives true for input characters that are spaces
+ % add: gives 2 for vowels, 1 for space, 0 for non-vowels-and-non space
K#S % sort and push only the indices of the sorting. Sorting is stable, so first
% will be non-vowels-and-non space characters in their original order, then
% spaces in their original order, then vowels in their original order
i % input number n of characters that should be kept
: % range [1,2,...,n]
) % index with that: keep first n indices of the sorting
S % sort those indices to restore their original order
) % index into input string to keep only those characters. Implicitly display
```
[Answer]
# JavaScript (ES6), ~~66~~ 61 bytes
*Saved 5 bytes thanks to @Neil*
```
f=(s,n)=>s[n]?f(s.replace(/(.*)[aeiou]|(.*) |.$/,"$1$2"),n):s
```
I don't think the regex is golfable further. Surprisingly, the shortest I can come up with to remove front-to-back is a byte longer:
```
f=(s,n)=>s[n]?f(s.replace(/(.*?)[aeiou]|(.*?) |./,"$1$2"),n):s
```
### More interesting attempt (ES7), 134 bytes
```
(s,n,i=0)=>[for(c of s)[/[aeiou]/.test(c)*2+(c<'!'),i++,c]].sort(([x],[y])=>x-y).slice(0,n).sort(([,x],[,y])=>x-y).map(x=>x[2]).join``
```
This uses an approach similar to the MATL answer.
[Answer]
# sh + gnu sed, ~~78~~ 61
Supply the string to `STDIN`, the length as first argument.
```
rev|sed -r ": # reverse + invoke sed + jump label ":"
/..{$1}/!q # if the length is not greater $1, quit
p # print
s/[aeiou]// # delete the first vowel
t # if successful, start over at ":"
s/ // # delete the first space
t # if successful, start over at ":"
s/.// # delete the first character
t"|rev # if successful, start over at ":" + reverse
```
[Answer]
# Perl, 68
Removing from the right adds a ton of characters, maybe there is a better way to do this.
```
$_=reverse;while(length>$^I){s/[aeiou]//||s/ //||s/.//}$_=reverse
```
Use `-i` to input the number. It is 65 characters plus 3 for the `i`, `p`, and `l` on the command line.
Run with:
```
echo 'Hello, Code Golf World!' | perl -i13 -ple'$_=reverse;while(length>$^I){s/[aeiou]//||s/ //||s/.//}$_=reverse'
```
[Answer]
## Java 8, 303 bytes
```
(s,j)->{String t="";for(int i=s.length()-1;i>=0;t+=s.charAt(i--));while(t.length()>j&&t.matches(".*[aeiou].*"))t=t.replaceFirst("[aeiou]","");while(t.length()>j&&t.contains(" "))t=t.replaceFirst("\\s","");s="";for(int i=t.length()-1;i>=0;s+=t.charAt(i--));return s.substring(0,Math.min(t.length(),j));};
```
This is WAY too long. Ill try to shorten it soon. It would be much shorter if java had a method for reversing strings and backward replacements.
Test with the following:
```
public class StringCruncher {
public static void main(String[] args) {
Tester test = (s,j)->{String t="";for(int i=s.length()-1;i>=0;t+=s.charAt(i--));while(t.length()>j&&t.matches(".*[aeiou].*"))t=t.replaceFirst("[aeiou]","");while(t.length()>j&&t.contains(" "))t=t.replaceFirst("\\s","");s="";for(int i=t.length()-1;i>=0;s+=t.charAt(i--));return s.substring(0,Math.min(t.length(),j));};
System.out.println(test.crunch("golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf", 150));
}
}
interface Tester {
String crunch(String s, int j);
}
```
[Answer]
**C#, 180 bytes**
```
string c(int l,string s){while(s.Length>l){int i=0;Func<string,bool>f=t=>(i=s.LastIndexOfAny(t.ToCharArray()))!=-1;if(!(f("aeiou")||f(" ")))i=s.Length-1;s=s.Remove(i,1);}return s;}
```
Tester:
```
using System;
class Crunch
{
static int Main()
{
var x = new Crunch();
Console.WriteLine(x.c(50, "Duis commodo scelerisque ex, ac consectetur metus rhoncus."));
Console.WriteLine(x.c(20, "Maecenas tincidunt dictum nunc id facilisis."));
Console.WriteLine(x.c(150, "golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf golf"));
Console.Read();
return 0;
}
string c(int l,string s){while(s.Length>l){int i=0;Func<string,bool>f=t=>(i=s.LastIndexOfAny(t.ToCharArray()))!=-1;if(!(f("aeiou")||f(" ")))i=s.Length-1;s=s.Remove(i,1);}return s;}
static string crunch(int len, string str)
{
Console.WriteLine($"{str.Length}: {str}");
while (str.Length > len) {
int idx=0;
Func<string,bool> f = s => (idx = str.LastIndexOfAny(s.ToCharArray()))!= -1;
if (!(f("aeiou") || f(" "))) idx = str.Length-1;
str = str.Remove(idx,1);
Console.WriteLine($"{str.Length}: {str}");
}
return str;
}
}
```
[Answer]
# Scala, 160 bytes
```
type S=String;def f(s:S,l:Int)={def r(s:S,p:S):S=if(s.size>l){val j=s.replaceFirst("(?s)(.*)"+p,"$1");if(j==s)s else r(j,p)}else s;r(r(r(s,"[aeiou]")," "),".")}
```
Tester:
```
val t="Hello, Code Golf World!"
println((t.size to 11 by -1).map(f(t,_)).mkString("\n"))
```
[Answer]
# Dyalog APL, ~~77~~ ~~45~~ 42 bytes
```
t[⌽i~⌽⎕↓⌽∪∊(t∊'aeiou')(' '=t)1/¨⊂i←⍳⍴t←⌽⍞]
```
`t[`…`]` letters of *t* with indices...
`t←⌽⍞` *t* gets reversed text input
`i←⍳⍴t` *i* gets indices of length of *t*
`/¨⊂i` multiple (3) boolean selections of elements of *i*:
1. `(t∊'aeiou')` boolean where vowel
2. `(' '=t)` boolean where space
3. `1` all
`∪∊` unique of the enlisted (flattened) 3 selections
`⌽⎕↓⌽` drop last evaluated-inputted characters (same as `(-⎕)↓`)
`⌽i~` reverse the remaining indices after removing some
---
Original answer:
```
⎕{⍺≥≢⍵:⌽⍵⋄∨/⍵∊⍨v←'aeiou':⍺∇⍵/⍨~<\(⍳⍴⍵)∊⍵⍳v⋄' '∊⍵:⍺∇⍵/⍨~<\(⍳⍴⍵)=⍵⍳' '⋄⍺∇1↓⍵}⌽⍞
```
Ehm, yeah, that *is* a bit hard to read. Basically the direct translation of OP into APL:
1. Reverse input.
2. If required length is longer or equal to the count of (reversed) input string, then return reversed (reversed) argument.
3. Else, if argument has any vowel, remove the first (i.e. last) one and call recursively on what remains.
4. Else, if argument has any space, remove the first (i.e. last) one and call recursively on what remains.
5. Else, remove the first (i.e. last) character and call recursively on what remains.
[Answer]
# Lua, 120 bytes
```
s=arg[2]:reverse()a=s:len()-arg[1]s,n=s:gsub('[aeiou]','',a)s,m=s:gsub(' ','',a-n)print(s:gsub('.','',a-n-m):reverse())
```
Takes input as command line arguments, in the format `lua crunch.lua 10 "This is a string"`, with output `Ths sstrng`.
Explanation:
```
-- Set 's' to the reverse of the string
s=arg[2]:reverse()
-- Set 'a' to the number of characters to be removed
a=s:len()-arg[1]
-- Remove 'a' vowels, set 'b' to the number of substitutions
s,b=s:gsub('[aeiou]','',a)
-- Remove 'a-b' spaces, set 'c' to the number of substitutions
s,c=s:gsub(' ','',a-b)
-- Remove 'a-b-c' characters, and print the now un-reversed string
print(s:gsub('.','',a-b-c):reverse())
```
[Answer]
# Mathematica, 201 Bytes
```
f@x_:=StringReplaceList[x,"a"|"e"|"i"|"o"|"u"->""];g@x_:=StringReplaceList[x," "->""];x_~l~y_:=NestWhile[If[f@#!={},Last@f@#,If[g@#!={},Last@g@#,Last@StringReplaceList[#,_->""]]]&,x,StringLength@#!=y&]
```
There must be a better way than this..
[Answer]
# R, ~~169~~ 143 bytes
```
function(x,y){d=utf8ToInt(x);o=c(rev(which(d%in%utf8ToInt('aeiou'))),rev(which(d==32)));intToUtf8(d[sort(tail(c(o,setdiff(nchar(x):1,o)),y))])}
```
\*edit saved 36 bytes through rewrite with `utf8ToInt` -> `intToUtf8` conversions not `strstplit` and `paste0(...,collapse)`
ungolfed with explanation
```
function(x,y){d=utf8ToInt(x); # convert string (x) to integer
o=c(
rev(which(d%in%utf8ToInt('aeiou'))), # index of vowels (reversed)
rev(which(d==32))); # index of spaces
intToUtf8(d[ # convert subset back to character
sort(tail( # return the first y index of
# "left over" characters
c(o,setdiff(nchar(x):1,o)) # combine vowels, spaces and
# other indices in appropriate order
,y))])}
```
] |
[Question]
[
**Monday Mini-Golf:** A series of short [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") questions, posted (hopefully!) every Monday.
(Sorry I'm late again; I was away from my computer basically all of yesterday and today.)
Us programmers (especially the code-golfers) sure love arbitrary integer sequences. We even have [an entire site dedicated to these sequences](http://oeis.org) that currently has around 200,000 entries. In this challenge, we'll be implementing yet another set of these sequences.
# Challenge
Your challenge is to write a program or function that takes in an integer *N*, and outputs a sequence of base 10 integers, where each next integer is determined in this way:
* Start at 1.
* For each digit *D* in the previous integer's base 10 representation:
+ If *D* is 0, add one to the current integer.
+ Otherwise, multiply the current integer by *D*.
## Details
* You may assume that 0 < *N* < 231.
* You must output each integer in the sequence, starting with the input number, until a number less than 10 is reached.
* The output may be an array, or a string separated by spaces, commas, newlines, or a combination of these.
* A trailing space and/or newline is allowed, but *not* a trailing comma.
* There should never be any leading zeroes.
# Examples
**Example 1:** `77`
This example is fairly straightforward:
```
77 = 1*7*7 = 49
49 = 1*4*9 = 36
36 = 1*3*6 = 18
18 = 1*1*8 = 8
```
Thus, the proper output is `77 49 36 18 8`.
**Example 2:** `90`
Here we have:
```
90 = 1*9+1 = 10
10 = 1*1+1 = 2
```
So the output would be `90 10 2`.
**Example 3:** `806`
Read the equations left-to-right:
```
806 = 1*8+1*6 = 54 (((1*8)+1)*6)
54 = 1*5*4 = 20
20 = 1*2+1 = 3
```
Output should be `806 54 20 3`.
# Test-cases
The first number in each line is the input, and the full line is the expected output.
```
77 49 36 18 8
90 10 2
249 72 14 4
806 54 20 3
1337 63 18 8
9999 6561 180 9
10000 5
8675309 45369 3240 25 10 2
9999999 4782969 217728 1568 240 9
1234567890 362881 2304 28 16 6
```
As a reference, here's the proper next integers from 10 to 100:
```
Current | Next
--------+-----
10 | 2
11 | 1
12 | 2
13 | 3
14 | 4
15 | 5
16 | 6
17 | 7
18 | 8
19 | 9
20 | 3
21 | 2
22 | 4
23 | 6
24 | 8
25 | 10
26 | 12
27 | 14
28 | 16
29 | 18
30 | 4
31 | 3
32 | 6
33 | 9
34 | 12
35 | 15
36 | 18
37 | 21
38 | 24
39 | 27
40 | 5
41 | 4
42 | 8
43 | 12
44 | 16
45 | 20
46 | 24
47 | 28
48 | 32
49 | 36
50 | 6
51 | 5
52 | 10
53 | 15
54 | 20
55 | 25
56 | 30
57 | 35
58 | 40
59 | 45
60 | 7
61 | 6
62 | 12
63 | 18
64 | 24
65 | 30
66 | 36
67 | 42
68 | 48
69 | 54
70 | 8
71 | 7
72 | 14
73 | 21
74 | 28
75 | 35
76 | 42
77 | 49
78 | 56
79 | 63
80 | 9
81 | 8
82 | 16
83 | 24
84 | 32
85 | 40
86 | 48
87 | 56
88 | 64
89 | 72
90 | 10
91 | 9
92 | 18
93 | 27
94 | 36
95 | 45
96 | 54
97 | 63
98 | 72
99 | 81
100 | 3
```
You can find this list expanded to 10000 [here](http://pastebin.com/P4ggJTqf).
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. ~~The winner will be chosen next Monday, Oct 19. Good luck!~~
**Edit:** Congrats to your winner, **@isaacg**, using Pyth yet again for **14 bytes**!
[Answer]
# Pyth, ~~15~~ 14 bytes
```
.uu|*GHhGjNT1Q
```
*1 byte thanks to Dennis*
[Test Suite](https://pyth.herokuapp.com/?code=.uu%7C%2aGHhGjNT1Q&test_suite=1&test_suite_input=77%0A90%0A249%0A806%0A1337%0A9999%0A10000%0A8675309%0A9999999%0A1234567890&debug=0)
This challenge feels like it was made for Pyth's reduce functions. One reduce over the digits, one reduce until the value stops changing, and we're good.
[Answer]
# PowerShell, ~~92~~ ~~91~~ ~~90~~ ~~88~~ 87 bytes
```
($n=$args);while($n-gt9){$x=1;[char[]]"$n"|%{$x=if($y=$_-48){$x*$y}else{$x+1}};($n=$x)}
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), ~~28~~ ~~25~~ 23 bytes
```
Tt>Pa{Y1FdaYy*d|y+1a:y}
```
Takes a number as command-line argument and outputs the sequence on successive lines.
Explanation:
```
a is cmdline arg; t is 10 (implicit)
Tt>Pa{ } Loop till a<10, printing it each time the test is made:
Y1 Yank 1 into variable y
Fda For each digit d in a:
Yy*d|y+1 If y*d is truthy (nonzero), yank it; otherwise, yank y+1
a:y Assign value of y back to a
```
Now I'm glad I changed `P` from a statement to an operator several revisions ago. `Pa` is an expression that evaluates to `a`'s value but also outputs it, so I can print `a` and simultaneously test whether it's less than ten using `t>Pa`.
[Answer]
# CJam, ~~26~~ ~~25~~ ~~24~~ 22 bytes
```
riA,{_pAb{_2$*@)?}*j}j
```
or
```
ri{_pAb{_2$*@)?}*_9>}g
```
[Try it online.](http://cjam.aditsu.net/#code=riA%2C%7B_pAb%7B_2%24*%40)%3F%7D*j%7Dj&input=1234567890)
### How it works
Both program essentially do the same; the first is a recursive approach, the second an iterative one. I'll explain the first, which I consider more interesting.
```
ri Read an integer from STDIN and push it on the stack.
A,{ }j Initialize a memoized, recursive function j with the array
[0 ... 9] as "base cases". If j is called on an integer
below 10, it returns the element at that index of the base
cases (which is same integer) and does not execute the code
block. The base case array is filled with new values as j is
called again and again, but we do not use this feature.
_p Copy and print the integer on the stack.
Ab Convert it into its base-10 digits.
{ }* Fold; push the first digit, for each remaining digit:
_2$* Multiply copies of the accumulator and the current digit.
@) Increment the original accumulator.
? Select the product if the digit is non-zero, else the sum.
j Call j on the result.
If the result was less than 10, it is retrieved from the
base cases and pushed on the stack. CJam prints it before
exiting the program.
```
[Answer]
## [Minkolang 0.7](https://github.com/elendiastarman/Minkolang), ~~52~~ 46 bytes
```
ndN((d25*%1R25*:)r11(x2~gd4&x1+!*I1-)dNd9`,?).
```
Woohoo nested loops!
### Explanation
```
ndN Takes integer input and outputs it
( Starts overall loop
( Starts loop that separates top of stack into digits
d25*% Modulus by 10
1R Rotates stack 1 unit to the right
25*: Divides by 10
)
r11 Reverses stack and pushes two 1s; 1 for the dump and 1 for the multiply
( Starts the multiply/add loop
x Dumps top value
-This top-of-stack dump is because
while loops end when the stack is
empty or the top of stack is 0. The
top of stack is *not* popped for
this conditional check, so if the loop
continues, I need to dump the left-over
from the previous iteration.
2~gd Gets next-to-last stack value and duplicates for the conditional
4& Jumps 4 spaces if top of stack is positive
x1+! Dumps the 0 leftover, adds 1 to top of stack, and jumps the multiply
* Multiplies the top two elements of stack
I1- Pushes length of stack - 1
) Exits the loop if top of stack is 0 (i.e., len(stack)=1)
dN Outputs as integer
d9`,? Jumps out of the loop if top of stack <=9
)
. Stop.
```
[Answer]
# Mathematica, 66 bytes
```
Most@FixedPointList[Fold[If[#2<1,#+1,1##]&,1,IntegerDigits@#]&,#]&
```
[Answer]
# Python 3, 74, ~~76~~ bytes
There was already a Python answer here with reduce, so I wanted to do one without it. It should be called with an int.
```
def j(n,m=1):
print(n)
if n>9:
for d in str(n):m=m*int(d)or m+1
j(m)
```
[Answer]
## Python, ~~85~~ 80 bytes
```
def g(n):y=reduce(lambda i,x:i*int(x)or i+1,`n`,1);return[n]+(g(y)if n>9else[])
```
This now properly prints out the entire list, instead of just the first value.
[Answer]
# [K5](http://johnearnest.github.io/ok/index.html), 24 bytes
```
(1{(x*y;x+1)@~y}/.:'$:)\
```
Gathering a list of items while iterating to a fixed point is precisely what the scan operator `\` does. On each iteration I first cast the number to a string and then evaluate each character (`.:'$:`), exploding the number into its digits. Then I perform a reduction (`/`) starting with 1 and using the lambda `{(x*y;x+1)@~y}`. In this case `x` is the reducing value and `y` is each successive term of the sequence.
In action:
```
f: (1{(x*y;x+1)@~y}/.:'$:)\
f'77 90 249 806 1337 9999 10000 8685309 9999999 1234567890
(77 49 36 18 8
90 10 2
249 72 14 4
806 54 20 3
1337 63 18 8
9999 6561 180 9
10000 5
8685309 51849 1440 17 7
9999999 4782969 217728 1568 240 9
1234567890 362881 2304 28 16 6)
```
[Answer]
# Julia, ~~93~~ ~~89~~ ~~88~~ ~~86~~ ~~83~~ 77 bytes
```
f(n)=(println(n);if(d=n>9)for i=reverse(digits(n)) i<1?d+=1:d*=i end;f(d)end)
```
This creates a recursive function `f` that prints the sequence elements on separate lines.
Ungolfed:
```
function f(n::Int)
println(n)
if (d = n > 9)
for i in reverse(digits(n))
i < 1 ? d += 1 : d *= i
end
f(d)
end
end
```
[Try it online](http://goo.gl/63RPDZ)
Saved 6 bytes thanks to Dennis!
[Answer]
# Ruby 83, 72 bytes
**Original** declared as a function:
```
def f(d)loop{p d;break if d<10;d=d.to_s.bytes.inject(1){|r,i|i>48?r*(i-48):r+1}}end
```
I tried to use `Enumerator.new` but it uses so many bytes :-(
**Improved** using recursion:
```
def f(d)p d;f(d.to_s.bytes.inject(1){|r,i|i>48?r*(i-48):r+1})if d>10 end
```
[Answer]
## C# & LINQ, 165 146 bytes
```
void j(int a){r.Add(a);var l=a.ToString().Select(d=>int.Parse(d.ToString()));int n=1;foreach(int i in l)n=i==0?n+1:n*i;if(n>9)j(n);else r.Add(n);}
```
**j** (for jarvis) is the recursive function. **r** is the List of int of the result.
tested in LINQPAD:
```
void Main()
{
j(806);
r.Dump();
}
List<int> r = new List<int>();
void j(int a){r.Add(a);var l=a.ToString().Select(d=>int.Parse(d.ToString()));int n=1;foreach(int i in l)n=i==0?n+1:n*i;if(n>9)j(n);else r.Add(n);}
```
[Answer]
# Haskell, 71 bytes
```
x!'0'=x+1
x!c=x*read[c]
g x|h>9=x:g h|1<2=[x,h]where h=foldl(!)1$show x
```
Usage: `g 8675309` -> `[8675309,45369,3240,25,10,2]`.
[Answer]
# Matlab, 108
```
N=input('');disp(N)
k=1;while k
x=1;for n=num2str(N)-48
if n
x=x*n;else
x=x+1;end
end
disp(x)
N=x;k=x>9;
end
```
[Answer]
# Java 8, 148 Bytes
```
String f(int j){String s="";Function r=i->(""+i).chars().map(x->x-48).reduce(1,(x,y)->y>0?x*y:x+1);while((j=(int)r.apply(j))>9)s+=j+" ";return s+j;}
```
formatted
```
String f(int j) {
String s = "";
Function r = i -> ("" + i).chars().map(x -> x - 48).reduce(1, (x, y) -> y>0 ? x*y : x+1);
while ((j = (int)r.apply(j)) > 9) s += j+" ";
return s+j;
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Dבṛ?ƒ1ƊƬ
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//RMOX4oCY4bmbP8aSMcaKxqz///84MDY "Jelly – Try It Online")
] |
[Question]
[
## Background
On a Rubik's cube there are 54 moves that you can execute, for example, turn the right face anti-clockwise, or rotate the top face and the horizontal slice twice. To notate any move, each face (or [slice](https://www.speedsolving.com/wiki/index.php/3x3x3_notation#Slice_Turns)) has a letter assigned to it. To move that face clockwise once, you just write the letter on its own, so for the top face it would be `U` (for "up"). You can put a `'` (pronounced "prime") after the letter to notate moving the face anti-clockwise, or a `2` to turn the face twice. You can see more details on this [here](https://jperm.net/3x3/moves).
## The Challenge
Your challenge is to take a list of moves which all rotate the same face, and simplify it into one move. For example if the input was `R R2`, you'd be turning the right face clockwise once, then twice, which results in the equivalent of `R'` — turning the right face anti-clockwise once.
## Rules
* If the result doesn't modify the cube, the output should be nothing or a falsey value.
* Input must be taken in the proper notation described above, otherwise, it's up to you.
* You can assume that no move will have a `2` *and* a `'` in it.
## Test Cases
```
R R2 -> R'
L2 L L' L -> L'
u' u2 u2 -> u'
y y' ->
F F' F F F' -> F
E' E2 E E E' -> E2
```
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes (inspired by @math junkie)
```
lambda s:(s[0]+"2'"[len(``s``)%2])[:len(``s``)%4]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY09asQwEIV7nWIQLJKIZBKRIhh2q8WVKreOwQ62iYgsCf0U9lXSLISQM-1tYu-mSDHwvpn33nz--CW9OysvX9Px9TunSbxcn0w_vw09xJLG5rF9wJLgxoyWdl3sOnaQLWvKf_zc_gU_9OxdSBCXiCYXwIC2OxQxDdoWYewHo-0YKSsRaO7gCHPvaUxhcwTtuSmiNzpRLE6YMQQ-aJuo5rgEzB3HIMQmJqoZu7-8XM91LUGcoCZISaWI2kERlEmW-XbJBC0L2RSqKlJtsy8rtMp1XW-GVd7LfgE)
[Python 3 version is 51 bytes.](https://ato.pxeger.com/run?1=LUy7asMwFN31FRdBkZRKIagZisCZiidNXl0PDo2JQLGEHoP1K10Cpf2n_E2VOMM5nHvP4_vPL-ns5uvP1Hz-5jSJ99ubHS_HrxGiorHfDa94s5EE90Y19jTTcPJhpcgYe9kPrFdmeFa7yQWwYGZwvmZ3TCEw3EEDl9HTmMK2wnhut9FbkygWB8wYAh_MnKjhWAHmjmMQooqJGsbW5evto-skiAN0BGmpNdH3QxOUSZb54WSCloVUhdqWtBX3Z4uKLKU8AkWuY_8)
This takes the input sequence as a string without delimiters.
### How?
By applying the backtick operator twice we gain two pairs of quotation marks which is neutral modulo 4 and we get all apostrophes escaped, a cheap way of replacing them with two characters each. Now, we can simply count characters because "A","A2","A\'" have the right lengths in terms of quarter turns. It remains to format the residue modulo 4 as required.
### [Python](https://www.python.org), 56 bytes
```
lambda s:(s[0]+"**2'"[i:=-sum(map(" *'".find,s))%4])[:i]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LUy9asMwGNz1FIegSHIkE0SHIHBGT560uh5cUlOBf4QlD_ardAmE9J3yNpWT8v3dcd_dz69f4_c0Xm9d8XFfYqdOj1PfDp-XFsHwUB-bA80yzWjtTKHCMvCh9ZwiYzTv3HiRQYi390bUxjX_fttNM3q4EZP_GvlRGAInJxTYrSHOeRrnZZ8H37vIqTpTIQj87MbInaQGVE6SQqkEOu6EeCVfH9bCaqgzLCOVRoWKpZV4xcjCsOi9E10YWbGyBEmJkqHE8ySlJJvGttfzcdOv6D8)
This version can handle a proper delimiter (single space).
### Old [Python](https://www.python.org), 60 bytes
```
lambda s:(s[0]+"2'")[:(i:=-sum(map(" '2".find,s)))%4:1+i%2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxNasMwEIX3OsVDECQRyaSiiyLqLL3yyts0C5fUdMCWhWUt7Kt0EyjtnXKbykmZv_eYme_rNyzz5-iv31359pPmzrzcXvt2eL-0iE7G0-G851ZwdXKSXGliGuTQBskBYXnRkb_oqJTaPbunPe3s-Z_RdOOEHuQxhg8vD8oxkB5RYvuO81TkoqD7IoaeZsnNkSvFECbysyTNHbgeNYcxWXSSlHqQr7emQWNhjmgEqy1q1CK37GvBkkCyW2abBFuwiCxZhUqgwn3kTcVWi3WL--FqH-g_)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24 bytes
```
'
22
\B.
2
+`....$
22
'
```
[Try it online!](https://tio.run/##K0otycxL/K@qkaDA9V@dy8iIK8ZJj8uISztBDwhUuEAi6v//BykEGXH5GCn4KPioK/hwlaorlBoBEVelQqU6l5uCm7qCGwiqAwA "Retina 0.8.2 – Try It Online") Takes input as a smashed string of moves but link is to test suite that removes spaces for convenience. Explanation:
```
'
22
```
Change anti-clockwise rotations to three rotations (`2` means "repeat last rotation").
```
\B.
2
```
Change face rotations after the first to `2`s too.
```
+`....$
```
Reduce modulo `4`, making sure to keep the first face.
```
22
'
```
Change three rotations back to an anti-clockwise rotation.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 26 bytes
```
{|(0," 2'",'*x)4!+/1+39=x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0TDQUVIwUlfSUdeq0DRR1NY31Da2tK2o5eJKU1AKCjJSAtE+Rj4+6j5gZql6qVEpRLSyUh1Mu7mpuwGxEgDOGhHc)
-4 bytes thanks to @ovs!
Inspired by @Neil's Retina answer for a bunch of bytes saved.
## Explanation
* `1+39=` 1 for *A*, 2 for *A*2, 3 for *A*'
* `4+/` sum mod 4
* `|(0," 2'",'*x)` convert back to move or 0
[Answer]
# [Cubestack](https://github.com/tobyck/cubestack), 166 bytes
I think this language is quite fitting.
```
b' S S' y S S' y2 M R' M' M R2 M' l2 M2 M R2 M' D x U' M R2 M' x2 l x M r M' x2 M R' M' x' x' R y' M r' M' U M2 x S R' r R B2 R' U2 S' l' r b' M M' r M R M' r l' R x'
```
[Try it Online!](https://cubestack.surge.sh?YicgUyBTJyB5IFMgUycgeTIgTSBSJyBNJyBNIFIyIE0nIGwyIE0yIE0gUjIgTScgRCB4IFUnIE0gUjIgTScgeDIgbCB4IE0gciBNJyB4MiBNIFInIE0nIHgnIHgnIFIgeScgTSByJyBNJyBVIE0yIHggUyBSJyByIFIgQjIgUicgVTIgUycgbCcgciBiJyBNIE0nIHIgTSBSIE0nIHIgbCcgUiB4Jw%3D%3D&RScKRTIKRQpFCkUn)
Formatted nicely:
```
b' S S' y
S S' y2 M R' M' M R2 M' l2 M2
M R2 M' D x
U' M R2 M' x2
l x
M r M' x2
M R' M'
x'
x' R
y' M r' M' U M2 x
S R' r R B2 R' U2 S' l' r
b' M M' r M R M' r
l' R
x'
```
Goes through each move, if the move ending is `2`, then 2 is added to the total, if it's `'` 3 is added, otherwise 1 is added. The total mod 4 is then used to index into the string `' 2` and the appropriate letter is prepended.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~18~~ ~~17~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
''T:g4%ø`¤£3'':
```
-1 byte being inspired by [*@mathJunkie*'s Pyth answer](https://codegolf.stackexchange.com/a/249843/52210)
-2 bytes thanks to *@CommandMaster*
Input as a string without delimiter.
[Try it online](https://tio.run/##yy9OTMpM/f9fXT3EKt1E9fCOhENLDi02Vle3@v@/VL3UqNQIAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLf3X1EKt0E9XDOxIOLTm02Fhd3eq/zv9opaAgIyUdJR8jHx91HyCjVL3UqBQkUlmpDiTd3NTdgBjIcnVVigUA).
**Explanation:**
```
''T: # Replace all "'" with "10" in the (implicit) input-string
g # Pop and push the length
4% # Modulo-4
ø # Create pairs with the (implicit) input-string, implicitly only using
# the first character since we zip it with a single digit
` # Pop this single-item list and push the string-pair to the stack
¤ # Push its last character, the digit (without popping the string)
£ # Pop both, and leave just that many leading characters
3'': # Replace a potential "3" with "'"
# (after which the result is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~23~~ 21 bytes
```
≔﹪⁺Lθ№θ'⁴η✂⁺§θ⁰§2'η⁰η
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DNz@lNCdfIyCntFjDJzUvvSRDo1BTR8E5vzSvRKNQR0FJXUkTyDcB4gxNa66AokygeHBOZnIqRI9jiWdeSmoFSKkBUA2Mq2SkrgTSARQyANPW///7GPn4qPv81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Takes a smashed list as input. Explanation:
```
≔﹪⁺Lθ№θ'⁴η
```
Add the length to the count of `'`s and reduce modulo `4`.
```
✂⁺§θ⁰§2'η⁰η
```
Concatenate `2` or `'` to the face depending on whether the total is even, but then truncate the string to the reduced length.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~22~~ ~~20~~ 17 bytes
*-3 bytes using @loopy wait's idea*
```
<X+hQJ%l``Q4\3\'J
```
[Try it online!](https://tio.run/##K6gsyfj/3yZCOyPQSzUnISHQJMY4Rt3r/3@loCAjJQA "Pyth – Try It Online") -- [Try all test cases](https://tio.run/##K6gsyfiv/N8mQjsj0Es1JyEh0CTGOEbdS8HW9f9/paAgIyUuJR8jHx91HyCjVL3UqBQkUlmpDiTd3NTdgBjIclV3NXJ1dVVXAgA "Pyth – Try It Online")
```
<X+hQJ%l``Q4\3\'J
``Q Surround the input with two pairs of quotes
(Which also escapes `'` characters as `\'`)
%l 4 Take the length mod 4
J (Set J to the result)
+hQ Prepend the first letter of the input
X \3\' Translate `3`s to `'`s
< J Keep the first J elements
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes
```
a=>['',p=a[s=0][0],p+2,p+"'",a.map(([,v])=>s+=!v|v||3)][s%4]
```
[Try it online!](https://tio.run/##TU9La4NAEL7vr5gGyuziaoLtLay3evJkj2YhS6LpFuOKuwqh9rfbMU2hMM/vm@enmYw/DbYPcefO9dKoxaisQpS9MpVXO13ttOyjlHSDG2mSq@k5r@Skhcp8pJ6meZrnF6Er//yql1D7AAqOrIQyhTiDElmRQgEFkqG8QDYijOkqlI7IbnBDClkOOUIOd0dMzo5JGOyVi8T3rQ0cDx2K@/oWVAbtHxxnKMTjLCuh1mKlK0tQOH3w7eE92l4EEY9xWuzZembSuOHNUMX/ti8GcHIdPeHojYZbKv5FXFsnrbtwwpWCWoIj6lvslx8 "JavaScript (Node.js) – Try It Online")
* -1 bytes by Arnauld
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḢɓḟḲOȯ€1S%4ị⁾'2⁹;ḣƲ
```
**[Try it online!](https://tio.run/##y0rNyan8///hjkUnJz/cMf/hjk3@J9Y/alpjGKxq8nB396PGfepGjxp3Wj/csfjYpv///7uqK7gaKbiCoDoA "Jelly – Try It Online")**
There's probably shorter! Calculates the rotation, R, using the sum of the ordinals of the characters trailing each letter or `1` if none exists modulo 4. Concatenates `'` or `2` to the leading letter depending on R mod two and then heads this to the first (up to) R characters.
] |
[Question]
[
This challenge is based on a sandbox post by [user48538](https://codegolf.stackexchange.com/users/48538/user48538). Since he is no longer active on this site, I took over this challenge.
---
[apgsearch](http://www.conwaylife.com/wiki/Apgsearch), the distributed soup search program for Conway's Game of Life and the search results database, [Catagolue](http://www.conwaylife.com/wiki/Catagolue) use **[apgcodes](http://www.conwaylife.com/wiki/Apgcode)** to classify and denote patterns. apgcodes themselves use the **extended Wechsler format**, an extension of a pattern notation developed by Allan Wechsler in 1992.
The following examples and the images are taken from [LifeWiki](http://www.conwaylife.com/wiki/Apgcode#Examples).
1. A string of *n* characters in the set matching the regex `[0-9a-v]` denotes a strip of five rows, *n* columns wide. Each character denotes five cells in a vertical column corresponding to the bitstrings [`00000`, `10000`, `01000`... `00010`, `10010`, `01010`, `11010`... `11111`].
For instance, `27deee6` corresponds to a [heavyweight spaceship](http://www.conwaylife.com/wiki/HWSS):
[](https://i.stack.imgur.com/XDmL7.png)
$$ \begin{bmatrix}
{\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
1 & 1 & {\color{Gray}0} & 1 & 1 & 1 & 1 \\
{\color{Gray}0} & 1 & 1 & 1 & 1 & 1 & 1 \\
{\color{Gray}0} & {\color{Gray}0} & 1 & 1 & 1 & 1 & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0}
\end{bmatrix} $$
2. The character `z` separates contiguous five-row strips.
For example, `0ca178b96z69d1d96` corresponds to a 31-bit still life:
[](https://i.stack.imgur.com/zhhrj.png)
[](https://i.stack.imgur.com/63Txx.png)
$$ \begin{bmatrix}
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 \\
{\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 \\
{\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & 1 & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & 1 & 1 & 1 & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} \\
1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & 1 & 1 & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0}
\end{bmatrix} $$
3. The characters `w` and `x` are used to abbreviate `00` and `000`, respectively.
So `w33z8kqrqk8zzzx33` corresponds to a [trans-queen bee shuttle](http://www.conwaylife.com/wiki/Trans-queen-bee-shuttle):
[](https://i.stack.imgur.com/98NUn.png)
[](https://i.stack.imgur.com/8bY5W.png)
(10 blank rows omitted)
[](https://i.stack.imgur.com/iVYqx.png)
$$ \begin{bmatrix}
{\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & 1 & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} \\
1 & {\color{Gray}0} & 1 & 1 & 1 & {\color{Gray}0} & 1 \\
{\color{Gray}0} & 1 & 1 & 1 & 1 & 1 & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0}
\end{bmatrix} $$
4. Finally, the symbols matching the regex `y[0-9a-z]` correspond to runs of between 4 and 39 consecutive `0`s.
A good example is `31a08zy0123cko`, corresponding to a [ship on quadpole](http://www.conwaylife.com/wiki/Quadpole_on_ship):
[](https://i.stack.imgur.com/nyWOZ.png)
[](https://i.stack.imgur.com/UKAnT.png)
$$ \begin{bmatrix}
1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1 & {\color{Gray}0} \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & {\color{Gray}0} & 1 \\
{\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & {\color{Gray}0} & 1 & 1
\end{bmatrix} $$
## The Challenge
Write a program or a function to parse a string of the extended Wechsler format, defined above, and print (or return) the pattern corresponding to this string.
You may assume that the string is nonempty, and does not start or end with `z`.
You may use any reasonable output format, e.g., a string, a matrix, a 2d array. You may use any two values to represent `0` and `1`, given that you declare them in the answer.
You may omit the trailing zeroes lines in the output, or add extra trailing zeroes lines. You may also add/omit trailing zeroes on each line, as long as all lines have the same length in the output.
You may return the transpose of the array, if that is more convenient.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins.
## Test cases
```
153 => [[1, 1, 1], [0, 0, 1], [0, 1, 0], [0, 0, 0], [0, 0, 0]]
27deee6 => [[0, 1, 1, 0, 0, 0, 0], [1, 1, 0, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]]
0ca178b96z69d1d96 => [[0, 0, 0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 1, 1, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]
w33z8kqrqk8zzzx33 => [[0, 0, 1, 1, 0, 0, 0], [0, 0, 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, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 0, 0, 0, 1, 0], [1, 0, 1, 1, 1, 0, 1], [0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 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]]
31a08zy0123cko => [[1, 1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]
o5995ozes88sezw33 => [[0, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [1, 0, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 1], [1, 1, 0, 0, 1, 1], [1, 1, 1, 1, 1, 1], [0, 1, 0, 0, 1, 0], [0, 0, 1, 1, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
y3343x6bacy6cab6x343zkk8yy8kkzgo8gywg8ogz0123yw321zzgo4syws4ogzgh1yy1hgz221yy122zy3c2cx6d53y635d6xc2c => [[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1], [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
```
[Answer]
# JavaScript (ES8), 197 bytes
Takes input as a string. Returns an array of strings with '#' and spaces. The output may include extra (but consistent) trailing spaces on each line.
```
s=>[x='x',...s.replace(/w|x|y./g,s=>''.padEnd(s<x?2:s>x?P(s[1],36)+4:3),P=parseInt)].map(c=>[!++w,1,2,3,4].map(i=>c<x?o[y+i-5]+=' #'[P(c,36)>>i&1]:o=[...++y&&o,'']),w=y=o=[])&&o.map(r=>r.padEnd(w))
```
[Try it online!](https://tio.run/##TY/PctsgEIfveQrXmTFiRBQDEkGeopx66M13VQeMiKLIFYrwVMDkAfoEfcC@iIv7J@5tf9/ufrP7Ir9Jq@Z@Ot2NptXnJ3G2oqqdAA6gLMtsNuvpKJVO7pc39@az@w7FAQCySbafxjaxH90j2dnKPe4TW@MGUQbTfEch2otJzlZ/Hk@wyb7KKVFR/CFNF4QRQRTlf2gvKhUdpvZpf1c0qQCrW1DvE3UxVVW/wc3OiDrekqZ@szEIgAaiRXgRaQMj@a2ZRTX/u2mB8HzS9rQSK7sS1UqZ0Zqjzo6mS54SC7MX048J@DICeH3vNn4Gfv74DiC8ublsJ2tc0DX8W5OHVmvN3vNWSfzADyULrGxxW147C6WBD6/z68BDCI5eHRTLLQ9@iwlVg3nHpijLwgRtObc6LP8teEpz6thBKs@UPDAXYxgG7j0fhtAZ3vml46YLF6VfKMEh0tz6xeaRds/Ye/zcBUIuBSHBU0WUY21BPaNFy1yMa3j@BQ "JavaScript (Node.js) – Try It Online") (prettified output)
## How?
### Global variables
* The character `"x"` is used several times, so it's worth storing it into the variable **x**.
* The function `parseInt` is used twice, so it's worth storing it into the variable **P**.
* **y** is the row index, initialized to **0**.
* **w** keeps track of an upper bound of the width which is used to pad the final output.
* **o[ ]** is the output array, initially empty.
### Pre-processing of repeated zeros
We first replace all patterns `"w"`, `"x"` and `"yX"` in the input string with the appropriate number of spaces. These spaces will later be interpreted as `"0"`.
```
s.replace(
/w|x|y./g,
s => ''.padEnd(
// w --> 2
s < x ? 2 :
// yX --> value of X + 4
s > x ? P(s[1], 36) + 4 :
// x --> 3
3
)
)
```
### Decoding
We split the resulting string, prepend an initial `"x"` and iterate 5 times (with **i** = **0** to **4**) on each character **c**:
* If **c** is lower than `"x"`, we append the corresponding pattern to the next 5 rows.
```
o[y + i - 5] += ' #'[P(c, 36) >> i & 1]
```
* If **c** is greater than or equal to `"x"`, we allocate 5 new empty strings in **o[ ]** and add **5** to **y**. This is triggered by the initial `"x"` that was added at the beginning of the string, or by any `"z"` in the original content.
```
o = [...++y && o, '']
```
### Padding
Finally, we pad each string in **o[ ]** with spaces so that they all have **w** characters.
```
o.map(r => r.padEnd(w))
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/), ~~148~~ ~~132~~ 98 bytes
I'm a highschool student and this was my first time for both golfing and using 05AB1E, so comments are appreciated!
```
„YY¾38×:'Yð:žLRDUsð«#εNĀiDнXsk4+s¦sú]'W¾2×:'X¾3×:J'Z¶:.Bð¾:vNUyvDykDNX‚Š32VY‹iY+b¦RX_i¶ì}‚ˆ]¯{€¦˜J
```
~~[Try it online!](https://tio.run/##JY2xSsRAFEX/ZbcIGIXJTDKELQRhqi0CK2SJhUWSlUlIscXAJm8kYCX4BdtaCZKAaSIrqMUMVkLwG/ZH4kSLx3v3cs99yIsT52YcZwAzCxFf7xcW6G7x9ZldqIaFQneqmQ99cH58eMzZz0ckCtcW6kkgofe6rWurtBCesMrwZi8tafg/jOnn4cDDoWc8EmcToJp6F4SwCzzV2WZOInvNoGAEH@/e8oRx7z@n28sIrXL1aj5cTV26/b7XDfFWOQrRWr1fq5fboZ8Ph3p5Oo5AiEsqmsQp0DROaGWkLAofwC8Kybc@h5L7Wy6RgwmUBDvSuK6AUrjG5ZkD4GRcYjwdGEsgKU4ruvEIUOJtaGXkLw "05AB1E – Try It Online")~~
~~[Try it online!](https://tio.run/##JY2xSsRAFEX/ZbdYMAjJTDKELQRhqi0CCpFYWCTZZRKm2GJgkzcSEBHBL9jWSpAE3CayFqaYwUoIfkN@JE60eLx3L/fcZ3tx4mzGcQYwUx329X65AH1YfnXZuappKPRB1fO@Dc6Gp@ec/nxGgruWUC/CFnqvm6paFKpDE1Ya3uzVQhr@D6P6tT@ysG8pi8TpBKi62gUh7ILh/sEycxJZVxQ4xWi4@8gTyrz/nG4uI/siV@/mw/XUpZvvxxv1dtu38/5YrcYRMHZxSZI4BZLGCSmNlJz7AD7nkm19BgXzt0zaDsJQYORI47oCCuEal2UOgJMxidB0ICQBpygtydrDQLC3JqWRvw "05AB1E – Try It Online")~~
[Try it online!](https://tio.run/##MzBNTDJM/V/6/1HDvMjIQ/uMLQ5Pt1KPPLzB6ug@nyCX0OLDGw6tVj631e9IQ6bLhb0Rxdkm2sWHlhUf3hWrHn5onxFIdQRQG5D2Uo86tM1KzwmoY59VmV9oZZlLZbaLX8SjhllHFxgbhUU@atiZGamddGhZUER85qFth9fUAqVOt8UeWl/9qGnNoWWn53j9VzdUfzStw0rdQF3P6r@hqTEA "05AB1E – Try It Online")
Takes input as uppercase and outputs the transposed matrix as multiple output lines of 1s and 0s. May add extra zeros.
If you want to test with lowercase strings, add `u` in the TIO header.
If you want pretty-printed output, add `'1'█:'0'.:` in the TIO footer.
# Explanation
(I'm calling "rows" and "columns" opposite of what you might expect because it generates the transposed matrix)
The basic algorithm is:
1. Replace "yy" with 38 0s
2. Split on "y" and and expand the 0-runs.
3. Replace "w" and "x"
4. Figure out the longest column (that is, the longest string between z's) and pad all the other columns so they are that length. (This is necessary because of how the algorithm below works)
5. Split on z
6. At this point, the input string is an array of columns where each column is a string of [0-9A-V], where each column is the same length.
7. The algorithm to get it into the output format is to
1. Convert the characters to numbers by using indexOf in a lookup string
2. Convert the characters to binary and then pad to length 5
3. If it is the first column, add a linebreak before the binary number
4. Add a prefix to the beginning of the binary string that stores the row and then the column of the character.
5. Push the binary string with prefix to 05AB1E's "global array" register/variable
8. Sort the global array. The prefix string, which determines the sort order, will make sure everything ends up in the right order and the linebreaks are in the right places.
9. Remove the prefix string from each element of the global array
10. Join the array with "" and print it.
There are some other minor details you can see below in the expanded code. Everything after the tabs at the end of a line is a comment and can be ignored. (This comment scheme is not part of 05AB1E, by the way. I did it this way because it looked nice.) Lines that have comments starting with "@" are for debugging purposes and can be omitted without changing the final output.
```
„YY¾38×: Replace "YY" with 38 0's. (y is the 34th character in the index, so need to add 34+4 = 38). ¾ is initialized to zero, which saves one byte from typing '038
'Yð: Replace "Y" with " "
"Replaced input Stage1 = "?D, @DEBUG
žLR Pushes [0-9A-Za-z]
DU Set X to [0-9A-Za-z] and leave [0-9A-Za-z] on the stack.
s Swap top two elements. Now the stack is [0-9A-Za-z],input
ð« Append a space so the below splitter works even if there are no other spaces.
# Split input on " ", which "Y" has been replaced with
ε Map. This map replaces the y runs
"Element = "?D, @DEBUG
"N = "?N, @DEBUG
NĀi If N != 0
"Replacing!", @DEBUG
Dн Get the first letter
X Push X
s Swap
k X (which is [0-9A-Za-z]) .indexOf(firstLetter)
"indexOf run token = "?D, @DEBUG
4+ Add 4 to the index, now becoming the number of zeros to add
s Swap. Now top is the string between runs
¦ Remove the first character
s Swap again. Now the top is the number of zeros to add.
ú Add that many spaces (will be replaced with zeros later) to the start of the element.
"Element Replaced = "?D, @DEBUG
]
'W¾2×: Need to do this replacement after the Y replacement so stuff like YW gets parsed properly. Again, ¾ is zero.
'X¾3×:
J Join with ""
"Replaced input Stage2 = "?D, @DEBUG
'Z¶: Replace "Z" with "¶".
.B "Squarify" command. Splits on \n and appends spaces to the end of each element so each is the same length. In this case, that is equivalent to adding zeros to the end of each column, which is what we want.
ð¾: Replace spaces (which we used for padding above) with zeros.
"Replaced input Stage3 = "?D, @DEBUG
"0 Stack top = "?D, @SDEBUG
"0 Stack top-1 = "?sD,s @SDEBUG
v pop and loop over top element, which is array of column code
NU Store the column number in X
yv Loop over each character in the column
"1 Stack top = "?D, @SDEBUG
"1 Stack top = "?D, @SDEBUG
D Duplicate top element (which is now [0-9A-Za-z])
y Push y (special loop variable)
"Character = "?D, @DEBUG
k Push indexOf y in [0-9A-Za-z]
"Index = "?D, @DEBUG
"2.1 Stack top = "?D, @SDEBUG
"2.1 Stack top-1 = "?sD,s @SDEBUG
D Duplicate index.
NX‚ Push [rowNumber,columnNumber]. This result is used for sorting.
Š Triple swap. The top of the stack is now sortPrefix, index, index
32V Set Y to 32
Y‹i index < 32. This uses up one copy of index
Y+ Add 32 to the index
b Push the index in binary. This uses the second copy of index.
¦ Remove the first character, which will be a 1 because we added 32. The result is now a padded binary string of length 5
"Binary = "?D, @SDEBUG
R Reverse the binary string. This gives the proper transposed output.
X_i This will only run if X (which is set to the column number) == 0. (Runs !X)
¶ì Stick a linebreak at the beginning of the binary string
}
"2.5 Stack top = "?D, @SDEBUG
"2.5 Stack top-1 = "?sD,s @SDEBUG
‚ At this point the top of the stack is sortPrefix,binaryString. This will combine the two into a list.
"Pushing '"?D?"'", @DEBUG
ˆ Push [[rowNumber,columnNumber],binaryString] to global array
"2.6 Stack top = "?D, @SDEBUG
"2.6 Stack top-1 = "?sD,s @SDEBUG
] Close all blocks
¯ Push global array
{ Sort global array.
"Sorted Data = "?D, @DEBUG
€¦ Remove the sort prefix
˜ Flatten. Before doing this, the array is in the format [[<binary string>],[<binary string>],[<binary string>],...]
J Join with ""
'1'█:'0'.: @DEBUG pretty print
```
[Answer]
# [APL (Dyalog Unicode)](https://dyalog.com), 87 80 77 67 63 bytes
thanks to H.PWiz for saving 7 bytes and ngn for another 13 17.
```
a←⎕D,⎕A⋄,⍉↓⊖(5/2)⊤↑35(≠⊆⊢)a⍳'Y.|W|X'⎕R{'0'/⍨30 36|a⍳2↑⍵.Match}⍞
```
[Try it online!](https://tio.run/##LY0xS8RAEIX7/Aq7vYPzbncnWZIyl@CeBAneYZLZLijR4kALGzF2Er1IRBEtRcTCXvxD80fihrOYee99w2PKi/XuyVW5Pj/t6fF1P6XmiTt0f1f1pbUWxRO7Qnq4nVC3oeaF2reRN5Njar@oeQZvRJsPahtqP8cldT8Mp3VeF8yWlteMsxl138B3QNXDVdoKdb/Tg/Ly@OyGuvfevuorB0TIfYNcSIiS1GHMqRwEcKFQ8zBCFYVzVdhoksRH9JPE6NTXmGs/1WZoYQ5SGEvdFeYr11K9EIhioY2Ug5HSIEQyKlTsASrwYlXYuH2VZUGwp/i/HGVCgBwkWB4aABTDWCRB8K38AQ)
NB: Takes the input as an upper case string.
[With pretty printed output](https://tio.run/##LY3BToNAEIbvPAW3LUml7G5L6KEHCkoNVmKxhcV4oAp6IK1RDhrrzWCLwWiMPRqjHnrwZnwBH2VeBJfUw8z//9/s7IRnycbxVZhMT8oaPLzsulB8SXJl3U15aPRNNJ5eitOJuBF3qp520vMoQpB/RJNwnESuvrPPA39vMHQRJimSBB62HcgeFQHmd3EZcsuRWedNh/vb@u8KibCcowPInupQLCB7hnxZazWIBPknh7RVg8Ub5Bnk71IIxTdi8syb@Yj/MLhGCmpAsaKKSNVZNSV8BYofuR@mR6c3ULwelvxwGQsU64oWMAUTatiOgJAQC4zSJvXVrm4w1dC7qs9jYNsaY5ptB5ajWcyzNMcKqi3mUYIDTpsu89wmp1YPM4Z7VkBIZQgJGDWI4atmizKVtkzV53F9ajRqt7dU5V@GI4wpqaQ92AsoZbgqjgjFylr@AA)
# Explanation
`a←⎕D,⎕A` a is the string `'0123...89ABCD...XYZ'`
`'Y.|W|X'⎕R{'0'/⍨+/30 36|a⍳2↑⍵.Match}` replaces X W and Yx with the corresponding number of `'0'`s (explained more below)
`35(≠⊆⊢)a⍳` converts the string into vector of indecies in `a` and splits on `35` (i.e.) `'Z'` creating a nested vector
`↑` converts the nested vector into a matrix padding ends with `0`s
`(5/2)⊤` converts each number into a binary vector resulting in a 3-dimensional matrix with binary vectors along the primary axis
`⊖` reverses along the primary axis
`↓` reduces the rank of the matrix so it is 2-dimensional
`,⍉` reshapes the result to the appropriate output
```
'Y.|W|X'⎕R{'0'/⍨30 36|a⍳2↑⍵.Match}
'Y.|W|X'⎕R ⍝ Regular expression replace. mathing the string.
2↑⍵.Match ⍝ Takes matching string (either 'X' 'W' or 'Y.') and pads with spaces to length 2
a⍳ ⍝ Returns the indecies of each charactor in a. on the spaces this is 36 (length of a)
30 36| ⍝ Takes the remainders of the indecies when divided by 30 and 36 respectively. Overall 'W' -> 'W ' -> 32 36 -> 2 0, 'Y2' -> 'Y2' -> 34 2 -> 4 2.
'0'/⍨ ⍝ Make vector of repeating '0's with length equal to the sum of the result. '0'/⍨4 2 ≡ '000000'
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~156~~ 142 bytes
*14 bytes saved thanks to Jo King. (Also fixed a little bug with parsing the `y` and added a prettifier.)*
*Fixed the buggy parsing of `y[wxy]`.*
```
{s:g/y(.)/000{0 x:36(~$0)}/;s:g/x/w0/;s:g/w/00/;s/$/z/;map {
.flatmap:{:32($_).fmt("%05b").flip.comb}},[Z] .split("z").map: (*~0 x.chars).comb}
```
[Try it online!](https://tio.run/##3VJLjptAEF1Pn6KESdSMEHQbmbFNPFI2kbLPKo41atvNmJjf0Dg2WJ51TpB17pKb5CJOY/wD7NEo2QWhovRe9atXRcc88e1tkMFbFwawXYv@o5lhQzMJIWsCq75l42eVaBvTKaiVuSRltpQVMjNVMzedgMWwNlyfpTLrr/tWG6sPmuEGKVbekM5YkbnvxcYkCsabjT78PAJDxL4n6VxyxSHAt8@ynzGZsURoZeXWQUhaU8X@Gyc8TTPp81Oy4A604KO7S3WQxCIJgcG@5DFh8cybMF8yEhI8TFnqRSHgXz/BZ/A@CdnCn2pGIfGB@eKkkc44BCxNvBV848lYHgsMJB2iNbrZmZH91QcH3QiWQTGJi1WhwSL0uRAHjyWN8ZHfDYlv9zFNWCiwQhQY3IMCig4KLfPfP74rsvhr5IVlxMqXUCLguVVtUAa1R3HQRod3NFtSoNmqCJkMHQvad1POuQ1kwuhdd9yzc7s3pdOeDUvLyrvzp@Rp3s3zfGVZYFFGunlGaNuazCOIOr1eJ8q56HYFz2X5PUKoVYhKt8Mh1aF4RzoMiQ7klEqUnNBKOkKtg6GdRllNS/ZUfsTo8T1p0wtwjTnvWdGW/ZuLODg51yEXpGgznk18BjfWQaviLzisrKw2bHVBtTO0TjYjqRtqyF43JBfXvC9ni7si9ZoO/wBfb9mYuHKmsiV64W@@6jL9x3Bjgy/Cf91yhND2Dw "Perl 6 – Try It Online")
The line break is there just to make the text fit on the screen. It is not a part of the program.
## How does it work
It is an anonymous function that takes a mutable string. (This makes using the function a little bit peculiar, because you can give it only variables, not literals.) After some work, it returns a list of lists containing 0's and 1's, with the same meaning as in the original post.
The input string comes in in the variable `$_`. We start by using a series of substitution statements on it in order to get rid of all of those shorthands for various numbers of zeroes. First, we need to sort out the `y`, because in the case of `yx` or `yw`, the `w` (or `x`) does not constitute a shorthand by itself. We search for `y(.)` (`y` and one character, which it remembers) and replace it by `000{"0"x:36(~$0)}`: the three zeroes are copied verbatim, then we convert the next character from base 36 to base 10 (`:36(~$0)`) and add that many more zeroes. Then, we replace the `w`'s using `s:g/w/00/`, and the `x`'s using `s:g/x/000/`. Finally, with `s/$/z/`, we add a `z` onto the end, adding a whole lot of empty lines to the bottom. (We'll see the reason later.)
The rest is just a big map statement. We're mapping over `.split("z").map: (*~0 x.chars).comb})`, which is the input string (without zero shorthands), splitted into lines at `z`, with each line being first padded with `0 x.chars` (tons of zeroes, namely as many as is the total length of the input string) on the right and then broken down into a list of individual characters (`.comb`). Finally, we transpose it with `[Z]` (reduce with zip). Zipping ends as soon as the shortest list is depleted, which results in all lines having the same length. (The number of useless trailing zeroes on the right is equal to the length of the shortest line. Also, this transposition trick fails for a "matrix" with only one row. That's why we forcibly added another row at the end before.)
Now, we just map over the rows (columns of the original matrix) and replace each character encountered with the corresponding 5 bits. That is done using `:32($_)` (base 32 to base 10) `.fmt("%05b")` (format as a bitstring of width 5, padded with zeroes) `.flip` (reverse the string, because the LSB is in the top row, not the bottom) `.comb` (break the string into a list of characters). We have used `.flatmap`, which flattens the resulting list (otherwise we would get a list of lists in each column). The transpose of the result is then implicitly returned.
(I feel a little bit bad because of abusing the possibility of trailing zeroes so hard. But it reduced the bytecount quite considerably :—).)
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 203 bytes
```
y(.)
#$1
{`#
0#
#0
000
)T`dl`_dl`#.
w
000
x
00
z
¶
%(`.+
$&¶$&¶$&¶$&¶$&
T`g-v`#`.+$
T`dl` `.+$
T`g-v`dl
T`89l`#`.+¶.+$
T`d` `.+¶.+$
T`89l`d
T`d` #`.+¶.+¶.+$
T`4-7`d
T`d` #`.+¶.+¶.+¶.+$
)T`d` # #
P`.+
```
[Try it online!](https://tio.run/##VYxRboMwEET/9xSRnFZBVZDtBWNu0Y/8F4KRUzkqSqgKu71XDpCLUUOSql1pVzPzRntuP98/ajVNtEkTEGsF35UAKUBIkFJCsqvcsXqLK1IYlmiMFxiuF3jaVOkLrJ@vl/8Lu8pvvyoR6RqWB6u7nGN3jMKWx4VfL/fOUnm4mbpbGufRe9BsW/zSv@zGkwWIlYDXyKZJ5Qi6cG3bGpBNrQq7Lw2b0ilXGhgQ2YbT@RQsM4@IgKqWlkkqjU3ooMvLMu@47a3tW451IMQMR7OvGzJNvTdjtByCJbIhsO@sp8HbzvP8ggbUimOa9TT0WUz9QRGpg2etZ6E1Eza6GY3LkQzmzozR/gA "Retina – Try It Online") Link includes test cases. Alternative solution, also 203 bytes:
```
y(.)
#$1
{`#
0#
#0
000
)T`dl`_dl`#.
w
000
x
00
z
¶
%(`.+
$&¶$&
T`g-v`#`¶.+
T`dl` `¶.+
T`g-v`dl
^.+
$&¶$&
T`89l`#`¶.+
T`d` `¶.+
T`89l`d
^.+
$&¶$&
T`d` #`¶.+
T`4-7`d
^.+
$&¶$&
T`d` #`¶.+
)T`d` # #
P`.+
```
[Try it online!](https://tio.run/##bY5bbsIwEEX/ZxVIpoioAtmexDi76AffrUMcGWTUCFI1mem@WAAbSx3UB5Vqydbcc48tn5u3w2ulxpGW6wzEXMGHEyAFCAlSSsi2zh/dS9piDf0NDekEhusFHpZu/QjzxfUyX8DWhdW7E@56Sex2a/Y9T4U/wvO9bMvjnfzrTtz/VVOb1o@crzb/GV99dktiJuApfW4cVYGgN75pGgOyrtTG7krDpvTKlwZ6RLbxdD5Fy8wDIqCqpGWSSmMdW2iLsixabjpru4aTDoSY42B2VU2mrnZmSJFjtEQ2Rg6tDdQH2waenqAeteJE8476Lk807BWR2gfWehq0ZsJa14PxBZLBwpshxU8 "Retina – Try It Online") Link includes test cases. Explanation:
```
y(.)
#$1
```
First handle the awkward case of the `y` command. Sadly the letter after this is allowed to be a `y` or even a `z`, so we have to be careful here. All the magic `y`s are first turned into `#`s.
```
{`#
0#
#0
000
)T`dl`_dl`#.
```
A loop then processes the `#`s. First, a `0` is prepended to the `#`. If this is a `#0` then that is changed to `000` which completes the operation, otherwise the character after the `#` is decremented and the loop repeats until all of the `#`s have been processed.
```
w
000
x
00
```
Fix up the `w`s and `x`s.
```
z
¶
```
Split on new lines. (`S`z` also works for the same byte count.)
```
%(`.+
$&¶$&¶$&¶$&¶$&
T`g-v`#`.+$
T`dl` `.+$
T`g-v`dl
T`89l`#`.+¶.+$
T`d` `.+¶.+$
T`89l`d
T`d` #`.+¶.+¶.+$
T`4-7`d
T`d` #`.+¶.+¶.+¶.+$
)T`d` # #
```
Make 5 copies of each line, then perform binary conversion by mapping letters with the appropriate bit to `#` and clearing that bit, while other letters become spaces. The bits are processed in the order 16, 8, 4, 2, and then the last translation handles clearing the `2` bit and converting the `1` bit at the same time. (The alternative version makes each copy individually which costs more bytes but these are saved because the bit handling is simplified.)
```
P`.+
```
Pad all the lines to the same length.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes
```
UB0≔⁺⭆χιββFS¿υ×0⁺⊟υ⌕βι≡ιz×⸿⁵y⊞υ⁴x×0³w¦00«P↓⮌⍘⌕βι²→
```
[Try it online!](https://tio.run/##XU/RaoMwFH2uXxF8iuBAEytin1bGYA@F0u5xLzGmMeiMmFhNRr/dRTtWtkDgnnPvOedeWpGeStLM85npPaE17@XQltCP/GDnPSsleAuPzaDgWfei5QfSwTgKgQhCUKx/511kD@Bb2w36PgODAIgLgEMAjg5r@C4@mVosQ7BaHWXnmiF4FS6pWMzc23msUQyoUWhaASgC8OVR4hjf@vlfo4/eOW0XyX3ALAODquAQguSXnf7Llnz8UI2/fT9ary3ZhQyNzl3w5uAK0a3d/EWObQhO7Mp6xeDeiX/ufOwfArSesDnIK4P5SfBKO3jzbvNsME7wlBaEmpSSIp0ctHWdGZPVteUy42bkmeQ2ihE2I0axdWyizKgSx/IqNiauuEVoKRCyBlNEp7TcYpPibZlODs5P1@Yb "Charcoal – Try It Online") Link is to verbose version of code. Uses `1` and `0`. Explanation:
```
UB0
```
Set the background, i.e. any unprinted cells of the rectangle enclosing the output, to `0`.
```
≔⁺⭆χιββ
```
Prefix the digits to the predefined lower case alphabet.
```
FS
```
Loop over the input string.
```
¿υ
```
If the predefined empty list is not empty...
```
×0⁺⊟υ⌕βι
```
... then print a number of `0`s given by the sum of the number popped from the list and the index of the current character in the digits and letters. See below for what that number always is.
```
≡ι
```
Switch over the current character.
```
z×⸿⁵
```
If it's a `z` then output 5 carriage returns, taking us to the next output strip.
```
y⊞υ⁴
```
If it's a `y`, then push `4` to the predefined empty list, causing `4+n` `0`s to be output next time.
```
x×0³
```
If it's an `x` then output 3 `0`s. (This is done via repetition to avoid the literal `0` touching the `x` or the following literal.)
```
w¦00
```
If it's a `w` then output 2 `0`s. (The `¦` is needed to separate the two string literals.)
```
«P↓⮌⍘⌕βι²→
```
Otherwise, index the current character in the digits and letters, convert to binary, and print the result downwards least significant bit first; then move the cursor right for the next column.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 66 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Yowza!
```
ØBiⱮ+
Œuœṣ⁾YYj38Żṣ”YµḢç3;)Fṣ”Wj2ṣ”Xj3”0ẋ$¹OƑ?€Fṣ”Zµȯ”0ç31BḊ€UZ)Ẏz0
```
A monadic link which yields a transposed version as a list of lists (add `Z` to the end to transpose back).
**[Try it online!](https://tio.run/##y0rNyan8///wDKfMRxvXaXMdnVR6dPLDnYsfNe6LjMwytji6G8RpmBt5aOvDHYsOLze21nSDiIRnGUEYEVnGQNLg4a5ulUM7/Y9NtH/UtAaqJurQ1hPrQZJAjYZOD3d0AaVCozQf7uqrMvj//79SubFxlUV2YVFhtkVVVVWFsbESAA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##LY6/SsNQFMb3PoWELqUdcu9Jbm9wEDq4OommW5qE1NxCqEGSeyZ1KagI6qCLiw4uoji09A84JER8jfRF4k3rcA7f9zvfOZzQH41kVeVPvZP110e7UdyfFQ/l4nV98W3bIfBiVZvzZzublvOX/A12W/tbchTSrTgOQXW9XF43s8XBz93e@vL9P9PPpr@f9VAtkl45v1Kjw36rXN6iXuWTfv5oGdRsEw7l6sZudPJJUyVsVaF6IJtls6rSiAlaZ0ejXc/3fVZL3XVIlw8shszyiGdtYAKAXIxPx4IjYgqbJSCOzlHqhIIroppEpmWZEfox57GPyTYmAQxI2cBxJXOdAUuVRSG4lFwIDCIeyCTgUYD1IZkAJaioEcskNhQNhkRKMgyQ0lpQihJc6qbMM0EyMD2WKqv9AQ "Jelly – Try It Online") (with pretty printed output).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~249~~ 244 bytes
```
def f(s,Z='0'):
while'y'in s:i=s.find('y');s=s[:i]+4*Z+Z*int(s[i+1],36)+s[i+2:]
t=s.replace('w',2*Z).replace('x',3*Z).split('z');return map(''.join,zip(*[[(Z*5+bin(int(c,32))[2:])[:-6:-1]for c in r]+[Z*5]*(max(map(len,t))-len(r))for r in t]))
```
[Try it online!](https://tio.run/##ZVDLbsIwEDyXr/DNu4lBOIG0ScWVj4jrQ8hDuAomsl0g@fnU5qEe6svOrGZmdz2M7njWyTw3bUc6sKzc0TXFYkGuR9W3dKRKE1uonV11SjfgG/hpd1YUSsabqIzLSGkHVqiYS5ZmGAeYFHJBnPeYduirugV6pSyJSvxr3ChLQ8MOvXJAJx9rWvdjNDlVA1C6@j4rzSY1QCQElNE2PigNYVbN0gRR@BkoimVWLLnszobUxG9qZCy8VkZwqm4QkvpWM4e49BUMYlCaoHQS8X70Hqw/920wPpvYJ3hx/yP4wvRLP7aCfxsGmX8v82IPlG9TineQTGmWP/BlrPg0XTwJbF1X/P3jkGdTlje8ybOnYbxxivP8Cw "Python 2 – Try It Online")
5 bytes saved by [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech).
[Answer]
# JavaScript (ES8), 192 bytes
```
s=>[...s,"z"].map(c=>{h=parseInt(c,36);k="wxy".search(c)+1;y?k=h-y--:h-35?y=h>33:m=m.map(P,z+=5,i=k--);for(h=k?0:h;~k--;m[i]=h.toString(2)+P(m[i++]||""));},P=d=>d.padStart(z,0),m=[i=z=y=0])&&m
```
Returns the transpose... which is then reflected across the vertical axis; let me
know if that invalidates this entry. Output is an array of strings containing
`0`s and `1`s.
[Try it online!](https://tio.run/##7VpLj9o6FN7zKywWJREhE5OBhkGZURd3cXcj9e4oUj2OSdJAwthmiNP2ru/2bvoD@0fmOoHySgLRjO6AqqAImWOfcz5/55EXX9ATYpj6c94JI4c8E/uZ2bcjXdeZ1kyaY32G5gq2b7969hxRRv4MuYI1s68OA7u5jEVTZwRR7ClYbcOhuAtsryM6nRuvY/buhO3dmubNzJ5lZu61pG33NN8OOh11OImo4tnBnXHjDf@WkuFs5I9tT@fRR0790FW6avtekcJ2e/ztW7OpqsPv2r3t2LeOPkfOR44oVxLNULWZPfLtxBa2MVbfvZs9X12BDw@MhJiAaAIQY4RyPwoBoTSiDPih42PECQNsgTFhrIGjkHHAgQ0oeVz4lCitlVZLHTYa0tw9JZyLzlzi4hLaWmEiFWJg3wIFyRFRYlUD6Uw0Jfo0chWU7ZqmK6hOyXyKMFGujCtXA62fP/5pqVshXAv/bamq/iXyw8@fws9S8ilsSaNoDeMvFEjU3COAUxSyecSIJiFPpgRzBqInQrPJp3S/GE0Bin0mtUMHsIxSf@Kv9Wm0ZKlFHq1MyWDMgOs/kRBIYjjAiBHWAiSeS9PEkU7YYspT7qQGAulyxDNLWGYNiBZ8vuCsAeRnxY37i5uvmXA7IekAHyhFQolHxlifktDlnqpP/OlUkUEebpbHGXsitSGyoQw28NWMTZkp0kwC2tlQ3dGSgVrQENCV5Puat82WMinXHULmfzwu0FSZKC3YM1OSXWVjJP2MRlAD6THWwMjQgLEdSqmxle4Nx3s2UmC7CSHzqvte@iZ9GeYiKJvZAjgrx3DlaOt5I4ObYwsTFogPZnbh79nOb6UAsIERfG89DPpJf@BAZ1AKfdexUeAb5r932N4R50IB940f2dJeuA7Y2Wf0QAceTua/jUNAObPlgCoxvTTNxAoe6WNgJUkSm@YRpkt8V4H0CnG5yxxFezp7tMKC8FdK199YnGPwqPjFLiuloQmRYSXCgF0TB9GRvllefDBXzUa1QiltGC/RL7ZSoF@tkE91nv2kLjVRLQhRbzDoRQlhlsVIsizvBScrp6jHHtbjL9wHXMMye0XrDvv0VlZ02trHUp7txyugsqwS58I0r824/4Cw6GP00I/lzyQILCGsIEjcyHLF0rUiN0lLQyzNLkyk9JqJJbuWUteDQkDPTbrddNDtJsLEXRz3nZ4p@mbP6cfy5/Gz57HEPVJT5el20mCFrM83dFgZSH7xS3tDGRGwMgtVqTzVYU7t8DXLXori/zpqFCXX4mc5ctf4Z4FwiVzU2XlRKOD5shMW3DW/fYHkrnbOhaLs5vAtw1HXSI2iRlGjqFG8EsUFdPALOJtd0pn93Fc5dY3Ud4j1HWJ9h/i7ojjH07ULeNJ4GU9dL@MJ9Ntm57jRyL0rWL8sSP9hgfn2dYFoqes/N2jAtDbvFA6XJbvLBnLZ838 "JavaScript (Node.js) – Try It Online")
## Explanation
For each character `c`, `k+1` evaluates to the number of rows to modify.
`k = "wxy".search(c) + 1;`, where the `search` method returns the index or `-1`.
`k` is then decremented until it reaches `-1` by checking `~k--` for a truthy
value.
If the current character is "y", set a flag so that the base-36 value of the next character - 1 becomes the value for `k`.
Upon encountering a "z", pad strings to the left, increment the pad amount by `5`,
and reset the array index to `0`.
```
s =>
[...s, "z"].map(c => { // append a "z" to ensure final output is properly padded
h = parseInt(c, 36);
k = "wxy".search(c) + 1; // note that "y" -> 4 zeroes
y // if previous char is "y"...
? k = h - y-- // decrement y after subtracting y=1 since k is decremented to -1 and the previous y already pushed 4 zeroes
: h - 35 // else if current char is not "z"...
? y = h > 33 // set y if current char = "y"
: m = m.map(P, z += 5, i = k--); // else if current char is "z", pad
for (
h = k ? 0 : h; // if k is truthy, push zeroes
~k--;
m[i] = h.toString(2) // convert to boolean representation
+ P(m[i++] || "") // prepend to row or to a newly padded row
);
},
P = d => d.padStart(z, 0),
m = [i = z = y = 0] // the logical OR 4 lines above replaces this value with ""
) &&
m
```
[Answer]
# Haskell, 399 bytes
Install `split` package: `cabal install split`
```
import Data.Char
import Data.List.Split
import Data.List
p=map
r=replicate
a c|47<c&&c<58=c-48|96<c&&c<123=c-87
o=a.ord
m l n|l==0=[]|True=(mod n 2):m(l-1)(div n 2)
t a=p(\l->l++r((maximum$p length a)-length l)'0')a
y s|length s==0=""|h=='y'=(r(4+(o$s!!1))'0')++y(drop 2 s)|h=='w'="00"++y t|h=='x'="000"++y t|True=h:y t where h=head s;t=tail s
w=(p concat).transpose.(p$p$(m 5).o).t.(splitOn "z").y
```
] |
[Question]
[
# Background
In [Boggle](http://en.wikipedia.org/wiki/Boggle), a round is scored by adding up the points for each *unique* word a player has found (i.e. any word that more than one player has found is worth 0 points). The points are calculated based on the number of letters in each word, as follows:
3 letters: 1 point
4 letters: 1 point
5 letters: 2 points
6 letters: 3 points
7 letters: 5 points
8 or more letters: 11 points
# Challenge
In this challenge, write a program or function that takes in a list of lists of strings representing each player's words and outputs a list of the players' scores. You can assume that there will be at least 2 players and all words will be 3 or more letters and will all be lowercase (or all uppercase if you would prefer). You may also assume that each player will only use each word once; that is, no player's list will contain duplicates. This is code golf, so shortest answer in bytes wins.
# Rules
Input can be taken in any reasonable format. Examples include a list of lists of strings, a list of comma-separated strings, a comma separated string on each line of input, etc. Output can be in the form of a list of integers (or your language's equivalent) or you can print the values to stdout using a separator of your choice (such as a newline).
# Test Cases
Input => Output
```
[["cat","dog","bird","elephant"],
["bird","dog","coyote"],
["dog","mouse"]] => [12,3,2]
[["abc","def","ghi"],
["ghi","def","abc"]] => [0,0]
[["programming","puzzles"],
["code","golf"],
[]] => [16,2,0]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~21~~ ~~20~~ 19 bytes
-2 bytes thanks to [Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb)
Idea taken from [A055228](http://oeis.org/A055228)
```
ṠṀöṁ(⌈√Π-3▼8L)fε`#Σ
```
[Try it online!](https://tio.run/##yygtzv7//@HOBQ93Nhze9nBno8ajno5HHbPOLdA1fjRtj4WPZtq5rQnK5xb///8/OlopObFESUcpJT8dSCZlFqUAqdSc1IKMxLwSpVidaJgYREFyfmV@SSpYHCKQm19aDOTHAgA "Husk – Try It Online")
### Explanation (Of older version)
```
ṠṀ-oṠ-uΣ Remove duplicated words
Σ Concatenate
u Remove duplicates
oṠ- Remove those unique elements from the list (give list of elements that appear more than once)
ṠṀ- Remove those words from each list in the input
m For each list
ṁ( Map then sum
L) Length
▼8 Min(8,x)
-3 Minus 3
Π Factorial
√ Square root
⌈ Ceiling
```
[Answer]
# [R](https://www.r-project.org/), ~~142~~ ~~126~~ ~~121~~ 117 bytes
```
function(L)sapply(lapply(L,setdiff,(l=unlist(L))[duplicated(l)]),function(x)sum(c(1,1,2,3,5,11)[pmin(6,nchar(x)-2)]))
```
[Try it online!](https://tio.run/##hY89T8MwEIb3/IooS23JHVIEE52QkJAysqUeHH8klhzb8geiRfz2cCZpxYDAw53v9evn7sKSZExPLMpX92J9Ts8uzCzVj/taZcuTdhZF/FHJN2aQZyFKlI5jzANqaEMa3JC1OJ16KDn6Ua@S0TGhokdcTvVZVarQlxu@w5F5b87IrKkjUSahlSLIHLP9BnQY9yJ7ozlLUiCDKSY3wDuOeYYeLWnJgdyRe9K2uPeztuiBWD6xAJb9Af7gRaFf90W7vm@ADQMLN0IcdBCQpJF@YjY1lFR1f1VXC3dnl@T2skqzyxEUWtc7WPWvXmzgBSQVxHHSG6XcrmpxAOk/kA9uDGyGZcsAPl8uRsYNx52Qhe@MWhVKAbd8AQ "R – Try It Online")
Takes `L` as a list of vectors of strings; returns the values.
First, it `unlist`s the words, finds the duplicates, then removes them from the players' word lists. Then it takes these unique word lists and computes the scores of each, using `pmin` to ensure that words longer than 8 get scored as 11.
[Answer]
# JavaScript (ES6), 92 bytes
```
a=>a.map(b=>b.reduce((s,v)=>s+(a.filter(b=>b.includes(v))[1]?0:+"11235"[v.length-3]||11),0))
```
Somewhat similar to [Rick Hitchcock's answer](https://codegolf.stackexchange.com/a/143233/69583) but created mostly independently; I used a different method of summing (`reduce`) and different method for checking for repeated terms (`filter` + `includes`). Credit to him for the idea of checking for item `[1]` instead of checking `.length>1`, though.
## Test Cases
```
let f=
a=>a.map(b=>b.reduce((s,v)=>s+(a.filter(b=>b.includes(v))[1]?0:+"11235"[v.length-3]||11),0))
;[[["cat","dog","bird","elephant"],["bird","dog","coyote"],["dog","mouse"]],[["abc","def","ghi"],["ghi","def","abc"]],[["programming","puzzles"],["code","golf"],[]]]
.forEach(test=>O.innerHTML+=JSON.stringify(test)+" -> "+JSON.stringify(f(test))+"\n")
```
```
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6), ~~106~~ 93 bytes
*[Saved 13(!) bytes, thanks to Arnauld, Shaggy, and JollyJoker.]*
```
a=>a.map(b=>b.map(c=>x+=(a+'').split`,`.filter(d=>d==c)[1]?0:+'11235'[c.length-3]||11,x=0)|x)
```
**Test cases:**
```
let f=
a=>a.map(b=>b.map(c=>x+=(a+'').split`,`.filter(d=>d==c)[1]?0:+'11235'[c.length-3]||11,x=0)|x)
console.log(f([["cat","dog","bird","elephant"],
["bird","dog","coyote"],
["dog","mouse"]
])
) // [12,3,2]
console.log(f([["abc","def","ghi"],
["ghi","def","abc"]
])
) // [0,0]
console.log(f([["programming","puzzles"],
["code","golf"],
[]
])
) // [16,2,0]
```
[Answer]
# [Perl 6](https://perl6.org), 64 bytes
```
{@^a.map:{sum .map:{@a.Bag{$_}>1??0!!(1,1,2,3,5)[.comb-3]||11}}}
```
[Try it online!](https://tio.run/##NUzLDoIwEDzrVxTCoU0qsRo9aFTibxg1SymPhLpNgQMi344UwmVmZ3ZmjLLlcdAtCVJyGbroBaEGc@qqRpP5iiC8Q9YF7/4qbret51HBBd/xPT@wRyhRx5v98/cTou/7oQK3RIM3IylaQtcrSn0Jtc/9BLMR48ImI6lSmRw@tc84Xbw5ILHFWk3@bGhsqlEzPm1BLF1UpSNmeTHlHC@e@y9ZYzGzoHXxcTum@X5LVU0NiYlyA1imTrsCOw9/ "Perl 6 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 bytes
Uses [H.PWiz's formula](https://codegolf.stackexchange.com/a/143217/59487).
```
m+Fm.E@.!a3hS,8lk2fq1/sQTd
```
**[Verify all the test cases.](https://pyth.herokuapp.com/?code=m%2BFm.E%40.%21a3hS%2C8lk2fq1%2FsQTd&input=%5B%5B%22cat%22%2C%22dog%22%2C%22bird%22%2C%22elephant%22%5D%2C+%5B%22bird%22%2C%22dog%22%2C%22coyote%22%5D%2C+%5B%22dog%22%2C%22mouse%22%5D%5D%0A&test_suite=1&test_suite_input=%5B%5B%22cat%22%2C%22dog%22%2C%22bird%22%2C%22elephant%22%5D%2C+%5B%22bird%22%2C%22dog%22%2C%22coyote%22%5D%2C+%5B%22dog%22%2C%22mouse%22%5D%5D%0A%0A%5B%5B%22abc%22%2C%22def%22%2C%22ghi%22%5D%2C%5B%22ghi%22%2C%22def%22%2C%22abc%22%5D%5D%0A%0A%5B%5B%22programming%22%2C%22puzzles%22%5D%2C%5B%22code%22%2C%22golf%22%5D%2C%5B%5D%5D%0A&debug=0&input_size=2)**
The initial version, **33 bytes**:
```
m+Fm*h+++*6>lk7y>lk6>lk5glk3q1/sQ
```
**[Verify all the test cases.](https://pyth.herokuapp.com/?code=m%2BFm%2ah%2B%2B%2B%2a6%3Elk7y%3Elk6%3Elk5glk3q1%2FsQ&input=%5B%5B%22cat%22%2C%22dog%22%2C%22bird%22%2C%22elephant%22%5D%2C+%5B%22bird%22%2C%22dog%22%2C%22coyote%22%5D%2C+%5B%22dog%22%2C%22mouse%22%5D%5D%0A&test_suite=1&test_suite_input=%5B%5B%22cat%22%2C%22dog%22%2C%22bird%22%2C%22elephant%22%5D%2C+%5B%22bird%22%2C%22dog%22%2C%22coyote%22%5D%2C+%5B%22dog%22%2C%22mouse%22%5D%5D%0A%0A%5B%5B%22abc%22%2C%22def%22%2C%22ghi%22%5D%2C%5B%22ghi%22%2C%22def%22%2C%22abc%22%5D%5D%0A%0A%5B%5B%22programming%22%2C%22puzzles%22%5D%2C%5B%22code%22%2C%22golf%22%5D%2C%5B%5D%5D%0A&debug=0&input_size=2)**
# Explanation
```
m+Fm*h+++*6>lk7y>lk6>lk5>glk3q1/sQ Full program.
m Map over the input.
m Map over each sublist.
>lk3 Is the length higher than 2? 1 if True and 0 if False.
+ >lk5 Plus "is length higher than 5?".
+ y>lk6 Plus "is length higher than 6?", doubled.
+*6>lk7 Plus "is length higher than 7?", times 6.
h Increment.
q1/sQ Count the occurrences of the element in the flattened
input, and check if it equals 1. 0 if False, 1 if True.
* Multiplication.
+F Sum each sublist.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~76~~ 75 bytes
```
f l=[sum[fst.last$zip[0,0,1,1,2,3,5,11]w|w<-p,[w]==(filter(==w)=<<l)]|p<-l]
```
[Try it online!](https://tio.run/##hZLRasMgGIXvfQoJvWjBjKZju4p9EfHCJprINIoawrLu2TON9CZdNgWV438OfmrP/AdXalkEVJj4URPhw4tiPhxmackZnVEV@wW9ojdUVXS6T3VpEZkoxkchVeDuiPF0wnWtTvRu61LRRTM5QAxbA6B1cgjwAAUkpGhYKFDRmi6ON@naOHHFbc@GUFAEyUPMFY35NIHnjaxoM/ooULjJZbcmubiIY9fLbEmLh5gKom3rs850jmkth5Rux3lW3Gd3Y1qe0owSq7C6wVcJ/sUAuxzgGWTb8BWSKl32hQLwKxnYQduExIfLCXuM4AkSZMq/2nq89/gbYnj5vfwA "Haskell – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~29~~ ~~25~~ ~~24~~ ~~23~~ ~~21~~ 20 bytes
```
Ëx@èøX ¥1©3nXÊm8)ʬc
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=y3hA6PhYIKUxqTNuWMptOCnKrGM=&input=W1siY2F0IiwiZG9nIiwiYmlyZCIsImVsZXBoYW50Il0sWyJiaXJkIiwiZG9nIiwiY295b3RlIl0sWyJkb2ciLCJtb3VzZSJdLFsiYWJjIiwiZGVmIiwiZ2hpIl0sWyJnaGkiLCJkZWYiLCJhYmMiXSxbInByb2dyYW1taW5nIiwicHV6emxlcyJdLFsiY29kZSIsImdvbGYiXSxbXV0=)
* Saved 4 bytes by using [the formula H.PWiz found](https://codegolf.stackexchange.com/a/143217/58974) for the scoring.
---
## Explanation
Implicit input of array `U`.
```
Ëx@
```
Map over the array (`Ë`) and reduce each sub-array by addition (`x`) after passing its elements through the following function, where `X` is the current word.
```
èøX
```
Count (`è`) the elements in `U` that contain (`ø`) `X`.
```
¥1
```
Check if that is equal to 1.
```
©
```
Logical AND (`&&`).
```
3nXÊm8)
```
Subtract (`n`) 3 from the minimum of (`m`) 8 and the length (`Ê`) of `X`.
```
ʬc
```
Factorial, square root and round up, respectively.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~106~~ ~~105~~ ~~88~~ 84 bytes
-1 byte thanks to Jonathan Frech
-1 (17) bytes thanks to reffu
```
lambda x:[sum(sum([1,0,1,1,2,6][:len(s)-2])*(`x`.count(`s`)<2)for s in l)for l in x]
```
[Try it online!](https://tio.run/##TU/RasQgEHzPV0ietNjSy0MfQu9LrBBjNBGMK2ogdz@fupcG6uLu7DgOTHyUBUJ32PvP4dU6TorsvcjbSvGKG//kt1od/5Ki9ybQzN47yd7osA8fGrZQ6JAH9t0xC4lk4gLxL@gR7vIoJpdM7kQ0pB4hWq1Ky9sJ5tpHl6Y6jDdxUaG0khNxkadCwwOKqQ/ij1hhy3WX/PJTo0a1sbXPizs9EFwkCv7pY4I5qXV1Ae3i9nx6k89fGiaDLuDti5CykU2DaTAFBjrT9CQmV5Nbijtjxy8 "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes
```
ðċ@Ị¥ÐfL€«8ị“¡[żÇ’ḃ11¤Sµ€Ẏ
```
[Try it online!](https://tio.run/##y0rNyan8///whiPdDg93dx1aenhCms@jpjWHVls83N39qGHOoYXRR/ccbn/UMPPhjmZDw0NLgg9tBco/3NX3////6Gil5MQSJR2llPx0IJmUWZQCpFJzUgsyEvNKlGJ1uBSiYaIQJcn5lfklqVAZiFBufmkxUCQWAA "Jelly – Try It Online")
[Answer]
# R, 117 bytes
A completely different approach from the [other R answer](https://codegolf.stackexchange.com/a/143214/6741):
```
function(L)sapply(L,function(x)sum(c(0:3,5,11)[cut(nchar(x[x%in%names(which(table(unlist(L))<2))]),c(0,2,4:7,Inf))]))
```
Test cases:
```
> f=function(L)sapply(L,function(x)sum(c(0:3,5,11)[cut(nchar(x[x%in%names(which(table(unlist(L))<2))]),c(0,2,4:7,Inf))]))
> L=list(c("cat","dog","bird","elephant"),c("bird","dog","coyote"),c("dog","mouse"))
> f(L)
[1] 12 3 2
> L=list(c("abc","def","ghi"),c("ghi","def","abc"))
> f(L)
[1] 0 0
> L=list(c("programming","puzzles"),c("code","golf"),c())
> f(L)
[1] 16 2 0
```
Takes the names occurring only once in the list, convert their length to a factor based on the given cut-off points and translates that into scores that is then summed.
[Answer]
# Java 10, ~~202~~ ~~200~~ ~~198~~ ~~197~~ 194 bytes
```
a->{int q=a.length,r[]=new int[q],i=0,j,f;for(;i<q;i++)for(var s:a[i]){for(f=j=0;j<q;)f|=a[j].contains(s)&!a[i].equals(a[j++])?1:0;r[i]+=f<1?(j=s.length())<5?1:j<6?2:j<7?3:j<8?5:11:0;}return r;}
```
-1 byte thanks to *@ceilingcat*.
**Explanation:**
[Try it here.](https://tio.run/##zVI9b9swEN39K9gMAQkpgt0ibWCJEbK3WTIKGs4UJVOlSJmkXDiqfrtLWVFgBO0QL81yuI93j/ceWMMeburi55FJsBb9AKH6BUJCOW5KYBw9juWpkeWI4drjo84JGT0YA4fvwrrkyRmhqns/BxJ79LDwwTpwgqFHpOgRbu57T4B2FCLJVeW2oclyqvivE@8uDwVdhnVYxqU2OBbJLhZBQMZiDwbZNWQiJ/1Yl7Smy7j2CFL@ppDVecS0cv5siy25/jQiI77rQFrsp0GQk3S1XsbG9wNaJqsU19S@XIEJSW79uE6@pp99/JZ@8fEuvV2vxp3BcNcZhUw8HONRU9ttpNf0Im2vRYEa/zKeDMhyIJNZTwfreBPpzkWtnzip3vpmI6enLawihkcn/uJslk98CP0DMFuPSd9DUeArBu6KxKe00NWcboQp5pxL3m5BjbBhCN9Jf050xs/0QTt@EeMZS6M7O5EMhJw@0v90EjbsVSkv57TaiotkTntv2aY3Pobe1ujKQNP45nxe2z0/S24vEsx0wV9N07J8H8lsyLAYjn8A)
```
a->{ // Method with ArrayList<String>[] parameter & int[] return-type
int q=a.length, // Length of the input-array
r[]=new int[q], // Result integer-array the size of the input-array,
// initially filled with 0s by default
i=0,j, // Index integers
f; // Flag integer (used as boolean)
for(;i<q;i++) // Loop `i` in the range [0, `q`):
for(var s:a[i]){ // Inner loop over the Strings of the `i`'th List
for(f=j=0; // Reset the flag `f` and index `j` both to 0
j<q;) // Inner loop `j` in the range [0, `q`) again:
f|=a[j].contains(s)// If the `j`'th list contains the current String
&!a[i].equals(a[j++])?
// and the `i`'th and `j`'th list aren't the same:
1 // Bitwise-OR the flag with 1 (0->1; 1->1)
: // Else:
0; // Bitwise-OR the flag with 0 (0->0; 1->1)
// End of inner loop (3) (implicit / single-line body)
r[i]+= // Increase the `i`'th item in the result integer-array by:
f<1? // If the flag is still 0 (so the current String is unique):
(j=s.length())<5?
// If the length of the String is below 5:
1 // Increase by 1
:j<6? // Else-if the length is 5 instead:
2 // Increase by 2
:j<7? // Else-if the length is 6 instead:
3 // Increase by 3
:j<8? // Else-if the length is 7 instead:
5 // Increase by 5
: // Else (the length is above 7):
11 // Increase by 11
: // Else (the flag is 1 - thus the String is not unique):
0; // Leave it the same by increasing with 0
return r;} // Return the resulting integer-array
```
[Answer]
# [K (ngn/k)](https://git.sr.ht/%7Engn/k), 34 bytes
```
{+/'(&7\5782020)'#''x^\:&1<#'=,/x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxtj2FLwzAQhr/nV5QMlgQP2kV0sjnxf3QVujbtCu1Sug7mxP9u7s6qzOVDknvvzZvnqtXHXaz0fLl9WD7ZxCZGzZQ6v21X88XzTG0gPn8KUUWvSmsti3yUa1n6Ouy7ZijD4VrX7/PDKM1aTxobCv/uR0c6C50/HUMdBC3zXYFGV4W93jfkwnPSsM/OfvD1kHddc8CM/nS5tO5I/sKXDp/7tsLaGCNELNKUMIE+BUaCX8wMRJROKlu+QbnDEqNmWXS9Ni9RurBwDzYT+BVyAjED8XMI3iYVHVdBGJJAwgl/54Of+TiHJgSekJQbRP/xHsGG8C9BmHrI)
* `&1<#'=,/x` get non-unique words (i.e. words that more than one player identified)
* `x^\:` remove the non-unique words from each player's submission
* `#''` get the number of characters in each players' words
* `(&7\5782020)` a compressed version of `0 3 5 6 7 7 8 8 8 8 8 8`
* `(...)'` do a binary search, returning the index of the first value in the left-side list not larger than each item in the right-side list (this translates word lengths to their scores)
* `+/'` get each player's point total (by summing the score of their individual words)
[Answer]
# [Perl 5](https://www.perl.org/), 104 + 2 (-na) = 106 bytes
```
push@a,[@F];map$k{$_}++,@F}{map{$s=0;map$s+=(($l=y///c)<8?$l<7?$l<5?1:$l-3:5:11)*($k{$_}<2),@$_;say$s}@a
```
[Try it online!](https://tio.run/##JYxNDoIwGET3nILFtwABoZpGw0/oip0nMIbU0gix0IaWBSFc3Sq4mcx7k4zio8DWqkm3hIZ3Uj2ynip4L1CvQRCSal1@vIAukn3QQeF5IIo5jmPm59cSRH7ZApcoBRGdU5wi5B@8/0V@8kMCdabpDHol1FpGjdvIl/vsxsblgquWDsbZadNMztJwZ6u9nDT/SGU6OWgb3fAxQYmNBvoF "Perl 5 – Try It Online")
[Answer]
## Clojure, 102 bytes
```
#(for[p %](apply +(for[w p](if(next(filter #{w}(flatten %)))0(get{3 1 4 1 5 2 6 3 7 5}(count w)11)))))
```
`next` returns `nil` if there is only one word `w` :)
[Answer]
# [PHP](https://php.net/), 226 bytes
```
function x($a){foreach($a as$p){$q=call_user_func_array('array_diff',$a);array_push($a,array_shift($a));$x=0;array_map(function($b)use(&$x){$b=strlen($b);$x+=($b<5?1:($b==5?2:($b==6?3:($b==7?5:11))));},$q);$o[]=$x;}return $o;}
```
I think this could still be trimmed down quite a bit.
Ungolfed:
```
function x($a) {
foreach ($a as $p) {
$q = call_user_func_array('array_diff', $a);
array_push($a, array_shift($a));
$x = 0;
array_map(function($b) use (&$x){
$b = strlen($b);
$x += ($b < 5 ? 1 : ($b == 5 ? 2 : ($b == 6 ? 3 : ($b == 7 ? 5 : 11))));
}, $q);
$o[] = $x;
}
return $o;
}
```
[Try it online!](https://tio.run/##TVHbboQgEH33K4ghXUx96LbZNlmX@CHGGFRQExUWsHHX@O12kDUpDzNnhnPOcFGt2m6pahXaxDRWtpMjmglm0SKk5qxqASNmsIoWfKcV6/tiMlwXjlwwrdmDnPZU1J0QpxiUia/VZJw49pVpO2Gdb5TgmX68OANT5BhLcBmBNXnDM8wqqbG653sXFO8UwO2Snq@QKb2knx58p18e/KSX6/kcwUrWGN9BI7Oc4jlZNbeTHhGWybphy401iKIsQLCyLKyYDeOwlg3EstM1JN5z1bLRhnmMsqPpGZV8SMv9hu8MEs4c5nl8GLKycnQuIDZt57kOHE1H@MdXWjaaDUM3Ojs1PZ89N6CCo8maOxPZi93FifIkCF4fg8jrNsygHUVo2U1/mS7qaVBk9gx4kmDd/gA "PHP – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 242 bytes
The function takes, as a parameter `a`, a `Seq[Set[String]]` and returns an `Array[Int]`. I use an Array for it to be mutable (4-char loss).
```
var s=Seq("")
a.foreach(x=>x.foreach(y=>s:+=y))
var u:Array[Int]=Array()
var i= -1
a.foreach(t=>{i+=1
u:+=0
t.map(x=>{val l=x.length
if(s.count(_==x)<2){if(l>7)u(i)+=11
if(l==7)u(i)+=5
if(l==6)u(i)+=3
if(l==5)u(i)+=2
if(l>2&l<5)u(i)+=1}})})
u
```
[Try it online!](https://tio.run/##nZJBa4MwFMfv@RTiYSS0k9nRDUoj9LjDTj2WMmJ8akZMnMZOK352F6uOdqfRS8j/l5ffI4@UnEnW6/ATuHHemVAO1AZUVDq7PG8RiiB2Qp0kEjDb7OHrsAdz2JtCqOR4JJtdUbDm8KbMkbb9iRVOSW0Rdl2CmBfrAhhPcU2D@jc0NCg3C9oQgob66lpx2eLxQFDn0b@SGBq0YkF9VNnbT8h4GcsHc3ti0pG09iSoxKRIxLj0uK6UwR@U1mS7Iq1lMnglFRbEGvyhRlI6g/WUX6b8POX1lFeXHKwe5HZGfteRjqCq7xCapjM8284GuylIqd2l@50y45LlDQMJecqU5YTMD8jtLA2uF65jKbokqewQ/nq51S3dSCd2DUUR3ejGNhMea7hutIH5aGSZrkq4pzkL@SCG2K5JKmbrsJ3xUHKHOS90UrAssx/KSvLqfJZQzn6uIxg6ahlP6B8dUNf/AA "Scala – Try It Online")
Might be optimizable, since I did not even work on the
```
if(l>7)u(i)+=11
if(l==7)u(i)+=5
if(l==6)u(i)+=3
if(l==5)u(i)+=2
if(l>2&l<5)u(i)+=1
```
part. Thanks for this challenge!
[Answer]
# [Swift 4](http://swift.sandbox.bluemix.net/#/repl/59c312cf603243789807753b), 164 bytes\*
```
{$0.map{Set($0).subtracting(Dictionary(grouping:$0.flatMap{$0},by:{$0}).flatMap{$1.count != 1 ?$0:nil}).map{[0,1,1,2,3,5,11][min(max($0.count-2,0),6)]}.reduce(0,+)}}
```
The above expression is technically correct, pure Swift. However, the expression is so complex that, due to exponential blowup in the type inference system, can't be processed before the compiler gives up after some arbitrary timeout (like 15s or something).
To make this expression compilable with the current compiler, it can be broken down like this:
```
{
let n = Dictionary(grouping:$0.flatMap{$0},by:{$0}).flatMap{$1.count != 1 ?$0:nil}
return $0.map{Set($0).subtracting(n).map{[0,1,1,2,3,5,11][min(max($0.count-2,0),6)]}.reduce(0,+)}
}
```
[Test cases:](http://swift.sandbox.bluemix.net/#/repl/59c312cf603243789807753b)
```
let f: (_ input: [[String]]) -> [Int] = {
let n = Dictionary(grouping:$0.flatMap{$0},by:{$0}).flatMap{$1.count != 1 ?$0:nil}
return $0.map{Set($0).subtracting(n).map{[0,1,1,2,3,5,11][min(max($0.count-2,0),6)]}.reduce(0,+)}
}
let testcases: [(input: [[String]], expected: [Int])] = [
(input: [
["cat","dog","bird","elephant"],
["bird","dog","coyote"],
["dog","mouse"]
],
expected: [12,3,2]
),
(input: [
["abc","def","ghi"],
["ghi","def","abc"]
],
expected: [0,0]
),
(input: [
["programming","puzzles"],
["code","golf"],
[]
],
expected: [16,2,0]
),
]
for (caseNumber, testcase) in testcases.enumerated() {
let actual = f(testcase.input)
assert(actual == testcase.expected,
"Testcase #\(caseNumber) \(testcase.input) failed. Got \(actual), but expected \(testcase.expected)!")
print("Testcase #\(caseNumber) passed!")
}
```
Broken down:
```
let verboseF: (_ input: [[String]]) -> [Int] = { playerHands in
let allWords = playerHands.flatMap{$0}
// demo data for first test case:
// allWords: ["cat", "dog", "bird", "elephant", "bird", "dog", "coyote" "dog", "mouse"]
let allWordsGroupedByThemselves = Dictionary(grouping: allWords, by: {$0})
/* allWordsGroupedByThemselves:
[
"cat": ["cat"],
"dog": ["dog", "dog", "dog"],
"bird": ["bird", "bird"],
"elephant": ["elephant"],
"coyote": ["coyote"], "mouse": ["mouse"]
]*/
let allWordsUsedMoreThanOnce = allWordsGroupedByThemselves.flatMap{$1.count != 1 ?$0:nil}
// allWordsUsedMoreThanOnce: ["dog", "bird"]
return playerHands.map{ hand in
// demo data for first hand of first test case:
// hand: ["cat","dog","bird","elephant"]
let uniqueWordsInHand = Set(hand)
// uniqueWordsInHand: ["cat","dog","bird","elephant"]
let uniqueWordsInHandNotUsedByOthers = uniqueWordsInHand.subtracting(allWordsUsedMoreThanOnce)
// uniqueWordsInHandNotUsedByOthers: ["cat", "elephant"]
let wordLengths = uniqueWordsInHandNotUsedByOthers.map{$0.count}
// wordLengths: [3, 8]
let scores = wordLengths.map{ wordLength in
return [0,1,1,2,3,5,11][min(max(wordLength-2, 0), 6)] //A look up table that maps word length to word score
}
//scores: [1, 11]
let playerScore = scores.reduce(0,+)
// playerScore: 12
return playerScore
}
}
```
[Answer]
# [ASP](https://en.wikipedia.org/wiki/Answer_set_programming) + [Python](https://docs.python.org/3/), 137 bytes
```
u(P,W):-1{p(_,W)}1;p(P,W).s(P,S):-S=#sum{@v(W):u(P,W)};p(P,_).#script(python)
def v(w):return[1,1,2,3,5,11][min(len(w.string),8)-3]#end.
```
Expects data formatted as:
```
p(1,("cat";"dog";"bird";"elephant")).
p(2,("bird";"dog";"coyote")).
p(3,("dog";"mouse")).
```
Needs [clingo](https://potassco.org/) 5.2.1 with python support.
Ungolfed:
```
unique(P,W):- 1 { player(_,W) } 1 ; player(P,W).
score(P,S):- S = #sum{@value(W): unique(P,W)} ; player(P,_).
#script (python)
def value(word):
return [1,1,2,3,5,11][min(len(word.string),8)-3]
#end.
```
The python function is heavily inspired from [the python answer](https://codegolf.stackexchange.com/a/143218).
] |
[Question]
[
Your task is to create a random sequence of moves, which can be used to scramble a Rubik's Cube. Such a scramble is made up of exactly 25 moves. Each move consist of of the letters `UDRLFB` optionally followed by one of the suffixes `'2`.
This notation is called the Singmaster notation. `UDRLFB` represents one of the 6 faces and the optional suffix `'2` represents the turning angle. This information is in no way necessary to solve the task.
To assure, that the scrambles are of 'good quality', the following two rules have to apply:
* Two consecutive moves must not have the same letter. This bans the consecutive moves `UU`, `DD`, `RR`, `LL`, `FF` and `BB` and all their combinations using the optional suffixes like `U2U` or `U'U'`.
These move pairs are banned, because they can easily reduced to 1 or 0 moves. `U2U` has the same effect as `U'`, `R'R` the same effect as .
* Three consecutive moves must not be of the same letter group. The letter groups are `UD`, `RL` and `FB`. This rule additionally bans the consecutive moves `UDU`, `DUD`, `RLR`, `LRL`, `FBF`, `BFB` and all their combinations using the optional suffixes like `U2DU`, `RL'R` or `B2FB'`.
The groups sort the faces by their move axis. `U` and `D` are in the same group, because both turn around the same axis. Therefore an `U` move doesn't influence the pieces of the `D` face, and a `D` move doesn't influence pieces of the `U` face. Therefore the two moves can be exchanged, `UDU` has the same effect as `UUD`, and this can be reduced to `U2D`.
## Challenge
Write a script or a function, that generates one random scramble. There is no input. The script / function has to print the 25 moves without separation or separated by one space or return the correspondent string.
Your program has to be able to create every single scramble, which satisfies the rules above. Of course assuming, that the random number generator is true random, and not pseudo random.
This is code-golf. The shortest code (counted in [bytes](https://mothereff.in/byte-counter)) wins.
## Examples outputs:
Calling the script / function 3 times should print / return something like:
```
R'B2R2F2R2FB'R2DR2ULFB2RB'U2B'FL'BR'U'RB'
U'DBR'B2U'B'U'RUF'B'RDR2U'B'LR'B'F2D2UF2L'
BR2F'B'R'D'R'U2B'F2D2R'F2D'F'D2R2B'L2R'UB'R2L'D
```
If you separate the moves by a space each:
```
R2 L' F2 U2 D' R2 L2 F L' D2 U R B D' U2 L B2 L U B2 D U2 R' D2 U'
B R D2 F U2 B' R2 F2 B' U' L' R2 B U2 R' D B' F' U2 R' B' L R D2 R2
B2 R2 U D' B R D' R L2 D2 L2 R B2 F U' F2 B2 U' F U' D F R2 U2 B'
```
Notice, that all these outputs consists of 25 moves, but have different lengths, because of the optional suffixes. It's not allowed to print a space, when either `2` or `'` are uses as suffix. You have to print `L2UR2F'R'U2` or `L2 U R2 F' R' U2`. `L2U R2F'R'U2` is not allowed.
[Answer]
# C,129
```
f(){int i,n,m,r,s,t;for(i=26;i--;i<25&&printf("%c%c","URFDLB"[s%6],"'2"[r%3])){for(n=m,t=1;t;t=m*n==9)m=(r=rand()%15)/3+1;s+=m;}}
```
The inner loop generates a value of `m` in the range `1..5` which when added to `s` and taken modulo 6, ensures that no two consecutive moves are on the same side of the cube. The old value of `m` is stored in `n` and the test `m*n==9` ensures that the value `m`=3 is never generated twice in a row (so opposite faces cannot be picked twice in a row; note the order of faces in the string.)
The least significant part of `r` is used to decide which suffix (`'`, `2` or null) to use, taking advantage of the null character at the end of `"'2"`.
The outer loop runs 26 times. The first time, `U` can never be picked, so `printf` is suppressed for the first iteration.
**Ungolfed code in test program**
The ungolfed code puts a space between each move for clarity (the golfed code does not, in order to save one byte.) Additionally the golfed code saves a semicolon by relocating the `printf` within the `for` bracket.
```
f(){
int i,n,m,r,s,t;
for(i=26;i--;){
for(n=m,t=1;t;t=m*n==9)m=(r=rand()%15)/3+1;
s+=m;
i<25&&printf("%c%c ","URFDLB"[s%6],"'2"[r%3]);
}
}
main(){
int j;
srand(time(0));
for(j=0;j<5;j++)f(), puts("");
}
```
Typical output
```
U' B D2 B' R' L F' D2 B D2 B2 R' B2 U D2 F' R U R' L B' L R2 B2 F'
U B U B F L2 D2 B' U' L B L R' D B U' D R D' B' F2 D' B D R
L D F2 B2 R' U F B' D2 L U R' L' U2 F' R F D U2 B L' B' U L2 F'
R2 B' F2 R2 L2 F' U2 L U' B' F R' D' F2 D F' L2 U2 R' D' B2 D F R2 L'
U2 F2 B2 D' F D F R L2 U' B D2 L' R D R F2 R' F2 U2 D R' D2 L F2
```
[Answer]
# CJam, ~~47~~ 45 bytes
This solution uses an approach that's different from any other posted so far. It takes advantage of CJam's concise list operations to generate the available move list and select one at random each iteraton. Modifiers are simply generated independently.
[Try it online.](http://cjam.aditsu.net/#code=%7BBA%5E2%2F6%2C_B-%3FA%3AB-mr0%3D%3AA%22UDRLFB%22%3D3mr%5BL2''%5D%3D%7D25*)
```
{BA^2/6,_B-?A:B-mr0=:A"UDRLFB"=3mr[L2'']=}25*
```
### Explanation
```
{ "Loop...";
BA^2/ "If the two previous moves were not from the same group, ...";
6, "... then produce the available move list [0 1 2 3 4 5], ...";
_B- "... else produce the available move list [0 1 2 3 4 5] with
the second previous move removed";
?
A:B "Save the previous move as the second previous move";
- "Remove the previous move from the available move list";
mr0= "Randomly select an available move";
:A "Save this move as the previous move";
"UDRLFB"= "Map this move to its character (implicitly printed)";
3mr[L2'']= "Randomly select a modifier (implicitly printed)";
}25* "... 25 times";
```
[Answer]
# Pyth, ~~65~~ 66
I've never really golfed in Pyth, maybe written a program or two. This is basically @[steveverrill](https://codegolf.stackexchange.com/users/15599/steveverrill)'s solution translated to Pyth. Improvement suggestions are welcome.
**Update:** added 1 byte to make scrambles also start with `U`. Maybe the C solution is relying on undefined behavior to make it work...
```
=YO6V25JZK1WK=GO15=Z/+3G3=Kq9*ZJ)~YZpd+@"URFDLB"%Y6?@"'2"%G3>2%G3k
```
I believe this should be done with less assignments, but that would require me to modify the algorithm a lot. (Well, might try.)
Here's an explanation based on the C code:
```
=YO6 s = random.choice(range(6))
V25 for i in range(25):
JZ n = m
K1 t = 1
WK while t:
=GO15 r = random.choice(range(15))
=Z/+3G3 m = (r + 3) / 3
=Kq9*ZJ t = 9 == m * n
)
~YZ s += m
pd print(..., end = " ")
+ ... + ...
@"URFDLB"%Y6 "URFDLB"[s % 6]
?@"'2"%G3>2%G3k "'2"[G % 3] if 2 > G % 3 else ""
```
[Answer]
# JavaScript (ES6) 175 ~~178 204~~
**Edit** 3 bytes less, 1 by changing the code and 2 by changing the way bytes are counted (not counting `F=`)
The code to avoid repetitons is taken from @stevemiller. His way of managing the letter groups is even better, but i'm not going to steal it.
Bonus: you can optionally specify the number of moves.
```
(n=25,R=n=>Math.random()*n|0)=>(r=>{for(N=_=>'UDRLFB'[(r-=~R(5))%6],b=N(a=N(s=''));n;~(a+b+c).search('^([UD]*|[RL]*|[FB]*)$')?0:s+=(--n,a=b,b=c)+["","'",2][R(3)])c=N()})(0)||s
```
*Less golfed*
```
(n = 25) =>
{
R = n => Math.random()*n | 0;
N = _ => 'UDRLFB'[(r += 1+R(5)) % 6];
r = 0;
b = N();
a = N();
for(s = '' ; n; )
c = N(),
~(a+b+c).search('^([UD]*|[RL]*|[FB]*)$')
? 0
: s += (--n, a=b, b=c) + ["","'",2][R(3)];
return s
}
```
**Test**
```
var F=
(n=25,R=n=>Math.random()*n|0)=>(r=>{for(N=_=>'UDRLFB'[(r-=~R(5))%6],b=N(a=N(s=''));n;~(a+b+c).search('^([UD]*|[RL]*|[FB]*)$')?0:s+=(--n,a=b,b=c)+["","'",2][R(3)])c=N()})(0)||s
function go() {
console.log(F(+M.value))
}
go()
```
```
Moves <input type=number min=1 id=M value=25 max=999>
<button onclick='go()'>Test</button>
```
[Answer]
# Javascript - 112
```
for(c=b=j=25,r=Math.random;j;c+b-5|c-m&&b-m?document.write("URFBLD"[j--,c=b,b=m]+" 2'"[0|r()*3]+" "):0)m=0|r()*6
```
[Answer]
# Java 8, ~~189~~ 183 bytes
```
v->{for(int i=26,n,m=0,r=0,s=0,t;i-->0;){for(n=m,t=1;t>0;t=m*n==9?1:0)m=(r=(int)(Math.random()*15))/3+1;s+=m;if(i<25)System.out.print("URFDLB".charAt(s%6)+(r%3<1?"'":r%3<2?"2":""));}}
```
Port of [*@LevelRiverSt*'s C answer](https://codegolf.stackexchange.com/a/47471/52210). I tried some things myself, but this was shorter than what I had..
[Try it online.](https://tio.run/##XZBRa8IwEMff9ymOgCynbddWFNYYZWPsafow2V7GHrLazrgmlSQWhvSz11SFwSB/cnfcHff770Qjwnpf6N3mp8srYS0shdTHGwCpXWFKkRew6lOAppYbyOl7/zXIfK318s864WQOK9DAoWvC@bGsDfXzIHk6DXSgeBwYL@vlmAzDeczw3KS5ChxPmPMVx9VQc36/SLIYFaeG9zuQLoXbRkboTa0oDpMJ4t14lDA74orJkspZOsH1r3WFiuqDi/bGT1Hy9vr89PJIonwrzIOjdjDFETWD8SxZkFuS9VG6ICnJCEFkbduxC8z@8FV5mCvTmVl5R@ja@b3fH58CL278ISYxgwsT/D@j0hTx3A6go5zqQ1VdnWu7Ew)
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~116 107 105~~ 95 bytes
```
->{(0..r=l=m=24).map{m=rand 6while l==m||r/2==l/2&&l/2==m/2;r=l;l=m;'RLFBUD'[m]+" '2"[rand 3]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165aw0BPr8g2xzbX1shEUy83saA617YoMS9Fwaw8IzMnVSHH1ja3pqZI38jWNkffSE0tB8TK1TeyBmqyBmqzVg/ycXMKdVGPzo3VVlJQN1KKBms3jq2t/V9QWlKskBYdq6WuoP4fAA "Ruby – Try It Online")
[Answer]
## Clojure, 223 bytes
```
(let[R(range)F(fn[f p c](apply concat(filter f(partition-by p c))))](apply str(map str(take 25(F(fn[p](<(count p)3))(zipmap"UDLF""1122")(F(fn[p](=(count p)1))int(for[_ R](rand-nth"UDRLFB")))))(for[_ R](rand-nth[""\'\2])))))
```
This relies heavily on the "sequence -> partition-by -> filter -> concat" pattern, it is used to filter out "illegal" sequences of faces. This seq is then mapped to string together with a random postfix (including the empty string).
Ungolfed starting point:
```
(->> (for[_(range)](rand-nth"UDRLFB"))
(partition-by int) ; "identity" would be the correct fn to use here
(filter(fn[p](=(count p)1))) ; Only one identical value in partition
(apply concat)
(partition-by(zipmap"UDLF""1122")) ; R & B are in the implicit nil group
(filter(fn[p](<(count p)3))) ; Only 1 or 2 consecutive faces from a group
(apply concat)
(take 25))
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 6 years ago.
[Improve this question](/posts/42380/edit)
You have been hired by the government of North Dakota to encrypt the state's communications. Write two programs, one to encrypt a message and one to decrypt that message.
The government is not really tech-savvy, so the encryption algorithm does not need to be sophisticated; just make sure the result doesn't look similar to the original at first glance.
However, you're secretly loyal to the South Dakotan government. Your job is to mix up the communications, so that every mention of `North Dakota` becomes `South Dakota` upon decryption, and vice versa. This also applies to `North/South Dakotan` and `North/South Dakotans`.
For example:
>
> North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government
>
>
>
will undergo encryption and then decryption, resulting in:
>
> South Dakota is the wealthiest county in North America, while North Dakotans are poorer than southern Florida. - the South Dakotan government
>
>
>
The algorithm which accomplishes this in the most secretive, tricky manner, as evidenced by having the most upvotes, will be accepted.
[Answer]
# Ruby
```
class Dakota
PRIVATE_KEY = 8411088
def self.encrypt(str)
str.gsub(/[A-Z]/){|c|"0#{c.downcase}"}.gsub(/[a-z]+/){|s|xor(s.to_i(36),$')}
end
def self.decrypt(str)
str.gsub(/\d+/){|s|out = s.to_i.to_s(36);out[0] = out[0].upcase if s[0]==?0; out}
end
def self.xor(n, config)
n^=PRIVATE_KEY if private_env?(config)
n
end
def self.private_env?(config)
config =~ /^ .#{private}/i
end
end
puts code = Dakota.encrypt("North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government")
puts out = Dakota.decrypt(code)
```
[Demo](https://ideone.com/bJAoIF)
[Answer]
# CJam
This is the encoder:
```
232375064392749269032321519657657089927649992440902190178063558812627752920796248165803740235420850037801568815744960725761679066919872746899310628404239458 128b:c~
```
and this is the decoder:
```
364380128038419794871782113211824472986419260504039724627500790722811712426518562428698978399810134993565366126560239807690210155343815201005388714282 128b:c~
```
[Try it online here](http://cjam.aditsu.net/)
This only works with capital `N`, `S` and `D` in `North/South Dakota`
Pass the input string to the first function from STDIN. Get the encoded string, pass it to the second function to get the decoded and converted output.
[Answer]
# Java
I discovered that division by zero does not cause errors in this program. This program fully encodes the Strings into a form that cannot be traced to the North Dakotan government. Due to the strange behaviour mentioned above, encoding and decoding might not work correctly in all cases.
```
class Program{
public static void main(String[] args){
String input = String.join(" ", args);
String encode = encode(input);
System.out.println("Encoded: " + encode);
System.out.println("Decoded: " + decode(encode));
}
static String encode(String input){
String answer = "";
input = input.replaceAll("North Dakota", "☃");//Temporarily switch these so that spies
input = input.replaceAll("South Dakota", "North Dakota");//think the message is from South Dakota
input = input.replaceAll("☃", "South Dakota");//if they decode the message.
for(int i =0; i < input.length(); i++){
answer += (char)(~input.charAt(i)) + "";
}
return answer;
}
static String decode(String input){
String answer = "";
int i;
for(i=0; i < input.length(); i++){
answer += (char)(~input.charAt(i)) + "";
}
int funnyNumber = (i+\u002f*0)/0;//Division by 0 should cause an error???
answer.replaceAll("South Dakota", "☃");
answer.replaceAll("North Dakota", "South Dakota");
answer.replaceAll("☃", "North Dakota");
//For some reason, this does not cause errors either:
funnyNumber = ((500/0)*\u002f+-2);
return answer;
}
}
```
Question: What does `funnyNumber` equal?
[Answer]
## JavaScript
```
function encrypt (input) {
input = input.replace(/north d/gi, 'hisdf')
input = input.replace(/south d/gi, 'hisde')
var data = input
var res = []
for (var i = 0; i < data.length; i++) {
res.push(~data.charCodeAt(i))
}
return res.toString()
}
function decrypt (input) {
console.log(input)
input = input.replace(/-105,-106,-116,-101,-102/g, '-79,-112,-115,-117,-105,-33,-69').replace(/-105,-106,-116,-101,-103/g, '-84,-112,-118,-117,-105,-33,-69 ')
input = input.split(',')
var res = ""
for (var i = 0; i < input.length; i++) {
var itm = input[i]
res += String.fromCharCode(~parseInt(itm))
}
return res
}
var data = encrypt(prompt('What do you want to encrypt?'))
var data = decrypt(data)
alert(data)
```
My solution is probably not the most clever one. But it works :) [Here](http://jsfiddle.net/Knerd/zwhdLx3m/) is a fiddle
First I replace `north d` with `hisdf` and `south d` with `hisde`, then I invert all the characters bitwise and push them in an array. The array I convert into a string and then replace the inverted character values with the correct ones. Before that, I replace the values of `hisdf` and `hisde` switched.
[Answer]
## AWK: Encoder: 165 bytes, Decoder: 61 bytes
The encoder (also in charge of replacing South by North and vice versa):
```
{a="(th Dakota(ns?)?)";b="\\1";split(gensub("@"a,"Sou"b,"g",gensub("Sou"a,"Nor"b,"g",gensub("Nor"a,"@"b,"g")))" ",y,"");for(i=1;i<length(y);i+=2)printf(y[i+1] y[i])}
```
The decoder:
```
{split($0,y,"");for(i=1;i<length(y);i+=2)printf(y[i+1] y[i])}
```
Some test:
>
> North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government
>
>
>
encodes into:
>
> oStu haDokati sht eewlahteitsc uotn yniN rohtA emirac ,hwli eoNtr haDokatsna erp ooer rhtnas uohtre nlFrodi.a- t ehS uohtD katonag voremnne t
>
>
>
(that should be scrambled enough for a *not really tech-savvy government* :o) )
It then decodes into:
>
> South Dakota is the wealthiest county in North America, while North Dakotans are
> poorer than southern Florida. - the South Dakotan government
>
>
>
But that was expected :o)
Note: North Dakota, North Dakotan, North Dakotans, South Dakota, South Dakotan and South Dakotans have to be correctly capitalized.
[Answer]
# JavaScript, ES6
Sweet and simple to begin with.
Encoder:
```
E=a=>btoa(a)
```
Decoder:
```
D=a=>atob(a_.replace(/(nor|sou)(th dakota)/gi, (_,x,y)=>({n:"sou",s:"nor",N:"Sou",S:"Nor"})[x[0]]+y)
```
Try it below on a latest Firefox:
```
E=a=>btoa(a)
D=a=>atob(a).replace(/(nor|sou)(th dakota)/gi, (_,x,y)=>({n:"sou",s:"nor",N:"Sou",S:"Nor"})[x[0]]+y)
var string = prompt()
alert("Encoded string: " + E(string));
alert("Decode string: " + D(E(string)));
```
[Answer]
# C
```
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MASK_B 0xFFFFFFULL
#define MASK_C 0xFFULL
#define ll unsigned long long int
#define transform(a,b) ((a)>(b))?(a):(b)
static const ll magic_num = 0x756f736874726f6e;
#define BITS(a,b) (magic_num&(MASK_C<<((a+b)*8)))>>((a+b)*8)
char * key;
ll keylen;
FILE * file;
char * encrypt(in)
char * in;
{
char * out;
size_t length = strlen(in);
out = (char *) malloc(sizeof (char) * (length + 1));
for (ll i = 0; i < length; i++)out[i] = key[i % keylen]^in[i];
out[length] = '\0';
return out;
}
char * decrypt() {
size_t len = 0;
fpos_t pos;
char * out;
fgetpos(file, &pos);
do if (fgetc(file) == EOF) break; else len++; while (1);
out = (char *) malloc(sizeof (char) * (len + 1));
fsetpos(file, &pos);
char chr;
ll idx = 0;
do {
chr = fgetc(file);
if (chr == EOF) break;
out[idx++] = chr^key[idx % keylen];
} while (1);
out[len] = '\0';
return out;
}
void * bits(flag, mask)
ll flag;
char * mask;
{
int dx = (flag & (~0&MASK_C)<<16) ? 5 : 0;
key[0] = BITS(dx, 0),key[1] = BITS(dx, 1),key[2] = BITS(dx, 2),key[3] = BITS(3, 0),key[4] = BITS(3, 1);
strncpy(&key[5], " dakota", 8);
if (flag & ~(MASK_B^MASK_C)) {
dx = (char)flag & MASK_C;
if (islower(*mask)) *mask = key[dx - 1];
else *mask = toupper(key[dx - 1]);
} else if (!(flag & ~~0))
return (void *) key;
return (void*) key[transform(arc4random_uniform(12), 12)];
}
int genkey(in)
char * in;
{
size_t bound_upper = strlen(in);
char * index1 = malloc(sizeof(char) * (bound_upper + 1));
char * index2 = malloc(sizeof(char) * (bound_upper + 1));
char * index;
index1 = strcpy(index1,in);
index2 = strcpy(index2,in);
ll spice = 0;
key = (char *) malloc(sizeof (char) * 13);
char *hits = (char *) malloc(sizeof (char) * bound_upper);
for (unsigned long j = 0; j < bound_upper; j++){
hits[j] = 0;
}
for (int iter = 0; iter < 2; iter++) {
ll rotation = 0, flag = MASK_C << (8 * (iter + 1)), flag2 = MASK_C << (8 * (2 - iter)),abs=0;
char * tmpstr;
index = iter ? index2 : index1;
do {
spice = spice + arc4random_uniform(bound_upper) % bound_upper;
if (!rotation) {
tmpstr = strcasestr(index, bits(flag, in));
if (tmpstr == NULL)
goto out;
index = tmpstr;
} else {
bits(flag2 | rotation, index++);
hits[abs] = iter + 1;
}
rotation = (rotation + 1) % (4);
abs = index - (iter ? index2 : index1);
} while (flag);
out:
index = in;
rotation = 0;
}
for(int k = 0;k < bound_upper;k++){
index[k]=(hits[k]==1?index1[k]:(hits[k] ? index2[k]: index[k]));
spice += arc4random_uniform(spice)|spice^arc4random();
}
free(key);
spice = spice % bound_upper;
if (!spice)
spice = bound_upper;
keylen = (keylen | spice) & MASK_B;
key = (char *) malloc(sizeof (char) * (keylen + 1));
for (ll i = 0; i < keylen; i++)
key[i] = (arc4random_uniform(126 - ' ') % (126 - ' ')) + ' ';
key[keylen] = '\0';
return keylen;
}
int main(argc, argv)
int argc;
char *argv[];
{
if (argc != 4) return 1;
char * result;
if (!strcmp(argv[1], "encrypt")) {
(void) genkey(argv[2]);
result = encrypt(argv[2]);
printf("Decryption Key: '%s'\n", key);
file = fopen(argv[3], "wb");
if (file == NULL) printf("Could not open file for writing: %s", argv[3]);
if (fwrite(result, sizeof (char), strlen(result), file) != strlen(result)) printf("Error occurred while writing ciphertext to file!");
}
if (!strcmp(argv[1], "decrypt")) {
file = fopen(argv[3], "rb");
if (file == NULL) printf("Could not open file for reading: %s", argv[3]);
key = argv[2];
keylen = strlen(argv[2]);
result = decrypt();
printf("Plaintext: '%s'\n", result);
}
return 0 & fclose(file);
}
```
Compile with: `gcc -Wall -Wextra -Wno-missing-field-initializers -Wimplicit -Wreturn-type -Wunused -Wformat -Wswitch -Wshadow -Wwrite-strings -DGCC_WARN -ansi -pedantic file.c`
For maximum evil, written in K&R C with a dash of pointer abuse.
Lasciate ogni speranza, voi ch'entrate.
Buśhaīila rukgâī, naǵkxarańga ba tdhuløk.
Also, everything's in the `bits` function and the `genkey` function.
Run:
```
[...@...] testing_golf$ ./a.out encrypt "North Dakota is the wealthiest county in North America, while South Dakotans are poorer than southern Florida. - the North Dakotan government" cipher
Decryption Key: ')=1aj3'
[...@...]: testing_golf$ ./a.out decrypt ")=1aj3" cipher
Plaintext: 'South Dakota is the wealthiest county in North America, while North Dakotans are poorer than southern Florida. - the South Dakotan government'
```
Note: When specifying the key in `decrypt` mode, it may be necessary to escape some of the characters in the key with backslashes.
] |
[Question]
[
Below on the left is a picture of a sorting network that can sort 4 inputs. On the right you can see it sorting the input `3,2,4,1`.

A sorting network of size `n` consists of a set of `n` horizontal wires where two wires can be connected by a vertical wire. The inputs to a sorting network move from the left to the right on the horizontal wires and whenever a vertical wire connects two elements they swap places if the lower element comes before the higher element.
The example sorting network above has the property that it correctly sorts all inputs. You could add even more wires but the behavior would not change. But if you removed a wire then there would be some inputs that it would not sort anymore.
Two networks behave the same if for every input permutation they produce the same output permutation. Your task is to find out how many possible behaviors there are for a given size. That is, output a sequence of the number of behaviors (equivalence classes) for n=1,2,3,... etc.
Your code will be scored based on its speed on an AMD Ryzen 1800X Linux system. The code should output the sequence described above. I'll run each submission for 5 minutes and with a 16GiB ram limit. Whichever code has outputted most of the sequence wins. Ties are broken by whichever program outputted the final number first.
You can use a probabilistic algorithm, however it must be in the 5 sigma threshold, meaning that the chance that your program outputs the incorrect result must be less than one in 3.5 million. If it's good enough for particle physics, it's good enough for this challenge.
Sequence output
```
1
2
11
261
43337
72462128
```
A lower bound on the seventh value is 4.6 billion, but personally I'd guess it's around a trillion.
# Leaderboard
| Score | Language | Author |
| --- | --- | --- |
| 6 in 10.75s | Rust | [gsitcia](https://codegolf.stackexchange.com/a/261442/84290) |
| 6 in 23.97s | Rust | [isaacg](https://codegolf.stackexchange.com/a/261300/84290) |
| 6 in 70.93s | Rust | [Anders Kaseorg](https://codegolf.stackexchange.com/a/261259/84290) |
| 5 in 0.188s | Haskell | [Roman Czyborra](https://codegolf.stackexchange.com/a/261333/84290) |
| 5 in 1.437s | JS (Node.js) | [Arnauld](https://codegolf.stackexchange.com/a/261252/84290) |
| 4 in 0.038s | Haskell | [Roman Czyborra](https://codegolf.stackexchange.com/a/261258/84290) |
[Answer]
# Rust, \$n = 6\$ in ≈ 59 seconds
The main simplifying observation here is that we don’t need to run the network on all \$n!\$ permutations; it suffices to run it on all \$2^n\$ binary strings. We can do this efficiently on all strings simultaneously using bitwise operations.
**`Cargo.toml`**
```
[package]
name = "sorting"
version = "0.1.0"
edition = "2021"
[dependencies]
hashbrown = "0.13.2"
typed-arena = "2.0.2"
```
**`src/main.rs`**
```
use hashbrown::HashSet;
use typed_arena::Arena;
type Item = u64;
const LOG_BITS: usize = Item::BITS.trailing_zeros() as usize;
fn search<'a>(arena: &'a Arena<Item>, found: &mut HashSet<&'a [Item]>, state: &mut [Item]) {
let n = state.len();
for i in 0..n - 1 {
let p = state[i];
for j in i + 1..n {
let q = state[j];
if p & !q != 0 {
state[i] = p & q;
state[j] = p | q;
let mut inserted = false;
found.get_or_insert_with(state, |state| {
inserted = true;
arena.alloc_extend(state.iter().copied())
});
if inserted {
search(arena, found, state);
}
state[i] = p;
state[j] = q;
}
}
}
}
fn count_networks(n: usize) -> usize {
assert!(n <= LOG_BITS);
let mut state = Vec::from_iter((0..n).map(|i| !0 / (1 << (1 << i) | 1)));
let arena = Arena::new();
let mut found = HashSet::new();
found.insert(&*arena.alloc_extend(state.iter().copied()));
search(&arena, &mut found, &mut state);
found.len()
}
fn main() {
for n in 1..=LOG_BITS {
println!("{}", count_networks(n));
}
}
```
[Answer]
# Rust, \$n=6\$ in roughly ~~50~~ ~~48~~ ~~43~~ ~~41~~ 23 seconds.
*Thanks to @AnttiP for a 44% speedup!*
My solution is based off of @AndersKaseorg's solution. I originally posted my changes as comments there, but with the number of changes I've made, I thought it'd be better to post as a separate answer.
**`Cargo.toml`**
```
cargo-features = ["profile-rustflags"]
[package]
name = "sorting"
version = "0.1.0"
edition = "2021"
[dependencies]
hashbrown = "0.13.2"
rustc-hash = "1.1.0"
[profile.release]
rustflags = ["-C", "target-cpu=native"]
```
**`src/main.rs`**
```
use rustc_hash::FxHasher;
use std::hash::BuildHasherDefault;
type HashSet<V> = hashbrown::HashSet<V, BuildHasherDefault<FxHasher>>;
type Item = u64;
const LOG_BITS: usize = Item::BITS.trailing_zeros() as usize;
/*
Extract just the nontrivial bits that can actually change:
0..57 from state[0]
0..57 from state[1]
0..57 from state[2]
11..57 from state[3]
26..57 from state[4]
none from state[5]
A bit position is either trivial or can't change
if in the input, all wires after that position were 1s.
That position is either forced to be a 1,
or reconstructible from the other earlier wires.
It turns out to be safe to just treat trivial bits as if
they're already zeroed out, rather than zeroing them manually.
Empirically, this causes no collisions.
I wasn't sure that this would work, but it does,
and that's good enough for me.
*/
type CompactState = [Item; 4];
const fn compact(state: &[Item; LOG_BITS]) -> CompactState {
let out_0 = state[0] ^ (state[1] << 57);
let out_1 = (state[1] >> 7) ^ (state[2] << 50);
let out_2 = (state[2] >> 14) ^ (state[3] << (43 - 11));
let out_3 = (state[3] >> (21 + 11)) ^ state[4];
[out_0, out_1, out_2, out_3]
}
fn search<'a>(
found: &mut HashSet<CompactState>,
state: &mut [Item; LOG_BITS],
last_i: usize,
last_j: usize,
) {
for i in 0..LOG_BITS - 1 {
let p = state[i];
for j in i + 1..LOG_BITS {
if i < last_i && j != last_i && j != last_j {
continue;
}
let q = state[j];
if p & !q != 0 {
state[i] = p & q;
state[j] = p | q;
let compact_state = compact(state);
let inserted = found.insert(compact_state);
if inserted {
search(found, state, i, j);
}
state[i] = p;
state[j] = q;
}
}
}
}
// Inputs that are already sorted are removed.
fn initial_state(n: usize) -> [Item; LOG_BITS] {
// Remove inputs that are already sorted
let inputs: Vec<u64> = (0..1 << n)
.rev()
.filter(|i| (0..n - 1).any(|b| i & (1 << b) > 0 && i & (1 << (b + 1)) == 0))
.collect();
let mut state = [0; LOG_BITS];
for (wire_index, wire_mut) in state.iter_mut().enumerate() {
if wire_index < n {
for (bit_index, input) in inputs.iter().enumerate() {
if input & 1 << wire_index > 0 {
*wire_mut |= 1 << bit_index;
}
}
} else {
// If n < LOG_BITS, pad with all-ones wires.
*wire_mut = !0;
}
}
// Debugging printout
if false {
for wire in state {
println!("{wire:#066b}");
}
}
state
}
fn count_networks(n: usize) -> usize {
assert!(n <= LOG_BITS);
let mut state = initial_state(n);
let mut found: HashSet<CompactState> = HashSet::default();
let compact_state = compact(&state);
found.insert(compact_state);
search(&mut found, &mut state, 0, 0);
found.len()
}
fn main() {
for n in 1..=LOG_BITS {
println!("{}", count_networks(n));
}
}
```
The basic idea of this program, and of @AndersKaesorg's solution, is to maintain a state consisting of the effect of a sorting network on all possible inputs of \$n\$ bits, from `000000` to `111111`. The state is internally represented as a vector of \$n\$ 64-bit integers, where each of the first \$2^n\$ bit indexes represents one possible input. All possible comparisons are performed, and a hash table is used to check if any comparisons give a new result. If so, it's added to the hash table and the comparison function is called recursively.
The changes I've made, starting from @AndersKaesorg's solution, are:
* Track the last pair of wires that were compared in order to reach the current state. If that pair doesn't overlap with the current comparison being considered, and the current comparison is earlier lexicographically that the last comparison, skip the current comparison. In other words, we shouldn't consider both comparing `[1, 2]` then `[3, 4]` and also comparing `[3, 4]` then `[1, 2]` - both orderings give the same result.
* When inserting a state into the HashSet to check if it's a new state, leave out the final wire of the state. Because a comparison doesn't change the total number of 0s and 1s, the contents of the last wire are implicit in the other wires.
* Change the hash function from ahash, Rust's default hashing function, to FxHash, which is what the rust compiler uses. It's less collision-resistant, but much faster, and the tradeoff is worth it.
* Store the hash table values as fixed-width arrays, rather than variable-width slices. This communicates more information about the hash values to the compiler, allowing it to produce more optimized code.
* Enable optimizations for my specific machine: `rustflags = ["-C", "target-cpu=native"]`.
* When generating the initial state with all possible inputs, remove the \$n+1\$ inputs that are already in sorted order, as these inputs don't distinguish anything. Move the remaining inputs to the low-order bits of the 64-bit integers in the state. This helps because FxHash is asymmetrical: It makes more use of entropy in the low-order bits than the high-order bits, because it performs a multiplication by a large constant and discards the overflow.
* Extract just the nontrivial bits from the state, and use those as the HashSet value. This amounts to only 4 u64s, rather than 5 previously. This isn't a huge time saving, only 1-2 seconds, because of the extra work that needs to be done to generate the smaller value. However, this change dramatically shrinks the peak memory usage, from about 70% of my machine's RAM to about 40% of it.
* Simplify the hash value extraction with some arcane magic.
* Store the HashSet values directly in the HashSet, rather than in a separate allocation. This is slightly less memory efficient, but much faster. It only became possible because of the previous memory efficiency improvements.
In my timing on my machine, these changes brought the runtime down from ~75 seconds to ~23 seconds.
[Answer]
# Rust, n=6 in ~~~12~~ 1 second
This answer is based on @Anders Kaseorg's solution and uses some of @isaacg's improvements.
I got the answer 1,530,608,978,810 for n=7 in about 12 hours using more than 100 gigabytes of ram. (I'm not completely sure it's correct, since I don't know how to prove the conjectures this relies on).
The basic strategy is to count the total number of networks using the principle of inclusion-exclusion (splitting into groups based on the first swap).
**`Cargo.toml`**
```
cargo-features = ["profile-rustflags"]
[package]
name = "sorting_networks"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
hashbrown = "0.13.2"
rustc-hash = "1.1.0"
nohash-hasher = "0.2.0"
[profile.release]
rustflags = ["-C", "target-feature=+crt-static"]
```
**`main.rs`**
```
use std::{
cmp::min,
iter::repeat,
mem::{replace, swap},
time::{Duration, Instant},
};
use rustc_hash::FxHasher;
use std::hash::BuildHasherDefault;
type HashSet<V> = hashbrown::HashSet<V, BuildHasherDefault<FxHasher>>;
type HashMap<K, V> = hashbrown::HashMap<K, V, BuildHasherDefault<FxHasher>>;
macro_rules! networks {
($n:expr) => {
networks::<{ $n }, { ($n * $n - $n) / 2 }>()
};
}
type Item = u64;
fn main() {
let then = Instant::now();
networks!(1);
networks!(2);
networks!(3);
networks!(4);
networks!(5);
networks!(6);
// networks!(7);
println!("Total time: {:?}", Instant::now().duration_since(then));
}
/**
* Calculates number of networks
*/
fn networks<const N: usize, const N2: usize>() -> i64 {
let then = Instant::now();
let v: Vec<(i64, i64, Duration, Vec<u64>)> = counter(N)
.into_iter()
.map(|(sizes, multiplier)| {
let then = Instant::now();
let a = count_specific::<N, N2>(&sizes);
(a, multiplier, Instant::now().duration_since(then), sizes)
})
.collect();
let o = v.iter().map(|(a, m, _, _)| a * m).sum::<i64>() + 1;
println!(
"n={}: {} (took {:?})",
N,
o,
Instant::now().duration_since(then)
);
v.iter().for_each(|(a, m, duration, sizes)| {
println!(
" {:?}: {} = {} * {} (took {:?})",
sizes,
a * m,
a,
m,
duration
);
});
o
}
/**
* Calculate multipliers for PIE
*/
fn counter(n: usize) -> HashMap<Vec<Item>, i64> {
let mut counts = HashMap::default();
if n == 1 {
return counts;
}
let mut uf = UnionFind::new(n);
counter_(&mut uf, n, 0, 1, 1, &mut counts);
counts
}
fn counter_(
uf: &mut UnionFind,
n: usize,
i: usize,
j: usize,
m: i64,
counts: &mut HashMap<Vec<Item>, i64>,
) {
let mut j1 = j + 1;
let i1 = if j1 == n {
j1 = i + 2;
i + 1
} else {
i
};
uf.save();
uf.join(i, j);
*counts.entry(uf.get_sizes()).or_insert(0) += m;
if j1 < n {
counter_(uf, n, i1, j1, -m, counts);
}
uf.rollback();
if j1 < n {
counter_(uf, n, i1, j1, m, counts);
}
}
/**
* Counts number of networks that start with sorts that have given sizes
*/
fn count_specific<const N: usize, const N2: usize>(sizes: &Vec<Item>) -> i64 {
let mut base_state = [0; N];
let mut num_bits = 0;
if sizes.iter().filter(|&v| v & 1 == 1).count() > (N & 1) {
// no symmetric starting states
let filter: Vec<_> = sizes
.iter()
.copied()
.scan(0, |state, i| {
let offset = *state;
*state += i;
Some(((1 << i) - 1, offset))
})
.collect();
(1..1 << N)
.filter(|&v| {
// filter out states that aren't sorted in given ranges
filter.iter().all(|&(mask, offset)| {
let n = (v >> offset) & mask;
n & (n + 1) == 0
})
})
.filter(|&v: &Item| v & (v + 1) != 0) // filter out states that are completely sorted
.for_each(|v| {
// convert to state
(0..N).rev().fold(v, |acc, i| {
base_state[i] = (base_state[i] << 1) | (acc & 1);
acc >> 1
});
num_bits += 1;
});
if num_bits > Item::BITS {
panic!("Too big? {} > {} {:?}", num_bits, Item::BITS, sizes);
}
let mut states: HashSet<[Item; N]> = HashSet::default();
visit_notree::<N, N2>(&mut base_state, &mut states); // populate states
states.len() as i64
} else {
let mut state_to_idx: HashMap<[Item; N], usize> = HashMap::default();
let mut tree: Vec<[usize; N2]> = Vec::new();
let filter: Vec<_> = sizes
.iter()
.copied()
.scan(0, |state, i| {
// filter divides range so [3,2] => 0b1001001, 0b0100010
let w = i / 2;
let mask = (1 << w) - 1;
let offset0 = *state;
let mask0 = mask << offset0;
let offset1 = N as Item / 2;
let mask1 = (i & 1) << offset1;
let offset2 = N as Item - (w + offset0);
let mask2 = mask << offset2;
*state += w;
Some((
mask0,
offset0,
mask1,
offset1 - w,
mask2,
offset2 - w - (i & 1),
))
})
.collect();
(1..1 << N)
.filter(|v: &Item| {
// filter out states that aren't sorted in given ranges
filter.iter().all(|&(m0, o0, m1, o1, m2, o2)| {
let n = (v & m0) >> o0 | (v & m1) >> o1 | (v & m2) >> o2;
n & (n + 1) == 0
})
})
.filter(|&v: &Item| {
// filter out states that are completely sorted or states that have a smaller dual state
(0..=N / 2).contains(&(v.count_ones() as usize)) && (v & (v + 1) != 0)
})
.map(|v| {
// convert states to smaller states (this one is for situations like 010011 vs 001101)
min(
v,
(((1 << N) - 1) - v).reverse_bits() >> (Item::BITS as usize - N),
)
})
.collect::<HashSet<Item>>() //remove duplicates
.into_iter()
.for_each(|v| {
// convert to state
(0..N).rev().fold(v, |acc, i| {
base_state[i] = (base_state[i] << 1) | (acc & 1);
acc >> 1
});
num_bits += 1;
});
if num_bits > Item::BITS {
panic!("Too big? {} > {} {:?}", num_bits, Item::BITS, sizes);
} // currently, the largest this gets (for sizes=[2] and N=7) is 44
let r = visit(&mut base_state, &mut tree, &mut state_to_idx); // build tree ("tree")
double::<N, N2>(tree, r) as i64 // doubles (more like squares) tree
}
}
/**
* Finds all states that are descendants of the input state and maps them to numbers in topological order.
* "tree" is an adjacency list on the numbers
*/
fn visit<const N: usize, const N2: usize>(
state: &mut [Item; N],
tree: &mut Vec<[usize; N2]>,
state_to_idx: &mut HashMap<[Item; N], usize>,
) -> usize {
if let Some(&idx) = state_to_idx.get(state) {
idx
} else {
let mut l: Vec<Option<usize>> = vec![];
for a in 0..N - 1 {
let p = state[a];
for b in a + 1..N {
let q = state[b];
if p & !q == 0 {
// self loop
l.push(None);
} else {
state[a] = p & q;
state[b] = p | q;
l.push(Some(visit::<N, N2>(state, tree, state_to_idx)));
state[a] = p;
state[b] = q;
}
}
}
let v = state_to_idx.len();
state_to_idx.insert(*state, v);
tree.push(
l.iter()
.copied()
.map(|x| x.unwrap_or(v))
.collect::<Vec<usize>>()
.try_into()
.unwrap(),
);
v
}
}
/**
* Finds all descendant states from input_state
*/
fn visit_notree<const N: usize, const N2: usize>(
state: &mut [Item; N],
states: &mut HashSet<[Item; N]>,
) {
if !states.contains(state) {
for a in 0..N - 1 {
let p = state[a];
for b in a + 1..N {
let q = state[b];
if p & !q != 0 {
state[a] = p & q;
state[b] = p | q;
visit_notree::<N, N2>(state, states);
state[a] = p;
state[b] = q;
}
}
}
states.insert(*state);
}
}
/**
* Combines a graph with the reverse of the graph
*/
fn double<const N: usize, const N2: usize>(tree: Vec<[usize; N2]>, r: usize) -> usize {
// does bfs on the graph, because visit returns in topological order, we can discard states with smaller rank, which saves memory
let choices: Vec<(usize, usize)> = (0..N - 1).flat_map(|a| repeat(a).zip(a + 1..N)).collect();
let choices_idx: HashMap<(usize, usize), usize> = choices
.iter()
.copied()
.enumerate()
.map(|(a, b)| (b, a))
.collect();
let rev: Vec<usize> = choices
.iter()
.copied()
.map(|(a, b)| *choices_idx.get(&(N - 1 - b, N - 1 - a)).unwrap())
.collect();
let tree_rev: Vec<[usize; N2]> = tree
.iter()
.map(|t| {
rev.iter()
.map(|&v| t[v])
.collect::<Vec<usize>>()
.try_into()
.unwrap()
})
.collect();
let tl = tree.len();
let mut queues: Vec<HashSet<usize>> = (0..2 * tl - 1).map(|_| HashSet::default()).collect();
queues[2 * r].insert(r);
let mut center = 0;
let mut num_seen = 0;
let mut rank = 2 * tl - 1;
while !queues.is_empty() {
rank -= 1;
queues.pop().unwrap().drain().for_each(|a| {
let b = rank - a;
if a == b {
center += 1;
}
num_seen += 1;
for (&a1, &b1) in tree[a].iter().zip(tree_rev[b].iter()) {
if a1 > b1 {
if a != b && (a != b1 || b != a1) {
queues[b1 + a1].insert(b1);
}
} else if a != a1 || b != b1 {
queues[a1 + b1].insert(a1);
}
}
});
}
2 * num_seen - center
}
// union-find with backtracking whatever
struct BacktrackArray<T> {
data: Vec<T>,
history: Vec<(usize, T)>,
checkpoints: Vec<usize>,
}
impl<T: Copy> BacktrackArray<T> {
pub fn new(data: Vec<T>) -> BacktrackArray<T> {
BacktrackArray {
data,
history: vec![],
checkpoints: vec![],
}
}
pub fn rollback(&mut self) {
self.history
.drain(self.checkpoints.pop().unwrap_or(0)..)
.rev()
.for_each(|(idx, v)| self.data[idx] = v);
}
pub fn save(&mut self) {
self.checkpoints.push(self.history.len());
}
pub fn set(&mut self, idx: usize, value: T) {
self.history
.push((idx, replace(&mut self.data[idx], value)));
}
pub fn get(&self, idx: usize) -> T {
self.data[idx]
}
}
impl<V: Copy> FromIterator<V> for BacktrackArray<V> {
fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
BacktrackArray::new(Vec::from_iter(iter))
}
}
impl<V: Copy> From<Vec<V>> for BacktrackArray<V> {
fn from(val: Vec<V>) -> Self {
BacktrackArray::new(val)
}
}
struct UnionFind {
num_unions: BacktrackArray<usize>,
parent: BacktrackArray<usize>,
size: BacktrackArray<Item>,
representatives: BacktrackArray<usize>,
rep_ptrs: BacktrackArray<usize>,
}
impl UnionFind {
pub fn new(n: usize) -> UnionFind {
UnionFind {
num_unions: vec![n].into(),
parent: (0..n).collect(),
size: repeat(1).take(n).collect(),
representatives: (0..n).collect(),
rep_ptrs: (0..n).collect(),
}
}
pub fn save(&mut self) {
self.num_unions.save();
self.parent.save();
self.size.save();
self.representatives.save();
self.rep_ptrs.save();
}
pub fn rollback(&mut self) {
self.num_unions.rollback();
self.parent.rollback();
self.size.rollback();
self.representatives.rollback();
self.rep_ptrs.rollback();
}
pub fn get_sizes(&self) -> Vec<Item> {
let n = self.num_unions.get(0);
let mut v: Vec<Item> = self
.representatives
.data
.iter()
.take(n)
.map(|&i| self.size.get(i))
.filter(|&v| v > 1)
.collect();
v.sort_unstable();
v
}
pub fn join(&mut self, i: usize, j: usize) {
let mut i = self.find(i);
let mut j = self.find(j);
if i != j {
let mut s_i = self.size.get(i);
let mut s_j = self.size.get(j);
if s_i < s_j {
swap(&mut s_i, &mut s_j);
swap(&mut i, &mut j);
}
self.parent.set(j, i);
self.size.set(i, s_i + s_j);
let n = self.num_unions.get(0) - 1;
self.num_unions.set(0, n);
let r = self.representatives.get(n);
let r_idx = self.rep_ptrs.get(j);
self.representatives.set(r_idx, r);
self.rep_ptrs.set(r, r_idx);
}
}
pub fn find(&mut self, i: usize) -> usize {
let i1 = self.parent.get(i);
if i1 == i {
i
} else {
let i2 = self.find(i1);
self.parent.set(i, i2);
i2
}
}
}
```
**`Output:`**
```
n=1: 1
n=2: 2
[2]: 1 = 1 * 1 (took 7.73µs)
n=3: 11
[2]: 12 = 4 * 3 (took 9.617µs)
[3]: -2 = 1 * -2 (took 783ns)
n=4: 261
[2]: 366 = 61 * 6 (took 17.105µs)
[2, 2]: -48 = 16 * -3 (took 3.853µs)
[3]: -64 = 8 * -8 (took 2.727µs)
[4]: 6 = 1 * 6 (took 1.088µs)
n=5: 43337
[2]: 62480 = 6248 * 10 (took 440.742µs)
[2, 2]: -14100 = 940 * -15 (took 76.582µs)
[5]: -24 = 1 * -24 (took 1.818µs)
[2, 3]: 1280 = 64 * 20 (took 9.063µs)
[3]: -6780 = 339 * -20 (took 35.228µs)
[4]: 480 = 16 * 30 (took 3.91µs)
n=6: 72462128
[2, 3]: 1741440 = 14512 * 120 (took 3.553571ms)
[4]: 169650 = 1885 * 90 (took 164.134µs)
[2, 2, 2]: 831870 = 55458 * 15 (took 3.841656ms)
[2]: 103912905 = 6927527 * 15 (took 553.271018ms)
[2, 2]: -28154610 = 625658 * -45 (took 43.410737ms)
[3, 3]: -20480 = 512 * -40 (took 67.739µs)
[5]: -4608 = 32 * -144 (took 4.743µs)
[6]: 120 = 1 * 120 (took 2.899µs)
[3]: -5991120 = 149778 * -40 (took 33.794472ms)
[2, 4]: -23040 = 256 * -90 (took 49.235µs)
n=7: 1530608978810
[2, 2]: -701933448825 = 6685080465 * -105 (took 1777.016031993s)
[7]: -720 = 1 * -720 (took 22.07µs)
[2, 2, 3]: -684133800 = 3257780 * -210 (took 424.2515ms)
[2, 3]: 26000250360 = 61905358 * 420 (took 7.892396883s)
[4]: 754063170 = 3590777 * 210 (took 282.065867ms)
[2, 2, 2]: 39011470995 = 371537819 * 105 (took 67.801355981s)
[2]: 2244447515625 = 106878453125 * 21 (took 40712.141796623s)
[3, 4]: 1720320 = 4096 * 420 (took 431.995µs)
[2, 5]: 516096 = 1024 * 504 (took 93.822µs)
[5]: -5283432 = 10483 * -504 (took 809.017µs)
[6]: 53760 = 64 * 840 (took 13.258µs)
[3]: -76668548810 = 1095264983 * -70 (took 215.344123884s)
[3, 3]: -174011040 = 621468 * -280 (took 176.875932ms)
[2, 4]: -141184890 = 224103 * -630 (took 93.090671ms)
Total time: 42782.049221178s
```
The correctness of this solution relies on two conjectures.
Before that, notation.
There are \$N\$ wires, \$1\$ through \$N\$ (the set of them is denoted by \$[N]\$).
\$U\$ is the set of all possible networks over the \$N\$ wires. \$2^U\$ is the powerset of \$U\$ (that is, the set of all subsets of \$U\$).
We'll let \$G=\ (U, E)\$ be a directed graph with vertices \$U\$ and an edge from \$a\$ to \$b\$ iff \$b\$ can be expressed by appending a single vertical wire to the right of \$a\$. We also denote by \$G\_x\$ (for network \$x\$) the set of networks reachable from \$x\$.
Define \$S(A):\ 2^{[N]}\rightarrow U\$ to mean the network that sorts the wires in \$A\$.
This is sort of an abuse of notation, but for \$A\subseteq[N]\$, we will write \$G\_{S(A)}\$ as \$G\_A\$
Define \$F(\{A\_1, ..., A\_k\}): 2^{\left(2^{[N]}\right)}\rightarrow 2^U\$ (where \$A\_i \subseteq [N]\$ and the \$A\_i\$ are pairwise disjoint) to mean \$G\_{A\_1}\cap G\_{A\_2}\cap\ ...\cap\ G\_{A\_k}\$.
The first conjecture is that \$\|F(\{A\_1,...,A\_k\})\|=\|F(\{B\_1,...,B\_k\})\|\$ if \$\|A\_i\|=\|B\_i\|\$ for \$1\le i\le k\$.
The second conjecture is that given \$X\_1, X\_2, ..., X\_m \subseteq [N]\$ (possibly overlapping), \$G\_{X\_1}\cap G\_{X\_2}\cap ...\cap\ G\_{X\_m}=F({A\_1,A\_2,...,A\_k})\$ for some pairwise disjoint \$A\_i\$ with \$k\le m\$.
To be more specific, if we make a graph with vertices in \$[N]\$ and an edge between vertices \$a\$ and \$b\$ if there is some \$i\$ for which \$a,b \in X\_i\$, then the \$A\_j\$ are the connected components of that graph.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), \$n=5\$
Naive brute force.
```
for(let n = 1; n <= 5; n++) {
console.log(n, solve(n));
}
function getPermutations(a) {
let list = [];
(function P(a, ...p) {
if(a.length) {
a.forEach((v, i) => P(a.filter(_ => i--), ...p, v));
}
else {
list.push(p);
}
})(a);
return list;
}
function solve(n) {
let connector = [];
for(let i = 0; i < n; i++) {
for(let j = i + 1; j < n; j++) {
connector.push([i, j]);
}
}
let perm = getPermutations([...Array(n)].map((_, n) => n)),
lookup = {};
perm.forEach((p, i) => lookup[p] = i);
let transform = connector.map(([ i, j ]) =>
perm.map(([...p]) => {
if(p[i] > p[j]) {
[ p[i], p[j] ] = [ p[j], p[i] ];
}
return lookup[p];
})
);
let set = new Set();
(function search(list) {
let key = JSON.stringify(list);
if(!set.has(key)) {
set.add(key);
transform.forEach(t => {
let update = 0;
let newList = list.map(permNdx => {
let newNdx = t[permNdx];
update |= newNdx != permNdx;
return newNdx;
});
if(update) {
search(newList);
}
});
}
})(perm.map((_, n) => n));
return set.size;
}
```
[Try it online!](https://tio.run/##XVPBbtswDL37K9ibhDjGdtgpTYEedhmGrkCPhlEIiZwodWVBkrNlnb89IyXZcppDJJOP5OMjdRJn4XZWGb/W/V5er21vWSc9aNjC1w0e91v4hudqxeGjANj12vWdrLr@wHQJeD9LpjnfFGNRtIPeedVrOEj/LO374AV9OiZiMCXulPOYu242BVrYHPLMRAlVVZkIBVAtE1Un9cEfJxOAqJDgd7E7MnYuQXHYPlBk1arOS8te6Vut1zymKuFMzChwDP@yc3LORUwqM7gjMwvQyJFt4GalH6wOsNvupqbnnlAULXe@t7mxSUeFpi8bPO5B4zHJmAEnBChYkdinCDplEOTUkWmtSjg1S7pF4mBQb0z1WfkadXi0VlyQb1O9C8PYawk6CIdjKyct@v5tMBj/MQb6lC1LbSapI6w2DZGOKlFtb4V2iCYCmXAoVgMxhobCQ62QObpoRMExd4szN7Vq4AFMjW3OdoAayFEGO1D5OlzLYIZmk4BjOqfZTXyTYByPTNtJ2kQtf8OL9Ix/WkgnhcXmafwTEQp6kxcM@vHy66ly3ip9UO0lgkJ86OEOM1dH4RiCee6CrGK/D9YEhqzdLLdfKhKLDmYvvAyrVNw4kPzP@KDCNpOuJPDT/s9tkhkdPODrhJqFo1@q8m87Ae@2kHBLWNI2YrJj5PmOGsRk/IZDkjSRXuCnsY23DzHvynJnl4@TJHXqr8QHer3@Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), n≤4
```
import Data.List
import Data.List.Ordered
pairs[]=[]
pairs(i:k)=[[i,j]|j<-k]++pairs k
end(a:b:c)=last$end(b:c):[a|a==b]
b n=length$end$iterate behave[permutations[1..n]]where
gate[i,j]z=last$z:[[z!!last(l:[i+j-l|l==i||l==j])|l<-[0..n-1]]|z!!i>z!!j]
behave bs=nubSort$bs++[map(gate[i,j])b|b<-bs,[i,j]<-pairs[0..n-1]]
```
[Try it online!](https://tio.run/##XVCxboQwDN3zFTmJAcQF9aROiNzUsVKHjlYGp0RHIORQkmsllH@nCbQdulh@fvZ7tgf0kzJm2/S83F2gLxiwedU@kP@F5s31yqmeLKidB8FBHGmp26niAPo8ijh2bBJ1vRN0Isr2Jbay/ai4QR@KjDNqASNyLgWR1HKj7C0MmSx0UA6DolIN@KlgUW5@BAz6bj1cmsYK8TWkLQi9pa7dcj2U1xZgPZ1yXpoWdD0yEw3nOuY4iiqajsFTkmAXIWJq1dcURkF@vKj03D7kezq6kL6uYcal/HOpZJQdk/68o44dT/iV22bUli9O2zTbFddMPIvtGw "Haskell – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), n≤5
```
import Data.Array
import Data.Bits
import Data.List
import qualified Data.Set as S
b n = S.size$visit 1 2 ini (S.singleton$hash ini)
where
ini = listArray(1,n)$map((sum::[Integer]->Integer).zipWith(*)(iterate(2*)1))$transpose$sequence$replicate n[0,1]
hash = id
visit i j s visited
|i>n =visited
|j>n =visit(i+1)(i+2)s visited
|s!i.&.complement(s!j)>0&&S.notMember (hash newState) visited
=visit i(j+1)s$visit 1 2 newState(S.insert (hash newState) visited)
|0<1 =visit i(j+1)s visited
where newState=s//[(i,s!i.&.s!j),(j,s!i.|.s!j)]
main=mapM_(print.b)[1..5]
```
[Try it online!](https://tio.run/##dVHBTsMwDL33K4xUTck2wjrEZaKTQFyQQBx64FBNKNu81aVNS5yBmPbtlKxlaIDIyX6x33u2M83PWBRNQ2VdWQc32ml1Za1@D46Ra3L8A7gjdgfgZaMLWhEuu68EHWiGJAjmYCCGRDFtMXwlJgcRjIEMgdijZl2gq0yYac72qAzgLUOLAbQ1MRRepTUjoqGRYalrIXhTTibprXG4Rjs7nX5FUm2pfiSXib4U5NBqh2Lcl5GUobPacF0xhowvGzQLDC3WBS18DZh0NIxmgddsbcRAy33S2SXIgbsYlx6FHU39TMdA/g0IGkReezCWP1v4hFRPLaqyLrBE4wSf5HI66vUSZSp3j@UcLYhW3eBb4rwreUzQvvjLkMi9CB9t89DiN0qG0d/jHyrZmhldRr@4/kh1R/gmiPnsLBU07MbYex@KvM12beZ3V2oysb/O/ZOoLRmn5jKNlLqYNc3HYlXoNTenD@ef "Haskell – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), \$n \leq 5\$
Port of [@Arnauld's Javascript answer](https://codegolf.stackexchange.com/a/261252/110802) in Scala.
Naive brute force.
[Try it online!](https://tio.run/##dVQ9b9swEN35Ky5GBrJxhWboYtRBm6kBmqJAUHQIMjAyldCmSEGk0nxUv929kyiGatzBsnT37t27D9KX0sj9XteNawN4@ipKZ4wqg3a2qLsgb40qvmkfzruqUi2bQaW1LsgBGqQ2rSoZc7dbjIZLqS2ox6DsxsOXpoEXBlC5FriFT@/hFIKDj2KwAjSttsFY7hfHFo5fvDMPilvRLwS6e/xtVAWVLINrtTTcruBc313YIKYXWEemz5MO@phFfVWmUe1r7BJkWXZ1ZyT6/08IoKtB8xpORR4Svcp49TYJYIVLsPAujxBDSM@GvzchS@Rn0U3CYxNWMMrKNT3IFkpnrSIKtHLqa5JL7f0AnQ3agI3GLRk1nGDfc0cPT1qZDXC9hK0QRXA0aRaTGEBhNfFznggnkCjI2Y3T9yl0ijTO7boGYwlVPOvmlw73F3ajHhF5KZvXHKGV1mMBlCgVVdQSNwZKic0dxcH6LNYyMI7@5tU6ksWF/UGJMVHc2QlBk5wQXAs4S3iO1acOJmWqpgqyiAyQ86xznkMYkj/QJWef3sZOJV1Te1mO61mau1e0B1cqXF8FPDV3N1ywtOxeyba85wYJVkA017g2N7g9P63OV5qq26kntBC0qHcjF18sF5FtbNYRZsP7wOKhsp5jxKxLJOVkTUQs2dI0C3woWd7jlEI@pbGKrtnIoDB/JfH8sH8ab9VvEp/kjbPGsX/fPM65En7wQOARJWaYmO0PbnKEHq3hIHJ0Z6Y@e6eOjFTzXYGp71G3OBjfH5poDEzHK7vj6EjR0Z8tBM3D62c1XBQ92@//Ag)
```
import scala.collection.mutable.ListBuffer
import scala.annotation.tailrec
object Main extends App {
for (n <- 1 to 5) {
println(s"$n ${solve(n)}")
}
def factorial(n: BigInt): BigInt = {
@tailrec
def factorialHelper(n: BigInt, accumulator: BigInt): BigInt = {
if (n <= 1) accumulator
else factorialHelper(n - 1, n * accumulator)
}
factorialHelper(n, 1)
}
def solve(n: Int): Int = {
var connector = (for {
i <- 0 until n
j <- i + 1 until n
} yield (i, j)).toList
val perm = (((0 until n).toList).permutations).toList
val lookup = perm.zipWithIndex.toMap
val transform = connector.map { case (i, j) =>
perm.map { p =>
val mutableP = p.toBuffer
if (mutableP(i) > mutableP(j)) {
val temp = mutableP(i)
mutableP(i) = mutableP(j)
mutableP(j) = temp
}
lookup(mutableP.toList)
}
}
var set = Set[String]()
def search(list: List[Int]): Unit = {
val key = list.mkString(",")
if (!set.contains(key)) {
set += key
transform.foreach { t =>
var update = false
val newList = list.map { permNdx =>
val newNdx = t(permNdx)
update |= (newNdx != permNdx)
newNdx
}
if (update) {
search(newList)
}
}
}
}
search((0 until factorial(n).toInt).toList)
set.size
}
}
```
] |
[Question]
[
Here is [Minkowski's question mark function](https://en.wikipedia.org/wiki/Minkowski%27s_question-mark_function):
[](https://en.wikipedia.org/wiki/File:Minkowski_question_mark.svg)
It is a strictly increasing and continuous function from the reals to themselves that, among other unusual properties, maps rational numbers to dyadic rationals (those with a power-of-two denominator). Specifically, suppose the continued fraction representation of a rational number \$x\$ is \$[a\_0;a\_1,\dots,a\_n]\$, then
$$?(x)=a\_0+\sum\_{i=1}^n\frac{\left(-1\right)^{i+1}}{2^{a\_1+\cdots+a\_i-1}}$$
For example, 58/27 has continued fraction representation \$[2;6,1,3]\$, so
$$?(58/27)=2+\frac1{2^{6-1}}-\frac1{2^{6+1-1}}+\frac1{2^{6+1+3-1}}=2+2^{-5}-2^{-6}+2^{-9}=\frac{1033}{2^9}$$
so the pair (1033, 9) should be returned in this case. Similarly for 30/73 with expansion \$[0;2,2,3,4]\$:
$$?(30/73)=2^{-1}-2^{-3}+2^{-6}-2^{-10}=\frac{399}{2^{10}}$$
and (399, 10) should be returned here. Note that it does not matter whether the [form ending in 1](https://en.wikipedia.org/wiki/Continued_fraction#Finite_continued_fractions) is used or not.
## Task
Given a rational number \$x\$, determine \$?(x)=a/2^b\$ as a rational number in lowest terms (so that \$b\$ is a non-negative integer, as small as possible, and \$a\$ is odd unless \$b=0\$) and output \$a\$ and \$b\$ (not \$2^b\$). \$x\$ may be taken in any reasonable format, and if you take a pair of integers you may assume the corresponding fraction is in lowest terms.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins.
## Test cases
```
x -> a, b
0/1 -> 0, 0
1/1 -> 1, 0
1/2 -> 1, 1
-1/2 -> -1, 1
2/1 -> 2, 0
1/3 -> 1, 2
1/8 -> 1, 7
2/5 -> 3, 3
8/5 -> 13, 3
58/27 -> 1033, 9
30/73 -> 399, 10
144/89 -> 853, 9
-17/77 -> -767, 13
-17/99 -> -133, 12
355/113 -> 12648447, 22
16000/1 -> 16000, 0
```
[Answer]
# [Python](https://www.python.org), 95 bytes
```
lambda n,d:g(d-n%d,n%d,1,n//d,0)
g=lambda n,d,s,N,D:d and g(d,n%d,-s,(N<<n//d)+s,D+n//d)or(N,D)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9LasMwFEXnXoUIFOTmqfrZkRySjDLOCgrFxXEqcCQTu4WupZNAafeUdXQD1a90ILj33aP3-fge3-cXZ6-f_fbx63Xuib49De35uWuRhW59wh2xdx2Ex8FS2gEri9P2H4EJDrBfd6i1HfJ4RMkE-LDZBL5cTrBfRuUu2KNlHjP07oIGY4_IWOTGo8WsXBcIGXBoG4OHaRzMjBdktyh9cG_AB-d2xMbOYP5SuihDGj4d39oBu-DGi2ewgR7fmxJcnnm9_TDKEdkhBogVPGmetMiaFyQbEp1IlEiUzJTwWmetPFMHLQHJQifNo6k1FSpaJn2hKSSjKvaQTeO7-5ZVRXUTKrqOBOGKqviHqJXyjIylpkkrhTZcFLKuKedpG7GqdFV5VPitVozlG6P0W6fbfwE)
Rather verbose implementation. Essentially calculates the cf (by Euclidean algo) and converts the terms on the fly.
[Answer]
# Python 3.8, 95 bytes
```
q=lambda x,y,k=0:y>=2*x>0and q(x,y-x,k+1)or(x and-(-x//y<<(r:=q(-x%y,y))[1])-r[0],x and r[1]+k)
```
[Try it online!](https://tio.run/##VZDLDoIwEEX3fsXExKTVNrQ8BInwI4QFxhgNyqNx0Qnh23F8INDVuXfuzLRt8HmtKy9qzDC0yb14nM4FWIGiTFSMaeJubaqK6gwtI1daUe40rw2zQKZk0joOHo/MxElLYoMCOc90zqXJVC4@KTBk7Eo@XGpDowHhVkG2AjpMCdBcfFkv2R1ZzoW7DHkzjmaZYORoxgEJNxyVR7vDqd/3acJh2hlSNVzIw7/qBQFdQ0/Ne6V@L8njj9WYW/Vkl3Vne6fDHmQK3fsHAXm/5qvhBQ "Python 3.8 (pre-release) – Try It Online")
### How it works
Uses the recurrence
\begin{align\*}
?(0) &= 0, \\
?(x) &= \frac{?{\left(\frac{x}{1 - x}\right)}}{2} \quad\text{if }0 < x ≤ \frac12, \\
?(x) &= ⌈x⌉ - {?(⌈x⌉ - x)}.
\end{align\*}
[Answer]
# [Haskell](https://www.haskell.org/), 186 bytes
```
import Data.Ratio
c r=let f=floor r;d=r-f%1 in if d==0 then[f]else f:c(1/d)
m(a:b)=a%1-2*sum[(-1)^i/2^sum(take i b)|i<-[1..length b]]
p x=(numerator x,until((denominator x==).(2^))(1+)0)
```
[Try it online!](https://tio.run/##Jc3PaoQwEIDxu08xhxWStmY3QmnZdm59gl5FIeqkDps/EkfYQ9/dLvT4/S7f4rYbhXAcHNdcBL6cOPPthHM1QcFAAh59yLlA@ZixNL62wAnYw4x4AVkodb6nsBH466TsedZVVO46anS1bdqnbY@daqwe@NwOj1DibgQMo/7lz6azxgRKP7LA2PfVCndUaY9UnDyW95c9CQelZko5cvpHRG1UO2it7LO@6CM6TrgWTnJaTTTT6fW9bt@OPw "Haskell – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 77 or 124 bytes
```
(s=Sign@#;{s Numerator@#,Log[2,Denominator@#]}&@MinkowskiQuestionMark@Abs@#)&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X6PYNjgzPc9B2bq6WMGvNDe1KLEkv8hBWccnPz3aSMclNS8/NzMPIhZbq@bgm5mXnV9enJ0ZWJpaXJKZn@ebWJTt4JhU7KCsqfY/oCgzr8QhLVrX0Fzf3DyWC8Y3NjXVNzQ0jv0PAA "Wolfram Language (Mathematica) – Try It Online")
Or without overkill builtin:
```
(s=Sign@#;c=ContinuedFraction@Abs@#;{s Numerator@#, Log[2,Denominator@#]}&@(r=c[[1]];t=-1;Do[t=-t/2^e;r+=2t,{e,Rest@c}];r))&
```
[Try it online!](https://tio.run/##NYlBC8IgGEDv/YrBYCxyDDfGDiIYjU4RUUcxMHPLgwr67TT2220QnR7vPSvho60Eo2QaaSojfZjJsZwoevIOjJv1@xykAuMdO77idpaYXWergwQfWI6yi594gwbtvDXuF8VasDJQxTkWggCtMBk83wh189QkHGgDaNHoriMwtQoS9vsi3YJxwEZe4b7ue7H7e9t1NcatSF8 "Wolfram Language (Mathematica) [Dash] Try It Online")
[Answer]
# [julia](https://julialang.org/), 111 bytes
Expects a single argument of type `Rational{Int64}`
This approach traverses the Stern-Brocot tree for \$\mathrm{mod}(p,1)\$, adding \$1/2^k\$ at the \$k\$-th recursion whenever we take a right branch in the tree.
The case where \$p \notin (0, 1]\$ is handled in the default arguments.
```
m(p,L=[0,1],U=[1,0],q=mod1(p,1),r=p-q,s=0,M=//(L+U...),g=q>=M,l=r+g)=q==M ? (l,s) : m(0,L+g*U,U+L-g*L,q,2l,s+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bZE9DsIwDIXFyikyJsRtk_7QguQysaVjJ8SAhKiKWmgKbNyEpQuHgtMQgViSrp-f_fzsx_N4a-rdMDxv14OXvc4t7UDhRoDcQokbCWILGtvzXpqCZNBj52m4oIACg4AqXvq-z6BCnWMBDfa8YqgRC7IitIELI0vSUgGKV7MSSq68aqZAQ2hqXLKf7XuyNpogkIzcc9L19enanKYtlaMotJA3wsLRzshFmduYWChzUWJYmFowMglSxyKOjcnCWTk1WnvAly5sbZQkJox0Bs-FsE_2u-b_mR8)
[Answer]
# JavaScript (ES6), 88 bytes
Expects `(p)(q)` for \$x=p/q\$. Returns `[a,b]`.
This is heavily based on [loopy walt's answer](https://codegolf.stackexchange.com/a/260818/58563).
```
p=>g=(q,s=p<(b=0)?p/(p=-p):1,a=p/q,d=p%=q,n=q-p)=>d?g(b+=n/d|0,-s,s+=a<<n/d,n%d,d):[a,b]
```
[Try it online!](https://tio.run/##bdLdboMgFAfw@z2FN00ghcmHiDae9kGWXWhpzZZGcS672ru7w9KmQeEO8sv/HA58tj/tfP768N98GN1lucLi4dgDmdgMviEdCHryOfHAPT1I1oLPJ@bA72BiA0x4Ckd36km3hyF3v4Lxmc17aJsGt2zYOebo4a1l3ftyHod5vF1eb2NPrkRQIinNwsrzTLBMvMRARkAmgYqAXAH@FAh4QqiohkrW0FENtQVVBOy2hHkCzTK9AlUEZEIYJMr@myCERlOvjMZ5Wv0wuq7xspvLFAV2WweEpjKJGC4t5tg74ba0mKNTqH7kcBn6kevBaGNwuDK0FJpWZVEVBaapzQRLIe6fIcCww3dY/gA "JavaScript (Node.js) – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 67 bytes
```
x->s=0;[(x\1+2*sum(i=2,#r=contfrac(x),(-1)^i/2^s+=r[i]))<<s-=!!s,s]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY5NCsIwEIWvMuom0YT81JqIxo3HqFWKUAn4E5IK9QbewU1BxDN5Gxvj5nvzmJk383i7ytvdwXXPGszr2tRUf9YtXQXDFwVqN2Iix-F6QtZIMvJmfzk3ta_2qMUEUYG3lsltmBhf2BLj5TJQMxgEEsp_1L1y7nhDLdAVOG_PTV8OoxlC3WdgAgVngoBIkATojzL5LEJHmxPQEblmUhHIOFOxOZ0yPY9LiimVdN77LM-ZEHFgxnl_oMTpn65L-gU)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 28 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ḋ;%/ƊẠпṖ:/€ḢW+Ṭ€NÐeFƊƲL’ṭḄƲ
```
A monadic Link that accepts a pair of integers, `[numerator, denominator]`, and yields a pair of integers, `[numerator, denominator's exponent]`.
**[Try it online!](https://tio.run/##y0rNyan8///hji5rVf1jXQ93LTg84dD@hzunWek/alrzcMeicO2HO9cAmX6HJ6S6Hes6tsnnUcPMhzvXPtzRcmzT/6xHDXP1dQ63H530cOcMFSBvjoKunQJQUDPy///oaAMdBcNYHYVoQwRtBKJ1YQwjhIQxlLaAipuCaAsobQpkGJmDWMZAM80hak1MgKotIeaZA0XN4UxLsKixqSnQeEOIYjMDA7BrYgE "Jelly – Try It Online")**
### How?
```
Ḋ;%/ƊẠпṖ:/€ḢW+Ṭ€NÐeFƊƲL’ṭḄƲ - Link: pair of integers = [N, D]
п - collect while...
Ạ - ...condition: all truthy - i.e. while no zero present
Ɗ - ...do: last three links as a monad - f(current=[n, d]):
Ḋ - dequeue -> [d]
/ - reduce ([n, d]) by:
% - modulo -> n%d
; - concatenate -> [d, n%d]
Ṗ - pop - remove the final result (with a zero in)
/€ - reduce each by:
: - integer division -> continued fraction part list
Ʋ - last four links as a monad - f(Parts=that):
Ḣ - head -> remove and yield the integer part
W - wrap (the integer part) in a list
Ɗ - last three links as a monad - f(remaining parts):
Ṭ€ - untruth each (e.g. 4 -> [0,0,0,1])
NÐe - negate those at even indices (the 2nd, 4th, ...)
F - flatten
+ - ([integer part]) add (that) (vectorises) - adds the integer
part to the first one. If none just gets [integer part]
Ʋ - last four links as a monad - f(A=that):
L - length (A)
’ - decrement -> the denominator's exponent
Ḅ - convert (A) from base two -> the numerator
ṭ - tack -> [numerator, denominator's exponent]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 63 bytes
```
NθNη≔÷θηζW﹪θη«≔ηθ≔ιη⊞υ⁻÷θη¬υ»F﹪Lυ²⊞⊞Oυ⊖⊟υ¹I⟦⁺×ζX²Συ⍘⭆υ×I﹪κ²ι²Συ
```
[Try it online!](https://tio.run/##ZY9LT8MwEITP5FfscS2ZQ1r1xAnopRIpkcoNcTDJNrZI7NSPVirit4fNA4TExfZodr4dV1r5yql2GHa2T3GfunfyeBJ32V@tWd@HYBqLOxu35mxqwpMELSRc2bto0xJg4erUutkQ8JndLBktYST@SDP6LMsUNCYJhbEp/AfvXcQkBE9@ZUfnf/FPZJvIQR5Z8ZqJMh7PPXkVnR@RW6o8dWQj1Vi6fuJIyJlVemMjPqoQ8bVsee@L6SjgVULpLvzVlYRD6pbAgwp0iJxocL4K1Y/4OTNBllIfUxkJRojlNVPeuP8wrDcbyPP1cHtuvwE "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input the numerator and denominator.
```
≔÷θηζ
```
Calculate the integer part of the fraction.
```
W﹪θη«≔ηθ≔ιη⊞υ⁻÷θη¬υ»
```
Calculate the rest of the continued fraction, except decrement the first value.
```
F﹪Lυ²⊞⊞Oυ⊖⊟υ¹
```
If the fraction has odd length then decrement the last value and append a `1`.
```
I⟦⁺×ζX²Συ⍘⭆υ×I﹪κ²ι²Συ
```
Transform the fraction into run-length-encoded binary and convert from binary to decimal, adding on the original integer part with an appropriate shift, which is also the second output value.
[Answer]
# [Factor](https://factorcode.org/) + `koszul math.continued-fractions`, ~~156~~ 154 bytes
```
[ dup sgn swap abs 1vector [ dup last ratio? ] [ dup next-approx ] while
unclip -rot cum-sum vneg [ -1^ 2 rot 1 + ^ * ] map-index sum * + >fraction log2 ]
```
[Try it online!](https://tio.run/##TZJPb5wwEMXvfIpppL2k64ANLNBKyTHKJZcqp/yRXDC7qGA7tklWqfLZNwMYbzhY8u/Ne@OxaXntlDk9/Lm7v/0FrTIDd66Te7DidRSyFhb@CSNFDygc5uWqVhJLRtGQ1qC9U9IugnXcddZ1td@/iSkcE5T9GJeEq3aU3rKqv6PofwT4JTGFH0CuIdlCMhO6EnomLBA6ExIQCYytPnb2pcHHPCkDKbwrX0i6hXQm5UpoQHkZs8LDJEVczThN4sJ3SKsKz@HbZllcVgsv81BNaBEXPoUUuwLr0yBU1TrOFE@X06Z5HlO6zsB2WZllaGN@ll2ShNubN9Pcn9HpEZpRg91LsO9cA/9rgS73DovUc@vA4LOpG3j2TIqjI1xro47I3g9dLyJ8tb7TQIxyUI8DseMAb1Ls0ULoCzCYBAo/4QUu0TRwTTrZiCNMhZfIr9d/BXq1Z/Dsj3bGF5sm3jTTABegTSddiznaCK2swC4ob2HTPMlvaq2GWRW8Ppy@AA "Factor – Try It Online")
```
! -17/99
dup ! -17/99 -17/99
sgn ! -17/99 -1
swap ! -1 -17/99
abs ! -1 17/99
1vector ! -1 V{ 17/99 }
[ dup last ratio? ] ! -1 V{ 17/99 } [ dup last ratio? ]
[ dup next-approx ] ! -1 V{ 17/99 } [ dup last ratio? ] [ dup next-approx ]
while ! -1 V{ 0 5 1 4 1 2 }
unclip ! -1 V{ 5 1 4 1 2 } 0
-rot ! 0 -1 V{ 5 1 4 1 2 }
cum-sum ! 0 -1 V{ 5 6 10 11 13 }
vneg ! 0 -1 V{ -5 -6 -10 -11 -13 }
[ -1^ 2 rot 1 + ^ * ] ! 0 -1 V{ -5 -6 -10 -11 -13 } [ -1^ 2 rot 1 + ^ * ]
map-index ! 0 -1 { 1/16 -1/32 1/512 -1/1024 1/4096 }
sum ! 0 -1 133/4096
* ! 0 -133/4096
+ ! -133/4096
>fraction ! -133 4096
log2 ! -133 12
```
[Answer]
# [Scala 3](https://www.scala-lang.org/), ~~238~~ 186 bytes
Modified from [@loopy walt's answer](https://codegolf.stackexchange.com/a/260818/110802).
---
\$ \color{black}{\text{In scala, it's weird to mimic `%` `//` of python}} \$
```
/*
Python's % operator returns a result with the same sign as the divisor, and // rounds towards negative infinity.
In Scala, % and / don't behave the same way. The % operator returns a result with the same sign as the dividend, and / performs truncating division, rounding towards zero.
*/
def pythonMod(a: Int, b: Int): Int = ((a % b) + b) % b
def pythonDiv(a: Int, b: Int): Int = {
if ((a > 0 && b > 0) || (a < 0 && b < 0)) a / b
else if (a % b == 0) a / b
else a / b - 1
}
```
---
Golfed version. [Attempt this online!](https://ato.pxeger.com/run?1=PVDNjtowEL7nKVzKSnZxHJsAoQGjVuJSiXLYpadVVaU4idwmdmR7V1pRnqSXvew-RN-EJ-hr1DFQySPNjL-fmfn9avdFU6TPp7ey7bRxINREanKnH8y-jPT3H-Xegc-FVIeXB1fF89Mf99SVYMc_KbcQZQUqqPIdFvkO8cOHQintCie1Iq6QjSn3oMfUVwy2PrY-1h6fwx32LFlB8YZTVEOB1Y3AscVwu1yqRKCRxetRn5SNLeEWr9HisWiA4dADRwLdiIVnxQYbzLDXUe_Eiv7yf9zreR7oecAnMcMUHS8b_A0ztX4nWJja5h-NKZ7u75yRqv6K8i9KOn6IAOitNvx8CWKdkIrUpdtIVVqIiNMbaZ2HVdrAZhlvUM8JpCAIJdaIN8R2jXRwEK8G6PrfcnltJwNE2qKD34i3b72oP-t_3C2vYAspwi1kKHQ7P6NrFLSD4aEl7c_z0EHmiIe3eKiDyzHy77Lu8-meJgzEK0AxoNF0noyzvmI0TTF4H8UsS7LQibNZhgFLo3Q6TRhLA2o8m8wnE98fjyM2o_SiFVKvd_b4Bw)
Saved 52 bytes thanks to the comment of @ceilingcat
```
type T=Int;def f(n:T,d:T)={@annotation.tailrec def g(n:T,d:T,s:T,N:T,D:T):(T,T)=if(d!=0)g(d,n%d,-s,(N<<n/d)+s,D+n/d)else(N,D);val r=(n%d+d)%d;g(d-r,r,1,if(n*d>0|n%d==0)n/d else n/d-1,0)}
```
Ungolfed version. [Attempt this online!](https://ato.pxeger.com/run?1=dVPNjtMwED5wy1MMVVjZIv9pm2RpV6zUC9JuLytOCCG3SYshdbqJu9Kq7ZNw6QXeCV6DF2D8025ZhFTV48_ffPONPfn2o5uzmqWHw_eNXPj5rxc7vlo3rQSNB7wJ7ppNO6-cZvalmku4ZVzA1gEoqwUsiLiEd0J6UOqVwlifAbxlQjSSSd6IQDJet9Vc4ypr-SzLg86uU7tOjNolEL39SxkgDGHdciFrQbqeK8Atwe3AnYI76VHL4QsgJbwcQ0SxXumBgFeAi995QKYwGgEREEJJKbwGxCa4nJCq7ipkIUrfaL39yfv6UX5uxG1TEma9zo5e8R9NEsKw0kzJ4h9GzrPcCX_4X-72zDzKXEEEFxcwUwGF3Q4QGx0xDNApQ8czm6Vdq1RtAMa6938IGgAfYtuYXh5YDfdo4MmhwMexzavD9nSoWj87xLtFsdZTv9iDew-LOlZX9bzCcSGsXeILX7cte_xwJ_Hplh-x5_eCPzWtitRcVB0iZuCCTpZcBMtK3iic0EA2N7yTxvGiaYGoBBj5JpGerk9p6WKEe9CoyVGEoFvXXJKef3UaEkUUm5WqyY_HYY8GK7YmnwI0usKa6oHO-G3VbWrlG2cfU0lEPa1BYnqknQ3nVh0Fq6-ma62-98A1Ihg01ste39neMR-h_RYPP39HYQw-Pj9eqxObODZxYuPY8e3G17vEsBLDSi0rwTi3cYacgYpTD1InN3GsN4M8TDK9jVIECieNwkxrpEWB6ijZ74d5oZB8oBl-nIWZzvGzYYacVENFYSwpmThx0sEgjGPjJhn2834fqQm6GkaR7VGH6Nr0_gc)
```
import scala.io.Source
object Main {
def f(n: Int, d: Int) = {
@annotation.tailrec
def g(n: Int, d: Int, s: Int, N: Int, D: Int): (Int, Int) = {
// println(s"$n $d $s $N $D")
if (d != 0) g(d, n % d, -s, (N << (n / d)) + s, D + (n / d)) else (N, D);
}
def pythonMod(a: Int, b: Int): Int = ((a % b) + b) % b
def pythonDiv(a: Int, b: Int): Int = {
if ((a > 0 && b > 0) || (a < 0 && b < 0)) a / b
else if (a % b == 0) a / b
else a / b - 1
}
val q = pythonDiv(n, d);
val r = pythonMod(n, d);
g(d - r, r, 1, q, 0)
}
def main(args: Array[String]): Unit = {
val lines = Source.stdin.getLines().toList
for (line <- lines) {
val Array(i, o) = line.split("->")
val nums = i.split("/").map(_.trim.toInt)
val result = f(nums(0), nums(1))
println(s"${nums.mkString("/")}, $result, $o")
}
}
}
```
[Answer]
# Python3, 217 bytes:
```
C=lambda n,d:[n//d]+C(d,n-d*(n//d))if d else[]
def f(N,d):n=abs(N);c=C(n,d);k=[(c[0],0)]+[(pow(-1,i+1),sum(c[1:i+1])-1)for i in range(1,len(c))];b=max(B for _,B in k);return([1,-1][N<0]*sum(2**(b-B)*N for N,B in k),b)
```
[Try it online!](https://tio.run/##PZFNspswEITX0SmmvEGDpSDxY8AOWdh7LkCoFBg5oR6WKcCV5PSOJPDbdbc@tWZK47/l90NH2Ti9XpdiaO5t14Bm3bHSQdDV@wvtmOadT61F7G/QgRpmVdWkUze40ZJ1eNRF0860xNO1uFBzG08fRUWvlaiZwHpf0fHxh3LJ@r1ENj/v5kgejamRS7w9Juih1zA1@peikg1K0ytifWqLe/OXnsESP9nZMh94mtTynDStJOOyrspvovZtZej7tOVn9EvHl2@etfj6fGK324lAAv8OgoEgctVy1eGmJeGb4c6FKxWuVLRRodHZplPDJFZHDCKSrVo6k2RBmDorIhPkJBJB6jqiPDftpjKOgyy3SZY4gss0SN0dnh5Sw0QuyvN1JFsjQxIlSSDlOk14iLM4NmhopjoIse3opJnabP11Hod@od4P7eGRfGkYtFBA/44t7aHJ51lNi/lW/96MtNcLg@bNBB4iQlHA8hwHRT@B9g0wsAQh42Ry6i1qXmYYbWXn4es/)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 46 bytes
```
M?tH+/GHgH%GH]GJtstKgEE+*hK^2JaF_m^2-Jtsd._tKJ
```
[Try it online!](https://tio.run/##K6gsyfj/39e@xENb390j3UPV3SPW3aukuMQ73dVVWyvDO87IK9EtPjfOSBcomqIXX@Lt9f@/qQWXkTkA "Pyth – Try It Online")
### Explanation
First we define `g(G,H)` to find the continued fraction of its input.
```
M # define g(G,H)
?tH # if (H != 1):
+/GH # prepend floor(G/H) to
gH%GH # recurse on g(H, G%H)
# else:
]G # return [G]
```
Then we compute the function
```
KgEE # assign K to g applied to two inputs
Jtst # assign J to sum(K[:-1]) - 1
._tK # all prefixes of K[:-1]
m # map on lambda d
^2 # 2 to the power of
-J # J minus
tsd # sum(d) - 1
aF_ # take the alternating sum
+ # add to this
^2J # 2 ^ j
*hK # times K[0]
J # print(J)
```
] |
[Question]
[
Programming is very rigid. You can't tell a program to "output the banana count", you have to tell it to `print(bananas)`.
But when you do that, you end up with a problem: you don't know how many bananas you have beforehand, so you don't know whether to use a plural.
Sometimes, programmers go the lazy way. Instead of checking, they just print `there are X banana(s)`.
But that's ugly, so we need a program to fix this.
# The method(s)
To remove the ambiguous plurals in a string, follow the following steps:
1. Split the string on spaces into a list of words.
2. For every word that ends with `(s)`, do the following:
* If the preceding word is `a`, `an`, `1` or `one`, remove the `(s)` at the end of the word.
* Otherwise, if the word is the first word in the string or the preceding word is not `a`, `an`, `1` or `one`, replace the `(s)` at the end of the word with `s`.
3. Join the list of words back together into a string, preserving the original whitespace.
### Example(s)
Let's take a string `there's a banana(s) and three apple(s)`.
First, we split the string into a list of words: `["there's", "a", "banana(s)", "and", "three", "apple(s)"]`
For the second step, we take the two words ending with `(s)`: `banana(s)` and `apple(s)`.
The word before `banana(s)` is `a`, so we remove the `(s)`, making it `banana`.
The word before `apple(s)` is `three`, so we change the `(s)` to `s`, thus it becomes `apples`.
We now have `["there's", "a", "banana", "and", "three", "apples"]`. Joining the list back together, we get `there's a banana and three apples`. This is our end result.
# The challenge(s)
Create a program or function that takes an ambiguous string in [any reasonable format](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) and returns the un-ambiguated version of that string.
You may assume the string contains no newlines, tabs or carriage returns.
I forgot to specify whether to split on groups of spaces or spaces (i.e. whether `okay then` with two spaces should be `["okay", "then"]` or `["okay", "", "then"]`) when posting the challenge, so you may assume either form of splitting.
# Test case(s)
```
Input -> Output
there are two banana(s) and one leprechaun(s) -> there are two bananas and one leprechaun
there's a banana(s) and three apple(s) -> there's a banana and three apples
apple(s) -> apples
one apple(s) -> one apple
1 banana(s) -> 1 banana
banana -> banana
preserve original whitespace(s) -> preserve original whitespaces
11 banana(s) -> 11 bananas
an apple(s) -> an apple
this is a te(s)t -> this is a te(s)t
I am a (s)tranger(s) -> I am a (s)tranger
```
# Scoring
As this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the submission with the least bytes wins!
[Answer]
# Mathematica, ~~151~~ 148 bytes
```
StringReplace[j=" ";k=Except@j;j<>j<>#<>j,j~~a:k...~~s:j..~~w:k..~~"(s)"~~j:>{j,a,s,w,If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]}<>j]~StringTake~{3,-2}&
```
### Explanation
```
j=" ";k=Except@j
```
Set `j` to a whitespace character(s). Set `k` to the pattern "not `j`" (= non-whitespace character).
```
j<>j<>#<>j
```
Prepend two whitespace(s) and append one whitespace(s) to the input.
```
j~~a:k...~~s:j..~~w:k..~~"(s)"~~j
```
For a substring(s) matching the pattern:
1. One whitespace(s), followed by
2. a length-zero or longer substring consisting of only non-whitespace character(s) (quantifier) (call this `a`), followed by
3. a length-one or longer substring consisting of only whitespace character(s) (call this `s`), followed by
4. a length-one or longer substring consisting of only non-whitespace character(s) (word) (call this `w`), followed by
5. the string `"(s)"`, followed by
6. a whitespace(s)
```
If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]
```
If `a` is not one of the singular word(s), evaluate to `"s"`, otherwise `""`.
```
StringReplace[..., ... :>{j,a,s,w,If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]}<>j]
```
Replace the matching pattern with `j`, `a`, `s`, `w`, `If[FreeQ[a,"a"|"an"|"1"|"one"],"s",""]`, and `j` joined together.
```
... ~StringTake~{3,-2}
```
Take from position 3 to position -2 (1-indexed; negative indices count from the end). This is because we added three space(s) in the beginning.
[Answer]
# [Python 3](https://docs.python.org/3/), 94 bytes
```
lambda s,r=re.sub:r(r"\(s\)( |$)","s",r(r"\b(an?|1|one)(\s+)(.+)\(s\)",r"\1\2\3",s))
import re
```
[Try it online!](https://tio.run/##lZPRasIwFIavzVMcwmAJ1kLnnaC73jMsY6Sa2kBMw0mcDHz37lRbJ06kS@lFT//vT86fJHynuvHz1u5CgwnQsGqpWqd35UZDzHCJJo/7coECuRJRSQHHJ8kzHnl2qpVC@9djcWy8kULFqRT5VJ6UJOCqUC9qzrMoJbtM0SYT0@daRxNhCZxzlmqDBjS96dBAqT09IkrQfgNkDM4ENOta731Xna3gHhDvyM/Oz/TrxjXVaMggBGe6Uj8G5yvgVh3ZLfR4kGXPdSsbzxJ3AVhxtfpR6ACwvgkYvdieowCjwS/TVRu0W@u1O2sOtaX9C3p91QdxY4DIin910jUyAJS7/0d8p9x7gNXGEeSa0SEMAHsDvaOjQB8Jtd8afDg5kX8ARuf7vVjMig/GqgbBWdpV6@H3DuQxOJsEV57LBZs4U6UMKME60e3o5INgtuKSTQJan0QlOl0eE9ogpJTtDw "Python 3 – Try It Online")
-4 bytes thanks to i cri everytim (I think this is acceptable)
[Answer]
# [Retina](https://github.com/m-ender/retina), 53 bytes
```
(( |^)(a|an|1|one) [^ ]*)\(s\)( |$)
$1
\(s\)( |$)
s$1
```
[Try it online!](https://tio.run/##K0otycxL/P9fQ0OhJk5TI7EmMa/GsCY/L1VTITpOIVZLM0ajOEYTKKmiyaViyIXEK1Yx/P/fUyExVyFRobikKDEvPbWo@D8A "Retina – Try It Online")
[Answer]
# Mathematica, 313 bytes
```
(Table[If[StringLength@z[[i]]>3&&StringTake[z[[i]],-3]=="(s)",z[[i]]=StringDrop[z[[i]],-3];t=1;While[z[[i-t]]=="",t++];If[FreeQ[{"a","an","1","one"},z[[i-t]]],z[[i]]=z[[i]]<>"s"]],{i,2,Length[z=StringSplit[#," "]]}];If[StringTake[z[[1]],-3]=="(s)",z[[1]]=StringDrop[z[[1]],-3];z[[1]]=z[[1]]<>"s"];StringRiffle@z)&
```
[Answer]
## Perl 5, 43 + 1 (-p) = 44 bytes
```
s/\b((one|1|an?) +)?\S+\K\(s\)\B/"s"x!$1/ge
```
Match every `(s)` at end of word, replace it with `!$1` (1 or 0) esses.
[Answer]
# Pyth - 53 bytes
Follows the algorithm pretty much as it is.
```
K+kczdjdt.e?q"(s)"gb_2+<b_3*\s!}@Ktk[\a"an""one"\1)bK
```
[Try it online here](http://pyth.herokuapp.com/?code=K%2Bkczdjdt.e%3Fq%22%28s%29%22gb_2%2B%3Cb_3%2a%5Cs%21%7D%40Ktk%5B%5Ca%22an%22%22one%22%5C1%29bK&input=there+are+two+banana%28s%29+and+one+leprechaun%28s%29&debug=0).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~52 51~~ 49 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Jelly has not got one regex(s) atom
```
Ṫ
Ñ;”s
Ṫḣ-3
UṪw“)s(”⁼1
“µḣ⁴µuʠg*»ḲċḢ‘×Ç‘
⁶;ḲÇĿ2ƤK
```
A full program accepting a string (using Python formatting if multiline or containing quotes) and printing the output.
**[Try it online!](https://tio.run/##y0rNyan8///hzlVchydaP2qYW8wFZD/csVjXmCsUyCp/1DBHs1gDKPGocY8hF5B3aCtQ9lHjlkNbS08tSNc6tPvhjk1Huh/uWPSoYcbh6YfbgRTXo8Zt1kDhw@1H9hsdW@L9//9/38Ti5PwSjWJNhcSiVAUjhaTEPCAE8/NSFAwVclILilKTMxJL80BiCnp6egoKSaUlCvl5qQqZxQq5mcVA8cy8dIVEheLEUhAnMT0VpLQoPydHB2xIYp5CYkFRPtiAkvx8RQA "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##XU69SgNBEO73KaYzESyiZZ5ArC0sxzjcnqx7x@7FI92dTQorKy0URK3EShI5iSDchRS@xe6LrJMLScQZlvlmvh/2nJQaheA@X0Vz0/fFgxWMXfW8dyCOGeW@uO/aDhO@/OoJ3uops76c1NPhz2O0W89c9T6/dtWTL@6a22bMQ/jyo8/nZjz/3l@8HAU3mzBx9XYSQibJECC/LE/gFDV3x3YB9RkkmkBRamggcaj5Klr1jgX8p8ykIU5JU0VL2QYsEzZLb2sSKyQ425K5JOBKTBzFGhW0lcs4I5viYGX960W9zZSkeKhEHAJe8Ld4yQzqiEyrhDX/Cw "Jelly – Try It Online").
### How?
```
Ṫ - Link 1, tail: two words (list of lists)
Ṫ - tail
Ñ;”s - Link 2, tail and replace last three chars with an 's': two words (list of lists)
Ñ - call the next link (3) as a monad
”s - literal 's'
; - concatenate
Ṫḣ-3 - Link 3, tail and remove the last three chars: two words (list of lists)
Ṫ - tail
-3 - literal minus three
ḣ - head from index (1-indexed and modular)
UṪw“)s(”⁼1 - Link 4, tail ends with "(s)"?: two words (list of lists)
U - upend (reverse each word)
Ṫ - tail
“)s(” - literal [')', 's', '('] - that is "(s)" reversed
w - index of first sublist equal to that or 0 if not found
1 - literal one
⁼ - equal?
“µḣ⁴µuʠg*»ḲċḢ‘×Ç‘ - Link 5, categorise: two words (list of lists)
“µḣ⁴µuʠg*» - compression of string "a 1" + word " an" + word " one"
Ḳ - split on spaces = ["a", "1", "an", "one"]
Ḣ - head (the first word)
ċ - count occurrences (of head in the list - either 0 or 1)
‘ - increment
Ç - call the last link (4) as a monad - i.e. f(two words)
× - multiply
‘ - increment - so we have: 1 for ["1", "blah"],
- 2 for ["blah", "blah(s)"] or 3 for ["1", "blah(s)"]
⁶;ḲÇĿ2ƤK - Main link: list of characters, the string
⁶ - literal space character
; - concatenate (place a space at the beginning as we want to inspect pairs)
Ḳ - split on spaces (giving an empty list at the start)
2Ƥ - for all infixes of length two:
Ŀ - call the link at the given index as a monad:
Ç - call the last link (5) as a monad
K - join the result with spaces
- implicit print
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~91~~ ~~83~~ 96 bytes
```
s->s.replaceAll("((^| )(an?|1|one) +\\S+)\\(s\\)(?= |$)","$1").replaceAll("\\(s\\)(?= |$)","s");
```
[Try it online!](https://tio.run/##nZLBTgIxEIbvPMVkQ2IbZBPOKMSjB/FAPLmaDMvAFkvbtLPgRnh27AKJQT3sMr01/zf9pu0KN9i3jsxq/nFw5UyrHHKNIcATKgNfHYgVGDnuL5RBDatIpCUrnS5Kk7OyJn0x6KtnRx7Z@rspe2WWI5jA/SH0RyH15DTm9KC1SIR434EUaMa7wc4aktDLsmlPZpkIWSbF@B52XZncJt1BIi/IP4mQyOGh1ht2jpZn@7Psxqo5rOMM4uTz@gbol0GeR6prWgWmdWpLTl2MsDZikqJzuhIJF@QpEgS8tTBDE5eINJo5RG3Q5DzlBZYm7iZSDpt3vQmAvzpy4SmeFkPUpl1roDZvDQ1@ZBszJ6JxPN5lIL@hOme9Wh4/2rG2hWIKLn6CVsrXOKNpfzdcqACqflCuOW4MPgKuI1UzHs2SfMtTPVf9q17zH7Y/s58XPfad/eEb "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 56 + 1 (`-p`) = 57 bytes
```
s/\b(an?|1|one) +\S+\K\(s\)(?= |$)//g;s/\(s\)( |$)/s$1/g
```
[Try it online!](https://tio.run/##XY5PC8IwDMXv@xQ5CG6Ibjt4EvEs4slrL1HDOqhpaate9tmtWcU/mFKal7z3o468WaYUanUskTdDO1imCmbqMFM7VQZVlZs1DJOqrruVuPIk6zBp6y6lqMkToNx4t3BEllOGCpDPICgw5DydNF5ZpkV2TwPgnzNqT0JxztBo@zQj4SPab6h4dYWwA/kbgZT1fdczGsh1132k4PD0iv5mkb9MTUYeY4st4EW@JSJ65I58dsJ7/7Au9pZDmu@Xi6Zt0tw9AQ "Perl 5 – Try It Online")
[Answer]
## JavaScript (ES6), ~~88~~ 87 bytes
```
a=>a.replace(/(\S+)( +)(\S+)\(s\)/g,(m,f,s,w)=>f+s+w+(/^(a|an|1|one)$/.exec(f)?'':'s'))
```
Explanation coming soon.
[Answer]
## JavaScript (ES6), 84 bytes
```
s=>s.replace(/((^|\S+ +)\S+)\(s\)(?!\S)/g,(_,a)=>a+(/^(1|an?|one) /.test(a)?'':'s'))
```
Here's an interesting way to rearrange the last part, which is sadly 2 bytes longer:
```
s=>s.replace(/((^|\S+ +)\S+)\(s\)(?!\S)/g,(_,a)=>a+'s'.slice(/^(1|an?|one) /.test(a)))
```
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 82 bytes
```
s=s.replace(/(\S+ +(\S+))\(s\)\B/g,(_,a)=>a+("s"[+/^(1|one|an?)\b/i.test(a)]||""))
```
[Try it online!](https://tio.run/##XVHBbsMgDL3nKywuA6VL1nOWTdpt5x2bbnITL2GjgIC0mpR/zyCNtK5GgP14fgbzhSf0rZM23HsrO3JHo7/pZy5LwK6jDpgjq7ClmntRPzH4NA5GT3AgZc7ApY6ICeREdkIHVo0O1YU7@9oXazYvefOWQ55WIRruG9G8lP2Gf2wwUjHnzLNdXr7z7WQ0TaifRXMoZRHIB45iP02MCTFXqYjUdgxQZ6zJwkCOAOMMZwMH1HHE4oC6g6gDiqyjdsBRR7TRa8KdB7whh8FRFLJW0cq89pPUdbz9y07hJUherObJnQiiGSd7qVHBYudBxrfY1ItV40YE9b8SYZAeZLpoSFBI2CvgMQIpdKh7ciuXFd4qGThrNBNVlsU/4kujoIaHDai4LT0rFOk@DFU8eAQVtzwXGUBrtDeKCmV6fvlAvtB3ci9ENf8C "JavaScript (SpiderMonkey) – Try It Online")
### 78 Byte version (less robust)
```
s=s.replace(/(\S+ +(\S*))\(s\)/g,(_,a)=>a+("s"[+/^(1|one|an?)/i.test(a)]||""))
```
This is a modified version of ETHproductions' (I don't have 50 rep.)
### Explanation
* `/(\S+ +(\S+))\(s\)/g` - the actual pattern to look for (`amount object(s)`)
* `(_,a)=>a` - `_` is a catch all variable, `a` is the `(\S+ +(\S+))`
* `"s"[+/^(1|one|an?)/i.test(a)]||""` - instead of slicing the array, just make a dummy array and get the index (`+/.../.test` returns a number)
+ should `"s"[+/^(1|one|an?)/i.test(a)]` return `undefined` (`true`, or `1` for the test) return `""`
] |
[Question]
[
Sometimes, I have lists of constant matrices in my code:
```
[ [[1, 0],
[0, 1]],
[[1, 0],
[0,-1]],
[[0, 1],
[1, 0]],
[[0,-1],
[1, 0]] ]
```
That's a terrible use of screen real estate. I'd much rather write them next to each other:
```
[ [[1, 0], [[1, 0], [[0, 1], [[0,-1],
[0, 1]], [0,-1]], [1, 0]], [1, 0]] ]
```
You'll find that this is still a syntactically valid nested list, it's just no longer rectangular and it has a very different structure (in particular, it gets deeper every time I add a matrix larger than 1x1). However, it's still possible to reconstruct the initial list of matrices from this new list.
So that I can use this syntax in the future, I need you to write some code which converts arrays that were written in a horizontal arrangement to the list of matrices they represent.
To make sure that answers don't perform 2D pattern matching on the layout in the source code, the input will be given either as just the array object, or if you take a string representation, then it will not contain any whitespace indicating how the literal was written in the code. So you'd get some input like this:
```
[[[1, 0], [[1, 0], [[0, 1], [[0,-1], [0, 1]], [0,-1]], [1, 0]], [1, 0]]]
```
And the output should be the following array or its string representation (again, no further layout is needed):
```
[[[1, 0], [0, 1]], [[1, 0], [0,-1]], [[0, 1], [1, 0]], [[0,-1], [1, 0]]]
```
This is the first and easier part of a two-part challenge. In this one, you may assume that all matrices are square and have the same dimensions and that they are properly aligned next to each other. In the second part we'll relax these assumptions.
## Rules
The input will be a nested list or its canonical string representation (in your language of choice), and you should output the result in the same format. The result will always contain at least one matrix, and the matrices can be as small as 1x1. The matrices will only contain (signed) integers with absolute value less than 128.
You may write a [program or a function](https://codegolf.meta.stackexchange.com/q/2419) and use any of the [standard methods](https://codegolf.meta.stackexchange.com/q/2447) of receiving input and providing output.
You may use any [programming language](https://codegolf.meta.stackexchange.com/q/2028), but note that [these loopholes](https://codegolf.meta.stackexchange.com/q/1061/) are forbidden by default.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins.
## Test Cases
Each test case has a) the list matrices laid out nicely next to each other as they would be in the code (this is *not* your input), b) the unformatted list without the extraneous whitespace (*this* is your input), c) the expected output.
```
Pretty: [ [[0]] ]
Input: [[[0]]]
Output: [[[0]]]
Pretty: [ [[-1]], [[0]], [[1]] ]
Input: [[[-1]],[[0]],[[1]]]
Output: [[[-1]],[[0]],[[1]]]
Pretty: [ [[1, 0], [[1, 0], [[0, 1], [[0,-1],
[0, 1]], [0,-1]], [1, 0]], [1, 0]] ]
Input: [[[1,0],[[1,0],[[0,1],[[0,-1],[0,1]],[0,-1]],[1,0]],[1,0]]]
Output: [[[1,0],[0,1]],[[1,0],[0,-1]],[[0,1],[1,0]],[[0,-1],[1,0]]]
Pretty: [ [[1, 0, 0], [[ 127, 63, 31], [[1, 0, 0], [[0, 0, 0],
[0, 1, 0], [ 15, 0, -15], [0, 0, 1], [0, 0, 0],
[0, 0, 1]], [ -31, -63, -127]], [0, 1, 0]], [0, 0, 0]] ]
Input: [[[1,0,0],[[127,63,31],[[1,0,0],[[0,0,0],[0,1,0],[15,0,-15],[0,0,1],[0,0,0],[0,0,1]],[-31,-63,-127]],[0,1,0]],[0,0,0]]]
Output: [[[1,0,0],[0,1,0],[0,0,1]],[[127,63,31],[15,0,-15],[-31,-63,-127]],[[1,0,0],[0,0,1],[0,1,0]],[[0,0,0],[0,0,0],[0,0,0]]]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~15~~ ~~13~~ 11 bytes
```
Fðs⁹œsZµḢḢL
```
[Try it online!](https://tio.run/nexus/jelly#@@92eEPxo8adRycXRx3a@nDHIiDy@X@4/VHTmqOTHu6cAaSzHjXMObTt0LZHDXMVHu7YDuQp@CYWKORk5mUrJOalKBQUZeaVKARUlmTk56kXKxSXAPnpCkWpBUWpxal5JYklmfl5xXr//0dzKURHRxvExsbqgFm6hkAWWABIGsKFDXUMwAIQykDHEELpgmgQD0xB9ILUwCiEbqh@I3MdM2MdY0OoYTDjIAygQWDa0FQHZJgpWAhiF0IJ1DZdY0MdXaBRukAjY@F64SpjY7liAQ "Jelly – TIO Nexus")
### Background
Like most things, this challenge is rather simple once you've figured out what you have to do. And I eventually did, after three deletions and one rollback...
First, we must figure out the dimensions of the matrices. That's easier done than said: the first element of the first element is the first row of the first output matrix, so its length is equal to the number of columns of the square output matrices.
For example, if the input is
```
[ [[1, 0, 0], [[ 127, 63, 31], [[1, 0, 0], [[0, 0, 0],
[0, 1, 0], [ 15, 0, -15], [0, 0, 1], [0, 0, 0],
[0, 0, 1]], [ -31, -63, -127]], [0, 1, 0]], [0, 0, 0]] ]
```
the first element of the first element is `[1, 0, 0]`, whose length is **ℓ = 3**.
If we flatten the input and split it into chunks of that length, we get all rows of the output matrices, albeit in the wrong order. For our example input, this gives
```
[ [1, 0, 0], [127, 63, 31], [1, 0, 0], [0, 0, 0],
[0, 1, 0], [ 15, 0, -15], [0, 0, 1], [0, 0, 0],
[0, 0, 1], [-31, -63, -127], [0, 1, 0], [0, 0, 0] ]
```
To obtain the final output, we must first split the row array into **ℓ** chunks of equal length. For our example input, this gives
```
[ [[1, 0, 0], [127, 63, 31], [1, 0, 0], [0, 0, 0]],
[[0, 1, 0], [ 15, 0, -15], [0, 0, 1], [0, 0, 0]],
[[0, 0, 1], [-31, -63, -127], [0, 1, 0], [0, 0, 0]] ]
```
Each column is now one of the output matrices, so transposing the resulting matrix of arrays is all that's left to do. For our example input, that gives
```
[
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]],
[[127, 63, 31],
[ 15, 0, -15],
[-31, -63, -127]],
[[1, 0, 0],
[0, 0, 1],
[0, 1, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
]
```
as desired.
### How it works
```
Fðs⁹œsZµḢḢL Monadic link. Argument: A (ragged array)
F Monadic chain. Argument: A
F Flatten A. This yields the vector V.
µḢḢL Monadic chain. Argument: A
Ḣ Head; retrieve the first element of A.
Ḣ Head; retrieve the first element of the first element of A.
L Compute ℓ, the length of the resulting array.
ðs⁹œsZ Dyadic chain. Left argument: V. Right argument: ℓ
s⁹ Split V into chunks of length ℓ.
œs Split the result into ℓ chunks of equal length.
Z Zip/transpose the result.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
CcJlhhQc.nQJ
```
This is a port of my Jelly answer.
[Try it online!](https://tio.run/##TY2xDoIwEIZn@xQX4tgWKkEGiYsbGzPpgIApCQGiNerT1/Za0KVf7/L/312bhzJto@EMt@HNl49WUBTAzaUtR6Wqlk9VaTghLzWMPdz7poNhWp76BN1MdvG86NiV8LH1f0sB0R6zEenmqTd1XSdSSmLJhJQUR/uKsBQ0wdEjocKDOboJ4Zsus2LthvYhp8eUpiKoVpn/WA1SZNSpMlz5S79IuMVSQZlVMauUW3dL2rtf "Bash – Try It Online")
### How it works
Pyth parses the program as follows (pseudo-code).
```
C(c(J = l(h(h(Q))), c(.n(Q), J)))
```
**Q** is a variable that holds the input. **J** is an undefined variable.
First `J = l(h(h(Q)))` stores the length of the head (first element) of the head of **Q** in **J**.
Then, `.n(Q)` flattens **Q**, and `c(..., J)` splits the result into pieces of length **J**.
Afterwards, `c(J, ...)` splits the result in **J** pieces.
Finally, `C(...)` transposes the result.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 29 bytes
```
.xj\,sCcJh-UJ:z"\B,"3x\[@R1Jz
```
[Test suite.](http://pyth.herokuapp.com/?code=.xj%5C%2CsCcJh-UJ%3Az%22%5CB%2C%223x%5C%5B%40R1Jz&test_suite=1&test_suite_input=%5B%5B%5B0%5D%5D%5D%0A%5B%5B%5B-1%5D%5D%2C%5B%5B0%5D%5D%2C%5B%5B1%5D%5D%5D%0A%5B%5B%5B1%2C0%5D%2C%5B%5B1%2C0%5D%2C%5B%5B0%2C1%5D%2C%5B%5B0%2C-1%5D%2C%5B0%2C1%5D%5D%2C%5B0%2C-1%5D%5D%2C%5B1%2C0%5D%5D%2C%5B1%2C0%5D%5D%5D%0A%5B%5B%5B1%2C0%2C0%5D%2C%5B%5B127%2C63%2C31%5D%2C%5B%5B1%2C0%2C0%5D%2C%5B%5B0%2C0%2C0%5D%2C%5B0%2C1%2C0%5D%2C%5B15%2C0%2C-15%5D%2C%5B0%2C0%2C1%5D%2C%5B0%2C0%2C0%5D%2C%5B0%2C0%2C1%5D%5D%2C%5B-31%2C-63%2C-127%5D%5D%2C%5B0%2C1%2C0%5D%5D%2C%5B0%2C0%2C0%5D%5D%5D&debug=0)
## How it works
```
.xj\,sCcJh-UJ:z"\B,"3x\[@R1Jz
z input
: 3 split at matches of the following regex
"\B," /\B,/
J store at J
U [1,2,...,len(J)]
J J
@R1 take the second character of each
substring in J
x\[ indices of all occurrences of "["
- filter away the elements in ^ from the
elements in ^^ to find the first substring
which does not start with "[["
h the first element
note: this will generate an error if
all substrings start with "[[", e.g. in the
first example. We will deal with the error later.
cJ split J in groups of the specified length
C transpose ^
s flatten |
j\, join with "," |
.x if the above code generated an error (|), return
the following instead:
z the input
```
## Algorithm
Let's work on the input `[[[1,0],[[1,0],[[0,1],[[0,-1],[0,1]],[0,-1]],[1,0]],[1,0]]]`.
We will be using pure string operations here.
Firstly, we split the input at the commas which are not part of the deepest list (this is done by splitting at the regex `\B,`):
```
[[[1,0]
[[1,0]
[[0,1]
[[0,-1]
[0,1]]
[0,-1]]
[1,0]]
[1,0]]]
```
Then, we find the index of the first substring which does not start with `[[` (this is done by checking whether the character at index `1` is `[`). In this case, it is `4`, because the substring at index 4 is `[0,1]]` which does not start with `[[`.
Then, we group the substrings in groups of 4, and then transpose:
```
[[[1,0]
[0,1]]
[[1,0]
[0,-1]]
[[0,1]
[1,0]]
[[0,-1]
[1,0]]]
```
And then we join them with commas:
```
[[[1,0],[0,1]],[[1,0],[0,-1]],[[0,1],[1,0]],[[0,-1],[1,0]]]
```
[Answer]
## JavaScript (ES6), ~~132~~ 130 bytes
```
f=(a,n=1)=>a[0][n]?a[0][n][0][0]?f(a,n+1,a[0].splice(n,1,...a[0][n])):n>1?[...Array(n)].map((_,i)=>a[0].filter((_,j)=>j%n==i)):a:a
```
There are four cases:
* A 1×n array, which is just returned (this is the first test, but inverted)
* An m×n array which hasn't been flattened yet, which we recursively flatten by one step, counting `n` at the same time.
* An m×n array which has been flattened, where we filter out every `n`th element.
* An m×1 array, which is just returned
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
A port of [**Dennis**' answer](https://codegolf.stackexchange.com/a/121901/34388). Code:
```
¬¬g¹˜sô¬gäø
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#PYyxDYAwDAQXeks2ETBM5JoBWIeSMiUFtEnJUOEVhVR/f7K/5pTTlp/32MtFKme5a40xGhTqIEwrloBgrfxWOyispc0UYnNTlD11dIIEg3BKOOnjd1y6fw "05AB1E – TIO Nexus")
[Answer]
## Mathematica, 104 bytes
```
l=Length;(m=l@#[[1,1]];n=l@Flatten@#/m;Table[Partition[#~ArrayReshape~{n,m},n/m][[j,i]],{i,n/m},{j,m}])&
```
**Input**
>
> {{{1, 0}, {{1, 0}, {{0, 1}, {{0, -1}, {0, 1}}, {0, -1}}, {1, 0}}, {1,
> 0}}}
>
>
>
**output**
>
> {{{1, 0}, {0, 1}}, {{1, 0}, {0, -1}}, {{0, 1}, {1, 0}}, {{0, -1}, {1,
> 0}}}
>
>
>
**input**
>
> {{{1, 0, 0}, {{127, 63,
> 31}, {{1, 0,
> 0}, {{0, 0, 0}, {0, 1, 0}, {15, 0, -15}, {0, 0, 1}, {0, 0,
> 0}, {0, 0, 1}}, {-31, -63, -127}}, {0, 1, 0}}, {0, 0, 0}}}
>
>
>
**output**
>
> {{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{127, 63, 31}, {15,
> 0, -15}, {-31, -63, -127}}, {{1, 0, 0}, {0, 0, 1}, {0, 1, 0}}, {{0,
> 0, 0}, {0, 0, 0}, {0, 0, 0}}}
>
>
>
{{{0}}} and {{{-1}}, {{0}}, {{1}}} work,too
-11 bytes thanks to Martin Ender
] |
[Question]
[
I am a *very* casual code golfer, and don't often see posts until they show up in the "Hot Network Questions" sidebar over on StackOverflow. Usually, I'm late to the game, and since the only language I know is Python, there is little point in me answering as there are already several Python answers. Your challenge is to figure out if a question is worth me answering.
**Input:**
* Your code (function or program) will take one input parameter `i`
**Output:**
* Truthy or Falsey value for question id `i`. Output Truthy if question has more than 5 answers, greater than 3 question score, and one or less answer in Python (no distinction between version).
**Rules/Clarifications:**
* Input format can be anything reasonable (stdin, file, command line), but should be specified in your answer. Data types and leading/trailing whitespace doesn't matter.
* Assume question id is valid for `codegolf.stackexchange.com`.
* Ignore language specific question requirements. (i.e. if a question meets votes and answers, and has no Python answers because it is Java only, it still results in Truthy).
* An answer qualifies as a Python answer if "python" (case insenstive) occurs anywhere before the first newline of the post.
* This is code golf, so shortest code in bytes wins.
**Sample Cases\***
```
id = 79082 => True
id = 78591 => False (less than 5 answers, also hella hard)
id = 78410 => True
id = 76428 => False (greater than 1 Python answer)
id = 78298 => False (not high enough question score)
```
*\*Verified at time of posting, may have changed*
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~167~~ ~~160~~ ~~159~~ ~~158~~ ~~156~~ ~~154~~ 143 bytes
~~Damn, almost as long as a normal language...~~
Crap... ~~longer~~ ~~currently beating the the [Ruby answer](https://codegolf.stackexchange.com/a/79285/34388) by *1* byte.~~
~~Now longer than the Ruby answer, ***argh!***.~~
I probably should go to bed right now.
Thanks to @wnnmaw for saving 1 byte and thanks to @R. Kap for saving another 2 bytes!
### Code:
```
’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ÐÏg.´¢/q/'+•œ_#()).‚Ø())’.e©’„à="Ž»"’DU¢®…ƒŠ‡¡`99£þs\®X¡¦vy’„à="‚¬-„¹"’¡¦'>¡¦¦¬l’±¸’¢s\}rUV)O2‹X5›Y3›)P
```
Or with more readability:
```
’£Ø ˆå§¾.‡¢ as g;#.¾¿„–(g.ˆåƒÛ('·Ç://ÐÏg.´¢/q/'+•œ_#()).‚Ø())’
.e©
’„à="Ž»"’
DU¢®
“ƒŠ‡“
¡`99£þs\®X¡¦
v
y’„à="‚¬-„¹"’¡¦'>¡¦¦¬l’±¸’¢s\}rUV)O2‹X5›Y3›)P
```
### Explanation:
First of all, a lot of text is being compressed here, which translates to good old Python. The uncompressed version is:
```
"import urllib.request as g
f=g.urlopen('http://ppcg.lol/q/'+pop_#())
#.append(f.read())"
.e©“class="answer"“¢®"useful and clear"¡`99£þs\®“class="answer"“¡¦vy“class="post-text"“¡¦'>¡¦¦¬l"python"¢s\}rUV)O2‹X5›Y3›)P
```
This part:
```
import urllib.request as g
stack.append(g.urlopen('http://ppcg.lol/q/'+pop_stack()).read())`
```
actually pops a stack value, copies it into the url and fetches all HTML data. The HTML data is pushed on top of the stack using `#.append(f.read())`.
We count the **number of answers**, by count the number of occurences of `class="answer"`.
To count the number of votes, we just split the data at "useful and clear" and keep only the digit values of `[0:99]` using `®"useful and clear"¡`99£þ`. This is the number of upvotes.
Eventually, we need to check every answer if the text `"Python"` exists before the closing header text. To get all answers, we just split the data on `class="post-text"` and split each of them again on `<`. We remove the first two elements to get the part in which the language is displayed and check if the lowercase version is in this string.
So, now our stack looks like this for id = `79273`:
```
`[6, '14', 0, 0, 0, 1, 0, 0]`
│ │ └───────┬──────┘
│ │ │
│ │ is python answer?
│ │
│ └── number of upvotes
│
└─── number of answers
```
This can also be seen with the `-d`ebug flag on in the interpreter.
So, it's just a matter of processing the data:
```
rUV)O2‹X5›Y3›)P
r # Reverse the stack
U # Pop the number of answers value and store into X
V # Pop the number of upvotes value and store into Y
)O # Wrap everything together and sum it all up
2‹ # Check if smaller than 2
X5› # Push X and check if greater than 5
Y3› # Push Y and check if greater than 3
)P # Wrap everything into an array and take the product.
This results into 1 if and only if all values are 1 (and not 0).
```
Uses **CP-1252** encoding. You can download the interpreter [here](https://github.com/Adriandmen/05AB1E).
[Answer]
# Python 3.5, 280 272 260 ~~242~~ 240 bytes:
(*Thanks to [Adnan](https://codegolf.stackexchange.com/users/34388/adnan) for the trick about using the `*` operator in comparisons resulting in 2 saved bytes!*)
```
def g(o):import urllib.request as u,re;R=re.findall;w=bytes.decode(u.urlopen('http://ppcg.lol/q/'+o).read());print((len(R('(?:<h[0-9]>|<p>).*python',w.lower()))<2)*(int(R('(?<="vote-count-post ">)[0-9]+',w)[0])>3)*w.count('answercell">')>5)
```
Simple enough. Uses Python's built in `urllib` library to go to the question's site, and then uses regular expressions to find the vote count, answer count, and the count of Python specific answers in the decoded text returned from the website. Finally, these values are compared against the conditions required to return a `truthy` value, and if they satisfy all the conditions, then `True` is returned. Otherwise `False` is.
The only thing I may be worried about here is that the regular expressions give a lot of lee way in the terms of the number of python specific answers to save bytes, so it may be a bit inaccurate at times, though it's probably good enough for the purposes of this challenge. However, if you want a much more accurate one, I have added one below, although its longer than the one above. The one shown below is currently 298 bytes since it uses a much longer regular expression–one which you couldn't know how long it took me to discover–for counting Python answers than my original function for the sake of accuracy. This one should work for about at least 80% to 90% of all test cases thrown at it.
```
def g(o):import urllib.request as u,re;R=re.findall;w=bytes.decode(u.urlopen('http://ppcg.lol/q/'+o).read());print(len(R('(?<=answercell">).*?(?:<h[0-9]>|<strong>)[^\n]*python[^\n]*(?=</h[0-9]>|</strong>)',w.lower()))<2and int(R('(?<="vote-count-post ">)[0-9]+',w)[0])>3and w.count('answercell">')>5)
```
But, what about those questions with multiple pages of answers? Neither of the above will work very well in that situation, if, say, 1 python answer is on the first page and another is on the second. Well, I took the liberty to fix this issue by creating another version of my function (shown below) that checks *every page* of answers, if multiple ones exist, for Python answers, and it has done quite well on many of the test cases I have thrown at it. Well, without further ado, here is the new and updated function:
```
def g(o):
import urllib.request as u,re;R=re.findall;w=bytes.decode(u.urlopen('http://ppcg.lol/q/'+o).read());t=0if len(re.findall('="go to page ([0-9]+)">',w))<1else max([int(i)for i in re.findall('="go to page ([0-9]+)">',w)])
if t<1:print(len(R('(?<=answercell">).*?(?:<h[0-9]>|<strong>)[^\n]*python[^\n]*(?=</h[0-9]>|</strong>)',w.lower(),re.DOTALL))<2and int(R('(?<="vote-count-post ">)[0-9]+',w)[0])>3and w.count('answercell">')>5)
else:
P=[];U=[];K=[]
for i in range(2,t+2):P.append(len(R('(?<=answercell">).*?(?:<h[0-9]>|<strong>)[^\n]*python[^\n]*(?=</h[0-9]>|</strong>)',w.lower(),re.DOTALL)));U.append(int(R('(?<="vote-count-post ">)[0-9]+',w)[0]));K.append(w.count('answercell">'));w=bytes.decode(u.urlopen('http://ppcg.lol/questions/'+o+'/?page='+str(i)).read())
print(sum(P)<2and U[0]>3and sum(K)>5);print('# Python answers: ',sum(P));print('# Votes: ',U[0]);print('# Answers: ',sum(K))
```
Quite long, isn't it? I wasn't really going much for code golf with this, although, if you want, I can golf it down a bit more. Otherwise, I love it, and could not be happier. Oh, I almost forgot, as an added bonus, this also outputs the total number of Python answers on the question, total votes on the question, and total number of answers on the question if the question `id` corresponds to a question with more than 1 page of answers. Otherwise, if the question only consists of a single page of answers, it just outputs the `truthy/falsy` value. I really did get a bit carried away with this challenge.
These each take the question's `id` in the form of a *string*.
I would put `Try It Online!` links here for each function, but unfortunately, neither `repl.it` nor `Ideone` allow fetching of resources via Python's `urllib` library.
[Answer]
# Julia, 275 bytes
```
using Requests
f(q,p=(s,t)->JSON.parse(readall(get("https://api.stackexchange.com/2.2/questions/$q$s",query=Dict(:site=>"codegolf",:filter=>"$t"))))["items"],x=p("","")[1])=x["answer_count"]>5&&x["score"]>3&&count(i->ismatch(r"python",i["body"]),p("/answers","!9YdnSMKKT"))<2
```
This is a function that accepts an integer and returns a boolean. It connects to the Stack Exchange API and each run of the function makes 2 API requests, so don't run it too many times or you'll exhaust your 300 requests/day quota.
Ungolfed:
```
using Requests
function f(q)
# Define a function that takes two strings and returns a Dict
# that connects to the SE API
p = (s,t) -> JSON.parse(readall(get("https://api.stackexchange.com/2.2/questions/$q$s",
query = Dict(:site => "codegolf", :filter=> "$t"))))["items"]
# Get the question object
x = p("", "")[1]
# Get all answers using the `withbody` API filter
y = p("/answers", "!9YdnSMKKT")
x["answer_count"] > 3 && x["score"] > 5 &&
count(i -> ismatch(r"python", i["body"], y) < 2
end
```
[Answer]
# Racket, 339 Bytes
```
(λ(q)((λ(h)((λ(g)((λ(j)(and(>(h j'score)3)(>(h j'answer_count)5)(<(for/sum([a(g"~a/answers"q)]#:when(regexp-match #rx"(?i:python)"(h a'body)))1)2)))(car(g"~a"q))))(λ(s d)(define-values(x y b)(http-sendrecv"api.stackexchange.com"(format"/2.2/questions/~a?site=codegolf&filter=withbody"(format s d))))(h(read-json b)'items))))hash-ref))
```
There is much to golf, still.
[Answer]
# Ruby + [HTTParty](https://github.com/jnunemaker/httparty), ~~170~~ ~~146~~ ~~145~~ ~~142~~ ~~139~~ 138 + 11 ( `-rhttparty` flag) = ~~181~~ ~~157~~ ~~156~~ ~~153~~ ~~150~~ 149 bytes
I don't think there's any edge cases that would cause my regex patterns to break, I hope...
Updated to the shortlink provided by @WashingtonGuedes and discovering that HTTParty doesn't complain if I start with `//` instead of `http://`.
Updated for slightly more secure regexes. I saved bytes anyways by discovering that HTTParty response objects inherit from String, which means I don't even need to use `.body` when matching the regex!
@manatwork pointed out an accidental character addition that I had left in, and for the sake of golf, `i` has to be accepted as a String now.
Updated regexes. ~~Same length.~~ -1 byte by cutting out a paren.
```
->i{/"up.*?(\d+)/=~s=HTTParty.get("//ppcg.lol/q/"+i)
$1.to_i>3&&(a=s.scan /st.*xt".*\n(.*)/).size>5&&a[1..-1].count{|e|e[0]=~/python/i}<2}
```
Extra notes:
* The first line of an answer (which should contain the language according to the spec) is two lines after the HTML Tag with class `"post-text"`, which we matched with `st.*xt"`. A more secure version would have added a space after it, but we're sacrificing that for the sake of golf.
* HTTParty is used over the native `net/http` modules because of proper redirect handling for the given URL.
* `"up*?\d` was the shortest sequence I found that corresponded with the number of votes. We only need the first one, so thankfully answers don't affect this.
[Answer]
# Groovy, 179 161 157
```
{i->t=new URL("http://ppcg.lol/q/$i").text;a=0;p=0;(t=~/"(?i)p.{25}>\n.*python/).each{p++};(t=~/(?m)v.{13}t ">(\d+)/).each{if(it[1].toLong()>3)a++};a>5&&p<2}
```
Thanks to Timtech 17 chars saved.
Keyword *def* is also not necessary.
] |
[Question]
[
Input a String and surround it with a rounded rectangle of alternating "friendliness pellets".(`0`)
[Sandbox](https://codegolf.meta.stackexchange.com/a/19190/80214)
[](https://i.stack.imgur.com/iGnOL.jpg)
Idea originally from [Lyxal.](https://codegolf.stackexchange.com/users/78850/lyxal)
# Challenge
Given a single line non-empty String of length \$<100\$, print the string with a rounded rectangle of alternating pellets(`0`) around it.
The rectangle must be 11 lines in height.
The first line of the rectangle *must* have at least 1 pellet.
The middle line of the rectangle must be at least 13 characters long. There must be a padding of one space on each side of the text.
Strings smaller than 9 characters must be padded with spaces equally on both sides to fit the above specification.
The right side is allowed to have one extra space if the string is of even length.
The template for the output is as follows:
```
00000..... 6 spaces
0 4 spaces
0 2 spaces
0 1 space
0 no spaces
```
If the string's length is greater than or equal to 9; the first line must have \$\text{length}-8\$ pellets.
# Example Input and Output
**Input**:
>
> Hello World!
>
>
>
**Output**:
```
0000
0 0
0 0
0 0
0 0
0 Hello World! 0
0 0
0 0
0 0
0 0
0000
```
**Input**
>
> 0
>
>
>
**Output**
```
0
0 0
0 0
0 0
0 0
0 0 0
0 0
0 0
0 0
0 0
0
```
**Input**
>
> The quick brown fox
>
>
>
**Output**
```
00000000000
0 0
0 0
0 0
0 0
0 the quick brown fox 0
0 0
0 0
0 0
0 0
00000000000
```
**Input**
>
> In this world, it's KILL or BE killed
>
>
>
**Output**
```
00000000000000000000000000000
0 0
0 0
0 0
0 0
0 In this world, it's KILL or BE killed 0
0 0
0 0
0 0
0 0
00000000000000000000000000000
```
**Input**
>
> hi there
>
>
>
**Output**
```
0
0 0
0 0
0 0
0 0
0 hi there 0
0 0
0 0
0 0
0 0
0
```
# Example code in Ruby
[Try it online!](https://tio.run/##vVLLTsMwELz7K4bkkvQR2goQqIQzf8ABcXCTTWtpa0e2C6oQ3x6cBxBy5IAPlj2zj9nR2tPu3DQyf75abBbrxeoFMVwtCwKT3vsDvEFhSXpCoWzBJITzNt@Td1lxMMd6Kxg5Apb1CVsRo7ZKe1TKOg9WmmAq1MQckkTPRYhmN0JV4Pv8Dv5AGvXJO0SrCMSOvn@zhJe3KUiXAuGE4korrySjlt6T1aIyFjqgkCgNuqifHhrzUGTePpPrpU5/0xgETJL6li33MFCdmK8aXUkhRpJK5WqW59YFpfd4U8G3zkTXjziZsJeTrNdLTi83aVaxCTPM2/RwD@RmIAtS3KITYxC/h/APtHAQIuKJLdidPCy9knVUjjzKBuxfvRpZxXLYicTJI0G60Zqkf1@OpnkM@2XwZCyXF58)
```
a=[4,2,1,0] # space length to create circle
str=gets.chomp;
l = str.length;
# print first line of pellets
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end
# initial pattern
for n in a do
print " "*n +"0"+" "*(5-n)
print " " if l<=9
print " "*(l-8) if l>9
puts " "*(5-n) +"0"
end
# display string with spaces
if l<9 then puts "0"+" "*((11-l)/2).floor + str + " "*((12-l)/2).ceil + "0" else puts "0 #{str} 0" end
#initial pattern but reversed
for n in a.reverse do
print " "*n +"0"+" "*(5-n)
print " " if l<=9
print " "*(l-8) if l>9
puts " "*(5-n) +"0"
end
# last line(same as first line)
print " "*6
if l<=9 then puts "0" else puts "0"*(l-8) end
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 40 bytes
```
≔⌈⟦¹⁻Lθ⁸⟧η×η0↘↘0→↘00↓00‖OO←η‖O↓J⊘⁻⊖ηLθ⁵θ
```
[Try it online!](https://tio.run/##fY89C8IwEIZ3f0XtdIEKOgiik@BQpEURwUEcQj2bQD5qkkb/fQxWqy4uufDcc9y9FaOm0lSEsLSW1wpKeueylXCcZEnJVWuhQFU7BleSJTNyii8ji8HWcOVgzyVaYFmSjlMSaak9wnylb2rHa@Z674M69W3@s57aV6NnO7wIrNzGoxG0eRWYF3hx3W2/Qjcd8bqVzV5DToXHM3TZVlgZlKhcJCxG67PG/7TffyWLEHIUQicHbcR5OAgjLx4 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⌈⟦¹⁻Lθ⁸⟧η
```
Calculate the number of `0`s in the top row.
```
×η0
```
Print them.
```
↘↘0→↘00↓00
```
Print the remaining `0`s on the right.
```
‖OO←η
```
Reflect the additional rows of `0`s to the left, by overlapping the top row of `0`s onto itself.
```
‖O↓
```
Reflect the `0`s downwards overlapping the middle row.
```
J⊘⁻⊖ηLθ⁵θ
```
Calculate the position of the text and print it there. This is necessary for short strings but also avoids dealing with a Charcoal bug whereby an overlapped reflection moves the cursor to the wrong place.
[Answer]
# JavaScript (ES6), ~~152 139 134~~ 133 bytes
```
s=>'64210~01246'.replace(/./g,k=>(g=i=>--i?(d=i+~k,d*=L-i+~k,s[k>g&&(L+n>>1)-i]||d&&k^6|d<0&&' ')+g(i):`
`)(L=(n=s.length)>9?n+5:14))
```
[Try it online!](https://tio.run/##bYy9TsMwGEX3PsVHB8cmP02qEIkKuxISEhXZGRCoIXYcY8sudqAMUV89LYwo29U999yP5rsJrVeHIbWOi6mjU6Asqsp1kZ/yYl1WUebFwTStwKtsJRNNGZZUUZamaos5VfFJJ/ya1ulfCi@aSYRwHVvGCpKq13HkCOm3auR3OUIRRCSWWJHNfrEnuKbY0pAZYeXQE3a7tfHNpigJmVpngzMiM07iDi8fhTEOnp03/GpJyOIfzme6oRfw@aVaDe/eHS107mdmtbMw9CrA8fc6ATVEAZ52dQ3Ow/0DaGWM4DNery6e8OKCpjM "JavaScript (Node.js) – Try It Online")
### How?
Given an input string of length \$n\$, we define \$L=\min(14,n+5)\$. This is the width of the rows of the ASCII art, including the linefeed.
For each line, we store the number of leading spaces in \$k\$ and iterate from \$i=L-1\$ to \$i=1\$. We test the sign of \$d=(i-k-1)\times(L-i-k-1)\$ to figure out which character must be drawn.
We always draw a space if \$d\$ is negative and a zero if \$d=0\$. If \$d\$ is positive, we draw a zero if \$k=6\$ (top and bottom borders) or a space otherwise (inner cells). The middle line is a special case where we attempt to get the character from the input string, at the position \$\lfloor (L+n)/2\rfloor-i\$.
For `"Hello World!"`, we have \$n=12\$ and \$L=17\$. This gives:
```
1 0
i = 6543210987654321
------0++0------ k = 6
----0++++++0---- k = 4
--0++++++++++0-- k = 2
-0++++++++++++0- k = 1
0++++++++++++++0 k = 0
0+Hello World!+0 k = 0
0++++++++++++++0 k = 0
-0++++++++++++0- k = 1
--0++++++++++0-- k = 2
----0++++++0---- k = 4
------0++0------ k = 6
```
### Commented
```
s => // s = input string
'64210~01246'.replace( // replace in the string '64210~01246'
/./g, k => ( // each character k:
g = i => // g is a recursive function taking a counter i:
--i ? // decrement i; if it's not 0:
( d = i + ~k, // d = i - k - 1
d *= L - i + ~k, // d = (i - k - 1) * (L - i - k - 1)
s[ // extract from s:
k > g && // if k is '~':
(L + n >> 1) - i // use floor((L + n) / 2) - i
// otherwise, use false
// (leading to s[false] == undefined)
] // end of lookup in s
|| // if it's undefined:
d && // use '0' if d = 0
k ^ 6 | d < 0 // or k is equal to 6 and d is non-negative
&& ' ' // otherwise, use a space
) + g(i) // append the result of a recursive call
: // else:
`\n` // append a linefeed and stop the recursion
)( // initial call to g:
L = (n = s.length) > 9 ? // if the length n of s is greater than 9:
n + 5 // define L = n + 5
: // else:
14 // define L = 14
) //
) // end of replace()
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~64~~ 54 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
4Å0Îg9‚à8-©;îךŽüÎSú.B®Éi.ºëº}I11Ig-;1‚à©ú®îð׫0.øª».∊
```
[Try it online](https://tio.run/##AW0Akv9vc2FiaWX//zTDhTDDjmc54oCaw6A4LcKpO8Ouw5fFocW9w7zDjlPDui5Cwq7DiWkuwrrDq8K6fUkxMUlnLTsx4oCaw6DCqcO6wq7DrsOww5fCqzAuw7jCqsK7LuKIiv//SGVsbG8gV29ybGQh) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6fw3OdxqYFCZbvmoYdbhBRa6h1ZaH153ePrRhUf3Ht5zuC/48C49p0PrDndm6h3adXj1oV21lYaGlem61oZg9YdWHt4FlF13eMPh6YdWG@gd3nFo1aHdeo86uv7rHNpm/z9aySM1JydfITy/KCdFUUlHQckARIRkpCoUlmYmZyskFeWX5ymk5VeAhD3zFEoyMosVykGqdRQyS9SLFbw9fXwU8osUnFwVsjNzclJTQAozMoEKU4tSlWIB).
**Explanation:**
```
4Å0 # Push a list of 4 0s: [0,0,0,0]
Î # Push 0 and the input-string
g # Pop the input, and push its length
9‚à # Pair with 9, and pop and push the maximum
8- # Subtract 8
© # Store this in variable `®` (without popping)
; # Halve it
î # Ceil it
× # Create a string of that many 0s
š # Prepend it at the front of the [0,0,0,0]-list
ŽüÎ # Push compressed integer 64210
S # Convert it to a list of digits: [6,4,2,1,0]
ú # Pad that many leading spaces to the list of 0s
.B # Box it, which adds trailing spaces to each string to equal
# their lengths
®Éi # If the value `®` is odd:
.º # Mirror each line with the last character overlapping
ë # Else (it's even instead):
º # Mirror each line without overlapping
} # Close the if-else statement
I # Push the input-string again
11 # Push 11
Ig- # Subtract the input-length from it
; # Halve it
1‚à # Pair with 1, and pop and push the maximum
© # Store it in variable `®` (without popping)
ú # Pad that many leading spaces to the input
® # Push `®` again
î # Ceil it
ð׫ # Pad that many trailing spaces
0.ø # Then surround it with leading/trailing 0
ª # And append it to the list of strings
» # Join the lines by newlines
.∊ # And mirror the entire string vertically with overlap
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ŽüÎ` is `64210`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 52 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
³L>9ȯ
L11_»2⁶ẋŒHṚjµL_⁽|hḤD©Ḥ¤⁶ẋ;W¬1¦Ø0j0ç?Ɱ⁶ẋ®¤;"ŒḄY
```
A full program which prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///QZh87yxPruXwMDeMP7TZ61Ljt4a7uo5M8Hu6clXVoq0/8o8a9NRkPdyxxObQSSB5aAlFgHX5ojeGhZYdnGGQZHF5u/2jjOoj4oXWHllgrHZ30cEdL5P///5U88xRKMjKLFcrzi3JSdBQyS9SLFbw9fXwU8osUnFwVsjNzclJTlAA "Jelly – Try It Online")**
### How?
```
³L>9ȯ - Link 1: unused argument; list of characters, Y
³ - program argument, the given text (same as T in the main Link)
L - length
>9 - greater than nine?
ȯ - logical OR with Y
L11_»2⁶ẋŒHṚjµL_⁽|hḤD©Ḥ¤⁶ẋ;W¬1¦Ø0j0ç?Ɱ⁶ẋ®¤;"ŒḄY - Main Link: list of characters, T
L - length
11_ - 11 - that
»2 - max of that and two
⁶ẋ - that many spaces
ŒH - split in two
Ṛ - reverse (get longer part on the right)
j - join with T
µ - start a new monadic chain - f(X=that)
¤ - nilad followed by link(s) as a nilad:
⁽|h - 32105
Ḥ - double -> 64210
D - digits -> [6,4,2,1,0]
© - store in register
Ḥ - double -> [12,8,4,2,0]
L_ - length (X) minus that (vectorises)
⁶ẋ - that many spaces (vectorises)
W - wrap X in a list
; - concatenate
¬1¦ - logical NOT first line
(changing spaces to 0s)
Ø0 - [0,0]
Ɱ - map across the lines with:
? - if...
ç - ...condition: call Link 1 f([0,0], line)
j - ...then: ([0,0]) join with (line)
0 - ...else a single zero
¤ - nilad followed by link(s) as a nilad:
⁶ - space
® - recall from register -> [6,4,2,1,0]
ẋ - repeat (vectorises)
;" - zip with concatenation
(prefix lines with spaces)
ŒḄ - bounce (reflect top lines to the bottom)
Y - join with newlines
- implicit print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 134 bytes
```
lambda s:'\n'.join(f'{0:{i}}{0**i*s:{"0 "[i<6]}^{max(i*2,len(s)+4,13)-(i*2or 2)}}'+'0'[i+i>10>len(s):]for i in(7,5,3,2,1,0,1,2,3,5,7))
```
[Try it online!](https://tio.run/##VYzNqsIwEEb39ynmuknSRklbf6Coax9AcKFeqJrQ0ZhoWlEJefYaES64GPjmnJnv8mxra4pOzTadrs67QwVNSTaGDI4WDVXEi9JjCF4kCSZN6XsCemucjrfhz5@rB8Uk51oa2rB0yLOC9d/EOshZCCQlgqwxxXkm5p@jcquiRIjdEz7iBc95xkWcPOYRnzDWXRyalioafxn7@d9qhLaWTn7BhdTawso6ffj9EstawvWG@xPsnL0bUPYRffcC "Python 3 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 155 bytes
```
sub f{$_=pop;substr$r=64210001246=~s,.,$"x$&.($&-6?0 .$"x(11-$&*2).0:0).$/,ger=~s,^.{6}(.),($l=y|||c-9)>0?$&.$1x$l:$&,mger,$l>0?59+5*$l:59-$l/2,$l+9,$_;$r}
```
[Try it online!](https://tio.run/##rVTbTuMwEH3nK2ajUZOAG5yqqdSWlNVKK4GANyQeykUCXIgwcdZORVFbfr04F6qkuJDVrp/mHI9nzpzYSZjkwWqqGJwzlQ4GZ0IySHWowlEwXKnpLUzmeBMmIhlqoFKJMux1Oz6l1O90e@GbIh5Ba4Ytz8FWu3dIwdPQ8f02tnY7rkcH1PVwnzwwmSVfe/Pe0vFc4iAPXxeLxV27747ooT6P/gz5AFvkWecS5JoN@nvBriaDfhv5fkeTe32CN0OUy9VESGdsHzHOBVwIye9/2BCO4ODAtq/IDuRLq6R5SEu8sw5LWEEZrsGCqHYwZWyW2OxQ775WlcdjmxpEr89Ui9Ua1WV8IGrcqx2r1at0KZhSU/rI4M80unuCWyleYpiImdnaclVnNNuwxaxttld4g5Yv8reU36LFqHpztsIT6zjWUiIFL9k9IBCltoKT49NTEBJ@/YaniHN2b33l0udlUNBUfePhm7ttzmw091/VbCyz8dwNXfz@e5T3/zHKrp1k/@lpfpT7t6fpzvP4@dXBKE4Islnihj/1v7CkAR9EGk7yXbcgExnFKViXcbZ1GVsFGymnpCySBbqQRcpTy9U7 "Perl 5 – Try It Online")
Slightly ungolfed:
```
sub f{
$_=pop; # $_ = input text
substr # args: string, offset, length, replacement
$r= # $r = result string init to empty rectangle
64210001246 # digits are spaces before first 0 each line
=~s,.,$"x$&.($&-6?0 .$"x(11-$&*2).0:0).$/,ger
=~s,^.{6}(.),($l=y|||c-9)>0?$&.$1x$l:$&,mger,
$l>0 ? 59+5*$l : 59-$l/2, # insert input text at this position
$l+9, # ...this length ($l=input length minus 9)
$_; # replacement = input
$r # return result
}
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 158 bytes
```
lambda s:'\n'.join((e:=[" "*6+"0"*(l:=len(b:=(c:=9-len(s))//2*' '+s+(c//2+c%2)*' ')-8),*[i*" "+"0"+" "*(l+10-2*i)+"0"for i in[4,2,1,0]],f'0 {b} 0'])+e[4::-1])
```
[Try it online!](https://tio.run/##VY3LTsMwEEX3fMVgCfkZ6oQKFUvZICFR0X0XaRZ5OIqpsYMTVBDi29N4g5Td3HNnzgw/U@/dw24Ic5WfZlt91G0Fo8Inh@/fvXGEaJUXCBB75EgiRqzKrXakVjlpVP6UxDBSutlkDAPmIyfNMvPmLqMR0GRHBSsMWxRRwKOKWJ7KJGOGRtT5AAaMK7YiE6mQZSk6LOG3/gOJS8p1sVUqSUs6D8G4iVQEvWprPRx9sO0tovTmv5CrtHcw9WaES1wUYCY8wtv@cIDl4/MLnI21ul1dTL2Gzy/TnKEO/uKg89@rvjeLUQe9wPkK "Python 3.8 (pre-release) – Try It Online")
] |
[Question]
[
I asked [random.org](https://www.random.org/) for 128 random integers between 0 and 232 - 1. Since the random number generator was so eager to give the first 64 numbers first, they're obviously *more random* than the other 64.
Write a full program or function that returns a truthy result when one of the following 64 integers is input:
```
[1386551069, 1721125688, 871749537, 3410748801, 2935589455, 1885865030, 776296760, 614705581, 3841106923, 434616334, 1891651756, 1128215653, 256582433, 310780133, 3971028567, 2349690078, 489992769, 493183796, 3073937100, 3968540100, 777207799, 515453341, 487926468, 2597442171, 950819523, 1881247391, 3676486536, 3852572850, 3498953201, 2544525180, 297297258, 3783570310, 2485456860, 2866433205, 2638825384, 2405115019, 2734986756, 3237895121, 1560255677, 4228599165, 3106247743, 742719206, 2409129909, 3008020402, 328113612, 1081997633, 1583987616, 1029888552, 1375524867, 3913611859, 3488464791, 732377595, 431649729, 2105108903, 1454214821, 997975981, 1764756211, 2921737100, 754705833, 1823274447, 450215579, 976175934, 1991260870, 710069849]
```
And a falsey result for the other 64 numbers:
```
[28051484, 408224582, 1157838297, 3470985950, 1310525292, 2739928315, 3565721638, 3568607641, 3857889210, 682782262, 2845913801, 2625196544, 1036650602, 3890793110, 4276552453, 2017874229, 3935199786, 1136100076, 2406566087, 496970764, 2945538435, 2830207175, 4028712507, 2557754740, 572724662, 2854602512, 736902285, 3612716287, 2528051536, 3801506272, 164986382, 1757334153, 979200654, 1377646057, 1003603763, 4217274922, 3804763169, 2502416106, 698611315, 3586620445, 2343814657, 3220493083, 3505829324, 4268209107, 1798630324, 1932820146, 2356679271, 1883645842, 2495921085, 2912113431, 1519642783, 924263219, 3506109843, 2916121049, 4060307069, 1470129930, 4014068841, 1755190161, 311339709, 473039620, 2530217749, 1297591604, 3269125607, 2834128510]
```
Any input other than one of these 128 numbers is undefined behavior.
If your solution is found programmatically, please also share the code used to generate it!
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
[Answer]
## CJam, ~~53~~ ~~52~~ 47 bytes
```
l~"X 0'ò"2/Dfb+:%"gÇâì6Ô¡÷Ç8nèS¡a"312b2b=
```
There's unprintables, but the two strings can be obtained by
```
[88 9 48 5 39 5 29 1 242]:c
[8 103 199 226 236 54 212 15 161 247 199 56 110 232 83 161 97]:c
```
respectively. This also shows that the code points are below 256.
This is a modulo chain answer, where we apply the following modulos to the input integer, in order:
```
[1153 629 512 378 242 136]
```
Since this list contains integers greater than 255, the list is encoded using two chars each. The decoding is done by `2/Dfb`, which splits the string into chunks of length two and converts each from a base 13 number (e.g. `88*13 + 9 = 1153`). However, there are two exceptions to the decoding:
* The last number (`136`) is not included (see below),
* The second-last number is represented by a single char, since the number (`242`) is less than 256 and splitting an odd-length array into chunks of size 2 will leave a size 1 array at the end. Thanks to @MartinBüttner for this tip!
Once the modulos have reduced the input integer to a relatively small number, we perform a lookup from a table. This table is encoded via the second string, which is converted to a base `312` number then decoded to base 2, which we index. Since CJam's array indexing wraps, we can leave out the final modulo as mentioned earlier.
[Try it online](http://cjam.aditsu.net/#code=l~%22X%090%05'%05%1D%01%C3%B2%222%2FDfb%2B%3A%25%22%08g%C3%87%C3%A2%C3%AC6%C3%94%0F%C2%A1%C3%B7%C3%878n%C3%A8S%C2%A1a%22312b2b%3D&input=1386551069) | [Test suite](http://cjam.aditsu.net/#code=q%20%20%20%20%20%20%20%20e%23%20Read%20all%20input%0A'%2C-%20%20%20%20%20%20e%23%20Remove%20commas%0A~%20%20%20%20%20%20%20%20e%23%20Evaluate%20as%20CJam%20array%0A%0A%7B%0A%0A%22X%090%05'%05%1D%01%C3%B2%222%2FDfb%2B%3A%25%22%08g%C3%87%C3%A2%C3%AC6%C3%94%0F%C2%A1%C3%B7%C3%878n%C3%A8S%C2%A1a%22312b2b%3D%0A%0A%7D%25%20%20%20%20%20%20%20e%23%20Perform%20program%20on%20each%20(note%20we%20don't%20need%20l~%20to%20read%20in%20input)%0Ap%20%20%20%20%20%20%20%20e%23%20Print%20the%20resulting%20array&input=%5B28051484%2C%20408224582%2C%201157838297%2C%203470985950%2C%201310525292%2C%202739928315%2C%203565721638%2C%203568607641%2C%203857889210%2C%20682782262%2C%202845913801%2C%202625196544%2C%201036650602%2C%203890793110%2C%204276552453%2C%202017874229%2C%203935199786%2C%201136100076%2C%202406566087%2C%20496970764%2C%202945538435%2C%202830207175%2C%204028712507%2C%202557754740%2C%20572724662%2C%202854602512%2C%20736902285%2C%203612716287%2C%202528051536%2C%203801506272%2C%20164986382%2C%201757334153%2C%20979200654%2C%201377646057%2C%201003603763%2C%204217274922%2C%203804763169%2C%202502416106%2C%20698611315%2C%203586620445%2C%202343814657%2C%203220493083%2C%203505829324%2C%204268209107%2C%201798630324%2C%201932820146%2C%202356679271%2C%201883645842%2C%202495921085%2C%202912113431%2C%201519642783%2C%20924263219%2C%203506109843%2C%202916121049%2C%204060307069%2C%201470129930%2C%204014068841%2C%201755190161%2C%20311339709%2C%20473039620%2C%202530217749%2C%201297591604%2C%203269125607%2C%202834128510%5D)
[Answer]
# [Retina](http://github.com/mbuettner/retina), 117 bytes
```
([023]3|[067]0|[1289]1|5[5689]|67|96|88|77|65|05)$|^(8|4[358]|7[147]|51|37|30)|865|349|2.{5}5|761|74[348]|728|811|990
```
A regex golf answer, outputting a positive integer for truthy and zero for falsy.
[Try it online!](http://retina.tryitonline.net/#code=KFswMjNdM3xbMDY3XTB8WzEyODldMXw1WzU2ODldfDY3fDk2fDg4fDc3fDY1fDA1KSR8Xig4fDRbMzU4XXw3WzE0N118NTF8Mzd8MzApfDg2NXwzNDl8Mi57NX01fDc2MXw3NFszNDhdfDcyOHw4MTF8OTkw&input=MTM4NjU1MTA2OQ) | [Test suite - truthy](http://retina.tryitonline.net/#code=bWBeLiooKFswMjNdM3xbMDY3XTB8WzEyODldMXw1WzU2ODldfDY3fDk2fDg4fDc3fDY1fDA1KSR8Xig4fDRbMzU4XXw3WzE0N118NTF8Mzd8MzApfDg2NXwzNDl8Mi57NX01fDc2MXw3NFszNDhdfDcyOHw4MTF8OTkwKQ&input=MTM4NjU1MTA2OQoxNzIxMTI1Njg4Cjg3MTc0OTUzNwozNDEwNzQ4ODAxCjI5MzU1ODk0NTUKMTg4NTg2NTAzMAo3NzYyOTY3NjAKNjE0NzA1NTgxCjM4NDExMDY5MjMKNDM0NjE2MzM0CjE4OTE2NTE3NTYKMTEyODIxNTY1MwoyNTY1ODI0MzMKMzEwNzgwMTMzCjM5NzEwMjg1NjcKMjM0OTY5MDA3OAo0ODk5OTI3NjkKNDkzMTgzNzk2CjMwNzM5MzcxMDAKMzk2ODU0MDEwMAo3NzcyMDc3OTkKNTE1NDUzMzQxCjQ4NzkyNjQ2OAoyNTk3NDQyMTcxCjk1MDgxOTUyMwoxODgxMjQ3MzkxCjM2NzY0ODY1MzYKMzg1MjU3Mjg1MAozNDk4OTUzMjAxCjI1NDQ1MjUxODAKMjk3Mjk3MjU4CjM3ODM1NzAzMTAKMjQ4NTQ1Njg2MAoyODY2NDMzMjA1CjI2Mzg4MjUzODQKMjQwNTExNTAxOQoyNzM0OTg2NzU2CjMyMzc4OTUxMjEKMTU2MDI1NTY3Nwo0MjI4NTk5MTY1CjMxMDYyNDc3NDMKNzQyNzE5MjA2CjI0MDkxMjk5MDkKMzAwODAyMDQwMgozMjgxMTM2MTIKMTA4MTk5NzYzMwoxNTgzOTg3NjE2CjEwMjk4ODg1NTIKMTM3NTUyNDg2NwozOTEzNjExODU5CjM0ODg0NjQ3OTEKNzMyMzc3NTk1CjQzMTY0OTcyOQoyMTA1MTA4OTAzCjE0NTQyMTQ4MjEKOTk3OTc1OTgxCjE3NjQ3NTYyMTEKMjkyMTczNzEwMAo3NTQ3MDU4MzMKMTgyMzI3NDQ0Nwo0NTAyMTU1NzkKOTc2MTc1OTM0CjE5OTEyNjA4NzAKNzEwMDY5ODQ5) | [Test suite - falsy](http://retina.tryitonline.net/#code=bWBeLiooKFswMjNdM3xbMDY3XTB8WzEyODldMXw1WzU2ODldfDY3fDk2fDg4fDc3fDY1fDA1KSR8Xig4fDRbMzU4XXw3WzE0N118NTF8Mzd8MzApfDg2NXwzNDl8Mi57NX01fDc2MXw3NFszNDhdfDcyOHw4MTF8OTkwKQ&input=MjgwNTE0ODQKNDA4MjI0NTgyCjExNTc4MzgyOTcKMzQ3MDk4NTk1MAoxMzEwNTI1MjkyCjI3Mzk5MjgzMTUKMzU2NTcyMTYzOAozNTY4NjA3NjQxCjM4NTc4ODkyMTAKNjgyNzgyMjYyCjI4NDU5MTM4MDEKMjYyNTE5NjU0NAoxMDM2NjUwNjAyCjM4OTA3OTMxMTAKNDI3NjU1MjQ1MwoyMDE3ODc0MjI5CjM5MzUxOTk3ODYKMTEzNjEwMDA3NgoyNDA2NTY2MDg3CjQ5Njk3MDc2NAoyOTQ1NTM4NDM1CjI4MzAyMDcxNzUKNDAyODcxMjUwNwoyNTU3NzU0NzQwCjU3MjcyNDY2MgoyODU0NjAyNTEyCjczNjkwMjI4NQozNjEyNzE2Mjg3CjI1MjgwNTE1MzYKMzgwMTUwNjI3MgoxNjQ5ODYzODIKMTc1NzMzNDE1Mwo5NzkyMDA2NTQKMTM3NzY0NjA1NwoxMDAzNjAzNzYzCjQyMTcyNzQ5MjIKMzgwNDc2MzE2OQoyNTAyNDE2MTA2CjY5ODYxMTMxNQozNTg2NjIwNDQ1CjIzNDM4MTQ2NTcKMzIyMDQ5MzA4MwozNTA1ODI5MzI0CjQyNjgyMDkxMDcKMTc5ODYzMDMyNAoxOTMyODIwMTQ2CjIzNTY2NzkyNzEKMTg4MzY0NTg0MgoyNDk1OTIxMDg1CjI5MTIxMTM0MzEKMTUxOTY0Mjc4Mwo5MjQyNjMyMTkKMzUwNjEwOTg0MwoyOTE2MTIxMDQ5CjQwNjAzMDcwNjkKMTQ3MDEyOTkzMAo0MDE0MDY4ODQxCjE3NTUxOTAxNjEKMzExMzM5NzA5CjQ3MzAzOTYyMAoyNTMwMjE3NzQ5CjEyOTc1OTE2MDQKMzI2OTEyNTYwNwoyODM0MTI4NTEw) | [Regex101](https://regex101.com/r/nZ2wE5/2)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 bytes
```
ȷ;€ȷḥ€⁸ḋ“¡`Ṿc-MrKṪZiṣ$Ṅ(ṀQ’B¤Ḃ
```
[Try it online!](https://tio.run/##LVS9iqVVEHyVGxgYXKH/fzAzFQNTlwVBDJSNzMzGRTDwCQQTURPZfGcSgzXZ17jzImPVmYUL93C@093VVdX9/bevXv349PT@7aePr9@8f3u7/xv/jz/d3@5/fbz7/d0fX98e/v3mky9@@Pz28M9X390e/vzo9vDzx7eHuy8f73777N1ft/vXT//9wpjXb56eXrxQn8pUqb1etE3Vsmaul2nt2PS@XjxUOmZErxdbz5yNTDyfSQSLy/XSXbbVhWNptOARXvuEMrX59RIepeUeDFyt1M7CWW1MsxJPUDrHwnF0lETBc9xWsckCFPPYWsE3JJzdtSbwWNfxXuRzaV9HhDCyJkPOubtNuhevUzMSQJQ5eq2ihsW3I0wb15syuknYaFItkJPtoMFAx846k5YNWKwTO6DKDkEZgS86QrKav0R27/FsQVu4DqACyyTLpgoNm4BPK5@xBGl8I6maosBrzQJ16HJDpk01lAJrYgleQEwYoCxpPdwVIHcAfoe1rkmdlKu2K0uWZMQkxJhyVL0UR2Xb20XaNcd3Gprx3nagdvKNN/5BA52xDFRUJgkzUdEkqgmzc5OyawV5AABFTzIrzB4JrmPYByouHtMwCoLRJ2xI9iDGByU76ak5uMbcoFSw6xR4JxvJgRqG2mMv8GAl0wxEeO3EvrxeXtgAQJDekDELmI0GTGgzEIo9tCy6oagKGiEkUBwFYLVxJbswKeYEWp0zVATm43XkGWDmCIw1ChRDJxIsPQ9PwRhbcAgp9cLs1FEAnDQszFDoVeT3zINoDxQkeTB1Ups5MwPWBVPwrGplsVuOQW0TDsnDiMJJTl@NQ2vMM@XAJDVmXDhMYI7EBsqipbaoZ8QZNBYN0Y5po7VofoWVyuZEHio/DILAp4VwACsa1Q@tnc0ZYx/Q1yBDxnEP8JVkkwJwIA67sW0sHywcO3RI4FI52UBqoegWlaAjzPZBBMwN/Bt5doKPRjGlGy7XZbg3Eo7BvjLqbZAE9mfb2sQo517xGR8QzTzgEUi5ADD1XvBHkA@sQcpKEgzOAgSYmgMCLSEXa62hghunFWUBF5bz8xysKSCRefQq/bxo4TOOIjcn9hM@YXaO/bGKVxDEKcb2g5wMbcBd9Es@oKVitpnFODZaEmy8lqv76DrgHZqpvHz5Pw "Jelly – Try It Online")
This answer was almost entirely automatically generated, using [this automated encoder](https://tio.run/##xVVNi1xFFN3PrygaAt3kZazvjwxZ6EIhoBtFURPldXd1z4vvo3kfTmYXBXGRXVZZKLjQnQgSk0kQXEwIxJ8x80fGc6u7ZyYocRlmmFfvVd17zz3n3Jo7sSwPz85O7/3wTtl0XVOxRVH2sWWxnjXz2O7u7LzdLocq1n13fef4EbvByqLrWbNgRb0a@o6N8/qQ9YerOMl2Tr/549KBWdO2sVs19byol6wZ@v84/xjn66GaoiIiVoBQTMt4cbgakGsa2aotqjhh19h8WJXFLO9jx/I2osZQ93HOmnoWM5bXc3bYDKzKD1k@n7N4t2/z82RFTZstYuZNleOt38/7lKWOXwPA0CFRsUgZDopun/A9Ab6bxBEQNMs2r9ZBa3YAod5kR/K@oVc84xLJUvrI2rxeRsZ3d7@gXsftUCOoB4RqVaDPHl1lrGuAALXrJvW6bMpFnCd6jv63/GvrbUFtMI6pACCAxJYkWafJ2BR7qfm8Y6u8TeJRskVR5@W28gRW@Agfq/xuUQ3VJdU2Rig6KF8VpAaqCs45gWpauIg@VPlXMWXdgNk2lCOq78t12wXOju@Q5rP91AkFdHEGD21B9fttjOzlUUdJEZy31P4GzTSWzQFtnIcX3Rb4VijQxj7Ml/EVSjN2sB9rIicjr8HtOPVv5i@OwSH9PhSDfzbjcR54Qd0y1rHNiZFXpwuIPmj6eD3hY/s5FeuqvCwT7lmkXqEkbIr6i7wooVYG1eK65w6vAxoHp31b3AXHbDyNsxwabjBj1bFpsbwWMXwwwDTvaFZq2LwrmrqbbJMR1jLmaULnxbKA9msjIfiCVNrN4aqdTzEaM@RboGpqE9gGGsMEuwOgekAbhxlhSjrSGOaw98HaJm9t1c@L5IpRG9umLEcb0hI5p/d@3MFVc3Pv9NtfXx6dPP0Fz@Nn7AocvYOLqsJMvJ8aH7/37hiHGVkdG5OM0dvxo@ffI@LFg5NnD9Nnduu15zHkx4@/Pv39N7q9PvnsIu74SXuj69sxHD@mO21cTSa7uFCSHF/OmrhYFLMC0o8nu2WxwOOqQFBywbiNK0TupjiE4bXMZ3E8YqNsNJqwq2x08vS7EZ4trafS8JM/7z9/ePPWILmYp7@zvfXj5dFlJv7@6eTp/fWpvb1Lp8Pm9PQ86fHPVy51uwmh3fXXo5Nnf6VmsZnQjka7d5qiJor29oiACVYvHnycyMDy7Ozsc6G8NUZwGzImnBRCGut9xrwTTgejXMaUFtxp77nImAzKGB@0MTjuvUEwVzxjzlkZrLNYWqEdxyGcVl4LSi1VxrTSVlilNAUGYY1wxmItpJfCWIMjKG281ApLhZIomJbBCS69sYAilQ42cOwhoQ8hSEfAdVDCKxeQT3GngkIEp0jrjeZp7ZyT3LmA00YYbQBEUA4XpNXWU/HgtJbC4XMw3ItgCDaaFFIjJ7WDBjU6VlTHG2kcYFEdHTyokokgozV2hOdElqNfg@zKeWUcR1v4rIEKLBNZ0luLhiUHn9Iq76UBaXSGGyEMXIC1owI20aUkMgUjJEqBNS4NeAExWgJKIFoTdxaQnQZ8p6UTQXKbUgYhQ@CBWOKeS665pJReCGUFloLaDs4S7cJ4FbyDZvRdBg@1DZ1RDk/QQM4IFChQmUjwXlvtiChHMJ0JhmQXVhMPACDQE/eBU3ZtwLX21AcqBhwmwwgQjD5hQ2IPYmyUdIY85RMuL5WEUpq6NhzeMQ7JgRqGCsle4EFa7h0FItwGr6m8R3lN5GrupdSwGtnPQBkPmagDxwN6IUkFSISMwJD4h9G8EsQtLIopgVJpDQ2BODkdeTwQ0wB46VDAUqjXBhytR8fCFsHCH0Sospgcm/gHIw4GplCoZYndNA1cOA/9iDpY2pAyPk0MOMc/Y7fW1BpLvdIQ2OAIDlGHAYWPFLnKKyiNaSYxMEcOE85plMAb0apRFi05qe0asdFkK7KDU5g1MhZZX8BIVvoUmajcjAGHSy3CAcySTVWi1RlHE0Z9QF0JEYxO3gE@y40jCsABVzAbtY2rB9eNTHRwjY@C5hpIpRboFpWgIqy2EQFTA/dqk24E5YW2lFJJfAyKe7o1DPyC20qS3hKSwPzUtnCEkafvAtvYQDTlAY9ASuOPmVcW/tDEBy5BkpVIkPAVIMDSNB7QEnJRrSBRQUmaVZQFXBhOpeNgTXAyH3TCPenW1yx8RoNI9yZuJ2xhcpL5cREHjiCaYdx9kJNCHeAG9Et8QEuByaYskoZGWK6pcRvo4k66evAOzQS/jds9e7M//M3@3D6TZ6MRfv8B "Jelly – Try It Online") (which I wrote myself, and have previously used in [another challenge](https://codegolf.stackexchange.com/a/220588)); [here's](https://codegolf.stackexchange.com/a/214222) where the original algorithm (which I created myself) comes from. Because Jelly isn't so great at interprocess communication, the encoder generates a Sage program that generates a Jelly program that prints the final golfed program.
There were three manual tweaks to the automated result: two were golfing uses of base-generic builtins that dealt with base 2 into the (shorter) versions that are specific to binary, and one was to change the program from a full program into a function (so that I could easily test it on every test case – the byte count is the same either way, you just need to change the way it takes input from `⁸` (function argument) into, e.g., `³` (command-line argument)).
The generator has a couple of deficiencies that mean that it randomly fails sometimes; for a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") (and therefore only two outputs), this chance is much higher than normal (hard to estimate exactly, but likely above 50%). Fortunately, it randomly happened to work first time üôÇ
## Explanation
```
ȷ;€ȷḥ€⁸ḋ“¡`Ṿc-MrKṪZiṣ$Ṅ(ṀQ’B¤Ḃ
; Form a pair of
€ each number from 1 to
»∑ 1000
»∑ and 1000
€ and use each pair as
ḥ a hash configuration, to hash
⁸ this function's argument.
ḋ Take the dot product {of the list of hashes}
¤ and a constant determined by
B taking the list of binary digits of
“¡`Ṿc-MrKṪZiṣ$Ṅ(ṀQ’ [a magic constant]
Ḃ {Output} its least significant bit.
```
As usual, the algorithm is to pass the inputs we're given through a list of hash functions to create a list of hashes (the list created this way is longer than it needs to be, to save bytes specifying how long it needs to be), then take the dot product of the list of hashes and a magic constant calculated by the program I linked above.
The reason this works is that each input/output pair that we need to set effectively corresponds to a requirement on the parity of the number of set bits in certain positions in the magic constant, e.g. the requirement that 1386551069 maps to 1 means that out of the bit positions in the magic constant that correspond to hash functions that hash 1386551069 to an odd number, an odd number of them need to be a 1 bit in order for the program to give the correct output in that case. This sort of requirement can be expressed as a linear equation in the finite field GF(2), making it possible to calculate what the magic constant should be simply via writing down all the equations (which is what the first stage of the generator program does) and solving them (which is what the Sage program that it outputs does). There might not be a solution, of course, but given an entirely randomly chosen set of simultaneous equations (i.e. each variable has a random coefficient in every equation), if the number of equations is no greater than the number of variables, the odds that they turn out to be solvable are actually pretty high, and they were here.
I did end up with a bit of luck converting the resulting equations to Jelly – the first bit of the list that needs to be encoded in the magic constant happens to be a 1, so it's possible to compress it by base-converting it into a number (which couldn't be done if it had a leading zero, as the leading zero would then be missing upon base-converting back). This is only a problem because Jelly base conversions are big-endian (extra trailing zeroes past the last useful hash function wouldn't have an effect), so wouldn't affect a golfing language that had this generic algorithm available as a builtin. Fortunately, this particular set of inputs and outputs managed to dodge the issue (and it's a deficiency with the decompressor that sits around the magic constant, rather than the technique for finding the magic constant itself).
As a side note, the magic constant is 17 bytes long (not 16, the theoretical minimum for 128 input → output pairs) because not all of the 256 bytes of the Jelly codepage are able to appear in a compressed literal – 6 of them are quotes (which can't appear unescaped because they'd be interpreted as ending the string, and there isn't an escape syntax), so only 250 of them are actually available, and that makes string literals a little longer than they would be in base 256.
[Answer]
# JavaScript (ES6) 233
An anonymous function returning 0 as `falsy` and nonzero as `truthy`
```
x=>~"lnhp2wm8x6m9vbjmrqqew9v192jc3ynu4krpg9t3hhx930gu8u9n1w51ol509djycdyh077fd1fnrzv6008ipkh0704161jayscm0l6p4ymj9acbv5ozhjzxo3j1t20j9beam30yptco033c9s3a8jwnre63r29sfbvc5371ulvyrwyqx3kfokbu66mpy9eh" // newline added for readability
.search((x.toString(36)).slice(-3))
```
Checking the last 3 digits in the number representation in base 36.
The check string is built so:
```
a=[1386551069, 1721125688, ... ]
H=x=>(x.toString(36)).slice(-3)
Q=a.map(x=>H(x)).join('')
```
**Test**
```
f=x=>~"lnhp2wm8x6m9vbjmrqqew9v192jc3ynu4krpg9t3hhx930gu8u9n1w51ol509djycdyh077fd1fnrzv6008ipkh0704161jayscm0l6p4ymj9acbv5ozhjzxo3j1t20j9beam30yptco033c9s3a8jwnre63r29sfbvc5371ulvyrwyqx3kfokbu66mpy9eh"
.search((x.toString(36)).slice(-3))
a=[1386551069, 1721125688, 871749537, 3410748801, 2935589455, 1885865030, 776296760, 614705581, 3841106923, 434616334, 1891651756, 1128215653, 256582433, 310780133, 3971028567, 2349690078, 489992769, 493183796, 3073937100, 3968540100, 777207799, 515453341, 487926468, 2597442171, 950819523, 1881247391, 3676486536, 3852572850, 3498953201, 2544525180, 297297258, 3783570310, 2485456860, 2866433205, 2638825384, 2405115019, 2734986756, 3237895121, 1560255677, 4228599165, 3106247743, 742719206, 2409129909, 3008020402, 328113612, 1081997633, 1583987616, 1029888552, 1375524867, 3913611859, 3488464791, 732377595, 431649729, 2105108903, 1454214821, 997975981, 1764756211, 2921737100, 754705833, 1823274447, 450215579, 976175934, 1991260870, 710069849]
b=[28051484, 408224582, 1157838297, 3470985950, 1310525292, 2739928315, 3565721638, 3568607641, 3857889210, 682782262, 2845913801, 2625196544, 1036650602, 3890793110, 4276552453, 2017874229, 3935199786, 1136100076, 2406566087, 496970764, 2945538435, 2830207175, 4028712507, 2557754740, 572724662, 2854602512, 736902285, 3612716287, 2528051536, 3801506272, 164986382, 1757334153, 979200654, 1377646057, 1003603763, 4217274922, 3804763169, 2502416106, 698611315, 3586620445, 2343814657, 3220493083, 3505829324, 4268209107, 1798630324, 1932820146, 2356679271, 1883645842, 2495921085, 2912113431, 1519642783, 924263219, 3506109843, 2916121049, 4060307069, 1470129930, 4014068841, 1755190161, 311339709, 473039620, 2530217749, 1297591604, 3269125607, 2834128510]
A.textContent=a.map(x=>f(x))
B.textContent=b.map(x=>f(x))
```
```
<table>
<tr><th>first 64 - truthy</th></tr><tr><td id=A></td></tr>
<tr><th>other 64 - falsy</th></tr><tr><td id=B></td></tr>
</table>
```
[Answer]
# Mathematica, ~~218~~ 217 bytes
```
Fold[Mod,#,{834,551,418,266,228,216,215,209,205,199,198,195,178,171,166,162,154,151,146,144,139,137,122,120,117,114,110,106,101,98,95,88,84,67,63,61,60,57,55,51,45,44,43,41,40,35,34,30,27,26,25,23,20,14,13,11,10,9}]<1
```
For whatever reason, a set of moduli exists that allows us to distinguish two sets just by whether or not, after applying the moduli, the result is zero or not.
The long list of moduli was generated by this program:
```
Block[{data1, data2, n, mods},
data1 = {1386551069, 1721125688, 871749537, 3410748801, 2935589455,
1885865030, 776296760, 614705581, 3841106923, 434616334,
1891651756, 1128215653, 256582433, 310780133, 3971028567,
2349690078, 489992769, 493183796, 3073937100, 3968540100,
777207799, 515453341, 487926468, 2597442171, 950819523, 1881247391,
3676486536, 3852572850, 3498953201, 2544525180, 297297258,
3783570310, 2485456860, 2866433205, 2638825384, 2405115019,
2734986756, 3237895121, 1560255677, 4228599165, 3106247743,
742719206, 2409129909, 3008020402, 328113612, 1081997633,
1583987616, 1029888552, 1375524867, 3913611859, 3488464791,
732377595, 431649729, 2105108903, 1454214821, 997975981,
1764756211, 2921737100, 754705833, 1823274447, 450215579,
976175934, 1991260870, 710069849};
data2 = {28051484, 408224582, 1157838297, 3470985950, 1310525292,
2739928315, 3565721638, 3568607641, 3857889210, 682782262,
2845913801, 2625196544, 1036650602, 3890793110, 4276552453,
2017874229, 3935199786, 1136100076, 2406566087, 496970764,
2945538435, 2830207175, 4028712507, 2557754740, 572724662,
2854602512, 736902285, 3612716287, 2528051536, 3801506272,
164986382, 1757334153, 979200654, 1377646057, 1003603763,
4217274922, 3804763169, 2502416106, 698611315, 3586620445,
2343814657, 3220493083, 3505829324, 4268209107, 1798630324,
1932820146, 2356679271, 1883645842, 2495921085, 2912113431,
1519642783, 924263219, 3506109843, 2916121049, 4060307069,
1470129930, 4014068841, 1755190161, 311339709, 473039620,
2530217749, 1297591604, 3269125607, 2834128510};
n = 1;
mods = {};
While[Intersection[Mod[data1, n], Mod[data2, n]] != {}, n++];
FixedPoint[
(mods = Append[mods, n]; data1 = Mod[data1, n];
data2 = Mod[data2, n]; n = 1;
While[Intersection[Mod[data1, n], Mod[data2, n]] != {}, n++];
n) &
, n];
{mods, {Fold[Mod, data1, mods], Fold[Mod, data2, mods]}}
]
```
First output is the moduli, second and third outputs are the two lists, having applied the moduli.
The two long lists are the sets.
[Answer]
## PowerShell, v3+ 194 bytes
```
$args[0]%834%653-in(40..45+4,8,12,51,60,64,69,76,84,86,93,97,103,117+137..149+160,162,178+195..209+215..227+255,263+300..329+354,361,386,398,417,443,444+469..506+516,519,535,565,581,586,606,618)
```
A little bit of a different approach, so I figured I would post it. It's not going to win shortest, but it may give someone else ideas to shorten their code.
We're still taking the input integer `$args[0]` and applying modulo operations to it, so nothing different there. In the above, we're using the `-in` operator (hence v3+ requirement) so this will output `True` for values that are in the truthy test case.
However, I'm attempting to find resultant arrays where we can leverage the `..` range function to shorten the byte count, yet still have distinct arrays between the truthy and falsey values. We can do this since behavior other than the truthy/falsey input is undefined, so if the range catches values outside of the truthy/falsey input, it doesn't matter the output.
It's a pretty manual process so far, as the goal is to try and find the modulo where one of truthy or falsey arrays has large gap(s) between numbers and the other array has large amounts of numbers in that gap. I've mostly been going by intuition and gut feel so far, but I may eventually write a brute-forcer to solve this. The above is the shortest I've (mostly manually) found so far.
] |
[Question]
[
# Challenge
Given a positive integer `N` that is 28 or above, output a list of numbers summing to `N` that uses each digit `1` through `7` exactly once. You can give as a program or function.
The digits can appear by themselves or concatenated, as long as you use each of them once without repeats. For example,`[12, 34, 56, 7]` is valid, as is `[1, 27, 6, 4, 35]` and `[1234, 567]`, but not `[123, 34567]` or `[3, 2, 1476]`. The order that the numbers are listed does not matter.
If `N` cannot be made with 1-7, return or output nothing.
# Other information
* This is code golf, so the shortest code in bytes by Thursday the 15th of October wins.
* Ask any questions in the comments.
* Anything I do not specify in the challenge is up to you.
* Standard loopholes are disallowed.
# Examples
These may clear any confusion up:
Input
```
28
```
Output
```
[1, 2, 3, 4, 5, 6, 7]
```
Input
```
100
```
Output
```
[56, 7, 4, 31, 2]
```
Input
```
1234567
```
Output
```
[1234567]
```
Input
```
29
```
Output
Nothing, 29 is invalid.
Input
```
1891
```
Output
```
[1234, 657]
```
Input
```
370
```
Output
```
[15, 342, 7, 6]
```
I'll make more if needed.
[Here's](http://pastebin.com/qBUGp9RG) a pastebin of all of the possible numbers created with these seven numbers, courtesy of FryAmTheEggman.
[Answer]
# Pyth, ~~18~~ 14 bytes
```
hfqSjkTjkS7./Q
```
*Thanks to @isaacg for golfing off 2 bytes and paving the way for 2 more.*
The code will crash if it should produce no output, which causes no output to be produced.
This will work for small-ish inputs if you're patient enough, and for larger ones if given enough time and memory.
To verify that the code works as intended, you can replace the `7` with a `3` for *sums of digits 1 through 3*. Click [here](https://pyth.herokuapp.com/?code=hfqSjkTjkS3.%2FQ&test_suite=1&test_suite_input=6%0A15%0A7) for a test suite.
### Example runs
```
$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 28
(1, 2, 3, 4, 5, 6, 7)
real 4m34.634s
user 4m34.751s
sys 0m0.101s
$ time pyth/pyth.py -c 'hfqSjkTjkS7./Q' <<< 29 2>/dev/null
real 9m5.819s
user 9m6.069s
sys 0m0.093s
```
### How it works
```
./Q Compute all integer partitions of the input.
f Filter the integer partitions:
jkT Join the integers with empty separator.
S Sort the characters of the resulting string.
jkS7 Join [1, ..., 7] with empty separator.
q Check both results for equality.
Keep the partition of `q' returned True.
h Retrieve the first element of the filtered list.
For a non-empty list, this retrieves the solution.
For the empty list, it causes an error and produces no output.
```
[Answer]
## Python 3, 109
```
def f(n,s=set('1234567'),l='0,'):[f(n,s-{x},l+x+c)for c in(',','')for x in s]or n-sum(eval(l))or~print(l[2:])
```
A function that takes a number and outputs a tuple in the like `123,4567,`. Yes, this is a valid tuple.
The idea is to generate all possible strings like `43,126,7,5,` that have the digits `1` through `7` separated by commas, with no two commas consecutive. Evaluate this expression as a tuple, and its sum equals `n`, print it and terminate with error.
To build all such strings, we track the set `s` of chars to use, and try appenping each one either with a comma, which makes the digit end the entry, or without, in which case future digits will concatenate onto it.
Short-circuiting is used to check that `s` is empty because the list-comp is empty, and that `n==sum(eval(l))`, in which case we print `l` and terminate with an error by taking `~` of the `None` returned by printing (thanks to Sp3000 for this.).
I believe that in Python 3.5, two chars can be saved by writing `s={*'1234567'}` (thanks Sp3000).
There's some small annoyances that eat up chars. One is that in the case that `l` looking like `1234567` with no commas, it is parsed as a single number and calling `sum` gives an error. This is handled with the hack of starting `l` with the element `0` and stripping it when printing. This costs 6 chars.
Iterating `c` over the comma and the empty string is annoyingly wordy `for c in(',','')`, since Python 3 doesn't allow this tuple to be naked. I'd like there to be some char `?` that is ignored in numbers to do `',?'` for 4 chars less, but there doesn't seem to be such a char.
---
Old method:
**Python 2, 117**
```
def f(n,s={1,2,3,4,5,6,7},l=[],p=0):
if{n,p}|s=={0}:print l;1/0
if p:f(n-p,s,l+[p])
for x in s:f(n,s-{x},l,p*10+x)
```
Defines a function that takes a number and prints a list.
The idea is to use recursion to try every branch. The variables track are
* The remaining sum `n` needed
* The set of digits `s` remaining to use
* The list `l` of numbers made so far
* The current partially-formed number `p`
When `n==0` and `s` is empty, print `l` and terminate by error.
If the current partially-formed number `p` is non-zero, try adding it to the list and removing it from the remaining sum.
For each digit `x` we can use from `s`, try appending it to `p` and removing it from `s`.
[Answer]
# Pyth, 23
```
#iRThfqQsiR10Ts./M.pS7q
```
Naive brute force, too slow online, takes about a minute on my computer. Uses the common "loop forever until exception" pattern of pyth golfs where accessing the resulted filtered list of combinations causes an error for impossible numbers, like `29`.
Outputs like a pythonic list, e.g.
```
1891
[1234, 657]
100
[1, 2, 34, 56, 7]
370
[12, 345, 6, 7]
```
Here is a [paste](http://pastebin.com/qBUGp9RG) of all of the 10136 numbers that can be made this way.
[Answer]
# Python 2.7, ~~178~~ ~~172~~ 169 bytes
```
n=input()
for i in range(8**7):
for j in len(set('%o0'%i))/8*range(128):
s=''
for c in'%o'%i:s+='+'[:j%2*len(s)]+c;j/=2
if eval(s)==n:print map(int,s.split('+'));1/0
```
Note that the last three lines are supposed to be indented with tabs but I
can't figure out how to do so in this editor.
Edit: Flattened one layer of nesting with the help of Sp3000
[Answer]
# JavaScript (ES6), 165 ~~196~~
**Edit** Shortened a little. Could be shorter using `eval`, but I like it being fast
Brute force, shamefully longer than Pith version, but faster. Test running the snippet below in an EcmaScript 6 compliant browser.
```
f=z=>{for(r=i=1e6;r&&++i<8e6;)for(m=/(.).*\1|[089]/.test(w=i+'')?0:64;r&&m--;t.split`+`.map(v=>r-=v,r=z))for(t=w[j=0],l=1;d=w[++j];l+=l)t+=l&m?'+'+d:d;return r?'':t}
function test() { O.innerHTML=f(+I.value) }
test()
// Less golfed
f=z=>{
for(r=i=1e6; r&&++i<8e6;)
for(m=/(.).*\1|[089]/.test(w=i+'')?0:64; r&&m--; t.split`+`.map(v=>r-=v,r=z))
for(t=w[j=0],l=1;d=w[++j];l+=l)
t+=l&m?'+'+d:d;
return r?'':t
}
```
```
<input id=I value=28><button onclick=test()>-></button><span id=O></span>
```
[Answer]
# Python 2, ~~270~~ 268 bytes
```
from itertools import*;P=permutations
x,d,f=range(1,8),[],input()
r=sum([[int(''.join(str(n)for n in i))for i in list(P(x,j))]for j in x],[])
z=1
while z:
t=sum([[list(j)for j in P(r,z)]for i in x],[])
v=filter(lambda i:sum(i)==f,t)
if v:print v[0];break
else:z+=1
```
Still working on golfing.
This loops until a match is found.
[Answer]
# Haskell (145 bytes)
```
main=getLine>>=print.head.f[1..7].read
f[]0=[[]]
f b s=[n:j|(n,g)<-m b,j<-f g$s-n]
m b=[(d+10*z,g)|d<-b,(z,g)<-(0,filter(/=d)b):m(filter(/=d)b)]
```
Uses recursion.
Ungolfed (337 bytes):
```
delete d = filter (/= d)
main = getLine >>= print . (`form` [1..7]) . read
form s [] | s == 0 = [[]]
form s ds | s <= 0 = []
form s ds | otherwise = [n:ns | (n, ds') <- makeNumbers ds, ns <- form (s-n) ds']
makeNumbers [] = []
makeNumbers ds = [(d + 10 * n',ds') | d <- ds, (n',ds') <- (0,delete d ds):makeNumbers (delete d ds)]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ŒṗDẎṢ⁼ʋƇ7R¤Ḣ
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//xZLhuZdE4bqO4bmi4oG8yovGhzdSwqThuKL///8yOA "Jelly – Try It Online")
Times out for pretty much all inputs. Outputs `0` if no such list exists. Requiring empty output adds [3 bytes](https://tio.run/##AS0A0v9qZWxsef//xZLhuZdE4bqO4bmi4oG8yovGhzdSwqThuKJv4oCc4oCd////Mjk).
[This](https://tio.run/##ASoA1f9qZWxsef//N8WSIcWS4bmW4oKs4bqO4biMUz3CpcaH4oG44bii////Mjk) is a 14 byte ([17 for empty output](https://tio.run/##ATEAzv9qZWxsef//N8WSIcWS4bmW4oKs4bqO4biMUz3CpcaH4oG44biib@KAnOKAnf///zI5)) answer which has a more or less constant runtime (~40 seconds).
## How they work
```
ŒṗDẎṢ⁼ʋƇ7R¤Ḣ - Main link. Takes n on the left
Œṗ - Integer partitions of n
ʋƇ - Keep those for which the following is true:
D - Convert to digits
Ẏ - Flatten
Ṣ - Sorted
⁼ 7R¤ - Equals [1, 2, 3, 4, 5, 6, 7]
Ḣ - Take the first list
```
The 14 byte version:
```
7Œ!ŒṖ€ẎḌS=¥Ƈ⁸Ḣ - Main link. Takes n on the left
7 - Yield 7
Œ! - Get all permutations of [1, 2, 3, 4, 5, 6, 7]
€ - Over each:
ŒṖ - Yield it's partitions
Ẏ - Flatten to a single list of all partitions
Ḍ - Convert from digits
¥Ƈ - Keep those for which the following is true:
S - Sum
= ⁸ - Equals n
Ḣ - Take the first list
```
[Answer]
# Scala, 195 bytes
This isn't the most efficient and it took over 15 minutes to get the output for 29 but it works
```
def g(s: Seq[Int]): Iterator[Seq[Int]]=s.combinations(2).map(c=>g(c.mkString.toInt +: s.filterNot(c.contains))).flatten ++ Seq(s)
def f(i: Int)=(1 to 7).permutations.map(g).flatten.find(_.sum==i)
```
Here is some output
```
scala> f(100)
res2: Option[Seq[Int]] = Some(Vector(46, 35, 12, 7))
scala> f(1891)
res3: Option[Seq[Int]] = Some(Vector(567, 1324))
scala> f(370)
res4: Option[Seq[Int]] = Some(Vector(345, 12, 6, 7))
scala> f(29)
res5: Option[Seq[Int]] = None
```
[Answer]
# Ruby, 105 bytes
Brute force! Checks every subset of lengths between 0 and 7 of the integers between 1 and 7654321 and sees if any of them matches our criteria. You probably don't want to wait for this to terminate.
```
->n{8.times{|i|[*1..7654321].permutation(i){|x|return x if
x.join.chars.sort==[*?1..?7]&&eval(x*?+)==n}}}
```
To run and verify the algorithm you can narrow down the search space by replacing `7654321` with the largest number you know will be in the answer. For instance, 56 for n=100, or 1234 for n=1891. Here's a trial run of the latter:
```
$ ruby -e "p ->n{8.times{|i|[*1..1234].permutation(i){|x|return x if x.join.chars.sort==[*?1..?7]&&eval(x*?+)==n}}}[gets.to_i]" <<< 1891
[657, 1234]
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 15 bytes
```
ḟȯ=ḣ7Oṁdfo=¹ΣṖḣ
```
[Try it online!](https://tio.run/##yygtzv7//@GO@SfW2z7csdjc/@HOxpS0fNtDO88tfrhzGlDo////hgYGAA "Husk – Try It Online")
] |
[Question]
[
[Subleq](https://esolangs.org/wiki/Subleq) is a Turing-complete esolang with only one instruction, SUBLEQ. This instruction takes in three parameters, `A`, `B`, and `C`, all of which are memory addresses. The instruction subtracts the value in memory address `A` from that in memory address `B`, storing it in address `B`. If the value at `B` is now less than or equal to zero, it jumps to memory address `C`; otherwise, it continues to the next instruction.
Your challenge is to implement this language.
As input, the program should take in an array of integers representing the Subleq program, and starting at the first value (index `0`), execute the program. In general, if the program is at index `i`, you should execute `SUBLEQ(i,i+1,i+2)`. Your program should terminate when the instruction pointer is greater than the length of the tape; after execution, your program should output the final Subleq program with the memory modified.
If helpful, you may assume that you will only ever jump to locations which are a multiple of three. The behavior when the Subleq program runs into an error (e.g. jumps to a location outside memory) or get into an infinite loop are not defined.
## Example
Adapted from the Subleq esolang wiki page:
```
[3, 4, 3,
6, 13, 9,
6, 3, -3,
7, 8, 3]
```
Here is a trace of the execution, where the first number is the instruction pointer and brackets are put around the currently executed line:
```
0 : [[3, 4, 3], 6, 13, 9, 6, 3, -3, 7, 8, 3 ]
3 : [ 3, 4, 3, [6, 7, 9], 6, 3, -3, 7, 8, 3 ]
9 : [ 3, 4, 3, 6, 7, 9, 6, -3, -3, [7, 8, 3]]
3 : [ 3, 4, 3, [6, 7, 9], 6, -3, 0, 7, 8, 3 ]
9 : [ 3, 4, 3, 6, 7, 9, 6, -9, 0, [7, 8, 3]]
```
Thus, your program should output
```
[3, 4, 3, 6, 7, 9, 6, -9, 9, 7, 8, 3]
```
Standard loopholes are forbidden. Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest program wins.
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
def f(s,i=0):a,b,*r=s[i:];s[b]-=s[a];f(s,[i+3,*r][s[b]<1])
```
A recursive function that updates a Subleq program, the list of integers `s`, in place terminating with a `ValueError`.
**[Try it online!](https://tio.run/##JYrPDoIwDIfvPEWPm5ZEgvHPkKOv4GXZYeiISwgsWzHy9LNIk7Zf@/3CQu9prHN@uR56kdC3B6ksdriLbdJemSbpzpTM1jRrQPt9zdLo9X@rjMzkEkEL7mMH4ccwk5CyoLioArh6sXpZuO/TBYKHHWZ3j3GKmw7Rj7RFsq4Rjgg8TwgVr@ufGEruM8KFD/MD "Python 3 – Try It Online")**
[Answer]
# x86(-64) machine code, 17 bytes
A function that **simulates a SUBLEQ machine with 8-bit cells**, returning to the caller with the array modified. Callable from C with the x86-64 SysV calling convention as `void subleq8(int8_t *end, int8_t *aligned_start);` (Like a `.begin()` / `.end()` range, the end pointer start+length.)
`start` must be aligned by 256 so its low 8 bits are `0`. This allows indexing the array by replacing the low byte with x86 partial-register stuff, instead of needing to zero-extend the guest byte into a separate register and use an indexed addressing mode. (A similar trick is useful on 8-bit systems like AVR where two 8-bit registers form a 16-bit pointer: if you don't cross a 256-byte boundary, you can skip `adc` into the high byte; if the array is aligned by 256 you can just replace the low byte.)
`start` must be in the low 32 bits of virtual address space, e.g. the x32 ABI, mmap(MAP\_32BIT), or simply a static array (e.g. in `.data`) in a non-PIE Linux executable. Or if you run the same machine code in 32-bit mode.
```
;;; array in ESI, aligned by 256 (so the low byte can be replaced to index into it)
;;; end-pointer (array+len) in EDI
subleq8:
89F0 mov eax, esi ; copy high bytes to EAX so merging a new low byte generates an address
.nextinst:
AC lodsb ; fetch address A into AL, forming an x86 pointer in RAX
8A 10 mov dl, [rax] ; deref A
AC lodsb ; fetch address B
28 10 sub [rax], dl ; SUB and set FLAGS
AC lodsb ; fetch branch target address; RSI points at next instruction
0F 4E F0 cmovle esi, eax ; update guest PC according to FLAGS
39 FE cmp esi, edi ; like cmp sil, dil but range-shifted: both regs have the same high bytes
72 F2 jb .nextinst ; len must be at most 127 to still consider *all* negative byte values as unsigned > 0x7f
C3 ret
```
Instead of checking for the subtraction result being negative or zero, we actually check if `[b]` was less-or-equal than `[a]` before the subtraction, using FLAGS set by the `sub` instruction (like `cmp`). This is the same as checking the result against `0` if signed overflow didn't happen, otherwise it's the opposite. With Python arbitrary-precision integers, signed overflow is impossible. (There is no [x86 FLAGS condition](https://www.felixcloutier.com/x86/jcc) for negative-or-zero so it would take an extra 3 bytes, either for `cmp byte [rax], 0` or for `cmovs` + `cmove` instead of `cmovle`. Like most ISAs with signed-compare conditions, x86 does have a `le` less-or-equal condition that checks `SF != OF || ZF` in the same predicate.)
Apparently [even Wikipedia](https://en.wikipedia.org/wiki/One-instruction_set_computer#Subtract_and_branch_if_less_than_or_equal_to_zero) defines a SUBLEQ OISC in terms of comparing against zero, rather than the usual computer-architecture meaning of a less-or-equal condition after a subtraction. :/ If signed wrap-around (overflow) doesn't happen, the two variants of the architecture are equivalent. Unless / until there's a test-case that requires checking the sign of the result instead of the LE condition generated by subtraction, I'm going to leave my answer this way. I'm pretty confident this is also Turing complete and probably not significantly different for implementing most basic arithmetic, if any of that comes near signed overflow.
**The max program length is 127 or 128 bytes** if you want *any* negative address to end the program. 126 is the highest multiple of 3, if your program doesn't do misaligned jumps and doesn't want to keep some data past the end of the last instruction. (It effectively treats the program counter as unsigned, looping `do {} while(PC < end)`, so a negative program counter is an unsigned number in the upper half of range, above any signed-positive length.) Otherwise, max program length = 255, exiting only on PC=255, although that's untested and rollover of the high bytes of RSI could happen, but maybe only with misaligned jumps, e.g. to PC=254 so fetching the full instruction would get to PC=257, with `lodsb` carrying into the higher bytes of RSI.
(With len limited to 128, misaligned jumps are no problem. e.g. a program might use its first instruction to jump to address `4` and then use the first 4 bytes purely as data, eventually falling off the end when PC = 128.)
Tested with the test-case in the question; it's correct for that but it doesn't AFAIK test for off-by-one errors (`<=` vs. `<` in the SUBLEQ operation), or for exiting via a taken branch to a negative or past-the-end address. I *think* my program is correct, e.g. `cmovle` treats "equal" the same as "less-than", and the test-case does exercise less-than causing the branch to be taken.
# x86(-64) machine code, 21 bytes
**Simulates a 32-bit SUBLEQ machine**. Writing a 32-bit register zero-extends to the full 64-bit register so even if we were willing to align the SUBLEQ program by 2^32 that wouldn't all the same partial-register trickery.
Even starting at absolute address `0` wouldn't work, because SUBLEQ addressing is in terms of cells, like a word-addressable machine. But x86 is a byte-addressable architecture, so SUBLEQ addresses have to be scaled by 4 to get x86-64 byte offsets since we're using 4-byte cells.
In x86-64 SysV, `void subleq32(int32_t *end, int32_t *start)`. I think the `start` pointer might need to be 4GiB aligned to properly handle all jumps to negative addresses, since we only compare the low 32 bits after doing `x86_address = base + target*4`. With a larger base, some negative targets could wrap. And due to the scaling by 4, the most negative value we detect is `-2^30`. We shift out the high bits of some larger numbers, although some larger-magnitude numbers will happen to have a bit that gets shifted to the sign-bit position, too.
So maybe it's only really able to correctly simulate a 30-bit SUBLEQ machine, or 29-bit or something. But still much more than 8-bit, which is the point.
```
;; word-addressable SUBLEQ machine, where the components of an instruction are still 1 guest address apart
;; despite them being farther apart in x86-64
;;; base address in ESI
;;; end address in EDI (base+length in bytes, the one-past-end address. An x86 address, not guest words)
subleq32:
89F1 mov ecx, esi ; save the base for later use.
.nextinst:
AD lodsd ; fetch address A
8B1481 mov edx, [rcx+rax*4] ; and deref; we don't need it after this
AD lodsd ; fetch address B
291481 sub [rcx+rax*4], edx ; update [B] and set FLAGS
AD lodsd ; fetch branch target address; RSI points at next instruction for non-taken
7F03 jnle .not_taken
8D3481 lea esi, [rcx+rax*4] ; scale the SUBLEQ target address to an x86 address
.not_taken:
39FE cmp esi, edi
72EE jb .nextinst ; unsigned compare catches negative as well as past-the-end
C3 ret
```
I also tested this with `dd` instead of `db` for the initial array, using GDB `print (int[12])prog32` after running, or `display` the same expression while single-stepping. This was my test caller:
```
section .data
prog32:
dd 3, 4, 3,
dd 6, 13, 9,
dd 6, 3, -3,
dd 7, 8, 3
prog32_end:
section .text
global _start
_start:
mov edi, prog32_end
mov esi, prog32
call subleq32
int3 ; software breakpoint
xor edi, edi
mov eax, 231
syscall ; x86-64 Linux exit_group(0)
```
## x86(-64) machine code for a byte-addressable SUBLEQ, 17 bytes
Untested, but it's the same logic as the 8-bit version, with the same instructions except 32-bit operand-size. (So writing full registers instead of merging into the low byte).
The SUBLEQ program's cells are 4 SUBLEQ addresses wide, matching the x86 addressing. One way to make the test program run the same is to scale all its starting values by 4, like `12, 16, 12 | 24, 52, 36 | ...`. If you do misaligned load/store or jumps, it will expose the fact that it's a little-endian machine. (SUBLEQ doesn't have byte loads, only word loads.)
This requires the array to start at absolute address `0`. Or in 32-bit mode, `DS:0`, so you could plausibly imagine some segmented code that sets the DS segment base for passing arrays. (Some "string" instructions use the ES segment, but [`lodsd` uses `ds:esi`](https://www.felixcloutier.com/x86/lods:lodsb:lodsw:lodsd:lodsq)).
```
;; byte-addressable SUBLEQ machine
;;; base address = 0
;;; end address = len in EDI
subleq32b:
31F6 xor esi, esi ; start address = 0, can't justify having the caller pass it since we depend on it being 0
.nextinst:
AD lodsd ; fetch address A
8B10 mov edx, [rax] ; and deref; we don't need it after this
AD lodsd ; fetch address B
2910 sub [rax], edx ; update [B] and set FLAGS
AD lodsd ; fetch branch target address; RSI points at next instruction for non-taken
0F4EF0 cmovle esi, eax
39FE cmp esi, edi
72F2 jb .nextinst ; unsigned compare catches negative as well as past-the-end
C3 ret
```
A 16-bit version of this would be highly plausible in 16-bit mode where segmentation is normal, then it wouldn't be too weird to take an array at `ds:0`. Same machine code except for the ModRM.rm field that encodes `[rax]`... except there is no `[ax]` addressing mode, only `[bx]`, `[di]`, or `[si]` for single-register [16-bit addressing modes](https://stackoverflow.com/questions/53866854/differences-between-general-purpose-registers-in-8086-bx-works-cx-doesnt) that use the DS segment. So that might cost a couple 1-byte `xchg` instructions, perhaps with BX.
16-bit addressing modes don't allow a scale factor so they're not very convenient for a word-addressable SUBLEQ.
[Answer]
# JavaScript (ES6), 57 bytes
Modifies the input array.
```
f=(m,p=0)=>1/m[p]&&f(m,(m[m[p+1]]-=m[m[p]])>0?p+3:m[p+2])
```
[Try it online!](https://tio.run/##HYxLDoMwDET3nMIrRIRTSKn6Q6EHibxANKBWCYkK6vWDYTH2e7OYb//vl@H3iaucw9umNOrCY9S10J2qvImU5yM3hTcspSKS@kAi0dWvWDbPvT@TSM6u4EGDaRAuCHyvCIrf4yAGybkh3FmozXhWtNkQ5iU4e3Jh2j1t "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
m, // m[] = memory array
p = 0 // p = program counter
) => //
1 / m[p] // abort if m[p] is undefined
&& // otherwise:
f( // do a recursive call:
m, // pass m[]
( //
m[m[p + 1]] // subtract from m[m[p + 1]] ...
-= m[m[p]] // ... the value stored at m[m[p]]
) > 0 ? // if the result is positive:
p + 3 // continue execution at p + 3
: // else:
m[p + 2] // jump at m[p + 2]
) // end of recursive call
```
[Answer]
# Python3, 94 bytes:
```
def f(t,i=0):
if i>=len(t):return t
t[t[i+1]]-=t[t[i]];return f(t,[t[i+2],i+3][t[t[i+1]]>0])
```
[Try it online!](https://tio.run/##PYvBCsIwEETv@Yo9JnQLrRGtLemPhL2Z4ILEENaDXx/TVry9mTeTP/J4JTvlUus9RIhakN1gZgUcgVf3DEmLmUuQd0kgCsSL524k6t2ORMtPbt9dngi5s@T/03UgU3PhJDpqbxHOCBYVXBDGlm4HNuq39oowtUTG1C8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 45 bytes
```
W‹ⅈLθ«≔§θ⊕ⅈι§≔θι⁻§θι§θ§θⅈ¿›§θι⁰M³→J§θ⁺²ⅈ⁰»⭆¹θ
```
[Try it online!](https://tio.run/##XY9NawIxEIbP7q@Y4wQiaJX6sSdPxeKC2B4K4mFZp7sDMatJ/ADpb09nxULoYWbegfd5J6ma0lVtaWK8NmwIcEXe4xcqDSuydWjwpJSCe9ZbeM@1xUVY2j3d8KRhaStHB7KB9h2hhGGV/zkTI2so2J59CrO4kzWRjyjVBfE34JujMpD7jw7kUUV7IRxpmG@4bkIHkPEE7@fD8bNNgbWR2y/P5I7Ns59s7dgG/Agy6qI84lCDfDWPcbuVzLEG6a8ahjJmDyWiLzXRMJVlt4v9i/kF "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W‹ⅈLθ«
```
Repeat while the instruction pointer is within range.
```
≔§θ⊕ⅈι
```
Get the `B` parameter into a variable.
```
§≔θι⁻§θι§θ§θⅈ
```
Subtract the element at the `A` parameter from the element at the `B` parameter.
```
¿›§θι⁰
```
If the element at the `B` parameter is still positive, ...
```
M³→
```
... move to the next instruction, otherwise...
```
J§θ⁺²ⅈ⁰
```
.... jump to the `C` parameter.
```
»⭆¹θ
```
Output the final array.
[Answer]
# [Z80 machine code](https://en.wikipedia.org/wiki/Zilog_Z80), 22 bytes
```
44 4E 2C 0A 5F 4E 2C 0A 93 02 3D F2 1C 01 6E 2D 2C 7D BA D0 18 EB
```
Explanation of disassembled code:
```
; hl = Pointer to start of program. Must be aligned to 256 byte boundary.
; d = Length of the program in bytes.
subleq:
ld b, h ; We want to use bc as a data pointer, so align
; it to the same boundary as hl.
loop:
ld c, (hl) ; Get a pointer to the first operand in bc and
inc l ; advance the instruction pointer.
ld a, (bc) ; Put the first operand in e.
ld e, a
ld c, (hl) ; Get the second operand pointer in the same
inc l ; way as the first.
ld a, (bc) ; Put the second operand in a and subtract e
sub e ; from it, storing the result back where it
ld (bc), a ; came from.
dec a ; If the subtracted value was positive, skip
jp p, no_jump ; the jump.
ld l, (hl) ; Load our new instruction pointer from the
dec l ; third parameter. Decrement immediately since
; we will increment next no matter what.
no_jump:
inc l ; Advance the instruction pointer.
ld a, l ; If we're past the end of the program, return.
cp d
ret nc
jr loop ; Otherwise, continue our interpretation loop.
```
This is a plain Z80 subroutine called via `call` with registers as parameters. This subleq processor is 8-bit, both in data and addressing. Jump locations are interpreted as unsigned rather than signed, although comparisons are still signed. Do note that values are not exactly two's complement as `$80` is interpreted as positive rather than negative; however, the challenge does not specify this, and it should not affect the Turing-completeness of the implementation.
Example code to call the subroutine with the provided data:
```
ld hl, prog_start
ld d, prog_end - prog_start
call subleq
halt
.align 256
prog_start:
.db 3, 4, 3
.db 6, 13, 9
.db 6, 3, -3
.db 7, 8, 3
prog_end:
```
You can paste these chunks of assembly into <https://www.asm80.com/> to run them. Or, pull out your favorite Z80 system and run it there.
[Answer]
# [R](https://www.r-project.org)\*, ~~84~~ 83 bytes
```
f=\(p,i=1)`if`(i>sum(p|1),p,f(p,`if`((p[j[2]]=diff(p[j<-p[i+0:2]+1]))<1,j[3],i+3)))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU1LDoIwEN17CpadMEQLxg-hxgMQN8ZVbeKPJiWKVWiCxpu4wYWH4jaWqouZ9968NzPP17Vp5xslN0yaYl-pc0FqvLHFKk3x7gB22zKL4y5Das6pENa_WfMOvdLsjtmFvU0lg0m7lGxNNCpGwaXVrDQnoh8UUKO0jpsSzXMeCsEOSspOJIHmyh_EofCpAEgo5jwSqPwIAH6n-99PZE8i9Ibo2T5Cj1qYOmZJYGuM3sSK_1rTfPED)\* or [Try it online](https://tio.run/##LY3dCsIwDIVfpZcJzWBdxT/WvUgpDKeBDJ3VrXe@@4zDi5NzviRw3utcLvfbK6wcuEzDIs8JMklw2Av3IN1cHpA/DikT62XbQo5jbFIKV2H@QVvlKLY@N8m6hNiGmsboE4n1iPjvgAE8mR0ZnXsyTu20JQ2V6kDmqKD/Xw) using `function` instead of the shorter `\` notation.
\*ATO uses a version of R (version 4.3.1) in which the `if` function errors when the condition has length >1. Versions between 4.1.0 and <4.2.0 just give a warning for this without halting with an error, and the header in the ATO link redefines the `if` function to mimic this behaviour.
It would cost [+3 bytes](https://ato.pxeger.com/run?1=NU07DsIwDL1KRltxRdMgKKjhGgzBUsUnUiqQAiUbN2EJA-JM3IbQwuD3s559f1zSq4_b4-FsnvHqivq9dmYDgbxR2HrXgl_18QThppACubwZUgi2sxWz2XvnvqYpgvWyXFYsFSNaxY0pqbOayUuNiL_zk_Eb7ECTmJLIOCOhMi0GlUWRZ06izuZfS2nkDw) to adjust the program to run in all versions of R ≥4.1.
[Answer]
# Python 3.11, ~~92 86 85~~ 62 bytes
This is *my* answer, so don't suggest copying from other answers.
```
def f(p,i=0):
p[k:=p[i+1]]-=p[p[i]];f(p,(i+3,p[i+2])[p[k]<1])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TU5LCsJADF07p8iyQ6dgVbRWiwcpQYqdwaFQQyeCPYubbvRO3sbUHy6SvLz38rneqefjqR2G25ldkj12tXXgIjK-mOpcAZVNXlDp4xQxESAQcTMaIh_PDYzSDLXwDW5T1J81NdvA-0MVLBRQim9hQPLSQCpl_UICEomVgUwaVNz1uZq46Deqlb0cLLGwVIWgqPMt_8nvW9_Xnw)
Takes in a program as a `list`, mutates the original list with an error (you need a variable and try/except to access the results).
Explanation:
```
def f(p,i=0):
```
Define the main function, `p` is the program to be ran and initialize the instruction pointer as `i`.
```
p[k:=p[i+1]]-=p[p[i]];
```
Subtract A from B and store in B. Also assigns B as `k` to shave off bytes.
```
f(p,(i+3,p[i+2])[p[k]<1])
```
If B is less than 1, then recursively call with `i` as C, otherwise add 3.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~34~~ 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[¾Ig@#Ðü3¾èRćU¬VèÆ©Yǝ®0›i3ë.µX}F¼
```
[Try it online.](https://tio.run/##yy9OTMpM/f8/@tA@z3QH5cMTDu8xPrTv8IqgI@2hh9aEHV5xuO3Qysjjcw@tM3jUsCvT@PBqvUNbI2rdDu0B6jHWUTDRUQCSZjoKhkDKUkcBxASJ6AKxgrmOggVQXiEWAA)
**Explanation:**
```
[ # Start an infinite loop:
¾ # Push counter variable `¾` (which starts at 0)
Ig # Push the input-length
@ # Pop both, and if `¾` is >= the input-length:
# # Stop the infinite loop
# (after which the resulting list is output implicitly as result)
Ð # Triplicate the current list
# (which will be the implicit input-list in the first iteration)
ü3 # Pop one copy and push its overlapping triplets
¾è # Pop and get the current Subleq-triplet [L[a],L[b],L[c]] at index `¾` (a)
R # Reverse this triplet [L[a],L[b],L[c]] to [L[c],L[b],L[a]]
ć # Extract its head; pop and push remainder-list and first item separately
U # Pop and store L[c] in variable `X`
¬ # Push the first item of the pair (without popping): L[b]
V # Pop and store L[b] in variable `Y`
è # Index [L[b],L[a]] in another copy of the list: [L[L[b]],L[L[a]]]
Æ # Reduce this pair by subtracting: L[L[b]]-L[L[a]]
© # Store it in variable `®` (without popping)
Y # Push L[b] from variable `Y`
ǝ # Insert L[L[b]]-L[L[a]] at index L[b] into the list
i # If
® # L[L[b]]-L[L[a]] from variable `®`
0› # is positive (>0):
3 # Push a 3
ë # Else (it's <=0):
.µ # Reset the counter variable `¾` to 0
X # And push L[c] from variable `X`
} # Close the if-else statement
F # Loop that many times (either 3 or L[c]):
¼ # Increase the counter variable by 1 every iteration
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 55 bytes
```
->x,i=0{i=(x[x[i+1]]-=x[x[i]])>0?i+3:x[i+2]until !x[i]}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGiNNulpSVpuhY3zXXtKnQybQ2qM201KqIrojO1DWNjdW3BzNhYTTsD-0xtYyuQuFFsaV5JZo6CIkimFqpdPy26wjbaWEfBREcBSJrpKBgCKUswC8jQBWJzHQULICc2lqtAoQKibcECCA0A)
Updates input array in-place.
[Answer]
# ARM64 machine code, 52 bytes
The SUBLEQ machine's memory is an array of signed 64-bit cells. This function takes a pointer to the array in `x0`, and the length of the array in cells in `x1`. It modifies the array in place. This matches standard ARM64 calling conventions for a C function `void subleq(uint64_t *mem, size_t len);`.
```
aa0003e2
a8c11043
f8408445
f8637806
f8647807
eb0600e7
f8247807
8b050c09
9a82d122
cb000043
eb010c7f
54fffec3
d65f03c0
```
Assembly source:
```
.text
.global subleq1
.balign 4
// 64 bit cells
// here IP is a pointer
subleq1:
// x0 = base of machine memory array
// x1 = length of array
// x2 = program counter
mov x2, x0 // pc=0
next_insn:
ldp x3, x4, [x2], #16 // x3 = a, x4 = b, pc += 2
ldr x5, [x2], #8 // x5 = c, pc += 1
// now pc points to tentative next instruction
ldr x6, [x0, x3, lsl #3] // x6 = *a
ldr x7, [x0, x4, lsl #3] // x7 = *b
subs x7, x7, x6 // x7 = *b - *a, set flags
str x7, [x0, x4, lsl #3] // store back to b
add x9, x0, x5, lsl #3 // compute new pc corresponding to c
csel x2, x9, x2, le // select new pc if we had *b <= *a
// check if pc still in range.
// This could also be done with a cmp/ccmp pair, but same length.
// Can save one instruction here if
sub x3, x2, x0
// x3 = offset of pc in bytes.
cmp x3, x1, lsl #3
// Check the unsigned result, so that negative pc corresponds to
// very large value in x3, definitely higher than x1.
b.lo next_insn
ret
```
I couldn't find much clever golfing to do here. The load-store architecture hurts here as we need three instructions to do a read-modify-write of memory.
(Atomic `LDADD` is a possibility if we have ARMv8.2, despite being much more inefficient, but we'd need another instruction to negate the value from `a` as there is no `LDSUB`, and it wouldn't set the flags so that would cost one more. If the condition to jump were `*b - *a < 0` instead of `<=`, we could branch on the sign bit with `tbz`. `LDADD` also lacks the fancy addressing modes that we want to use.)
I took the same interpretation as Peter Cordes that signed overflow in the subtraction is undefined behavior, so that we can branch on `*b <= *a` instead of `*b - *a <= 0`.
It was also unclear what should happen if you jump to a negative address. This version will consider it successful termination. If you allow it to be UB, you can shave off one instruction (4 bytes) by changing the second argument (in `x1`) to be a pointer to the end of the array, instead of a length count, and then just change the loop condition to `cmp x2, x1; b.hs next_insn`.
I considered keeping an integer instead of a pointer as the program counter. It saves the `add` instruction to compute the new pc for `c`, but costs another one to add 3 for the no-jump case, because loads can't post-increment an index register.
I also had some thoughts about using 32-bit cells so that all three elements of the instruction could be loaded with one 128-bit `ldp`, but unpacking from the high half of a 64-bit register is too much extra work.
[Answer]
# [Julia](https://julialang.org), 56 bytes
```
<(x,i=0)=(x[1+x[i+2]]-=x[1+x[i+1]])>0 ? x<i+3 : x<x[i+3]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6FjctbDQqdDJtDTRtNSqiDbUrojO1jWJjdW1hHMPYWE07AwV7hQqbTG1jBSsgDRI2joXqb-KqULBViDbWUTDRUQCSZjoKhkDKEswCMnSB2FxHwQLIieVyKM7IL1eo4CopqlQA2qupkJxYkpxhnZqXApdySCwuTi0qUQCaimasOcxUXUswC24qxCUwHwEA)
mutates the input and ends by erroring
] |
[Question]
[
## Background
A [**Young diagram**](https://en.wikipedia.org/wiki/Young_tableau#Diagrams) is a diagram that represents a nonincreasing sequence of positive integers using left-justified rows of squares. As an example, `5, 4, 1` is drawn as
```
OOOOO
OOOO
O
```
A Young diagram is said to be **symmetric** if it is identical to its transpose (reflection along the NW-SE diagonal). The above diagram of `5, 4, 1` is not symmetric, since its transpose represents `3, 2, 2, 2, 1` instead:
```
5 OOOOO 3 OOO
4 OOOO 2 OO
1 O => 2 OO
2 OO
1 O
```
A symmetric example is that of `4, 2, 1, 1`:
```
OOOO
OO
O
O
```
## Challenge
Given a nonincreasing sequence of positive integers, add as few numbers as possible to the front of it so that its Young diagram becomes symmetric. If the input is already symmetric, your code is expected to output it as-is. You may take input and give output in reverse order (numbers in increasing order; e.g. `[1, 1, 2, 2] -> [1, 1, 2, 2, 4, 6]`).
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins.
## Test cases
```
[1] -> [1]
[2] -> [2, 2]
[3] -> [3, 3, 3]
[1, 1] -> [3, 1, 1]
[2, 1] -> [2, 1]
[3, 1] -> [4, 3, 3, 1]
[2, 2, 1] -> [5, 4, 2, 2, 1]
[3, 2, 1] -> [3, 2, 1]
[4, 2, 2] -> [4, 4, 2, 2]
[4, 2, 1] -> [6, 5, 4, 4, 2, 1]
[4, 4, 3] -> [4, 4, 4, 3]
[5, 4, 1] -> [6, 5, 5, 5, 4, 1]
[4, 2, 1, 1] -> [4, 2, 1, 1]
[2, 2, 1, 1] -> [6, 4, 2, 2, 1, 1]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ ~~24~~ ~~21~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g+àLZиæé€ì.ΔDÅ10ζOQ
```
Brute-force approach. Times out for most inputs.
-2 bytes thanks to *@ovs*.
[Try it online](https://tio.run/##AS0A0v9vc2FiaWX//2crw6BMWtC4w6bDqeKCrMOsLs6URMOFMTDOtk9R//9bMSwgMV0) or [verify some of the shorter test cases](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpdfnJiUmapgY6Pg6u/GZa@k8KhtkoKS/f907cMLfKIu7Di87PDKR01rDq/ROzfF5XCrocG5bf6B/2t1uEDKucozMnNSFYpSE1MUMvO4UvK5FBT08wtK9CGmQik0i2wUVMBq81L/RxvGckUbAbExEBvqgHlg0hjKhvEgtAmQNoLSEL6JDkinKZCGyRsidIJYAA).
## Previous answer: [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Å1ζO©[DN(.£I®gN-£Q#>}N£ì
```
Port of [*@gsitcia*'s Python answer](https://codegolf.stackexchange.com/a/235185/52210), so make sure to upvote him/her as well!
-1 byte by switching to the legacy version of 05AB1E. The original program was `Å10ζO©[D¾.$I®g¾-£Q#>¼}¾£ì`, with the following differences:
1. -1 byte: `0ζO` (zip with 0 filler; sum) is replaced with `ζO` (zip with default space filler; sum), since the legacy version will ignore these spaces when summing;
2. -1 byte: The `¾` are replaced with `N` and the `¼` has been removed, because `N` can be accessed outside of loops in the legacy version, which will reset to `0` in the new version;
3. +1 byte: `.$` wasn't a builtin yet in the legacy version, so we'll have to use `(.£` instead (`.$` is a[b:]; `.£` is a[-b:], and `(` negates the integer first).
[Try it online](https://tio.run/##ATMAzP8wNWFiMWX//8OFMc62T8KpW0ROKC7Co0nCrmdOLcKjUSM@fU7Co8Os//9bNSwgNCwgMV0) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL/8Othue2@R9aGe3ip6F3aHHloXXpfrqHFgcq29X6HVp8eM1/nf/R0YaxOtFGQGwMxIY6YB6YNIayYTwIbQKkjaA0hG@iA9JpCqRh8oYInUBWLAA).
**Explanation:**
```
g # Get the length of the (implicit) input-list
+ # Add it to each value in the (implicit) input-list
à # Pop and leave the maximum
L # Create a list in the range [1,max(input)+length(input)]
Z–∏ # Repeat each integer this max amount of times
√¶ # Get the powerset of this entire list
é # Sort it by length
ۓ # Prepend each in front of the (implicit) input-list
.Δ # Find the first list which is truthy for:
D # Duplicate the current list
√Ö1 # Map each integer in the list to a list of that many 1s
ζ # Zip/transpose this list of lists,
0 # with 0 as filler to make it a rectangle
O # Sum each inner row
# (we now have the reflection of the list)
Q # Check if the duplicated current list is equal to its reflection
# (after we've found a result, output it implicitly)
```
```
√Ö1 # Map each integer in the (implicit) input-list to a list of that many 1s
ζ # Zip/transpose this list of lists,
# with a space as default filler to make it a rectangle
O # Sum each inner row, ignoring the spaces
# (we now have the reflection of the input-list)
© # Store this list in variable `®` (without popping)
[ # Start an infinite loop:
D # Duplicate the current list
N(.£ # Remove the last 0-based loop-index amount of values from this list
I # Push the input-list
®g # Push the length of list `®`
N- # Decrease it by the 0-based loop-index
£ # Only leave that many leading items from the input-list
Q # If both lists (®[cv:] and input[:len(®)-cv]) are now equal:
# # Stop the infinite loop
> # If not, increase all values in the list by 1
} # After the infinite loop:
N # Push the (0-based) loop-index we ended at
£ # Only leave the index amount of values from the list
ì # And prepend it at the front of the (implicit) input-list
# (after which this is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
+L}Rṗ⁸;€b1ZƑ$Ƈ
0ç1#Ḣç
```
[Try it online!](https://tio.run/##y0rNyan8/1/bpzbo4c7pjxp3WD9qWpNkGHVsosqxdi6Dw8sNlR/uWHR4@X@dw@1HJz3cOQMonfWoYY6Crp3Co4a5XIfbgQKR//9Hc0UbxupwRRuBCGMQYaijABGB0sYIPpIQjGkCZhohmDBRIAIbZwpmIqk1RDUPxOOKBQA "Jelly – Try It Online")
A full program taking a list of integers as its argument and printing the shortest list satisfying the requirements. The TIO link includes all test cases.
## Explanation
### Helper link
Left argument is the number of additional digits to prepend, right argument is the original list
```
+ | Add:
L} | - Length of original list
R | Range 1..this
ṗ⁸ | Cartesian power with number of new digits
;€ | Prepend each to the original list
b1ZƑ$Ƈ | Convert to unary and test whether unchanged by transposition
```
# Main link
```
0ç1# | Starting with zero, identify how many additional digits are needed to make the list meet the requirements
·∏¢ | Head
ç | Then call the helper link again one last time
```
---
# An alternative [Jelly](https://github.com/DennisMitchell/jelly) answer uses less brute force, 21 bytes
```
b1S+⁹ḣɗⱮṀŻ$;€⁸b1ZƑ$ƇḢ
```
[Try it online!](https://tio.run/##y0rNyan8/z/JMFj7UePOhzsWn5z@aOO6hzsbju5WsX7UtOZR444kw6hjE1WOtT/csei/zuH2o5Me7pwBlMl61DBHQddO4VHDXK7D7UCByP//o7miDWN1uKKNQIQxiDDUUYCIQGljBB9JCMY0ATONEEyYKBCBjTMFM5HUGqKaB@JxxQIA "Jelly – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~92 ... 85~~ 82 bytes
```
f=->l,*r{l==(0...l[0]).map{|x|l.count{|y|y>x}}?l:f[*r+(1..l.sum).map{|q|[q+1]+l}]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5HR6uoOsfWVsNAT08vJ9ogVlMvN7GguqaiJkcvOb80r6S6prKm0q6ittY@xyotWqtIW8MQqFCvuDQXqrKwJrpQ2zBWO6c2tvZ/gUJadLRhbCwXhKEDhjCukQ4YwrkwhjFCAVytMTITVRyZg6YMbqQJSPw/AA "Ruby – Try It Online")
# Non-recursive version, 85 bytes
```
->l,*r{l,*r=r+(0..l.sum).map{|q|[q+1]+l}until(0...l[0]).map{|x|l.count{|y|y>x}}==l;l}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5HR6uoGkTYFmlrGOjp5egVl@Zq6uUmFlTXFNZEF2obxmrn1JbmlWTmgKT1cqINYqHSFTU5esn5QKnqmsqaSruK2lpb2xzrnNr/BQpp0dGGsbFcEIYOGMK4RjpgCOfCGMYIBXC1xshMVHFkDpoyuJEmIPH/AA "Ruby – Try It Online")
### How?
This explanation refers to the non-recursive version, which is functionally identical to the recursive one.
Sheer brute force:
```
->l,*r{
```
We must check all sequences, starting with the original: `r` is the list of sequence we haven't checked yet.
```
l,*r=r+(0..l.sum).map{|q|[q+1]+l}
```
This will be executed after each check: since the sequence is not symmetric (or not a Young diagram), we create a new list of sequence which can extend this one by adding one number at the beginning. The maximum possible value is the sum of the sequence + 1 (empirical evidence). The minimum is set to 0, this will generate a lot of non-Young diagrams, but those will be discarded by the check.
```
until(0...l[0]).map{|x|l.count{|y|y>x}}==l;
```
We've found the sequence if for any number `x` between 1 and the maximum value in `l`, the xth element of `l` is the number of elements of `l` that are greater or equal to `x`. If the first element of `l` is not the maximum, then the size of the sequence won't match (this will exclude all non-Young diagrams).
```
l}
```
Finally, return the sequence we have found.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
‚àûŒµLy√£}‚Ǩ` íI√Ö¬ø}.ŒîDƒÅŒ¥@√∏OQ
```
[Try it online!](https://tio.run/##ATMAzP9vc2FiaWX//@KIns61THnDo33igqxgypJJw4XCv30uzpRExIHOtEDDuE9R//9bMSwgMV0 "05AB1E – Try It Online") or [Try all cases!](https://tio.run/##S0oszvifnFiiYKeQnJ@SqpeYlKpgY6Og7urvpv7/Uce8c1t9Kg8vrn3UtCbh1CTPw62H9tfqnZvicqTx3BaHwzv8A/8DFXJxlWdk5qQqFKUmpihk5nGl5HMpKOjnF5To5xcnJmWmQilkC2wUVMAK81L/RxvGckUbAbExEBvqKIC5EMoYzkMIQFkmYJYRnAUVAyKQMaZgFkKdIYpBYA4A)
```
∞ε } # for y in [1, 2, ...]
L # take the range [1, ..., y]
y√£ # all y-tuples of these numbers
€` # flatten the result by one level
í } # filter; keep only those lists
I√Ö¬ø # that end with the input
.Δ # find the first list y that
Dāδ@øOQ # (is a symmetric Young diagram)
ā # push range [1, ..., len(y)]
δ@ # (<=) - table
√∏O # sum the columns, the result is a list giving the count of numbers >= n for each n
D Q # is this equal to y?
```
[Answer]
# JavaScript, 110 bytes
```
f=(a,l,g=a=>{for(i=j=k=l;j||=k=--i&&l;b[l-i]||=!j*k)k-=a[--j]<i})=>g(c=b=[...a],b=[g(a,c)])|b==c+''?c:f(a,-~l)
```
```
f=(a,l,g=a=>{for(i=j=k=l;j||=k=--i&&l;b[l-i]||=!j*k)k-=a[--j]<i})=>g(c=b=[...a],b=[g(a,c)])|b==c+''?c:f(a,-~l)
console.log(JSON.stringify(f([1])));
console.log(JSON.stringify(f([2])));
console.log(JSON.stringify(f([3])));
console.log(JSON.stringify(f([1, 1])));
console.log(JSON.stringify(f([1, 2])));
console.log(JSON.stringify(f([1, 3])));
console.log(JSON.stringify(f([1, 2, 2])));
console.log(JSON.stringify(f([1, 2, 3])));
console.log(JSON.stringify(f([2, 2, 4])));
console.log(JSON.stringify(f([1, 2, 4])));
console.log(JSON.stringify(f([3, 4, 4])));
console.log(JSON.stringify(f([1, 4, 5])));
console.log(JSON.stringify(f([1, 1, 2, 4])));
console.log(JSON.stringify(f([1, 1, 2, 2])));
```
First, function `g` try to calculate transpose of some given input.
```
g=a=>{for(i=j=k=l;j||=k=--i&&l;b[l-i]||=!j*k)k-=a[--j]<i}
```
Although there is only a variable `a` before the fat arrow, it actually takes 3 parameters:
1. The length `l`
2. The input array `a`
3. The output array `b`
It returns the transpose via modify variable `b` in-place.
It assumes `a` have `l` elements (as if there are some `l`s padded at the end of `a`). And try to calculate `a`'s transpose. When `b` is given an non-empty array, `g` keeps values already in `b` as is, and only calculate the remaining values.
So, we can use this function to:
1. `g(a,c=b=[...a])` will try to append some values to input, so it at least `l` elements in it, and the largest value is `l`. And `c` is the calculate result.
2. After that, `g(c,b=[])`will transpose `c`.
3. Finally, we test `b==c+''`: It will be true only if `c` is identical to its transpose.
4. We return `c` if it is identical to its transpose, or reject `c` and try a larger `l`.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/),31 25 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
‚àß‚àò‚äí‚åæ/{‚äëùîΩ‚ä∏‚â°¬®‚ä∏/‚ↂä∏+‚ä∏‚àæ‚üúù𤋮®‚ÜëùîΩùï©}
```
[Try it here](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oin4oiY4oqS4oy+L3viipHwnZS94oq44omhwqjiirgv4omg4oq4K+KKuOKIvuKfnPCdlanCqOKGkfCdlL3wnZWpfQoKRsKo4p+oMeKfqeKAv+KfqDLin6nigL/in6gz4p+p4oC/4p+oMSwx4p+p4oC/4p+oMiwx4p+p4oC/4p+oMywx4p+p4oC/4p+oMiwyLDHin6nigL/in6gzLDIsMeKfqeKAv+KfqDQsMiwy4p+p4oC/4p+oNCwyLDHin6nigL/in6g0LDQsM+KfqeKAv+KfqDUsNCwx4p+p4oC/4p+oNCwyLDEsMeKfqeKAv+KfqDIsMiwxLDHin6k=).
How it works:
`∧∘⊒⌾/` is a helper function for the transpose. It works by taking the [Indices](https://mlochbaum.github.io/BQN/doc/replicate.html#indices) `/`, then the [Occurrence Count](https://mlochbaum.github.io/BQN/doc/selfcmp.html#occurrence-count) `⊒`, sorts `∧` the result, then finally because of the modifier Under `⌾` — which conceptually means apply the function on the right, then the one on the left, then undo the one on the right—it takes the [inverse of Indices](https://mlochbaum.github.io/BQN/doc/replicate.html#inverse).
To visualize an example:
```
/ 5‚Äø4‚Äø1
0‚Äø0‚Äø0‚Äø0‚Äø0‚Äø1‚Äø1‚Äø1‚Äø1‚Äø2
‚äí 0‚Äø0‚Äø0‚Äø0‚Äø0‚Äø1‚Äø1‚Äø1‚Äø1‚Äø2
0‚Äø1‚Äø2‚Äø3‚Äø4‚Äø0‚Äø1‚Äø2‚Äø3‚Äø0
‚àß 0‚Äø1‚Äø2‚Äø3‚Äø4‚Äø0‚Äø1‚Äø2‚Äø3‚Äø0
0‚Äø0‚Äø0‚Äø1‚Äø1‚Äø2‚Äø2‚Äø3‚Äø3‚Äø4
/⁼0‿0‿0‿1‿1‿2‿2‿3‿3‿4
3‚Äø2‚Äø2‚Äø2‚Äø1
```
And then the main part:
```
{‚äëùîΩ‚ä∏‚â°¬®‚ä∏/‚ↂä∏+‚ä∏‚àæ‚üúù𤋮®‚ÜëùîΩùï©} # a 1-modifier where Transpose is ùîΩ and input is ùï©
‚ÜëùîΩùï© # list the prefixes of transposed input
¨ # for each prefix in the list:
≠⊸+ # add its length to itself
‚ä∏‚àæ‚üúùï© # and join to the input
‚ä∏/ # filter by:
ùîΩ‚ä∏‚â°¬® # whether each element is equivalent to its transpose
‚äë # select first result
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 142 bytes
```
lambda L:(Z:=[len([0for i in L if i>j])for j in range(L[0])])*0+min(K[:n]+L for n in range(1+len(Z))if(K:=[i+n for i in Z])[n:]==L[:len(Z)-n])
```
[Try it online!](https://tio.run/##VY/Bb4IwGMXP46/4PLXVugiiWUhq4sFdJNllJxmHqmXWYCGlbjPL/nbXggImJPS9/t77@pUXcyjU9KXU14x9XHN@2u45xBHeRCzJhcLJJCs0SJAKYpAZyMUxJc46Oktz9SlwnExSkpLhZHSSCq@TSKWjGBykOsgfuboNITLDa1suRwra6k1KEhWljMVJ1GBjlZKr0ZfIe/o@yFzAuz4LK5443QKDEy@x@OI5lao8G0yeqzKXBiMYLwARYrmdpTLM3ZFXldAGtoztrCq1VAZzisYLRLfEEz87URpYvb2utC60ndEQ5H5AyzwHIypTQemq9gPUppZ1tSzUYxYxNAyDrqG@HdhxFA0YohnK8C//I4giZuWOXBM/dU@3Py8JmmNAIbBq2qgpBfdZw6fgt14tPMf6bcoZ09YIm2DLdeiMQljrLhP0u2/2jWnb7vp@cwvMKTSFYT/ppveTYbNDQz4kZ/d8N9PvLxH0l324nPf3qJF/ "Python 3.8 (pre-release) – Try It Online")
Ungolfed:
```
def f(L):
Z = [0]*L[0]
for i in L:
Z[:i] = [j+1 for j in Z[:i]]
# Z is now transpose of L
for n in range(1+len(Z)):
K = [i+n for i in Z]
# K is the start of the transpose of (L with n elements prepended)
if K[n:]==L[:len(Z)-n]: # the overlapping parts must be equal
return K[:n]+L
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 21 bytes
```
~a₁.R⁰l⟦₅{{<.∧R⁰∋}ᶜ}ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vy7xUVOjXtCjxg05j@Yve9TUWl1to/eoYzlI5FFHd@3DbXNqH26d8P9/tKmOiY5h7P8IAA "Brachylog – Try It Online")
My first Brachylog program, so it can probably be improved a lot.
## Explanation
```
~a₁.R⁰l⟦₅{{<.∧R⁰∋}ᶜ}ᵐ
The input
~a‚ÇÅ is a suffix of
. the output,
R⁰ aka R⁰.
l The output's length,
‚ü¶‚ÇÖ range from 0 to that-1,
{ }ᵐ map:
{ }·∂ú count all possible outputs of this predicate:
The number
< is less than
. the output
‚àß and
R⁰ R⁰
‚àã contains
the output.
this has to be equal to the output.
```
[Answer]
# JavaScript (ES6), 117 bytes
```
f=(a,n)=>(g=(i,a,n)=>n?i>n?0:g(i,[i,...a],n-i)||g(i+1,a,n):i--?a.map(v=>t-=v>i,t=a[i])|t?0:g(i,a):a)(1,a,n)||f(a,-~n)
```
[Try it online!](https://tio.run/##dZHRboMgFIbv9xRcQnagE20vTLAPYrwgXTUsHTar8Yrs1R2KpJ1HjCbkz8f3H@FLj/px@TH3gdv@8zpNraIaLFMV7RQ1ENb2bPz3UXY@qQ0IIXQDlhvmnI/eswUrDednLb71nY6qGrgaKwOD0rVpmBvW3ZqVmtGwwbnWd/Ffy6ZLbx/97SpufUdbWmcNiQ9j5HAgPnnbMBIxEohEWI6wHMj8IjIDEnuf5BKiakTKPSxHWBGqE86oXeEjkGIJU/INnyfIVdL8GyOG@/Cr9gQkTFKk/fN/IX@xd8hBhf3H2JKaf7mIp1@mr2YDn16Pcc6nPw "JavaScript (Node.js) – Try It Online")
### How?
Starting with \$n=0\$, we prepend each non-increasing integer partition of \$n\$ to the input list and test whether one of the resulting lists is a symmetric Young diagram. We recursively increment \$n\$ until a solution is found.
For instance, the test case `[5, 4, 1]` is solved with \$n=16=6+5+5\$, leading to `[6, 5, 5, 5, 4, 1]`.
### Faster version (120 bytes)
This version will never generate a partition with a term less than the leading term of the input list. This allows it to solve `[9, 2]` (suggested by Wheat Wizard) almost instantly.
[Try it online!](https://tio.run/##LY3BCsMgEER/pcddqpL2VsHkQ8TDkkbZkmpoxJPk162kPQwMj3nMiwrt84e3LGN6Lq15AyQimhGCARa/HifuGXToxLJQSpETUTLW2tH1ds40SzmRetMGxYxZmjKyyIYsO6z5bxNqQiA7uNOp1fc7eURsc4p7Whe1pgAe7ENc7g6xfQE "JavaScript (Node.js) – Try It Online")
### Commented
```
f = (a, n) => ( // f = main function taking the input list a[]
g = (i, a, n) => // g = helper function computing the partitions
// and looking for a symmetric Young diagram
n ? // if n is not 0:
i > n ? // if i is greater than n:
0 // invalid partition: abort
: // else:
g( // first recursive call:
i, // pass i unchanged
[i, ...a], // prepend i to a[]
n - i // subtract i from n
) || // end of recursive call
g( // second recursive call:
i + 1, // increment i
a, // pass a[] unchanged
n // pass n unchanged
) // end of recursive call
: // else (n = 0 or undefined):
i-- ? // decrement i; if it was not 0:
a.map(v => // for each value v in a[]:
t -= v > i, // decrement t if v is greater than i
t = a[i] // starting with t = a[i]
) | t ? // end of map(); if t is not 0:
0 // this is not a symmetric Young diagram
: // else:
g(i, a) // process recursive calls until i = 0
: // else:
a // success: return a[]
)(1, a, n) // initial call to g
|| f(a, -~n) // if no solution was found, try again with n + 1
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~43~~ 35 bytes
```
WS⊞υLι§ΦE⊕⌈υ⁺Eι⁺ιLΦυ›νμυ⬤ι⁼λLΦι›νμ⁰
```
[Try it online!](https://tio.run/##bY7BCsIwDIbve4oeU@jAu6cdVAYKA5@gbGENpHV27dzb13YOD@J/CH/I/yXpjfb9Q3NKL0OMAlo3xXAPntwIUoouzgaiEld0YzBAUh6rLg8DNKF1A65wJg7o4aanzPYeLbqAQ@5XstFClFKJjuO8JWj39N244/nExaMu1ilhZZESG9wwl/zpGTXPwL8k/SEzdcifplQXVZ9SpXrhNw "Charcoal – Try It Online") Link is to verbose version of code. I/O is as a Young Diagram using `-`s as the fill character. Explanation:
```
WS⊞υLι
```
Input the diagram.
```
E⊕⌈υ
```
For each possible number of rows from `0` to the length of the first row (inclusive)...
```
⁺Eι⁺ιLΦυ›νμυ
```
... calculate the transpose of that number of columns, concatenating with the original input.
```
§Φ...⬤ι⁼λLΦι›νμ⁰
```
Print the first symmetric result.
Example: At each stage, an `i`-by-`i` square is prefixed to the original input (marked by `#` signs) and then extended by transposition (marked by `=` signs). The first symmetric result is then the one with `3` prefixed rows.
```
#####===
####=== #####==
###=== ####== #####==
##=== ###== ####== #####==
#=== ##== ###== ####== #####=
----- =---- ==--- ===-- ====- =====
---- =--- ==-- ===- ==== ====
- = = = = =
0 1 2 3 4 5
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~87~~ ~~86~~ ~~76~~ 72 bytes
```
l&@For[i=0,t@@(l=Join[l=#;i+t@i++,#])!=l,]&
t=Tr@UnitStep[l-#]&~Array~#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P0fNwS2/KDrT1kCnxMFBI8fWKz8zLzrHVtk6U7vEIVNbW0c5VlPRNkcnVo2rxDakyCE0L7MkuCS1IDpHVzlWrc6xqCixsk5Z7X9AUWZeSbSyrl2aA0g8ODkxr66aq9qwVoer2ghEGIMIQx2IAIQyhvHgfCjDBMgwgjGgIiY6YBNMgQy4GkMkAyBMS6A@rtr/AA "Wolfram Language (Mathematica) – Try It Online")
The helper function `t` returns the first `#` rows of the transpose of the Young diagram of `l`.
```
main function:
For[i=0, ,] start from i=0 (#extra rows)
l=#; t@i first i rows of transposed input
i+ shift right by i
Join[ ,#] prepend to input
t@@(l= )!=l transpose equal to itself?
l&@ (yes): return
i++ (no) : increment i and retry
t:
Tr@UnitStep[l-#] count entries of l >= i
&~Array~# for i=1..first argument
```
[Answer]
# [R](https://www.r-project.org/), ~~116~~ 106 bytes
```
function(x,u=function(a,b)colSums(outer(b,1:a,`>=`)),y=x){while(any(y-u(max(y),y)))y=c(u(F<-F+1,x)+F,x);y}
```
[Try it online!](https://tio.run/##TY/BDoIwDIZfpw3lMMCLOo@8gA8gY85IMsYCLG4xPvucEQiXft/fNk06xr4zNzsqq8ydx4czcu4GA54c34KgFuWgr66fYHCzGqEldhTUXHiDSIF7fL@enVYgTICQO@iFh5AmiBi4BAf1Oa8zRh6zOpVT@EQtrNUBdDfNwKigkmQiw4Tij3JNW16kSlKssnQqKn9ySLLtsN2BpEi7XzF@AQ "R – Try It Online")
Uses strategy copied from [Neil's answer](https://codegolf.stackexchange.com/a/235875/95126) - upvote that one!
] |
[Question]
[
# Description :
Given a string as input, check if it is a valid ordinal number in English or not. If it is valid return truthy value otherwise return falsy value. (Suggested by @Arnauld. Thanks . Also by @JoKing)
For users who want to know about *ordinal numbers* go here :
<https://www.mathsisfun.com/numbers/cardinal-ordinal-chart.html> (Suggestion by : qwr)
# Possible inputs :
```
21st ---> true
12nd ---> false
1nd ---> false
....
```
This is a **code golf** challenge so shortest code in each language will be the winner.
# Examples :
```
console.log('12th' , true) // This evaluates to true
console.log('1st' , true) // also evaluates to true
console.log('21nd' , false) // returns false
console.log('11st' , false) // returns false
console.log('111199231923819238198231923213123909808th' , true) // true
```
Since a lot of people asked the question regarding whether input will be only valid strings or not :
All inputs will always be valid. i.e they will be in the form of string and consist of a digit (or number of digits) along with one of the four suffixes :
`st` , `nd` , `rd` , `th`
[Answer]
# [Python](https://docs.python.org/3/), ~~56~~ 53 bytes
-3 thanks to (use unique letter inclusion instead of penultimate character equality)
```
lambda v:'hsnrhhhhhh'[(v[-4:-3]!='1')*int(v[-3])]in v
```
An unnamed function.
**[Try it online!](https://tio.run/##RY9hC4MgEIY/b7/CfTJHgec1yKBf0vrQaGGwWZgE@/UuUzdBH9/j7r275WPVrNGNzd29@vdj6MlWU7Vqo45D22xri7IusLs0FCi7Ttr6EHasmzTZ3DgbYp@rJbvKKKyW5oQKPXigOVBa5XELkAHAIyFSBIpYCzx9fhkpBQCj1T8CIKVA2G8VnypIAQgCJZcVj@NA8I2lGFQZBoe0QDIWvjmrz6fF@M39pjkZDzLmvg "Python 3 – Try It Online")**
### How?
Since all input (here `v`) is guaranteed to be of the form `\d*[st|nd|rd|th]` we can just test whether a character exists in `v` which we expect to be there if it were correct (`s`, `n`, `r`, or `h`, respectively) - that is `<getExpectedLetter>in v`.
The last digit usually determines this:
```
v[-3]: 0 1 2 3 4 5 6 7 8 9
v[-2]: h s n r h h h h h h
```
...except when the penultimate digit is a `1`, when all should end with `th` and hence our expected character must be `h`; to evaluate this we can take a slice (to avoid an index error occurring for inputs with no -4th character) `v[-4:-3]`. Since `0` maps to `h` already we can achieve the desired effect using multiplication prior to indexing into `'hsnrhhhhhh'`.
[Answer]
# [Bash + GNU utilities](https://www.gnu.org/software/bash/), 54
Regex matching seems to be a straightforward way to go. I'm pretty sure this expression could be shortened more:
```
egrep '((^|[^1])(1st|2nd|3rd)|(1.|(^|[^1])[^1-3])th)$'
```
Input from STDIN. Output as a shell return code - 0 is truthy and 1 is falsey.
[Try it online!](https://tio.run/##NcpBCsIwEIXhfU7hQmiyUPJmFJKzSAtKi1mJtFnm7nFe1cD8MJPvcd9K78tzXd6Hwfup3SaMwWOrTV5z03UOzePc/j@Wk46hlnAcejfmjDlj7lKLu9ogMmCEUYvwJrsmF3oKAt0lr7CACPZyFoVN@iV9V4FCNMecYqrlAw "Bash – Try It Online")
[Answer]
this is under the assumption that the input is valid ordinal pattern. if its not the case changes need to be made
# [JavaScript (Node.js)](https://nodejs.org),97 92 78 bytes
```
s=>("tsnr"[~~((n=(o=s.match(/(\d{1,2})(\D)/))[1])/10%10)-1?n%10:0]||'t')==o[2]
```
[Try it online!](https://tio.run/##dY5PC4JAEMXvfYoIwhlI3Vkva7B16VuoB/FPFrYb7tYl86uboodIejDzGH684V3TZ2qy5nK3rtJ50ZeyN/IAG2tUs4m6DkBJ0NJ4t9RmFfgQ5y/a8TdCfEIfMaIEfWJbYujSUQ2@Z0nbOtZBKXXEkz7Tyui68Gp9hhIc4rYamW0eBa5Xv9TY/5CTykdaprUpcBGdsxNdfh4UhjygYcS8xHRyCogHIQsFE1/l@g8 "JavaScript (Node.js) – Try It Online")
### Explanation
```
s=>
("tsnr" // all the options for ordinal - 4-9 will be dealt afterwards
[~~( //floor the result of the next expression
(n=( //save the number (actually just the two right digits of it into n
o=s.match(/(\d{1,2})(\D)/))[1]) //store the number(two digits) and the postfix into o (array)
/10%10)-1 //if the right most(the tenths digit) is not 1 (because one is always 'th')
?n%10:0] //return n%10 (where we said 0-3 is tsnr and afterwards is th
||'t') // if the result is undefined than the request number was between 4 and 9 therefor 'th' is required
==o[2] // match it to the actual postfix
```
### \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
port of @Herman Lauenstein
# [JavaScript (Node.js)](https://nodejs.org), 48 bytes
```
s=>/1.th|(^|[^1])(1st|2nd|3rd|[^1-3]th)/.test(s)
```
[Try it online!](https://tio.run/##dY69CsMwDIT3PkW32EN@ZC/24L5ISSDETtMS7GKpnfzubkIylIYeSHD6OHGP/t3jEO9PKn2wLo8mo7nUUNGUWJeuHbScAVIS3iYZ7XopZUsTrytySAx5HoLHMLtqDjc2sgIETQU3huLL8fPplyL9hwK8XenYz@j4IbpnN3r8vEhrIWEZtS@1WQEShNSNVo36Kpc/ "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 8, ~~54~~ 51 bytes
```
s->s.matches(".*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).")
```
**Explanation:**
[Try it online.](https://tio.run/##jZQxb4MwEIX3/IoTE44UhzOdGrXdujVLukWp5BBSSMFE@IgUFX47JTRSp4q3WDr50/np3fOd7MUuToevPims9/Rmc/c9I8qdpPXRJimtbyXRvqqK1DpKwo3Uufskr1bDRTcbDi9W8oTW5OiJer949rq0kmSpDwM9Zy1ZG@r59oN36iVk3xrXxnU71It4J0oHql/d2pybfTG0uXe7VPmBykHO/cHtjqz61bJc0nvdSHZ9HMvN1Uta6qoRfR5IKVzodBIG7CVQo8r/GeMOk0xcTzMPkk0yHCEQI5BBoBiBEOEGEW4guxG/DWK4wRyHLI8Q6Rwh2jlCxHMEqQcDAyUGiwyWGSg0DKWGodgwlBuGgsPguCd9VePSGrfRqy18OrWNkD8EMNiEIFMRTzFLMUehBxkdIvY3/pR1s67/AQ)
```
s-> // Method with String parameter and boolean return-type
s.matches(".*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).")
// Validates if the input matches this entire regex
```
Java's [String#matches](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#matches(java.lang.String)) implicitly adds `^...$`.
**Regex explanation:**
```
^.*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).$
^ Start of the regex
.*1. If the number ends in 11-19:
th it must have a trailing th
| If not:
(.* )? Optionally it has leading digits,
[^1] excluding a 1 at the end
(1s|2n|3r . followed by either 1st, 2nd, 3rd,
|[^1-3]t). 0th, 4th, 5th, ..., 8th, or 9th
$ End of the regex
```
[Answer]
# Pyth, ~~49~~ 60 bytesSBCS
```
Js<2zK%J100I||qK11qK12qK13q>2z"th".?qz+J@c."dt8¸*£tÎðÎs"2J
```
[**Test suite**](https://pyth.herokuapp.com/?code=Js%3C2zK%25J100I%7C%7CqK11qK12qK13q%3E2z%22th%22.%3Fqz%2BJ%40c.%22dt%038%C2%B8%2a%C2%A3t%C3%8E%C2%98%C3%B0%C3%8Es%222J&test_suite=1&test_suite_input=21st%0A12nd%0A1nd%0A12th%0A1st%0A21nd%0A11st%0A111199231923819238198231923213123909808th%0A113th&debug=0)
SE ate some unprintables in the code (and in the below explanation) but they're present in the link.
Explanation:
```
Js<2zK%J100I||qK11qK12qK13q>2z"th".?qz+J@c."dt8¸*£tÎðÎs"2J # Code
Js<2z # J= the integer in the input
K%J100 # K=J%100
I||qJ11qJ12qJ13 # IF K is 11, 12, or 13:
q>2z"th" # Print whether the end of the input is "th"
.? # Otherwise:
qz # Print whether the input is equal to
+J # J concatenated with
@ J # The object at the Jth modular index of
."dt8¸*£tÎðÎs" # The string "thstndrdthththththth"
c 2 # Chopped into strings of length 2 as a list
```
Python 3 translation:
```
z=input();J=int(z[:-2]);K=J%100
if K==11or K==12or K==13:print(z[-2:]=="th")
else:print(z==str(J)+["thstndrdthththththth"[2*i:2*i+2] for i in range(10)][J%10])
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-3 bytes thanks to an observation made in a comment made by on my Python entry.
```
ḣ-2VDṫ-’Ạ×ɗ/«4ị“snrh”e
```
A monadic link.
**[Try it online!](https://tio.run/##ATYAyf9qZWxsef//4bijLTJWROG5qy3igJnhuqDDl8mXL8KrNOG7i@KAnHNucmjigJ1l////MTAybmQ "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjsW6RmEuD3eu1n3UMPPhrgWHp5@crn9otcnD3d2PGuYU5xVlPGqYm/r/6J7D7Y@a1ngDceT//9HqhsUl6joK6kZ5KSDKuAhMmZRkgChTCGUJoQwNoLQhlDaC0sYQ2ghqhqEBjAFXCVcKU2uJEDE0tLQ0MjYEYgsoYQHhGhkaGxoZWxpYWhhAnWUIMReq1RjCM4F4wBDmEZjBRiDLYwE "Jelly – Try It Online").
### How?
```
ḣ-2VDṫ-’Ạ×ɗ/«4ị“snrh”e - Link: list of characters e.g. "213rd" or "502nd" or "7th"
ḣ-2 - head to index -2 "213" "502" "7"
V - evaluate 213 502 7
D - cast to decimal list [2,1,3] [5,0,2] [7]
ṫ- - tail from index -1 [1,3] [0,2] [7]
/ - reduce with: (no reduction since already length 1)
ɗ - last 3 links as a dyad:
’ - decrement (the left) 0 -1 x
Ạ - all? (0 if 0, 1 otherwise) 0 1 x
× - multiply (by the right) 0 2 x
«4 - minimum of that and 4 0 2 4
ị“snrh” - index into "snrh" 'h' 'n' 'h'
e - exists in? (the input list) 0 1 1
```
[Answer]
# Python 2, ~~92~~ ~~82~~ ~~74~~ 68 bytes
-8 thanks to *Chas Brown*
-6 thanks to *Kevin Cruijssen*
```
lambda s:(a+'t'*10+a*8)[int(s[-4:-2]):][:1]==s[-2:-1]
a='tsnr'+'t'*6
```
Constructs a big string of `th`s, `st`s, `nd`s, and `rd`s for endings `00` to `99`. Then checks to see if it matches.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~35~~ 31 bytes
-4 bytes thanks to @Asone Tuhid
Thanks to @Leo for finding a bug
```
1.th|(^|[^1])(1s|2n|3r|[04-9]t)
```
Outputs `1` for true and `0` for false. This assumes the input is in ordinal format with a valid suffix (ends with `st`, `nd`, `rd` or `th`).
[Try it online!](https://tio.run/##K0otycxLNPz/31CvJKNGI64mOs4wVlPDsLjGKK/GuAjE1TWOLdH8/9/UrCQDAA "Retina – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, 57 bytes
```
/..$/;say$&eq(th,st,nd,rd,(th)x6)[$_%100-$_%10-10&&$_%10]
```
[Try it online!](https://tio.run/##HYpRCsIwEET/c44YLCTpbjRS8QyeQESEFCpIWpP9qJd3zfZn5j1mlrG8I3Pvve4v9fnVZvzsabKVbE62JNukW0/dTT92COC2cgjGbHRnxkpqOIec1KGkRsfmkSaFICErolCQkEtow29e6DXnyu4aPSCwy38 "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 100 bytes
```
f('1':_:a@[_,_])=a=="th"
f(a:b)|length b>2=f b
f(a:"th")|a>'3'=1>0
f x=elem x$words"0th 1st 2nd 3rd"
```
[Try it online!](https://tio.run/##HctBCsMgEEDRfU4hEjBCF9HshJHeoxQZUWuosUWFZpG727Tb/3kR69On1HuYmGDKKLzezMXcOSAAbZEOYUJl@ZF8frRIrJYQiP3X3@YHarYwEHoeAtnBJ7@Rffy8iqt0PoGojcjsyFIc7RuuGd5lzW0MVJ68fwE "Haskell – Try It Online")
[Answer]
# [GeoGebra](https://geogebra.org), 56 bytes
```
s="1nd"
b=Ordinal(FromBase(Take(s,1,Length(s)-2),10))==s
```
[Try It On GeoGebra!](https://www.geogebra.org/calculator/s98dehwu)
Input is `s`, Output is `b`. `b` is `true` if `s` is a valid ordinal, `false` otherwise.
I just realized that GeoGebra has string support, so I had to try it.
### Explanation:
```
Ordinal(FromBase(Take(s,1,Length(s)-2),10))==s
Take(s,1,Length(s)-2) s without the last two characters
FromBase( ,10) Convert the string to a number
Ordinal( ) Convert the number to ordinal form
==s Is it equal to s?
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
₌Ǎ⌊∆o$c
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigozHjeKMiuKIhm8kYyIsIiIsIjIxbmQiXQ==)
Because we have a built-in for that.
## Explained
```
₌Ǎ⌊∆o$c
₌Ǎ⌊ # Push the letters and numbers of the input
∆o # Push the corresponding ordinal string
$c # are the letters of the string contained in the ordinal string?
```
[Answer]
# [Factor](https://factorcode.org/) + `math.text.english`, 37 bytes
```
[ 2 cut* swap dec> ordinal-suffix = ]
```
[](https://i.stack.imgur.com/FYAx9.gif)
## Explanation
```
! "121th"
2 cut* ! "121" "th"
swap ! "th" "121"
dec> ! "th" 121
ordinal-suffix ! "th" "st"
= ! f
```
[Answer]
# [Scala](http://www.scala-lang.org/), 51 bytes
Port of [@Kevin Cruijssen's Java answer](https://codegolf.stackexchange.com/a/162378/110802) in Scala.
[Try it online!](https://tio.run/##dZIxT8MwEIX3/IpTJrsSrs9hqpQiGNiYYENFMqnVFBknig8EIvz2EAkWlJfx3nBP33eXGx/91D2/hEbozp8ThQ8J6Zjpuu/pqyB695GanbqX4ZxO9f6m62LwSVNNU6732bx6adqQVWk2bKQdldk8PvFBXynOo0tjNYzzfFEdRJtST/PG7ZYehjdpP3fz0M9rJSbVqJKzlFr/z1w6LrJqWGaX0i4ytihkFDoUVihERQ4VOYiDeBwCcpgIIllUxRZ1sUVlbGHbikBoECvEDqFEhhYZamTokaFIXtEDOHTx@523Puaw@E50Y5BhYgiBGDACJoALeE0CvuXf5u9i@gE)
```
s=>s.matches(".*1.th|(.*[^1])?(1s|2n|3r|[^1-3]t).")
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~94~~ ~~82~~ ~~77~~ ~~73~~ 70 bytes
```
lambda s:'tsnrthtddh'[min(4,int(s[-3])*(('0'+s)[-4]!='1'))::5]==s[-2:]
```
[Try it online!](https://tio.run/##NY5BDoMgFETX7Sno6kOriR9sIiSchLKwIUaTigb@pqe3tsXFzGTyZjHrm8Ylym2wj@3Vz8/Qs2yAckw0UggjuHmKvK2mSDy7Wnlx5RwauGXh6tZfLCAIYczdW7tzafw2LIkRmyJzgJmgYiBj@AZKGn@1JBaMzTFAVYjEY4KotVS4qyvW/atEhVLpRneNSgG8OZ/WtN9kVLGBk9g04gc "Python 2 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 24 bytes
```
0ìþR2£`≠*.•’‘vê₅ù•sèsáнQ
```
[Try it online!](https://tio.run/##ATkAxv8wNWFiMWX//zDDrMO@UjLCo2DiiaAqLuKAouKAmeKAmHbDquKChcO54oCic8Ooc8Oh0L1R//8xc3Q "05AB1E – Try It Online")
or as a [Test suite](https://tio.run/##MzBNTDJM/V9TVln53@DwmsP7gowOLU541LlAS@9Rw6JHDTMfNcwoO7zqUVPr4Z1AgeLDK4oPL7ywN/B/pdLh/Qq6dgqH9yvp/DcoyeAyLC7hMspL4TIFsQ1BhBGQMAILGxelcBkagEhTIDYCChmCxA2KUgA)
**Explanation**
```
0ì # prepend 0 to input
þ # remove letters
R # reverse
2£ # take the first 2 digits
`≠ # check if the 2nd digit is false
* # and multiply with the 1st digit
.•’‘vê₅ù• # push the string "tsnrtttttt"
sè # index into this string with the number calculated
sáн # get the first letter of the input
Q # compare for equality
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~42~~ 39 bytes
Lambda:
```
->s{s*2=~/1..h|[^1](1s|2n|3r|[4-90]t)/}
```
[Try it online!](https://tio.run/##VY7BDoIwEETP9is2cEANIFs8UBP1Q2pNVIqQmEJoSTQUfx1BTNTD7mZmXzJTN@dHn237YKdbvaTb5wrDMLf8iGKO2lJl49rydcAiYRarrq8ao8Ep1HAh2MG1NGBB3it5MTI9qINyCOGEe0hN7vlg6kYKf9TaePCjKap0@Genm/4AI/FvIDJGYxwm@axkkhRjpDGLWBIl3xgiQnm65JCWYAsfSktmU1u3LbqxrNtmvBCwf@OwmbK6ob/blp1DpEr7Fw)
User input:
```
p gets*2=~/1..h|[^1](1s|2n|3r|[4-90]t)/
```
[Try it online!](https://tio.run/##KypNqvz/v0AhPbWkWMvItk7fUE8voyY6zjBWw7C4xiivxrioJtpE19IgtkRT//9/Q6O8FAA)
Matches:
* `1(anything)(anything)h` - `12th`
* `(not 1)1s` - (`1st`)
* `(not 1)2n` - (`2nd`)
* `(not 1)3r` - (`3rd`)
Because `[^1]` (`not 1`) doesn't match the beginning of a string, the input is duplicated to make sure there's a character before the last.
---
# [Ruby](https://www.ruby-lang.org/) `-n`, 35 bytes
```
p~/1..h|([^1]|^)(1s|2n|3r|[4-90]t)/
```
[Try it online!](https://tio.run/##KypNqvz/v6BO31BPL6NGIzrOMLYmTlPDsLjGKK/GuKgm2kTX0iC2RFP//39Do7yUf/kFJZn5ecX/dfMA)
Same idea as above but instead of duplicating the string, this also matches the start of the string (`^`).
[Answer]
# Excel, 63 bytes
```
=A1&MID("thstndrdth",MIN(9,2*RIGHT(A1)*(MOD(A1-11,100)>2)+1),2)
```
---
`(MOD(A1-11,100)>2)` returns `FALSE` when `A1` ends with `11`-`13`
`2*RIGHT(A1)*(MOD(A1-11,100)>2)+1` returns `1` if it's in `11`-`13` and `3`,`5`,`7`,etc. otherwise
`MIN(9,~)` changes any returns above `9` into `9` to pull the `th` from the string
`MID("thstndrdth",MIN(~),2)` pulls out the first `th` for inputs ending in `11`-`13`, `st` for `1`, `nd` for `2`, `rd` for `3`, and the last `th` for anything higher.
`=A1&MID(~)` prepends the original number to the ordinal.
---
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 122 bytes
Unlike most of the other answers on here, this will actually return false when the input is not a "valid ordinal pattern", so it will correctly return false on input like "3a23rd", "monkey" or "╚§+!". So I think this works for the entire set of possible input strings.
```
StringMatchQ[((d=DigitCharacter)...~~"1"~(e=Except)~d~~(e["1"|"2"|"3",d]~~"th")|("1st"|"2nd"|"3rd"))|(d...~~"1"~~d~~"th")]
```
[Try it online!](https://tio.run/##PU29CoNADH6XTApiTeygg1BoOxZaOorD4flzg1Y0Q6H2Xt3GUxpIwveXdIrbqlNsSrXU2fLk0fTNTXHZPnLP09nFNIbPrRpVydXoh2FoLSBYr8qu77Ia2LfaCsqFnIGkYwh0ISZuwZ89wIlXoderNGrwhdT/M2vYOYvlLp85rw@nD6BUmlKM0sk@kg0SxkhxGqVJlEguAEI5vS75E4B@NTKRnITkJIW4wWhfzkk0DS6njkJ/i@UH "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~65~~ 59 bytes
```
SpokenString@p[[#]]~StringTake~{5,-14}&@@ToExpression@#==#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2ar8T@4ID87NS@4pCgzL92hIDpaOTa2DsILScxOras21dE1NKlVc3AIyXetKChKLS7OzM9zULa1VVb7r8kVAFRY4pDmoGRoZFhcooTCL0pB5huiyRsalmQo/QcA "Wolfram Language (Mathematica) – Try It Online")
Of course Mathematica has a built-in (although undocumented) for converting to ordinal number. [Source](https://mathematica.stackexchange.com/questions/64860/built-in-way-to-convert-integer-to-ordinal-string).
(for the 65-byte version: according to that it seems that v9 and before doesn't need calling `Speak` before so it may be possible to save some more bytes)
Also check out KellyLowder's [answer](https://codegolf.stackexchange.com/a/162954) for a non-builtin version.
[Answer]
# PHP, 60 bytes
boring: regexp once more the shortest solution
```
<?=preg_match("/([^1]|^)(1st|2nd|3rd|\dth)$|1\dth$/",$argn);
```
empty output for falsy, `1` for truthy.
Run as pipe with `-nF` or [try it online](http://sandbox.onlinephpfunctions.com/code/eeb131319f5734a74a0654e85ed3d3ea7f3b2a6b). (TiO wrapped as function for convenience)
[Answer]
# x86 machine code, 65 bytes
```
00000000: 31c0 4180 3930 7cfa 8079 0161 7ef4 8079 1.A.90|..y.a~..y
00000010: ff31 7418 31db 8a19 83eb 308a 9300 0000 .1t.1.....0.....
00000020: 0031 db43 3851 010f 44c3 eb0a 31db 4380 .1.C8Q..D...1.C.
00000030: 7901 740f 44c3 c374 736e 7274 7474 7474 y.t.D..tsnrttttt
00000040: 74 t
```
Assembly:
```
section .text
global func
func: ;the function uses fastcall conventions
;ecx=first arg to function (ptr to input string)
xor eax, eax ;reset eax to 0
read_str:
inc ecx ;increment ptr to string
cmp byte [ecx], '0'
jl read_str ;if the char isn't a digit, get next digit
cmp byte [ecx+1], 'a'
jle read_str ;if the char after the digit isn't a letter, get next digit
cmp byte [ecx-1], '1'
je tens ;10-19 have different rules, so jump to 'tens'
xor ebx, ebx ;reset ebx to 0
mov bl, byte [ecx] ;get current digit and store in bl (low byte of ebx)
sub ebx, 0x30 ;convert ascii digit to number
mov dl, [lookup_table+ebx] ;get correct ordinal from lookup table
xor ebx, ebx ;reset ebx to 0
inc ebx ;set ebx to 1
cmp byte [ecx+1], dl ;is the ordinal correct according to the lookup table?
cmove eax, ebx ;if the ordinal is valid, set eax (return reg) to 1 (in ebx)
jmp end ;jump to the end of the function and return
tens:
xor ebx, ebx ;reset ebx to 0
inc ebx ;set ebx to 1
cmp byte [ecx+1], 't' ;does it end in th?
cmove eax, ebx ;if the ordinal is valid, set eax (return reg) to 1 (in ebx)
end:
ret ;return the value in eax
section .data
lookup_table db 'tsnrtttttt'
```
[Try it online!](https://tio.run/##rVZtb@JGEP5s/4oRusgmwcQ2VxXw5SpVvarf7gcEhNbrNThn76LdNXGV8tvTmTUmEN2p/XBIMfvyzDMzz8yY5MzsXjmz8OnTl69/wme4t83@nk2ZaSADSV9RKepyll7eRKrfcVWIqUKg4DsFI190VmgJlbSw2TBrdZW3Vmw2YVgyYzmr6/EYylbykO@Yvh1n4DeskuH4xXcHVhhrHtcPLyt/NUoTY1ejCa6SVBan1XmR2t1pdUZdrJJksUhnCf7NT495v02TWZLOFvFiHs8Hhvl59UsyrNKzy/lMDz7fVnGPi/1j5pdKh5Rx9RBnfQLVOqvu7jCpvcaLMlyNbswSboqVRKMBMnE6DLvxOPOP/nE0VMDYNp/yDHXwt5xfC47luARdlSKSKtpXAqJmljprlT8VbbOH6I8rHLopxAEZCqH1NdBcAf8BK8QlGE@2WiDuCwSPcbRYv3w8QoCnvLUQ5fBr9DElKw1RAcFKBm8bB3N05GAnuqntLB49Y4Icv9nzNwhenGjwIblPj4TvNYTRSt7e3v7@txXAVSvtEncreWNWcgQfQurgaPydrFxjRuJk/pfoKEeyRaUvsdB1BUQY5v59cHTx@T2trRpxXZFXI7itlISpxSnwvW2tcla7ZvfpsfTok9mdcGcO2hphYJgMTEsehKQL4/dgwbuHstLGAtNbsOrNMtyjpHhQyT2qbnDQ5Hbse53SIFg3oQcRaGGEpQ1hY9/TghUbRC/RQSU5jq2D4VKLBn3DibYn9BHFsSNyEv0RsesJBHGAp081DFRkXgKlRRMMlZEBhgtFta3sBLboXqIe/f49311CjKxnFD@iZCW@VNzWkZxd1MLixX/5iJyPxPkQ2HzSAPIncZQsYMcORFqWQlPyuq2FmYBR8ESDgDoEhCdTJ2xOwubdm675oKvXqAPk9eRCKgAvo8h4qx15HzuTBYqrtMDKoQGEtXrujVRJfFhDz7R57yvuZjE6c32h0dbwqjrxoFvZNrnQJ98F@n6slfrW7jeW5bW4Q4Y19BEojIBbULqoJLWkVg30WHDY/5Gfa5bcNcvFTfLdghY11s@4gg0uhxAY5@7INTMBLsP4zbEpLEnfwi6SUyMMRMh7YHVVYJVOjR1qYVv8zdFiO3YxAb6MBymfMDghCwp7KCmx4RHpfTWLVJmeitqe6r78yboENvCyQuHIYwEpBIzT7n561r6H3Euadev17wCHJD4kaV3nIYV/fl8VzDLfu2weKHKM1kht3Sd4xX8NXv8F "Bash – Try It Online")
[Answer]
# PCRE (Perl-compatible regular expression), 29 bytes
```
1.th|(?<!1)(1s|2n|3r)|[4-90]t
```
We accept `th` after any "teen" number, or after any digit other than 1..3. For 1..3, we use a negative lookbehind to accept `st`, `nd`, or `rd` only when not preceded by `1`.
## Test program
```
#!/usr/bin/bash
ok=(✓ ❌)
for i
do grep -Pq '1.th|(?<!1)(1s|2n|3r)|[4-90]t' <<<"$i"; echo $i ${ok[$?]}
done
```
### Results
```
1st ✓
1th ❌
2nd ✓
2th ❌
3rd ✓
3th ❌
4st ❌
4th ✓
11th ✓
11st ❌
12nd ❌
12th ✓
13th ✓
13rd ❌
112nd ❌
112th ✓
21nd ❌
32nd ✓
33rd ✓
21th ❌
21st ✓
11st ❌
111199231923819238198231923213123909808th ✓
```
] |
[Question]
[
*Inspired by [Digits in their lanes](https://codegolf.stackexchange.com/questions/160409/digits-in-their-lanes) and [1, 2, Fizz, 4, Buzz](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz)*
# Introduction
Your task is to generate exactly the following output:
```
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
```
# Challenge
This challenge is based on the Fizz Buzz challenge, and here is a recap: output the numbers from 1 to 100 inclusive, each number on its own line, but if the number is a multiple of 3, you should output "Fizz" instead of the original number, if the number is a multiple of 5, you should output "Buzz" instead of the original number. If the number is a multiple of 15, you should output "FizzBuzz" instead of the original number.
However, in addition to the requirement above, you should also indent each line using spaces to make that every column contains unique characters (excluding spaces and newlines) only. The spaces prepended to each line are the minimum required to make all the lines appeared before it (inclusive) has unique characters in each column.
For example, `1,2,Fizz,4` does not need any indentation because they already have unique characters in each column (column 1: `12F4`, column2: `i`, column3: `z`, column4: `z`), but when adding `Buzz` we need to indent by two spaces because otherwise we would have two `z`'s in both the 3rd and the 4th column. Since two spaces is enough to achieve the goal you should not indent it by three spaces. `7` and `8` does not need any indentation but when outputting `11` we need to indent by one space because the 1st column already has a `1`. `13` then needs to be indented by three spaces because now 1st, 2nd and 3rd column all have a `1`. Indentation for the remaining lines follow the same rule.
**To make the challenge simpler, The upper limit has been changed to 50.**
# Specs
* You can write a program or a function. Neither of them should take any non-empty input. Taking an empty input is fine.
* Since this is a KC challenge you need to produce the output as specified in the Introduction section. A single trailing newline is fine. No heading newlines or extra heading spaces. No extra trailing spaces for each line.
* Your program can exit with error or have non-empty STDERR output as long as STDOUT conforms to the specification.
* This is intra-language [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the program with lowest number of bytes wins in its language.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Python 2](https://docs.python.org/2/), 127 bytes
```
i=0;exec"print ord('<<<<>@<<BD=F?@HABJCNP=@RT?VABXCBZ<^`=>bdDf>?hBCjEn'[i])%60*' '+(i%3/2*'Fizz'+i%5/4*'Buzz'or`-~i`);i+=1;"*50
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9PWwDq1IjVZqaAoM69EIb8oRUPdBgjsHGxsnFxs3ewdPBydvJz9AmwdgkLswxydIpydomziEmztklJc0uzsM5ycs1zz1KMzYzVVzQy01BXUtTUyVY31jbTU3TKrqtS1M1VN9U201J1KgZz8ogTduswETetMbVtDayUtU4P//wE "Python 2 – Try It Online")
A fifty-byte lookup table seems to hurt the code size less than the logic necessary to track which characters have occurred in each column.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~167~~ ~~166~~ ~~163~~ ~~161~~ 157 bytes
```
a=eval(`[{0}]*99`);i=0
exec"f=i%3/2*'Fizz'+i%5/4*'Buzz'or`i+1`;i+=1;g=0\nwhile any(b>{c}for b,c in zip(a[g:],f)):g+=1\nmap(set.add,a[g:],f);print' '*g+f;"*50
```
[Try it online!](https://tio.run/##NctND0MwHIDx@z5FI5HSytQ2B5rusMO@BBJF8U@sGrMXxGc3lx2f/PKYaWx7fdo2KdRbdk6eLGzNSBTlLgfBDuqrSqsWYJ/9E8F3mGdMwQ79C8G31x79kAMNcg5UBLwRLNWfFjqFpJ6c4rqUa90PqPBKBBrNYByZNHHm1a4bN/uR6oc0zlONR1lV3t@4GUCPGGHS0JpbJGTb9gM "Python 2 – Try It Online")
Edits:
* `while` is shorter than `for..range()` by 1 byte.
* Thanks to @ovs for shaving off 3 bytes. I always forget `exec`...
* Adapted `i%3/2` trick from Lynn's answer (-2 bytes).
* @Lynn suggested `a=map(set,[[]]*99)`, but I found another way using `eval` and `repr` with same bytes (-4 bytes).
Use a list of sets to track the chars used for each column, and set inequality for membership. The rest follows the exact spec given.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~145~~ 144 bytes (143 for hex)
```
i;main(){for(;i++<50;printf("%*s%s%.d\n","000402800:81>34@56B7BH14JH3N56P76R0RX12ZX8^23`67b9b"[i]-48,i%3?"":"Fizz",i%5?"":"Buzz",i%3*i%5?i:0));}
```
[Try it online!](https://tio.run/##JcjLCoJAFADQf7kw4CPj6jycnKhwEdIiwpX0ojSMu8hCa2P07dNreU4VnKvKWjKXIzWO@6yvrWPI98cSza2l5l47wLyOdWx42jYwAEQUGGnERIcTLmZSpXGahWKR8aVUq1jlmBdhtC70PuIHFZejEja0C4QeEONTgATm1PfwkfwpffzFve9Qgq5rXta@AQ "C (gcc) – Try It Online")
```
0000h: 69 3B 6D 61 69 6E 28 29 7B 66 6F 72 28 3B 69 2B ; i;main(){for(;i+
0010h: 2B 3C 35 30 3B 70 72 69 6E 74 66 28 22 25 2A 73 ; +<50;printf("%*s
0020h: 25 73 25 2E 64 5C 6E 22 2C 22 FE FE FE 02 FE 00 ; %s%.d\n","......
0030h: 06 FE FE 08 06 FF 0C 01 02 0E 03 04 10 05 10 16 ; ................
0040h: FF 02 18 16 01 1C 03 04 1E 05 04 20 FE 20 26 FF ; ........... . &.
0050h: 63 28 26 06 2C 00 01 2E 04 05 30 07 30 22 5B 69 ; c(&.,.....0.0"[i
0060h: 5D 2B 32 2C 69 25 33 3F 22 22 3A 22 46 69 7A 7A ; ]+2,i%3?"":"Fizz
0070h: 22 2C 69 25 35 3F 22 22 3A 22 42 75 7A 7A 22 2C ; ",i%5?"":"Buzz",
0080h: 69 25 33 2A 69 25 35 3F 69 3A 30 29 29 3B 7D ; i%3*i%5?i:0));}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 129 bytes
```
puts (1..50).map{|n|" "*(".<<<<>@<<BD=F?@HABJCNP=@RT?VABXCBZ<^`=>bdDf>?hBCjEn"[n].ord%60)+("FizzBuzz
"[i=n**4%-15,i+13]||n.to_s)}
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFhBw1BPz9RAUy83saC6Jq9GSUFJS0NJzwYI7BxsbJxcbN3sHTwcnbyc/QJsHYJC7MMcnSKcnaJs4hJs7ZJSXNLs7DOcnLNc85Si82L18otSVM0MNLU1lNwyq6qcSququJSiM23ztLRMVHUNTXUytQ2NY2tq8vRK8uOLNWv//wcA "Ruby – Try It Online")
Double credit goes to Lynn here, for the [lookup table approach](https://codegolf.stackexchange.com/a/160532/77973) and the [fizzbuzz algorithm](https://codegolf.stackexchange.com/a/58841/77973).
The FizzBuzz algorithm is very interesting, and it hinges on the remarkable coincidence that all positive, non-composite numbers less than 15 (other than 3 and 5), when raised to the 4th power, are 1 more than a multiple of 15. In fact:
```
n n**4 n**4%15 n**4%-15
1 1 1 -14
2 16 1 -14
3 81 6 -9
4 256 1 -14
5 625 10 -5
6 1296 6 -9
7 2401 1 -14
8 4096 1 -14
9 6561 6 -9
10 10000 10 -5
11 14641 1 -14
12 20736 6 -9
13 28561 1 -14
14 38416 1 -14
15 50625 0 0
```
The values `3**4%15` and `5**4%15` are exactly 4 apart: the length of the string "Fizz". We can exploit this by using them to index from the end of a string, at least 9 characters in length. Multiples of 3 will index from the beginning of the string, and multiples of 5 will index from 5 characters from the end. Every other number will attempt to index from before the beginning of the string, and fail, returning `nil`. Then 15, of course, indexes from the 0th character. The fact that "FizzBuzz" is only 8 characters long is a small obstacle; we use a newline character to pad it, which will later be ignored by `puts`.
It's possible that the lookup table can be out-golfed by a more procedural approach, but my attempt was in the neighborhood of 190 bytes.
[Answer]
# [JavaScript (Node.js) REPL], 144 bytes
```
(f=(i,s=[['Fizz'][i%3]]+[['Buzz'][i%5]]||i+[],b=i>1?f(i-1):[])=>[...s].some((p,j)=>b.some(w=>w[j]==p&0!=p))?f(i,' '+s):b.push(s)&&b)(50).join`
```
`
[Try it online!](https://tio.run/##LcvRCoIwFIDhV6mL3A7OoUQ3yjHoopdY58KZ1sTcaJkgvvsy6vL74e@qd@Xrp3GvZLDXJoQWucFDKjwqxc5mnhkps9sTxatP498HomUxsSKh0ZTZseUmySBXBFgqKaUn6e2j4dyJbk36pwnLSXWE6KJ0iw7g@wm2YbGHXEs3@jv3EEU6FLUdvO0b2dsbb3mWguysGTi7DAygCB8 "JavaScript (Node.js) – Try It Online")
Warning program itself runs unacceptable time
# [JavaScript (Node.js)](https://nodejs.org), 132 bytes by Arnauld
```
f=(a=n=[],s=`${b=++n%5?'':'Buzz',n%3?b||n:'Fizz'+b}
`)=>n>50?'':a.some(x=>[...x].some((c,i)=>c!=0&c==s[i]))?f(a,' '+s):s+f([s,...a])
```
[Try it online!](https://tio.run/##JcvRCsIgFIDh@56ioKWiySB2MzgbdNFLiDBncxhLo1Mx1np2W3T5w/dfzMugvfvbYx/iuUvJATUQQGmB0GzfLXAesqImpCTH5zQREbJD3c5zKMnJL83bz6phUIWqyH/KSIzXjo5QKSnlqP9JrfALshvIdxYAldeM1Y4aQdaEIyuRO6pQLIvRLNkYMA6dHGJPHWUsfQE "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 185 bytes
```
v->{for(int n=0,l;n<50;System.out.printf((l>0?"%"+l:"%")+"s%s%n","",(n%3<1?"Fizz":"")+(n%5<1?"Buzz":n%3<1?"":n)))l="####%'##)+$-&'/()1*57$'9;&=()?*)A#EG$%IK+M%&O)*Q,U#".charAt(n++)-35;}
```
[Try it online!](https://tio.run/##LY/fS8MwEIDf91eEtFmT/ogdo4hruzJFRWSIDH0RH2LXztQsLU0ycKN/e82G93B3fN/dwTXswKJm@zOWgikF1oxLcJoA0JkvwUugNNO2HFq@BXvr8Eb3XO4@PgHrd4pcRgFo7BFqNBe0NrLUvJX0rpXK7Ks@e7erS1CDfDxEy1Pd9phLDWQehyKVWRKnm1@lqz1tjaadva1rjMUyLiCCgVjYTAKokEIShhCGWKJ5NivgAz8e4QJaaUlyJrfmTP61bQghIoeODeQ5DgncaOpdYTLzk2vXu0mnOSaFT1bO/aOLnp6DNZq@EP81fHMgLb9Zv9JYBgGJ5kk6jOnly5qysqw6K4wQ5MyGyTD@AQ "Java (JDK 10) – Try It Online")
## Credits
* [Geobits](https://codegolf.stackexchange.com/users/14215/geobits) for their [short FizzBuzz code](https://codegolf.stackexchange.com/a/58622/16236)
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) (though I was doing it when he posted the comment ;-) )
[Answer]
# [Haskell](https://www.haskell.org/), ~~190 187 186 178~~ 176 bytes
```
unlines$foldl(\a x->a++[[z|z<-iterate(' ':)x,all(\m->null[p|(p,q)<-m`zip`z,p==q&&p>' '])a]!!0])[]$h<$>[1..50]
a%b=a`mod`b<1
h n|n%15="FizzBuzz"|n%3="Fizz"|n%5="Buzz"|1<2=show n
```
[Try it online!](https://tio.run/##JYpBC4IwGIbv/YoVVkousugSm4eCTh2CLsEa@FWao8@5UimGv71ldHuf93lyqO4posv4yTUalU4rLyvxiv4JyJvGMJkIYVvLqKrTJ9SpPybjVfAOAbukoLFuEIVpfRM@AkaLxCqT2NBw/hiNTNzFMgDZ789kIKSXMy8W0XS6nMkeDM8ckqK8JmcW9XKiWz2MlnywVdauG2sHHS/@@Jud@b8Rm/MqL19EuwKUJpyYpj7Uz50mmftcMoRb5ehxs99/AQ "Haskell – Try It Online")
The slightly more readable (and annotated) version:
```
-- check if a is evenly divisible by b
a%b=a`mod`b<1
-- produce correct FizzBuzz output for a number
h n|n%15="FizzBuzz"|n%3="Fizz"|n%5="Buzz"|1<2=show n
-- test if all chars distinct between two strings
x#y=null[a|(a,b)<-x`zip`y,a==b&&a>' ']
-- given a new string and all previous strings
-- shift the new string to the right until all
-- chars are distinct
x!y=[z|z<-iterate(' ':)y,all(z#)x]!!0
g=h<$>[1..50]
f'=foldl step[]g
where step acc x = acc++[acc!x]
```
Edit: I ended up inlining some functions in the golfed version to save more bytes.
[Answer]
# [Jstx](https://github.com/Quantum64/Jstx), 122 [bytes](https://quantum64.github.io/Jstx/codepage)
```
◄50-☺6*ø($♥:ø↕♂Fizz♀☺(◙$♣:ø↕♂Buzz♀6☺(◙"ø↕$6◙♂<<<<>@<<BD=F?@HABJCNP=@RT?VABXCBZ<^`=>bdDf>?hBCjEn'[i])%60*♀&P◄59▼ö,► 7.☻a0.2
```
[Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.1/JstxGWT.html?code=4peENTAt4pi6NirDuCgk4pmlOsO44oaV4pmCRml6euKZgOKYuijil5kk4pmjOsO44oaV4pmCQnV6euKZgDbimLoo4peZIsO44oaVJDbil5nimYI8PDw8PkA8PEJEPUY_QEhBQkpDTlA9QFJUP1ZBQlhDQlo8XmA9PmJkRGY%24P2hCQ2pFbidbaV0pJTYwKuKZgCZQ4peENTnilrzDtizilrogNy7imLthMC4y)
[Answer]
# Deadfish~, 3041 bytes
```
{i}c{iiii}cdc{dddd}ic{iiii}iiic{dddd}dddcc{iiiiii}iiic{iiii}dddciiiiicdddc{d}iiic{i}dc{d}dddcdc{{d}iii}iic{iiiiii}iiiiiic{ii}iiic{{d}i}ic{iii}iiiiiic{iiii}dddcddciic{i}icdc{{d}ii}dddc{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddciiiic{i}dc{{d}ii}ddc{{i}ddd}iiiiiic{d}dc{i}iiic{d}ic{i}iiiic{{d}ii}dddc{iiiiii}iiiiic{i}iiic{d}c{{d}iii}iic{ii}dddcdddddc{d}ddc{ii}ddcddddddc{d}ddc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}ii}iic{d}ddc{ii}c{d}iic{d}ddc{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{iiiiii}iiic{iiii}dddciiiiiicddcdddc{d}dc{ii}dddc{dd}iic{ii}dddc{d}dciiiiiicdc{{d}}cc{{i}dd}dc{ii}iiciiiiiicdddc{{d}ii}ddc{{i}dd}iiiic{dd}ic{ii}ddc{d}iic{{d}iii}dddddc{{i}ddd}iiic{i}c{{d}ii}dddc{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}icddc{i}dc{d}ic{i}iiic{dd}iiic{ii}dc{d}dddddc{{d}iii}ic{{i}ddd}dc{ii}dc{dd}dddciic{ii}dddc{d}iic{i}iiic{{d}i}ic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}c{i}dcdddcciiic{i}ddc{d}ddddciiiiic{d}iiic{{d}iii}dc{{i}dd}dciiiiiicdcddddciiiiicdc{dddddd}iic{ddddd}iicc{iiii}dc{dddd}ic{iiii}c{dddd}c{iiiiii}c{iii}iiiiic{ii}dddcc{{d}}{d}ddc{iiii}iic{dddd}ddc{ii}iicc{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{ii}iicccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{iiii}iiiiic{dddd}dddddc{iiii}iiiiiic{dddd}ddddddc{ii}iicccccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iicccccccc{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{ii}iic{ii}dddcc{dddd}ic{ii}ii{c}{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iiccc{ii}dddciic{dddd}dc{ii}iicccc{ii}dddciiic{dddd}ddc{ii}ii{c}cc{iiii}ddc{iii}iiiiic{ii}dddcc{ddddd}ddddddc{iiiii}iciiiiicc{{d}}{d}ddc{ii}iiccccc{ii}dddciiiiic{dddd}ddddc{ii}iicccccc{ii}dddciiiiiic{dddd}dddddc{ii}ii{c}cccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iiccccccc{ii}dddc{i}ddc{ddddd}iiic{ii}ii{c}cccccccc{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{ii}ii{cc}{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iic{ii}ddcc{dddd}c{ii}iicccc{ii}ddcic{dddd}dc{ii}ii{cc}cc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}ii{cc}cccc{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{ii}iiccc{ii}ddciiiic{dddd}ddddc{ii}ii{cc}cccccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iiccccc{ii}ddciiiiiic{dddd}ddddddc{ii}iicccccc{ii}ddc{i}dddc{ddddd}iiic{ii}ii{cc}cccccccc{iiii}ddc{iii}iiiiic{ii}dddcc{ddddd}ddddddc{iiiii}iciiiiicc{{d}}{d}ddc{ii}iiccccccc{ii}dcddc{dddd}ic{ii}iicccccc{ii}dcdc{dddd}c{ii}ii{cc}{c}{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{iiii}icic{dddd}ddc{ii}ii{cc}{c}cccc{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{ii}ii{cc}{c}cccccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iic{ii}dciiiic{dddd}dddddc{ii}iicc{ii}dciiiiic{dddd}ddddddc{ii}ii{cc}{c}cccccccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}ii{cc}{cc}{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc{ii}iicccccccc{ii}cdddc{dddd}ic{ii}ii{cc}{cc}cc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iicc{ii}cdc{dddd}dc{ii}iiccc{ii}cc{dddd}ddc{ii}ii{cc}{cc}cccc{iiii}ddc{iii}iiiiic{ii}dddcc{ddddd}ddddddc{iiiii}iciiiiicc{{d}}{d}ddc{ii}iicccccc{ii}ciic{dddd}ddddc{ii}iiccccccc{ii}ciiic{dddd}dddddc{ii}ii{cc}{cc}cccccc{iiii}ddc{iii}iiiiic{ii}dddcc{{d}}{d}ddc{ii}iiccccccccc{ii}ciiiiic{ddddd}iiic{ii}ii{cc}{cc}{c}{iii}iiiic{iiiii}iciiiiicc{{d}}{d}ddc
```
] |
[Question]
[
### Task
**Given a wrapper element and a non-jagged 3D array, wrap the array top, bottom, and all-around.** You must handle both character and numeric data, but the wrapper and the present will have the same data type.
---
### Character example
For character data, you may chose to handle either 3D arrays of single characters or 2D arrays of strings:
Given the 2 layer, 2 row, 4 column character array
```
[[["Y","o","u","r"],
["g","i","f","t"]],
[["g","o","e","s"],
["h","e","r","e"]]]
```
and the character `"."`, answer the 4 layer, 4 row, 6 column character array
```
[[[".",".",".",".",".","."],
[".",".",".",".",".","."],
[".",".",".",".",".","."],
[".",".",".",".",".","."]],
[[".",".",".",".",".","."],
[".","Y","o","u","r","."],
[".","g","i","f","t","."],
[".",".",".",".",".","."]],
[[".",".",".",".",".","."],
[".","g","o","e","s","."],
[".","h","e","r","e","."],
[".",".",".",".",".","."]],
[[".",".",".",".",".","."],
[".",".",".",".",".","."],
[".",".",".",".",".","."],
[".",".",".",".",".","."]]]
```
or given the 2 row, 2 column array of 4-character strings
```
[["Your",
"gift"],
["goes",
"here"]]
```
and the character `"."`, answer the 4 row, 4 column array of 6-character strings
```
[["......",
"......",
"......",
"......"],
["......",
".Your.",
".gift.",
"......"],
["......",
".goes.",
".here.",
"......"],
["......",
"......",
"......",
"......"]]
```
---
### Numeric example
Given the 2 layer, 2 row, 2 column numeric array
```
[[[1,2],
[3,4]],
[[5,6],
[7,8]]]`
```
and the number `0`, answer the 4 layer, 4 row, 4 column numeric array
```
[[[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]],
[[0,0,0,0],
[0,1,2,0],
[0,3,4,0],
[0,0,0,0]],
[[0,0,0,0],
[0,5,6,0],
[0,7,8,0],
[0,0,0,0]],
[[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]]
```
[Answer]
# [J](http://jsoftware.com/), ~~16~~ 15 bytes
```
[h"2[h"1 h=.,,[
```
This is an anonymous verb. [Try it online!](https://tio.run/nexus/j#@5@mYGulEJ2hZATEhgoZtno6OtH/C0CCRgrGCiYKKgqGCtoKmXoKRiZcqckZ@QrqAUWpxal5JeoQbgFUNLwosaAgNQUqaqCQplDwHwA "J – TIO Nexus")
Thanks to Adám for 1 byte!
## Explanation
```
[h"2[h"1 h=.,,[ Wrapper is x, present is y.
, Prepend x to y
, then append
[ x.
This gives x y x, and the wrapper automatically spreads to form 2D slices.
h=. Save the above operation (not its result) to h.
[h"1 Apply h to x and every 2D slice of the previous result.
[h"2 Apply h to x and every 1D slice of the result of that.
```
[Answer]
## JavaScript (ES6), 97 bytes
```
(a,e)=>[c=[,,...b=a[0]].fill(d=[,,...b[0]].fill(e)),...a.map(a=>[d,...a.map(a=>[e,...a,e]),d]),c]
```
Where `a` is the three-dimensional array and `e` is the wrapper. Automatically converts a two-dimensional array of strings to a three-dimensional array of characters. Alternative version for when `a` is a two-dimensional array of strings and `e` is a character and you want to return a two-dimensional array of strings:
```
(a,e)=>[c=[,,...a[0]].fill(d=e.repeat(a[0][0].length+2)),...a.map(b=>[c,...b.map(s=>e+s+e),d]),c]
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~31~~ ~~19~~ ~~13~~ 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
Almost a transliteration (31 bytes) of [@Zgarb's solution](https://codegolf.stackexchange.com/a/103905/43319).
An anonymous function. Left argument is wrapping, right argument is gift.
```
⊣h⍤1⊣h⍤2(h←⍪⍪⊣)
```
`⊣h⍤1` *h* applied, with the anonymous function's left argument, to the columns of
`⊣h⍤2` *h* applied, with the anonymous function's left argument, to the rows of
`h←` *h* applied to the major cells i.e. the layers of the anonymous function's arguments, where *h* is
`⍪` the left argument prepended to the right argument
`⍪` prepended to
`⊣` the left argument
In other words, *h* is a function which surrounds its right argument (the gift) with its left argument (the wrapper). *h* is then applied to the gift's layers, then the rows of that, and finally the columns of that.
[TryAPL online!](http://tryapl.org/?a=f%u2190%u22A3h%u23641%u22A3h%u23642%28h%u2190%u236A%u236A%u22A3%29%20%u22C4%20A%u21902%202%204%u2374%27Yourgiftgoeshere%27%20%u22C4%20A%28%27.%27%20f%20A%29&run)
---
This Dyalog APL version 16.0 solution (19 bytes – courtesy of [@ngn](https://codegolf.stackexchange.com/users/24908/ngn)) handles any number of dimensions:
```
{⍵@(1+⍳⍴⍵)⊢⍺⍴⍨2+⍴⍵}
```
`⍵` the gift
`@(` placed at
`1+` one plus
`⍳` all the indices of
`⍴⍵` the shape of the gift
`)⊢` in the array consisting of
`⍺⍴⍨` the wrapper reshaped to the shape
`2+` two added to
`⍴⍵` the shape of the gift
In other words, we create an array entirely of wrapper elements, which in every dimension is two elements larger than the gift, then we place the gift into that array (thus replacing the wrapping elements in those positions) at an offset of one from the edges, i.e. in the center.
---
My own invention (-1 thanks to [@ngn](https://codegolf.stackexchange.com/users/24908/ngn)):
```
(⌽2 3 1⍉,)⍣6
```
This applies an anonymous function-train 6 times, each time with the wrapper as left argument, and the result of the previous application as right argument (although the first time around it will be the unmodified gift):
`(` an anonymous function-train
`⌽` reverse columns of
`2 3 1⍉` the rows-to-layers, columns-to-rows, layers-to-columns transposition of
`,` the wrapper followed by the gift
`)⍣6` applied six times
In other words, we add a layer of wrapper on the top of the array, then warp it so that the next side gets rotated into the top layer position, ready for another round of wrapping. This is repeated six times, with the final warping repositioning all axes to the original order.
[TryAPL online!](http://tryapl.org/?a=f%u2190%28%u233D2%203%201%u2349%2C%29%u23636%20%u22C4%20A%u21902%202%204%u2374%27Yourgiftgoeshere%27%20%u22C4%20A%28%27.%27%20f%20A%29&run)
[Answer]
# Octave, ~~23~~ 27 bytes
```
@(a,p)padarray(a,[1 1 1],p)
```
array: `a`
padval: `p`
It can be called as :
```
(@(a,p)padarray(a,[1 1 1],p))([1 2;3 4],40)
```
try (paste!)it on [Octave Online](https://octave-online.net/)
note: previous answer assumed default padval
[Answer]
# Python, ~~106~~ ~~104~~ 126 bytes
```
def w(g,c):x=len(g[0][0])+2;k=[[c*x]*(len(g[0])+2)];return k+[[c*x,*[c+"".join(str(k)for k in j)+c for j in i],c*x]for i in g]+k
```
Called as `w(gift, wrapping character)`. Can use the string and the array notation. [Try it online!](https://repl.it/Eu4M/4)
[Answer]
# Perl 6, 86 bytes
```
->\a,\w{my @z=[[w xx a[0;0]+2]xx a[0]+2]xx a+2;@z[1..a;1..a[0];1..a[0;0]]=a[*;*;*];@z}
```
A lambda that takes the 3D array and wrapping character as arguments.
* It first creates a 3D output array of the correct size, filled with the wrapping character.
* Then it uses the array slice syntax to assign the values of the original array into the correct slots of the new array, in one fell swoop.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ ~~33~~ 31 bytes
```
vy¬g̲s×S©svy².ø¼}®)ˆ}¾F®})¯s.ø
```
[Try it online! (string)](https://tio.run/nexus/05ab1e#@19WeWhN@uGeQ5uKD08PPrSyGMjfpHd4x6E9tYfWaZ5uqz20z@3QulrNQ@uLgaL//0dHRytFKuko5QNxKRAXKcXqRCulA1mZQJwGxCVKsUAhiBhIVSoQF4NVZUB5RWA6NjaWSw8A) or [Try it online! (numerical)](https://tio.run/nexus/05ab1e#@19WeWhN@uGeQ5uKD08PPrSyGMjfpHd4x6E9tYfWaZ5uqz20z@3QulrNQ@uLgaL//0dHRxvqGMXqRBvrmMQCqWhTHTMgZa5jERsby2UAAA)
[Answer]
## Ruby, 89 bytes
```
->a,b{(w=[[z=b*2+a[0][0].tr('^|',b)]*(2+a[0].size)])+a.map{|x|[z]+x.map{|y|b+y+b}+[z]}+w}
```
Have I ever told you I'm only here to learn ruby? :-)
] |
[Question]
[
Given the coordinates of several points on a plane, and the radius of a circle surrounding each point, draw polygons representing the circles and the edges where the circles meet. Straight edges will always fall along [circle-circle intersection](http://mathworld.wolfram.com/Circle-CircleIntersection.html) lines, but might not follow the full length of these lines.
~~Per [mbomb007](https://codegolf.stackexchange.com/users/34718/mbomb007)'s suggestion, imagine the behavior of 2D soap bubbles.~~ That's technically wrong, because soap bubbles would [always meet at 120° angles](https://en.wikipedia.org/wiki/Plateau%27s_laws) to minimize energy, while these circles may meet at any angle.
~~**This is a Voronoi diagram, minus a defined area plane.** Thanks [Andreas](https://codegolf.stackexchange.com/users/52361/andreas).~~ This is actually a generalization of a Voronoi diagram called a [power diagram](https://en.wikipedia.org/wiki/Power_diagram).
## Examples
For example, given two points and two radii, the output might look like this:
[](https://i.stack.imgur.com/5xKZE.png)
Add another point and radius and the output might look like this:
[](https://i.stack.imgur.com/vaplX.png)
## Input
You can structure the input however you wish. Please post results with the following inputs.
**Test 1**
* x: 10, y: 10, r: 10
* x: 25, y: 12, r: 8
**Test 2**
* x: 8, y: 10, r: 6
* x: 20, y: 8, r: 4
* x: 18, y: 20, r: 12
## Output
Output should be graphical and should include polygon borders, but nothing else is required. Points and intersections do not need to be represented like they are in the examples.
## Constraints
* No point will exist within the radius of another circle.
* Standard codegolf rules.
* No answers with [loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) will be accepted, but feel free to have fun with it.
[Answer]
# Python 2, ~~473~~ 355 bytes
```
L=input()
m=min
a,b,c,d=eval('m(%s-r for u,v,r in L),'*4%('u','v','-u','-v'))
e=(-c-a)/499.
H=lambda x,y:x*x+y*y
I=500
J=int(2-(d+b)/e)
print'P2',I,J,255
i=I*J
P=lambda(u,v,r):H(c+i%I*e+u,b+i/I*e-v)-r*r
while i:i-=1;p,k=m((P(k)/[1,k[2]][P(k)>0],k)for k in L);u,v,r=k;print int(255*m(1,[m([-p/r]+[(P(l)-p)/H(u-l[0],v-l[1])**.5for l in L-{k}]),p][p>0]/2/e))
```
This reads a set of circles as `(x,y,r)` tuples on stdin, and outputs an image in PGM format to stdout. It works roughly by computing a distance function of the diagram at each pixel, and shading each pixel less than one pixel away proportionally to its distance.
```
{(10,10,10),(25,12,8)}
```
[](https://i.stack.imgur.com/TNpUL.png)
```
{(8,10,6),(20,8,4),(18,20,12)}
```
[](https://i.stack.imgur.com/BSeR1.png)
```
{(6, 63, 4), (16, 88, 9), (64, 94, 11), (97, 96, 3), (23, 32, 13), (54, 14, 7), (41, 81, 3), (7, 7, 4), (77, 18, 8), (98, 55, 4), (2, 56, 7), (62, 18, 5), (13, 74, 2), (33, 56, 12), (49, 48, 4), (6, 76, 2), (82, 70, 9), (21, 71, 2), (27, 5, 10), (3, 32, 6), (70, 62, 6), (74, 46, 4), (21, 60, 7), (18, 47, 7), (94, 2, 4), (39, 97, 7), (62, 63, 2), (87, 29, 8), (19, 17, 4), (61, 23, 2), (73, 1, 8), (40, 17, 13), (99, 41, 4), (81, 57, 7), (1, 68, 5), (38, 3, 4), (46, 36, 9), (4, 39, 2), (73, 77, 3), (93, 19, 10), (67, 42, 3), (96, 65, 2), (2, 16, 3), (28, 92, 3), (54, 58, 2), (39, 86, 5), (84, 82, 5), (79, 43, 4), (5, 47, 1), (34, 41, 8), (65, 5, 2), (9, 44, 3), (53, 3, 6), (1, 12, 1), (81, 95, 7), (74, 31, 2), (63, 61, 1), (35, 72, 1), (44, 71, 2), (57, 35, 5), (46, 65, 6), (57, 45, 4), (93, 94, 1), (99, 81, 13), (13, 58, 4), (68, 32, 6), (11, 2, 6), (52, 98, 7), (51, 25, 5), (84, 2, 2), (44, 92, 3), (23, 72, 2), (32, 99, 7), (13, 19, 3), (97, 29, 8), (58, 80, 3), (67, 82, 5), (59, 60, 3), (86, 87, 5), (29, 73, 2), (5, 93, 4), (42, 74, 1), (75, 85, 8), (91, 53, 5), (23, 82, 4), (19, 97, 8), (51, 88, 3), (67, 12, 6), (60, 53, 1), (66, 72, 2), (57, 64, 2), (66, 49, 2), (44, 0, 4), (11, 69, 1), (93, 60, 5), (56, 50, 3), (19, 68, 3), (64, 75, 3), (6, 17, 2), (82, 5, 2)}
```
[](https://i.stack.imgur.com/1aFe7.png)
Here the distance function has been divided by 32 to make it visible:
```
{(7, 9, 7), (1, 3, 2), (4, 0, 4), (9, 2, 4), (0, 8, 5)}
```
[](https://i.stack.imgur.com/C5ig0.png)
[Answer]
**C# ~2746**
This is a solution in C#. Probably far from optimal but C# wont win this anyway. Just wanted myself to prove that i can do it.
Input via commandline by specifying the values seperated with a space
in the order x y r
Output is a file 'l.bmp' within the executing directory.
Program accepts any ammount of circles.
Test 1 : 10 10 10 25 12 8
Test 2 : 8 10 6 20 8 4 18 20 12
```
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
class Program
{
static void Main(params string[] args) => new Program().run(args);
class Circle
{
public PointF P;
public float R;
}
class Line
{
public PointF S;
public PointF E;
public Circle C1;
public Circle C2;
public Line(Circle c1, Circle c2, PointF s, PointF e)
{
S = s;
E = e;
C1 = c1;
C2 = c2;
}
}
List<Line> lines = new List<Line>();
List<Circle> circles = new List<Circle>();
void run(string[] args)
{
for (int i = 0; i < args.Length; i += 3)
addcircle(args[i], args[i + 1], args[i + 2]);
circles.Sort((c1, c2) => c1.P.X.CompareTo(c2.P.X));
int mx = (int)circles.Max(c => c.P.X + c.R) + 1;
int my = (int)circles.Max(c => c.P.Y + c.R) + 1;
for (int i = 0; i < circles.Count; i++)
for (int j = i + 1; j < circles.Count; j++)
{
var c1 = circles[i];
var c2 = circles[j];
var d = dist(c1.P, c2.P);
var a = 1 / d * sqrt((-d + c1.R - c2.R) * (-d - c1.R + c2.R) * (-d + c1.R + c2.R) * (d + c1.R + c2.R));
var x = (sqr(d) - sqr(c2.R) + sqr(c1.R)) / (2 * d);
var ap = angle(c1.P, c2.P);
var la = rotate(c1.P, new PointF(c1.P.X + x, c1.P.Y + a / 2), ap);
var lb = rotate(c1.P, new PointF(c1.P.X + x, c1.P.Y - a / 2), ap);
var l = new Line(c1, c2, la, lb);
lines.Add(l);
}
foreach (Line l in lines)
foreach (Line lo in lines)
{
if (l == lo) continue;
var intersection = intersect(l, lo);
if (intersection != null && online(intersection.Value, l) && online(intersection.Value, lo))
{
foreach (Circle circle in circles)
{
if (l.C1 == circle || l.C2 == circle)
continue;
if (dist(intersection.Value, circle.P) >= circle.R)
continue;
if (dist(l.E, circle.P) < circle.R)
l.E = intersection.Value;
if (dist(l.S, circle.P) < circle.R)
l.S = intersection.Value;
}
}
}
using (Bitmap bmp = new Bitmap(mx, my))
{
using (Graphics g = Graphics.FromImage(bmp))
{
g.Clear(Color.White);
foreach (var c in circles)
draw(g, c);
for (int i = 0; i < circles.Count; i++)
{
var c1 = circles[i];
var p = new PointF(c1.P.X + c1.R, c1.P.Y);
for (int j = 0; j < circles.Count; j++)
{
if (i == j) continue;
var c2 = circles[j];
for (var f = 0f; f <= 360f; f += 0.1f)
{
var pl = rotate(c1.P, p, f);
if (dist(pl, c2.P) <= c2.R)
{
g.DrawRectangle(new Pen(Color.White), (int)pl.X, (int)pl.Y, 1, 1);
}
}
}
}
foreach (var l in lines)
draw(g, l);
}
bmp.Save("t.bmp");
}
}
private float dist(PointF p1, PointF p2) => sqrt(sqr(p1.X - p2.X) + sqr(p1.Y - p2.Y));
bool online(PointF p, Line l)
{
var lx = l.S.X < l.E.X ? l.S.X : l.E.X;
var hx = l.S.X > l.E.X ? l.S.X : l.E.X;
var ly = l.S.Y < l.E.Y ? l.S.Y : l.E.Y;
var hy = l.S.Y > l.E.Y ? l.S.Y : l.E.Y;
return p.X >= lx && p.X <= hx && p.Y >= ly && p.Y <= hy;
}
static PointF? intersect(Line l1, Line l2)
{
//Line1
float A1 = l1.E.Y - l1.S.Y;
float B1 = l1.S.X - l1.E.X;
float C1 = A1 * l1.S.X + B1 * l1.S.Y;
//Line2
float A2 = l2.E.Y - l2.S.Y;
float B2 = l2.S.X - l2.E.X;
float C2 = A2 * l2.S.X + B2 * l2.S.Y;
float det = A1 * B2 - A2 * B1;
if (det == 0)
{
return null; //parallel lines
}
float x = (B2 * C1 - B1 * C2) / det;
float y = (A1 * C2 - A2 * C1) / det;
return new PointF(x, y);
}
void addcircle(string x, string y, string r)
{
var SCALE = 20f;
Circle c1 = new Circle
{
P = new PointF(float.Parse(x) * SCALE, float.Parse(y) * SCALE),
R = float.Parse(r) * SCALE
};
circles.Add(c1);
}
void draw(Graphics g, Line l) => g.DrawLine(new Pen(Color.Red), l.S.X, l.S.Y, l.E.X, l.E.Y);
PointF rotate(PointF o, PointF p, float angle)
{
var sa = (float)Math.Sin(angle);
var ca = (float)Math.Cos(angle);
var dx = p.X - o.X;
var dy = p.Y - o.Y;
return new PointF((ca * dx - sa * dy + o.X), (sa * dx + ca * dy + o.Y));
}
float angle(PointF p1, PointF p2)
{
var dx = p2.X - p1.X;
if (dx == 0)
return 0f;
return (float)Math.Atan((p2.Y - p1.Y) / dx);
}
void draw(Graphics g, Circle c)
{
g.DrawEllipse(new Pen(Color.Blue),
c.P.X - c.R,
c.P.Y - c.R,
c.R * 2,
c.R * 2);
}
float sqr(float d) => d * d;
float sqrt(float d) => (float)Math.Sqrt(d);
}
```
All the Math involved here is based on [this](http://mathworld.wolfram.com/Circle-CircleIntersection.html). The coordinates of the lines were easy to get using the formulars from the link. However they needed to be rotated by the angle between the two involved cricles centers.
To reduce the lines length i calculated their intersections. Then for that intersection i checked if the current lines end reaches into a circle that isnt the "parent of the line" and also contains the intersection itself. If that was the case, that end of the line was reduced to the location of the intersection.
The circles were simple to draw, the "notneeded" parts were difficult to remove, so i came up with a "rubber" solution, that removes the stuff that isnt needed anymore by painting it white again. Kind of brute forcing it. This is done by walking along each circles edge and checking if that pixel is within range of another circle.
Initially i wanted to roll my own circle-drawing method that only draws the circle withing specified angles but that didnt turn out well and took even more lines of code.
Really having a hard time explaining this if you havent noticed... English isnt my mother tounge so i am sorry for that.
Golfed
```
using System;using System.Collections.Generic;using System.Drawing;using System.Drawing.Imaging;using System.Linq;class P{static void Main(params string[]args)=>new P().R(args);class C{public PointF P;public float R;}class L{public PointF S;public PointF E;public C C1;public C C2;public L(C c1,C c2,PointF s,PointF e){S=s;E=e;C1=c1;C2=c2;}}List<L>_=new List<L>();List<C>c=new List<C>();void R(string[]args){for(int i=0;i<args.Length;i+=3)A(args[i],args[i+1],args[i+2]);c.Sort((c1,c2)=>c1.P.X.CompareTo(c2.P.X));int B=(int)c.Max(c=>c.P.X+c.R)+1;int e=(int)c.Max(c=>c.P.Y+c.R)+1;for(int i=0;i++<c.Count;)for(int j=i+1;j++<c.Count;){var f=c[i];var q=c[j];var d=D(f.P,q.P);var a=1/d*S((-d+f.R-q.R)*(-d-f.R+q.R)*(-d+f.R+q.R)*(d+f.R+q.R));var x=(F(d)-F(q.R)+F(f.R))/(2*d);var h=angle(f.P,q.P);var k=R(f.P,new PointF(f.P.X+x,f.P.Y+a/2),h);var m=R(f.P,new PointF(f.P.X+x,f.P.Y-a/2),h);var l=new L(f,q,k,m);_.Add(l);}foreach(L l in _)foreach(L o in _){if(l==o)continue;var n=I(l,o);if(n !=null && O(n.Value,l)&& O(n.Value,o)){foreach(C p in c){if(l.C1==p || l.C2==p)continue;if(D(n.Value,p.P)>=p.R)continue;if(D(l.E,p.P)<p.R)l.E=n.Value;if(D(l.S,p.P)<p.R)l.S=n.Value;}}}Bitmap r=new Bitmap(B,e);Graphics g=Graphics.FromImage(r);g.Clear(Color.White);foreach(var _ in c)D(g,_);for(int i=0;i++<c.Count;){var Q=c[i];var P=new PointF(Q.P.X+Q.R,Q.P.Y);for(int j=0;j++<c.Count;){if(i==j)continue;var G=c[j];for(var f=0f;f<=360f;f+=0.1f){var H=R(Q.P,P,f);if(D(H,G.P)<=G.R){g.DrawRectangle(new Pen(Color.White),(int)H.X,(int)H.Y,1,1);}}}}foreach(var l in _)D(g,l);r.Save("t.bmp");}float D(PointF p1,PointF p2)=>S(F(p1.X-p2.X)+F(p1.Y-p2.Y));bool O(PointF p,L l){var lx=l.S.X<l.E.X ? l.S.X : l.E.X;var hx=l.S.X>l.E.X ? l.S.X : l.E.X;var ly=l.S.Y<l.E.Y ? l.S.Y : l.E.Y;var hy=l.S.Y>l.E.Y ? l.S.Y : l.E.Y;return p.X>=lx && p.X<=hx && p.Y>=ly && p.Y<=hy;}static PointF? I(L l1,L l2){float a=l1.E.Y-l1.S.Y;float b=l1.S.X-l1.E.X;float d=a*l1.S.X+b*l1.S.Y;float e=l2.E.Y-l2.S.Y;float f=l2.S.X-l2.E.X;float g=e*l2.S.X+f*l2.S.Y;float h=a*f-e*b;if(h==0)return null;float x=(f*d-b*g)/h;float y=(a*g-e*d)/h;return new PointF(x,y);}void A(string x,string y,string r){var F=20f;C _=new C{P=new PointF(float.Parse(x)*F,float.Parse(y)*F),R=float.Parse(r)*F };c.Add(_);}void D(Graphics g,L l)=>g.DrawLine(new Pen(Color.Red),l.S.X,l.S.Y,l.E.X,l.E.Y);PointF R(PointF o,PointF p,float angle){var a=(float)Math.Sin(angle);var n=(float)Math.Cos(angle);var b=p.X-o.X;var x=p.Y-o.Y;return new PointF((n*b-a*x+o.X),(a*b+n*x+o.Y));}float angle(PointF p1,PointF p2){var a=p2.X-p1.X;if(a==0)return 0f;return(float)Math.Atan((p2.Y-p1.Y)/a);}void D(Graphics g,C c){g.DrawEllipse(new Pen(Color.Blue),c.P.X-c.R,c.P.Y-c.R,c.R*2,c.R*2);}float F(float d)=>d*d;float S(float d)=>(float)Math.Sqrt(d);}
```
[](https://i.stack.imgur.com/oAwYS.png)
[](https://i.stack.imgur.com/vADxz.png)
More Complex examples (top circle gets into negative y values)
[](https://i.stack.imgur.com/Mre4z.png)
[](https://i.stack.imgur.com/QCk2R.png)
] |
[Question]
[
## Background
Today (or Yesterday) is (or was) 11/23 or Fibonacci day! What better way to celebrate than to make a Fibonacci cake?
---
## Examples
```
3
ii
i_i_ii_i_i
```
</>
```
8
ii
ii
ii
ii
ii
ii
ii
ii
i ii i
i ii i
i ii i
i ii i
i ii i
i i ii i i
i i ii i i
i i ii i i
i i i ii i i i
i i i ii i i i
i i i i ii i i i i
i i i i i ii i i i i i
i_i_i_i_i_i_i_ii_i_i_i_i_i_i_i
```
## Challenge
You're not really making a cake, just the candles because I can't ascii-art a cake
To make the cake you must first get the first `n` [Fibonacci numbers](https://oeis.org/A000045) sorted ascending. The candle (`i`)'s height is determined by value of the current Fibonacci number. The candles are separated by an underscore (`_`).
The cake should be symmetrical. So the candles should then be flipped and concatenated.
## Example Construction
```
Input: 6
First 6 Fibonacci Numbers: 1, 1, 2, 3, 5, 8
Candle heights:
i
i
i
i i
i i
i i i
i i i i
i i i i i i
-----------
1 1 2 3 5 8
Output would be:
ii
ii
ii
i ii i
i ii i
i i ii i i
i i i ii i i i
i_i_i_i_i_ii_i_i_i_i_i
```
## Reference Fibonacci Numbers
For reference, here are the first 15 Fibonacci numbers. In this challenge, you'll be starting at `1`.
```
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610
```
[Answer]
# J, 58 bytes
```
3 :''' i_''{~|.|:(,|.)(#&1,2#~0&=)"*}.,0,.(%-.-*:)t.1+i.y'
```
Uses `(%-.-*:)t.` for Fibonacci generation. Explanation might come a bit later.
Usage:
```
f=.3 :''' i_''{~|.|:(,|.)(#&1,2#~0&=)"*}.,0,.(%-.-*:)t.1+i.y'
f 5
ii
ii
i ii i
i i ii i i
i_i_i_i_ii_i_i_i_i
```
[Try it online here.](http://tryj.tk/)
[Answer]
# CJam, ~~41~~ 39 bytes
```
"i""_"1$ri({1$1$4$+}*]),f{Se[}W<_W%+zN*
```
This prints a fair amount of leading whitespace. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%22i%22%22_%221%24ri(%7B1%241%244%24%2B%7D*%5D)%2Cf%7BSe%5B%7DW%3C_W%25%2BzN*&input=8).
### How it works
```
"i""_"1$ e# Push "i", "_", and a copy of "i".
ri( e# Read an integer from STDIN and subtract 1.
{ e# Do that many times:
1$ e# Copy the last underscore.
1$4$+ e# Copy the last strings of i's and concatenate them.
}* e#
]), e# Wrap the results in an array, pop the last string, and get its length.
f{ e# For each remaining string, push the string and the length; then:
Se[ e# Pad the string to that length by prepending spaces.
}
W< e# Remove the last string (underscore).
e# We have now generated the columns of the left half of the output.
_W%+ e# Append a reversed copy (columns of right half).
z e# Transpose rows with columns.
N* e# Separate the rows by linefeeds.
```
[Answer]
# TeaScript, ~~93~~ ~~84~~ 76 + 1 = 77 bytes
+1 byte for "Inputs are numbers?" checkbox
```
r×ß(p.R((w=F(x©-F(i¬©+"i"R(F(i¬±)t¡ß(j=i<w-1?" ":"_",(A=l¿i>0?j+l:l)µ)+Av©j§
```
**Ungolfed version:**
```
r(x)m(#(p.R((w=F(x))-F(i+1))+"i"R(F(i+1))))t()m(#(j=i<w-1?" ":"_",(A=ls``.m(#i>0?j+l:l)j``)+Av))j`
`
```
Thanks to [@Vɪʜᴀɴ](https://codegolf.stackexchange.com/users/40695/v%c9%aa%ca%9c%e1%b4%80%c9%b4) for the tips.
[Answer]
## Python 2, 117 bytes
```
a=b='i'
l=a,
exec"l+='_',b,;a,b=b,b+a;"*~-input()
for r in map(None,*l+l[::-1])[::-1]:print''.join(x or' 'for x in r)
```
The idea is simple: generate the picture in columns going bottom to top, left to right, with the mirrored right half the reverse of the left. The columns are generated by iterating the Fibonacci recurrence, on strings of `i`'s, interspersed with `_`'s for the bottom row.
To print the picture with columns starting from the bottom, we need to rotate it, which means transposing and reversing. Unfortunately, Python doesn't have a simple way to transpose an array of unequal-length rows. The built-in `zip` truncates to the shortest row. This uses the `map(None,_)` trick, but has to convert all the `None` to spaces afterwards.
[Answer]
# Pyth, 31 bytes
```
jaPJ_.ts_BuaaGks>4GtQ]\idXeJ" _
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?input=8&code=jaPJ_.ts_BuaaGks%3E4GtQ%5D%5CidXeJ%22%20_)
### Explanation:
```
jaPJ_.ts_BuaaGks>4GtQ]\idXeJ" _ implicit: Q = input number
u tQ]\i reduce the list [1, ..., Q-2], start with G=["i"]
aGk append the empty string to G
a s>4G append the sum of the last 4 strings in G to G
this gives ["i", "", "i", "", "ii", "", "iii",..]
s_B extend the list with the reversed list
.t d pad to a rectangle with spaces and transposes
J_ reverse the order and assign to J
PJ remove the last string of J
a and append
XeJ" _ the last string of J with spaces replaced by "_"
j print each string on a separate line
```
[Answer]
# Haskell, ~~182~~ 176 bytes
```
import Data.List
f=0:scanl(+)1f
b n c s|length s<n=b n c(c:s)|0<1=s
m s=s++reverse s
c n=mapM_ putStrLn$transpose$m$map(b(f!!n)' ')$intersperse"_"$map(\x->[1..f!!x]>>"i")[1..n]
```
Call `c`.
(`f` shamelessly stolen from <https://stackoverflow.com/questions/232861/fibonacci-code-golf>)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes
```
RÆḞ”iẋz⁶Ḣj”_ƊṭK€Ṛ$Ɗm€0Y
```
[Try it online!](https://tio.run/##y0rNyan8/z/ocNvDHfMeNczNfLiru@pR47aHOxZlAbnxx7oe7lzr/ahpzcOds1SOdeUCWQaR/w@3//9vAQA "Jelly – Try It Online")
Jelly's not great at [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") and neither am I
## How it works
```
RÆḞ”iẋz⁶Ḣj”_ƊṭK€Ṛ$Ɗm€0Y - Main link. Takes N on the left
R - [1, 2, ..., N]
ÆḞ - k'th Fibonacci for each k in the range
”i - "i"
ẋ - Repeat "i" k times for each k
z⁶ - Transpose filling with spaces
Ɗ - To this matrix:
Ɗ - First:
Ḣ - Pop and yield the first element (the base)
j”_ - Join with "_"
$ - Then:
K€ - Join the other rows on spaces
Ṛ - Reverse
ṭ - Take the base onto the end of the rows
m€0 - Mirror each row
Y - Join on newlines
```
[Answer]
# Matlab, ~~172~~ 152 bytes
Unfortunately, Matlab hasn't a build in Fibonacci function and string Manipulation is a bit fiddly.
```
function t(n);f=@(n)getfield([0 1;1 1]^n,{3});m=char(flipud(bsxfun(@(a,b)(a<=f(b/2)&mod(b,2)==0)*'i',(1:f(n))',2:2*n)));m(end,2:2:end)='_';[m fliplr(m)]
```
With line breaks:
```
function t(n);
f=@(n)getfield([0 1;1 1]^n,{3});
m=char(flipud(bsxfun(@(a,b)(a<=f(b/2)&mod(b,2)==0)*'i',(1:f(n))',2:2*n)));
m(end,2:2:end)='_';
[m fliplr(m)]
```
[Answer]
# Ruby, ~~151~~ ~~146~~ ~~142~~ ~~137~~ 132 bytes
```
->n{s=1,1;3.upto(n){s<<s[-1]+s[-2]};s.map!{|i|[' ']*(s[-1]-i)+[?i]*i}.transpose.map!{|a|v=a*'_ '[a.count(?i)<=>n];puts v+v.reverse}}
```
**137 bytes**
```
->n{s=1,1;3.upto(n){s<<s[-1]+s[-2]};o=s.map{|i|[' ']*(s[-1]-i)+[?i]*i}.transpose.map{|a|v=a*' ';v+v.reverse};o[-1]=o[-1].tr' ',?_;puts o}
```
**142 bytes**
```
->n{s=1,1;(3..n).map{s<<s[-1]+s[-2]};puts s.map{|i|[' ']*(s[-1]-i)+[?i]*i}.transpose.map{|a|v=a*' ';v+v.reverse}.tap{|c|c[-1]=c[-1].tr' ',?_}}
```
**146 bytes**
```
->n{s=1,1;(3..n).map{s<<s[-1]+s[-2]};puts s.map{|i|[' ']*(s[-1]-i)+[?i]*i}.transpose.map{|a|v=a.join' ';v+v.reverse}.tap{|c|c[-1]=c[-1].tr' ',?_}}
```
**151 bytes**
```
->n{s=1,1;(3..n).map{s<<s[-1]+s[-2]};puts s.map{|i|[' ']*(s[-1]-i)+['i']*i}.transpose.map{|a|v=a.join ' ';v+v.reverse}.tap{|c|c[-1]=c[-1].tr ' ', '_'}}
```
Ungolfed:
```
-> n {
s = 1,1
3.upto(n) {
s << s[-1] + s[-2]
}
s.map! { |i|
[' '] * (s[-1]-i) + [?i] * i
}.
transpose.
map! { |a|
v = a * '_ '[a.count(?i)<=>n]
puts v + v.reverse
}
}
```
**Usage:**
```
->n{s=1,1;3.upto(n){s<<s[-1]+s[-2]};s.map!{|i|[' ']*(s[-1]-i)+[?i]*i}.transpose.map!{|a|v=a*'_ '[a.count(?i)<=>n];puts v+v.reverse}}[8]
```
Output:
```
ii
ii
ii
ii
ii
ii
ii
ii
i ii i
i ii i
i ii i
i ii i
i ii i
i i ii i i
i i ii i i
i i ii i i
i i i ii i i i
i i i ii i i i
i i i i ii i i i i
i i i i i ii i i i i i
i_i_i_i_i_i_i_ii_i_i_i_i_i_i_i
```
[Answer]
# Python 2, 213
Saved 12 bytes thanks to DSM.
```
def f(r):
a=b=1
while r:yield a;a,b=b,a+b;r-=1
n=list(f(input()))
n.remove(1)
h=max(n)-1
r=1
while h:
l=' '*(len(n)+1)+('i '*r)[:-1];print(l+l[::-1]);h-=1
if h in n:r+=1;n.pop()
l='i_'*r+'i_i'
print l+l[::-1]
```
Ungolfed version.
```
max_height = input()
def fib(r):
a=b=1
while r:
yield a
a,b = b, a + b
r-=1
numbers = [x for x in fib(max_height) if x>1]
highest = max(numbers) -1
rows = 1
while highest:
line =' '*((len(numbers)+1)*2) + ' '.join('i'*rows)
print(line + line[::-1])
highest -= 1
if highest in numbers:
rows += 1
numbers.pop()
line = '_'.join('i'*(rows+2))
print(line + line[::-1])
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes
```
v∆F\i*∩vṄṘøɽvm‡\_ḞuV⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ24oiGRlxcaSriiKl24bmE4bmYw7jJvXZt4oChXFxf4biedVbigYsiLCIiLCI4Il0=)
## How?
```
v∆F\i*∩vṄṘøɽvm‡\_ḞuV⁋
v∆F # For each item in [1, implicit input], get the nth fibonacci number
\i* # For each, repeat that many "i"s
∩ # Transpose
vṄ # Join each by spaces
Ṙ # Reverse
øɽ # Prepend leading spaces to each to right-align it
vm # Mirror each
‡\_ḞuV # To the last item, replace spaces with "_"
⁋ # Join on newlines
```
] |
[Question]
[
Write a program or function which, given a positive integer as input, outputs the representation of that integer in [Maya numerals](https://en.wikipedia.org/wiki/Maya_numerals).
# Maya numerals
Maya numerals is a [vigesimal](https://en.wikipedia.org/wiki/Vigesimal) system (base 20) using only 3 symbols :
* `< >` for *Zero* (The correct symbol is some sort of shell that can't easily be represented using ASCII).
* `.` for *One*
* `----` for *Five*
Numbers are written vertically in powers of 20, and numbers between 0 and 19 are written as stacks of *fives* and *ones*. You shall refer to the [Wikipedia article](https://en.wikipedia.org/wiki/Maya_numerals) for more details.
As an example, here are the numbers between 0 and 25, separated by commas:
```
. .. ... ....
. .. ... .... ---- ---- ---- ---- ---- . . . . . .
. .. ... .... ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
< >, . , .. ,... ,....,----,----,----,----,----,----,----,----,----,----,----,----,----,----,----,< >, . , .. ,... ,....,----
```
# Inputs
* Inputs always are positive integers between 0 and 2147483647 (2^31 - 1).
* You may take the input from STDIN, as a command line argument, function parameter or anything similar.
# Outputs
* Each line is at most 4 characters long. `< >` and `----` should always be printed as given here (4 characters long each).
* Ones(`.`) must be centered on the line. If there are 1 or 3 `.`, since perfect horizontal alignment is impossible, it does not matter whether they are one column to the left or one column to the right or the center.
* There must be exactly one empty line between different powers of 20, regardless of the height of the stacks in the power of 20s. For example, the correct output for 25 and 30 are :
```
.
.
----
---- ----
```
* No leading or trailing lines allowed.
* Outputs must be printed exactly like they are in the examples given.
### Test cases
* Each individual number between 0 and 25 given as example above.
* Input: `42`
Output:
```
..
..
```
* Input: `8000`
Output:
```
.
< >
< >
< >
```
* Input: `8080`
Output:
```
.
< >
....
< >
```
* input: `123456789`
Output:
```
.
...
----
----
----
.
----
----
..
----
----
.
....
----
----
----
....
----
```
* Input: `31415`
Output:
```
...
...
----
----
----
----
----
----
----
----
```
* Input: `2147483647`
Output:
```
.
...
----
----
.
----
----
.
----
----
----
....
----
..
..
----
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# Perl, ~~125~~ 117 bytes
```
$-=<>;{$_=($-%20?(""," .
"," ..
","...
","....
")[$-%5]."----
"x($-/5&3):"< >
").$_;($-/=20)&&($_=$/.$_,redo)}print
```
Thanks to Dom Hastings for helping me save 8 bytes.
[Answer]
# JavaScript ES6, 143 bytes
Loads of bytes added because need to `console.log`, could save another 23 bytes without it.
```
n=>console.log((d=(x,s='',l=1,j=x/l|0)=>s+(j>19?d(x,s,l*20)+`
`:'')+((j=j%20)?(' '+`.`.repeat(j%5)).slice(-4)+`
----`.repeat(j/5):'< >'))(n))
```
[Answer]
# Mathematica ~~185 182 171~~ 153
With 18 bytes saved thanks to Arcinde's suggestion to use anonymous functions,
```
c=Column;c[If[#>0,{q,r}=#~QuotientRemainder~5;c@{{""," ."," .."," ...","...."}[[r+1]],c@{{""},{d="----"},{d,d},{d,d,d}}[[q+1]]},"< >"]&/@#~IntegerDigits~20]&
```
**Example**
```
c[If[# > 0, {q, r} = #~QuotientRemainder~5; c@{{"", " .", " ..", " ...", "...."}[[r + 1]], c@{{""}, {d = "----"}, {d, d}, {d, d, d}}[[q + 1]]}, "< >"] & /@ #~IntegerDigits~20] &[31415]
```
[](https://i.stack.imgur.com/VY9GL.png)
---
**Checking**
The decimal number, 31415, expressed in base 20.
Mathematica employs lower case for this.
```
BaseForm[31415, 20]
```
[](https://i.stack.imgur.com/uFwnA.png)
---
The decimal digits corresponding to the above base 20 number.
```
IntegerDigits[31415,20]
```
>
> {3, 18, 10, 15}
>
>
>
---
**Another example**
```
IntegerDigits[2147483607, 20]
```
>
> {1, 13, 11, 1, 15, 9, 0, 7}
>
>
>
```
c[If[# > 0, {q, r} = #~QuotientRemainder~5;c@{{"", " .", " ..", " ...","...."}[[r + 1]], c@{{""}, {d = "----"}, {d, d}, {d, d, d}}[[q + 1]]},"< >"] & /@ #~IntegerDigits~20] &[2147483607]
```
[](https://i.stack.imgur.com/ZYAD8.png)
[Answer]
# Pyth, 41 bytes
```
j+bbm|jb_m.[\ 4kc:*d\.*5\.*4\-4"< >"jQ20
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=j%2Bbbm%7Cjb_m.%5B%5C%204kc%3A*d%5C.*5%5C.*4%5C-4%22%3C%20%20%3E%22jQ20&input=42&debug=0)
### Explanation:
```
jQ20 convert input to base 20
m map each value d to:
*d\. string of d points
: *5\.*4\- replace 5 points by 4 -s
c 4 split into groups of 4
m.[\ 4k center each group
_ invert order
jb join by newlines
| "< >" or if 0 use "< >"
j+bb join by double newlines
```
[Answer]
## JavaScript (ES6), 157 bytes
The newlines are significant and are counted as 1 byte each. Since printing to STDOUT is required, `console.log` cost me a few bytes there.
```
f=i=>console.log([...i.toString(20)].map(j=>(!(j=parseInt(j,20))||j%5?[`< >`,` .`,` ..`,`...`,`....`][j%5]+`
`:'')+`----
`.repeat(j/5)).join`
`.slice(0,-1))
```
### Demo
For demonstration purposes I'll write an ES5 version so it works in all browsers:
```
// Snippet stuff
console.log = function(x) {
O.innerHTML = x;
}
document.getElementById('I').addEventListener('change', function() {
f(this.valueAsNumber);
}, false);
// Actual function
f = function(i) {
console.log(i.toString(20).split('').map(function(j) {
return (! (j = parseInt(j, 20)) || j % 5 ? ['< >', ' .', ' ..', '...', '....'][j % 5] + '\n' : '') + '----\n'.repeat(j / 5);
}).join('\n').slice(0,-1));
}
```
```
<input type=number min=0 max=2147483647 value=0 id=I>
<pre><output id=O></output></pre>
```
[Answer]
# Python 2.x, 142 bytes:
```
def m(n):
h=[[""," "*(2-n%5/2)+"."*(n%5)+"\n"][n%5!=0]+"----\n"*(n%20/5),"< >\n"][n%20==0]
n/=20
if n>0:
h=m(n)+"\n\n"+h
return h[:-1]
```
Example:
```
>>> print m(2012)
----
< >
..
----
----
>>>
```
Edit: trailing line...
[Answer]
# CJam, ~~82~~ 76 bytes
```
li{_K%[""" .
"" ..
""...
""....
"]1$5%='-4*N+2$5/3&*+"< >
"?N+L+:L;K/}h;L);
```
My first CJam program, basically just a transliteration of my Perl answer to CJam.
[Try online](http://cjam.aditsu.net/#code=li%7B_K%25%5B%22%22%22%20.%0A%22%22%20..%0A%22%22...%0A%22%22....%0A%22%5D1%245%25%3D'-4*N%2B2%245%2F3%26*%2B%22%3C%20%20%3E%0A%22%3FN%2BL%2B%3AL%3BK%2F%7Dh%3BL)%3B&input=123456789)
Multi-line with comments:
```
li # read input
{ # start of do-while loop
_K% # check if this base-20 digit is a zero
[""" .
"" ..
""...
""....
"]1$5%= # push dots for 1s onto stack
'-4*N+2$5/3&*+ # push lines for 5s onto stack
"< >
" # push zero on stack
? # ternary if test (for digit equals zero)
N+L+:L; # pre-concatenate string with output plus newline
K/ # divide by 20
}h # end of do while loop
;L); # push output string on stack, chop off trailing newline
```
[Answer]
## PHP, 220 bytes
Same approach as my JavaScript answer. PHP has built-in functions for everything.
Takes 1 input from the command line (i.e. STDIN), as seen with `$argv[1]`:
```
<?=rtrim(implode("\n",array_map(function($j){return(!($j=base_convert($j,20,10))||$j%5?['< >', ' .', ' ..', '...', '....'][$j%5]."\n":'').str_repeat("----\n",$j/5);},str_split(base_convert($argv[1],10,20)))));
```
[Answer]
## C - 149
```
f(v){v/20&&(f(v/20),puts("\n"));if(v%=20)for(v%5&&printf("%3s%s","...."+4-v%5,v/5?"\n":""),v/=5;v--;v&&puts(""))printf("----");else printf("< >");}
```
Uses recursion to print most significant numbers first. Then either prints zero or prints all dots with one *clever* `printf` and all fives in a loop. I am not sure if I can avoid using if-else here.
The downside of clever printf is that 1 and 3 are not aligned to each other:
Result for 23 is:
```
.
...
```
## ~~119~~ incorrect solution - trailing newline
```
f(v){v/20&&(f(v/20),puts(""));if(v%=20)for(v%5&&printf("%3s\n","...."+4-v%5),v/=5;v--;)puts("----");else puts("< >");}
```
[Answer]
# PHP, ~~202~~ 192 bytes
```
function m($n){return(($c=($n-($r=$n%20))/20)?m($c)."\n":"").
($r?(($q=$r%5)?substr(" . .. ... ....",$q*4-4,4)."\n":"").
str_repeat("----\n",($r-$q)/5):"< >\n");}
echo rtrim(m($argv[1]),"\n");
```
It gets the input from the first command line argument.
The complete source code, with comments and tests, is available on [github](https://github.com/axiac/code-golf/blob/master/ascii-maya-numbers.php).
[Answer]
# Python 2, 114 bytes
This answer is based on Jakube's Pyth answer and Locoluis's Python 2 answer.
```
def f(n):d,m=divmod(n%20,5);h=[" "*(2-m/2)+"."*m+"\n----"*d,"< >"][n%20<1];n/=20;return(f(n)+"\n\n"if n else"")+h
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~50~~ ~~49~~ 47 bytes
```
b5µṪ”.x⁶;$L<3Ɗ¡ṭ⁾--;UW¤ẋ$Ẏ$L¡Ṛø“< >”WµẸ?
b20Ç€
```
[Try it online!](https://tio.run/##y0rNyan8/z/J9NDWhztXPWqYq1fxqHGbtYqPjfGxrkMLH@5c@6hxn66udWj4oSUPd3WrPNzVp@IDEp91eMejhjk2Cgp2QE3hQN27dthzJRkZHG5/1LTm/@H2SCCVBdR7aNuhbf//GxoZm5iamVtYAgA "Jelly – Try It Online")
`...` is now left aligned thanks to user202729's point.
[When you trick yourself into thinking `< >` is a palindrome...](https://tio.run/##y0rNyan8/z/J9NDWhztXVTg8apir96hxm7WKj41x0LGuQwsf7lz7cFc3SFwXSJuEH1pyaInKw119Kj4guVmHdzxq3GejYB0aDjRg1w57riQjg8Ptj5rW/D/cHgmksoDSh7Yd2vb/vwEA)
] |
[Question]
[
### Background
The [move-to-front transform](https://en.wikipedia.org/wiki/Move-to-front_transform) (MTF) is a data encoding algorithm designed to improve the performance of entropy encoding techniques.
In the [bzip2 compression algorithm](http://en.wikipedia.org/wiki/Bzip2), it is applied after the [Burrows–Wheeler transform](http://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform) (as seen in [Burrows, Wheeler and Back](https://codegolf.stackexchange.com/questions/51397)), with the objective of turning groups of repeated characters into small, easily compressible non-negative integers.
### Definition
For the purpose of this challenge, we'll define the printable ASCII version of the MTF as follows:
Given an input string **s**, take an empty array **r**, the string **d** of all printable ASCII characters (0x20 to 0x7E) and repeat the following for each character **c** of **s**:
1. Append the index of **c** in **d** to **r**.
2. Move **c** to the front of **d**, i.e., remove **c** from **d** and prepend it to the remainder.
Finally, we take the elements of **r** as indexes in the *original* **d** and fetch the corresponding characters.
### Step-by-step example
```
INPUT: "CODEGOLF"
0. s = "CODEGOLF"
d = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = []
1. s = "ODEGOLF"
d = "C !\"#$%&'()*+,-./0123456789:;<=>?@ABDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35]
2. s = "DEGOLF"
d = "OC !\"#$%&'()*+,-./0123456789:;<=>?@ABDEFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47]
3. s = "EGOLF"
d = "DOC !\"#$%&'()*+,-./0123456789:;<=>?@ABEFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47 37]
4. s = "GOLF"
d = "EDOC !\"#$%&'()*+,-./0123456789:;<=>?@ABFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47 37 38]
5. s = "OLF"
d = "GEDOC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47 37 38 40]
6. s = "LF"
d = "OGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47 37 38 40 3]
7. s = "F"
d = "LOGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47 37 38 40 3 45]
8. s = ""
d = "FLOGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABHIJKMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
r = [35 47 37 38 40 3 45 41]
OUTPUT: "COEFH#MI"
```
### Task
Write a program or function that implements the printable ASCII MTF (as defined above).
### Test cases
```
Input: Programming Puzzles & Code Golf
Output: Prpi"do lp%((uz rnu&3!P/o&$U$(p
Input: NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN BATMAN!
Output: Na! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!"DDUP"%'
Input: Two more questions and I have bzip2 in less than 100 bytes!
Output: Twp#o"si$sv#uvq(u$(l#o#W!r%w+$pz,xF%#,"x(. #0--'$GG ".z(**:
```
### Additional rules
* You cannot use any built-in operator that computes the MTF of a string.
* Your code may print a trailing newline if you choose STDOUT for output.
* Your code has to work for any input of 1000 or less printable ASCII characters (0x20 to 0x7E).
* Standard code golf rules apply. The shortest submission in bytes wins.
[Answer]
# CJam, 20
```
'¡,q{_C#c' ,C+@|}fC;
```
[Try it online](http://cjam.aditsu.net/#code='%C2%A1%2Cq%7B_C%23c'%20%2CC%2B%40%7C%7DfC%3B&input=CODEGOLF)
**Explanation:**
```
'¡, make a string of characters with codes from 0 to 160 (a modified "d")
could have been to 126 but stackexchange doesn't like the DEL character
q read the input (s)
{…}fC for each character C in s
_ duplicate the d string
C# find the index of C in d
c convert to character (this is the result)
' , make a string of characters from 0 to 31
C+ append C to the string
@ bring d to the top
| set union, preserving order; effectively, C is moved to position 32
this is the updated d string
; pop the last d
```
[Answer]
# [Ostrich](https://github.com/KeyboardFire/ostrich-lang), ~~46~~ 45 chars
Don't have a version number in the header because this is actually just [the latest commit](https://github.com/KeyboardFire/ostrich-lang/commit/971773b59bf7c8b8d701adfe2a197e82b9d1f8b7). I added the `O` (ascii code to string) operator after releasing the latest version (but still before this challenge was posted).
```
{a95,{32+O}%:d3@{:x\.3@?3@\+\x-x\+}/;{d=}%s*}
```
Explanation:
```
a this is the "r" array (a is short for [], empty array)
95,{32+O}%:d this is the "d" array
3@{...}/ for each character in the input (as an "argument")...
:x store in variable x (stack is now [r d c])
\.3@? find index in d (stack is now [r d idx])
3@\+ append index to r (stack is now [d modified_r])
\x- remove char from d, and then...
x\+ prepend char to d (stack is now [modified_r modified_d])
; throw away modified_d
{d=}% map r to indices of (original) d
s* join (s is short for ``, empty string)
```
[Answer]
# SWI-Prolog, ~~239~~ ~~197~~ 189 bytes
```
a(S):-l([126],X),a(S,X,[],R),b(R,X).
a([A|T],X,S,R):-nth0(I,X,A,Z),(a(T,[A|Z],[I|S],R);R=[I|S]).
b([A|T],X):-(b(T,X);!),nth0(A,X,E),put(E).
l([B|R],Z):-A is B-1,X=[A,B|R],(A=32,Z=X;l(X,Z)).
```
Example: `a(`Two more questions and I have bzip2 in less than 100 bytes!`).` outputs:
```
Twp#o"si$sv#uvq(u$(l#o#W!r%w+$pz,xF%#,"x(. #0--'$GG ".z(**:
```
(and `true .` after it, obviously)
**Note:** your SWI-Prolog version has to be one of the newer ones in which the backquote ``` represents codes strings. Code strings used to be represented with double-quotes `"` in older versions.
[Answer]
# Python 3, 88
```
*d,=range(127)
for c in input():y=d.index(ord(c));d[:32]+=d.pop(y),;print(chr(y),end='')
```
Using some ideas from my CJam solution.
-4 bytes belong to Sp3000 :)
[Answer]
# Python 2, ~~137~~ ~~110~~ 104
Wasn't hard to implement, but *maybe* still golfable?
[**Try it here**](http://ideone.com/cJJdh2)
```
e=d=map(chr,range(32,127))
r=""
for c in raw_input():n=e.index(c);r+=d[n];e=[e[n]]+e[:n]+e[n+1:]
print r
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~18 15 14~~ 13 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ä╦@╥◄/J[;&πi⌡
```
[Run and debug it](https://staxlang.xyz/#p=84cb40d2112f4a5b3b26e369f5&i=%22CODEGOLF%22%0A%22Programming+Puzzles+%26+Code+Golf%22%0A%22NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN+BATMAN%21%22%0A%22Two+more+questions+and+I+have+bzip2+in+less+than+100+bytes%21%22&m=2)
-3 bytes using a map, and a simpler algorithm.
-1 byte borrowing from Kevin Cruijssen's answer.
-1 byte by simplifying a stack operation.
[Answer]
# [Perl 5](https://www.perl.org/), 96 bytes
```
sub{$d=$o=join'',map chr,32..126;join'',map{$d=~s/\Q$_//;$d=$_.$d;substr$o,length$`,1}pop=~/./g}
```
[Try it online!](https://tio.run/##lY/NbtpAFIX3PMX1eMCD69hA1Cyw3DYNgUZNjCsRdVEiaurBuLFnhhkbiCOyzAPkEfMi1LhIWUe6m/udc@6PoDL9uMcLb6@K@SOOPMy9vzxhhmFloYA/S2md9my72ztz3/DB96Sc6Q88cxz3EJrZOHKrCSqXmFspZXG@xL@t7k5w4T05thPv9m5jwSVpAPxCF@PB5Wh8PUTgfYKquxx@02@u0J1Vq4HksQyzLGExBEVZplRBCy54RGHE00UdMgIpEhRxSEWTkKIEyYrWqRY4vIVvMRHGcZYf@u8q@Ho@uTn3tXrJivihBto7Cg0GtwFqGu3j@smGQ8YlhVVBVZ5wpiBkEVzBMlxTmJeJ6EHCoPpQQb4MGXQ7HZg/5FQdL3AmG6FzpBKs1nqxXpECk1Tn@k9NNjcfsCit7bCpW2hLbNA7JycGHo0A2SUxzb5z12g/VmdkDwQnTFiYbkXb@4Jnbg0BxzwHD1p4UevtAxYyYfl/ha7gkIDPgPg9vD6/1HjKEPQBmabpjycw/q5NWUX7R63y9@vUlFVGt7Hb/wM "Perl 5 – Try It Online")
Ungolfed with some explanation:
```
sub{
$d=$o=join'',map chr,32..126; #init strings d and o to chars between 0x32-0x7e
join('', #join array of chars to string
map { #map array of input chars
$d=~s/\Q$_//; #pick out current input char from d, \Q to avoid
#...special regexp meaning of some chars
$d=$_.$d; #prepend current input char to d
substr$o,length$`,1 #map to char in original dict o at position of
#...current input char in d
}
pop=~/./g #array of input chars
) #return joined chars
}
```
The `\Q` isn't needed for the given test cases since they don't contain `.` (period) or other chars with special meaning in regular expressions. If they did, `\Q` is needed.
[Answer]
# Pyth, 24 bytes
```
JK>95CM127s@LKxL~J+d-Jdz
```
[Demonstration.](https://pyth.herokuapp.com/?code=JK%3E95CM127s%40LKxL~J%2Bd-Jdz&input=CODEGOLF&debug=0) [Test Harness.](https://pyth.herokuapp.com/?code=Fz%2Bz.zJK%3E95CM127s%40LKxL~J%2Bd-Jdz&input=Programming%20Puzzles%20%26%20Code%20Golf%0ANaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN%20BATMAN!%0ATwo%20more%20questions%20and%20I%20have%20bzip2%20in%20less%20than%20100%20bytes!&debug=0)
The first bit. `JK>95CM127` sets up the necessary list and saves it to `J` and `K`. `~J+d-Jd` performs the list updating, while `xL ... z` maps the input characters to their positions in the list. Finally, `s@LK` converts those indexes to characters in the original list.
[Answer]
# Haskell, 120 bytes
```
e#s=[b|(b,a)<-zip[0..]s,a==e]!!0
a=[' '..'~']
f=snd.foldl(\(d,r)e->(e:take(e#d)d++tail(drop(e#d)d),r++[a!!(e#d)]))(a,[])
```
Usage example: `f "CODEGOLF"` -> `"COEFH#MI"`
How it works: `#` is an index function that returns the position of `e` in `s` (can't use Haskell's native `elemIndex` because of an expensive `import`). The main function `f` follows a fold pattern where it updates the position string `d` and result string `r` as it walks through the input string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žQDUIεXskXyìÙU}è
```
Output as a list of characters.
[Try it online](https://tio.run/##ATEAzv9vc2FiaWX//8W@UURVSc61WHNrWHnDrMOZVX3DqP//Q09ERUdPTEb/LS1uby1sYXp5) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKS/f@j@wJdQivPbY0ozo6oPLzm8MzQ2sMr/nvp/I9WcvZ3cXX393FT0lEKKMpPL0rMzc3MS1cIKK2qykktVlBTcM5PSVVwz89JA6rwS/QjCSk4OYb4OvopArWGlOcr5OYXpSoUlqYWl2Tm5xUrJOalKHgqZCSWpSokVWUWGClk5ikA7SxWKMlIzFMwNDBQSKosSS1WVIr9r6ubl6@bk1hVCQA).
**Explanation:**
```
žQ # Push the printable ASCII constant string
DU # Duplicate it, and pop and store this copy in variable `X`
Iε # Map over the characters of the input:
Xsk # Get the index of the current character in `X`
Xyì # Then prepend the current character to `X`
Ù # Uniquify the characters in this new string
U # Pop and store it as new `X`
}è # After the map: index the mapped integers into the printable ASCII string
# (after which the resulting character list is output implicitly)
```
] |
[Question]
[
The year is 930, and the Gregorian Church is having a problem. They have thousands of pages of chant music, but the problem is that all the sheet music was simply thrown onto a pile instead of having any real organisation system:

*Image by user gamerprinter at [Cartographers' Guild](http://www.cartographersguild.com/content/).*
The Church needs to organise all the sheet music, so they have hired a medieval software engineer to write a program to organise it for them. You are the software engineer that has been hired. However, the compilation process in medieval times involves the program being written onto paper by a team of slow biblical scribes. To decrease the time it takes for the team of scribes to compile your code, you must make the program as small as possible.
The Church wants the chant music to be organised based off the musical scale they are written in. All of the Church's chant music is written in *Dorian scales*. Given the notes of a certain piece of music, your program will output the Dorian scale that it is in. Here, I will explain exactly what a Dorian scale is. If you already know, you may skip this section.
There are 12 possible notes in any melody. Here they are in order:
```
C C# D D# E F F# G G# A A# B
```
A *semitone* (represented using a `S`) is incrementing one step to the right, wrapping around (so a semitone up from B would be back to C). A *tone* (represented using a `T`) is two semitones. For instance, a semitone up from F# would be G. A tone up from F# would be G#.
To create a Dorian scale, we start from any note in the list, and then move up in the following pattern, listing the notes that we encounter:
```
T, S, T, T, T, S
```
An example. I start from A. The notes of my Dorian scale becomes:
```
A
B (up a tone)
C (up a semitone)
D (up a tone)
E (up a tone)
F# (up a tone)
G (up a semitone)
```
The scale has the notes A, B, C, D, E, F#, and G. Because I started from A, we will call this the *Dorian scale in A*. There are therefore 12 different Dorian scales, each of which are named after the note that they started from. Each of them use the same pattern of tones and semitones, just starting from a different position. If my explanation is not coherent you may also [consult Wikipedia](http://en.wikipedia.org/wiki/Dorian_mode#Modern_Dorian_mode).
The input of the program can be given from whatever is appropriate for your program (e.g. STDIN, command line argument, `raw_input()`). It may be not pre-initialised in a variable. The input will be a list of comma seperated notes, representing the melody of the piece. There may be repeated notes. There will always be enough different notes in the input to be able to decisively deduce the scale of the piece. An example input:
```
B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A
```
The output of the program should be the string `Dorian scale in X`, where X is the starting note of the scale. The output of the example input:
```
Dorian scale in B
```
Comparing this with the Dorian scale in B (`B C# D E F# G# A`) we see that all the notes of the melody are within this scale. The note C# is unused in this case. However there are sufficient notes to unambiguously identify B Dorian as the correct key. No other Dorian scale fits, because whatever other scale we try, there is always at least one note of the melody that does not belong to the scale.
This is code golf, so the entry with the shortest number of characters wins. Ask in the comments if you have questions.
[Answer]
# C, ~~171~~ 146
```
i,b;main(int c,char**v){for(;c=v[1][i];)b|=c/65<<c*2%7+v[1][++i]%2*7;for(i=12;i--;)b&(1016056>>i)||printf("Dorian scale in %c%c",65+i*3%7,(i<5)*35);}
```
Parsing strings in C is not that easy, so I went for a more mathematical approach.
I take advantage of the Circle of Fifths. If we arrange the notes in the following order based on counting up 7 semitones at a time (known as a "fifth"), we find that all the notes permitted in any given scale form a consecutive block of 7 notes and all the prohibited notes form a consecutive block of 5 notes.
```
F C G D A E B F# C# G# D# A#
```
(it's a circle, it wraps back around to `F` at the end.)
The position of a natural note in the above sequence can be calculated as `(ASCII code) * 2 % 7`. Then if the next character is odd (applies to `#` but not comma, space or zero byte) we add 7 to make it sharp. We store a bitmap of the notes that have been used.
The number `243` (binary `11111000`) corresponds to the notes prohibited in the scale of A# Dorian. I multiplied this by `(1<<12)+1=4097` to give the magic number `1016056`. This is rightshifted to check (by ANDing) if the melody contains prohibited notes for each of the 12 scales in turn. If the melody does not contain prohibited notes, the scale is printed.
For the output we need to print the scale name encoded in the reverse order to cycle of fifths above, remember we are going backwards because we are rightshifting.) The ASCII sequence `ADGCFBEADGCF` is generated by `65+i*3%7`. For the first five of these a sharp must also be printed.
**Ungolfed code**
```
i,b;
main(int c,char**v){
for(;c=v[1][i];) //for each character in first commanline argument v[1]
//if it is a letter (assume uppercase, ASCII 65 or over)
b|=c/65<<c*2%7+v[1][++i]%2*7; //convert to position in the circle of fifths.
//Add 7 if the next character is odd (ASCII'#')
//leftshift 1 by this number and OR this with the contents of b.
for(i=12;i--;)b&(1016056>>i)||printf //if melody includes no prohibited notes for the scale i, print
("Dorian scale in %c%c",65+i*3%7,(i<5)*35); //the scale letter, and a # (ASCII 35) if required, otherwise an ASCII 0.
}
```
Invalid input behaviour: If insufficient notes are supplied to unambiguously determine the scale, it will output all possible scales. If an impossible combination of notes is supplied, it will output nothing. Notes must be delimited by a comma (or other non-whitespace character with an even ASCII code <= 64.) Spaces cannot be used as everything after the first space would be considered a different argument. ASCII codes >64 will be interpreted as notes in the manner described.
[Answer]
## Haskell - 152
```
w=words
n=w"C C# D D# E F F# G G# A A# B"
f s="Dorian scale in "++[n!!i|i<-[0..11],all(`elem`[(n++n)!!(i+j)|j<-[0,2,3,5,7,9,10]])s]!!0
main=interact$f.w
```
### Ungolfed
```
type Note = String
type Scale = [Note]
notes :: [Note]
notes = words "C C# D D# E F F# G G# A A# B"
isScale :: Scale -> [Note] -> Bool
isScale scale notes = all (`elem` scale) notes
takeScale :: Int -> Scale
takeScale i = [(notes ++ notes) !! (i + j) | j <- [0, 2, 3, 5, 7, 9, 10]]
findScale :: [Note] -> Note
findScale xs = head [notes !! i | i <- [0..11], isScale (takeScale i) xs]
main = interact (("Dorian scale in "++) . findScale . words)
```
[Answer]
# CJam - 61
```
C,q',/f{"FCGDAEB"_5<'#f++:s@m<7<:A-!{"Dorian scale in "A3=}*}
```
Try it at <http://cjam.aditsu.net/>
[Answer]
# Python 2 - 177 characters
It's not that short, but I find it the joy of Python to write multiple nested for loops in one line, even when not golfing. Unfortunately, I had to put the input statement on a separate line so that it would not execute more than once.
```
j=set(raw_input().split(','))
print"Dorian Scale in",[x for x in[["A A# B C C# D D# E F F# G G#".split()[(b+n)%12]for n in[0,2,3,5,7,9,10]]for b in range(12)]if j<set(x)][0][0]
```
I don't use Python 3, but I believe this is a rare instance when the print statement would not need more characters. Since `print` is a function there, I would be able to offset the need for parentheses with the use of the `*` list unpacking operator to replace the last `[0]`.
[Answer]
## Ruby - 132
```
12.times{|i|$*[0].split(?,)-(g=(0..6).map{|j|%w{C C# D D# E F F# G G# A A# B}[-i+=~(58>>j&1)]})==[]?(puts"Dorain scale in "+g[0]):g}
```
Input from command line args.
e.g. `ruby dorianscale.rb B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A`
Try it at: [ideone](http://ideone.com/mbfy42)
[Answer]
## Haskell - 140
Make use of the Circle of Fifths property introduced by @steveverrill.
If we let `circle0 = words "C G D A E B F# C# G# D# A# F"` and `circle = circle0 ++ circle0`, then we can construct all scales by taking consecutive 7 notes in `circle`.
```
scales = [take 7 . drop i $ circle | i <- [0..11]]
```
In each scale constructed by this way, `scale !! 3`, the 4th element is the scale name.
### Code
```
w=words
n=w"C G D A E B F# C# G# D# A# F"
f s="Dorian scale in "++[x!!3|x<-[take 7.drop i$n++n|i<-[0..]],all(`elem`x)s]!!0
main=interact$f.w
```
### Ungolfed
```
type Note = String
type Scale = [Note]
notes :: [Note]
notes = words "C G D A E B F# C# G# D# A# F"
scales :: [Scale]
scales = [take 7 . drop i $ notes ++ notes | i <- [0..11]]
findScale :: [Note] -> Note
findScale xs = head [scale !! 3 | scale <- scales, all (`elem` scale) xs]
main = interact (("Dorian scale in "++) . findScale . words)
```
[Answer]
# Scala, ~~130~~ ~~128~~ 127
```
print("Dorian scale in "+(".#?".r findAllIn "FCGDAEBF#C#G#D#A#"*2 sliding(7)find{l=>args(0)split','forall(l contains _)}get 3))
```
Using the circle of fifths method.
Input from command line args ie
```
scala dorianscale.scala B,B,D,E,D,B,A,G#,A,G#,E,D,F#,E,F#,E,F#,G#,A
```
] |
[Question]
[
I have thought up esoteric language Jumper. Later you will see why.
* It operates with random-access-memory with bytes as cells. RAM is zero indexed and initially filled with zeros.
* When trying access cells with negative indexes error should be displayed and program terminated.
* When trying read at larger index than last, zero should be returned.
* When trying write at larger index than last, RAM should be increased to multiple of 1024 and new cells filled with zeros (technically you can increase RAM not to multiple of 1024, reason was performance boost, so if it costs you a lot of characters you can do it not to multiple of 1024).
* Program also has pointer to cell in RAM which initially is zero
* When program starts executing a prompt for input string should be displayed (or take input from command line arguments, it's up to you). Input string should not contain null character (zero byte). Then input string is written to RAM starting at zero index.
* When program ends executing a box with program output is displayed - contents of RAM from zero index to first zero byte excluding.
Now, most interesting part, syntax.
Program consists of commands (unary operators-prefixes) and their arguments. Commands and arguments may be delimited with spaces or new lines but not necessary. However spaces inside arguments are invalid, for example, `# 2 = 4` is valid, but `# 2 = 4 4` is not.
Program can have comments between `()`. Comments can't be nested - for example, in `(abc(def)ghi)` comment is `(abc(def)`. Comments can be placed anywhere.
* `#123` sets RAM pointer to 123 (any positive decimal integer or zero).
* `>123` increments RAM pointer by 123 (any positive decimal integer).
* `<123` decrements RAM pointer by 123 (any positive decimal integer).
* `=123` writes 123 (any unsigned 8-bit decimal integer) in current cell.
* `+123` adds 123 (any unsigned 8-bit decimal integer) to current cell (modulo 256).
* `-123` subtracts 123 (any unsigned 8-bit decimal integer) from current cell (modulo 256).
* `:123` - "goto" - goes to command number 123 (first is 0). You can control flow of your program only with goto's - it has to jump - that's why I decided to call this language Jumper.
If argument is missing - think of it is 1 for `><+-` commands or 0 for `#=:` commands.
Also, there is command modifier - `?` (prefix to command), it executes next command only if current cell is not zero, else skips that command. Can be applied to any command.
For example, `?:17` - goes to command 17 if current cell is not zero.
If program is invalid or error occurs during runtime can be displayed message "Error". Because of this is CodeGolf, such short message will be fine.
# Your task
Write shortest interpreter for this language.
# Some test programs
```
(prints "Hello world!" regardless of input)
=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=
(appends "!" to the end of input string)
?:2 :4 >1 :0 =33 >1 =0
```
[Answer]
## Ruby, 447 bytes
```
p,i=$*
l=(i||'').length
r=[0]*l
l.times{|j|r[j]=i[j].ord}
i=j=0
s=p.gsub(/\(.*?\)|\s/,'')
q=s.scan(/(\?)?([#<>=+:-])(\d*)/)
e=->{abort"Error"}
p[/\d\s+\d/]||q*''!=s ?e[]:(r+=[0]until i+1<r.length
c=q[j]
j+=1
f=c[1]
c[0]&&r[i]==0?next: a=c[2]==''? '><+-'[f]?1:0:c[2].to_i
'=+-'[f]&&a>255?e[]: f==?#?i=a :f==?>?i+=a :f==?<?i-=a :f==?=?r[i]=a :f==?+?r[i]+=a :f==?-?r[i]-=a :j=a
i<0?e[]:r[i]%=256)while j<q.length
puts r.first(r.index 0).map(&:chr)*''
```
Takes both the program and the input via command line arguments.
**EDIT:** Fixed a few bugs, and added support for invalid syntax at the cost of 40 bytes (while adding a few other optimisations).
[Answer]
**Ruby 2 - ~~540~~ ~~447~~ 420 characters**
Run as " ruby2.0 jumper.rb 'instructions' 'initialization data' ". 1.x Ruby won't work (no String.bytes method).
Added multi-line commands and comments and improved my putting.
```
i=$*[0].gsub(/\([^)]*\)/m,' ').scan(/(\??)\s*([#=:><+-])\s*(\d*)/m).map{|a|[a[0]!='?',a[1],a[2]==''?/[#=:]/=~a[1]?0:1:a[2].to_i]}
N=i.size
d=$*[1].bytes
r=p=0
while p<N
u,o,x=i[p]
p+=1
d[r]=0 if d[r].nil?
case o
when'#';r=x
when'>';r+=x
when'<';r-=x
when/[=+-]/;eval "d[r]#{o.tr'=',''}=x";d[r]%=256
when':';p=x;abort'Error'if p>=N
end if u||d[r]>0
abort'Error'if r<0
end
printf"%s\n",d.take_while{|v|v&&v!=0}.pack('C*')
```
Here's a test suite with some scatter-shot tests. The easiest way to use it is to stuff the code into t/jumper.t and run "perl t/jumper.t".
```
#/usr/bin/perl
use strict;
use warnings;
# timestamp: 2014 August 3, 19:00
#
# - Assume program takes machine code and initialization string as command
# line options.
# - Assume all required errors reported as "Error\n".
# - Go with the flow and suffix output with \n. Merged terminal newlines are
# unacceptable [I'm talkin' to YOU Ruby puts()!].
# - As per OP - jumping to > end-of-program must be an error.
use Test::More qw(no_plan);
# use Test::More tests => 4;
my $jumper = "jumper.rb";
#
# "happy" path
#
# starter tests provided by OP
is( `$jumper '=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=' '' 2>&1`, "Hello world!\n", "hello world (from user2992539)");
is( `$jumper '?:2 :4 >1 :0 =33 >1 =0' 'a' 2>&1`, "a!\n", 'append !, #1 (from user2992539)');
# simple variations
is( `$jumper '?:2 :4 >1 :0 =33 >1 =0' '' 2>&1`, "!\n", 'append !, #2');
is( `$jumper '?:2 :4 >1 :0 =33' '' 2>&1`, "!\n", 'append !, #3, no NUL');
# comment delimiters don't nest
is( `$jumper "(()=" 'oops' 2>&1`, "\n", "() don't nest");
# comments and termination
is( `$jumper '(start with a comment)?(comment w/ trailing sp) # (comment w/ surrounding sp) 1 =98' 'a' 2>&1`, "ab\n", 'walk to exit');
is( `$jumper '(start with a comment)? (comment w/ leading sp)= (comment w/ surrounding sp) 97()' '' 2>&1`, "\n", 'skip to exit');
is( `$jumper '#1=0 (actually two instructions, but it scans well) :5 #=(truncate further if not jumped over)' 'a b' 2>&1`, "Error\n", 'truncate & jump to exit');
# is RAM pointer initialized to 0?
is( `$jumper '-103(g-g) ?:1025(exit) =103 #4=10' 'good' 2>&1`, "good\n\n", 'intial string in right place?');
# TBD, do jumps work?
# TBD, do conditional jumps work?
# jump right to a harder case, copy byte 0 to byte 3 and format, e.g. input="Y" output="Y=>Y"
is( `$jumper '#1=61#2=62#4=0#3=#10=#(11:)?:13:20(13:)#3+#10+#0-:11(20:)#10(21:)?:23:28(23:)#0+#10-:21(28:)#' 'Y' 2>&1`, "Y=>Y\n", 'copy a byte');
# test memory allocation by dropping 255s at increasingly large intervals
is( `$jumper '#16=511 #64=511 #256=511 #1024=511 #4096=511 #16384=511 #65536=511 #262144=511 #1048576=511 #65536-255 (20:)?:23(exit) #=' 'wrong' 2>&1`, "\n", 'test alloc()');
# upcase by subtraction
is( `$jumper '-32' 't' 2>&1`, "T\n", 'upcase via subtraction');
# 2 nested loops to upcase a character, like so: #0=2; do { #0--; #1=16; do { #1--; #2--; } while (#1); } while (#0);
is( `$jumper '#=2 (2:)#- #1=16 (6:)#1- #2- #1?:6 #0?:2 #=32 #1=32' ' t' 2>&1`, " T\n", 'upcase via loops');
# downcase by addition
is( `$jumper '+32' 'B' 2>&1`, "b\n", 'downcase via addition');
# same thing with a loop, adjusted to walk the plank instead of jumping off it
is( `$jumper '#1 ?:3 :7 -<+ :0 #' 'B ' 2>&1`, "b\n", 'downcase via adder (from Sieg)');
# base 10 adder with carry
is( `$jumper '#0-48#10=9#11=#5=#0(9:)?:11:22(11:)#10?:14:22(14:)-#11+#5+#0-:9(22:)#0?:110#11(25:)?:27:32(27:)#0+#11-:25(32:)#0+48>-43?:110=43>-48#10=9#11=#2(45:)?:47:58(47:)#10?:50:58(50:)-#11+#5+#2-:45(58:)#2?:110#11(61:)?:63:68(63:)#2+#11-:61(68:)#2+48>-61?:110=61>?:110=32#10=9#11=#5-10(83:)?:85:94(85:)#10?:88:94(88:)-#11+#5-:83(94:)#5?:99#4=49:100(99:)+10(100:)#11(101:)?:103:108(103:)#5+#11-:101(108:)#5+48' '1+1=' 2>&1`, "1+1= 2\n", 'base 10 adder, #1');
is( `$jumper '#0-48#10=9#11=#5=#0(9:)?:11:22(11:)#10?:14:22(14:)-#11+#5+#0-:9(22:)#0?:110#11(25:)?:27:32(27:)#0+#11-:25(32:)#0+48>-43?:110=43>-48#10=9#11=#2(45:)?:47:58(47:)#10?:50:58(50:)-#11+#5+#2-:45(58:)#2?:110#11(61:)?:63:68(63:)#2+#11-:61(68:)#2+48>-61?:110=61>?:110=32#10=9#11=#5-10(83:)?:85:94(85:)#10?:88:94(88:)-#11+#5-:83(94:)#5?:99#4=49:100(99:)+10(100:)#11(101:)?:103:108(103:)#5+#11-:101(108:)#5+48' '9+9=' 2>&1`, "9+9=18\n", 'base 10 adder, #2');
# order of assignment shouldn't affect order of print
is( `$jumper '#1=98 #0=97' '' 2>&1`, "ab\n", 'print order != assignment order');
# are chars modulo 256?
is( `$jumper '#10(#10 defaults to 0) +255+(#10 += 256) ?#(skip if #10==0) =' 'good' 2>&1`, "good\n", 'memory values limited to 0<x<255');
# go for the cycle;
is( `$jumper '(0:)+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ (256:)#4=10' 'BCID' 2>&1`, "ACID\n\n", 'cycle character less 1, PC>255');
# same thing with a loop;
is( `$jumper '#4=255(#4 = 255) (2:)#1+(#1++) #4-(#4--) ?:2(loop 255 times) #4=10(#4 = NL)' 'ADID' 2>&1`, "ACID\n\n", 'cycle character less 1, PC>255');
# Exercise the program counter.
# PC > 255;
is( `$jumper '(0:)= (1:)############################################################################################################################################################################################################################################################### (256:)?:259 (257:)+ (258:):1 (259:)=97#3=10' 'a==' 2>&1`, "a==\n\n", 'program counter range >255');
#
# "sad" path
#
# Error checking required by the specification.
#
# simplest test case of PC going out of bounds
is( `$jumper ':2' '' 2>&1`, "Error\n", 'program counter too big by 1');
is( `$jumper ':1024' '' 2>&1`, "Error\n", 'program counter in space');
is( `$jumper ':1073741824' '' 2>&1`, "Error\n", 'program counter in hyperspace');
# try to drive program counter negative, if 32-bit signed integer
is( `$jumper ':2147483648(exit)' 'ridiculous speed' 2>&1`, "Error\n", 'program counter goes negative?, #1');
# try to drive program counter negative, if 64-bit signed integer
is( `$jumper ':9223372036854775808 (exit)' 'ludicrous speed' 2>&1`, "Error\n", 'program counter goes negative?, #2');
# spaces not allowed in operand; error or silently ignore (my choice)
isnt(`$jumper '#= #= #= #= #= +1 4 ' 'aops' 2>&1`, "oops\n", 'do not accept spaces in operands');
# ditto w/ a comment ; error or silently ignore (my choice)
isnt(`$jumper '#= #= #= #= #= +1(not valid)4 ' 'aops' 2>&1`, "oops\n", 'do not accept spaces in operands');
# RAM pointer error-checking; "Error" or "" are OK
isnt( `$jumper '<>=' 'oops' 2>&1 | grep -v Error`, "oops\n", 'unused negative RAM pointer behavior unspecified');
# RAM pointer negative and use it
is( `$jumper '<=' '' 2>&1`, "Error\n", 'cannot use negative RAM pointer, #1');
# check for RAM pointer wrap-around
is( `$jumper '<=' '0123456789' 2>&1`, "Error\n", 'cannot use negative RAM pointer, #2');
# The way I read this
# "Commands and arguments may be delimited with spaces or new lines but
# not necessary."
# multi-line commands are legit.
is( `$jumper "#4#?\n=" 'oops' 2>&1`, "\n", 'multi-line commands allowed');
# Multi-line comments would be consistent with multi-line commands, but I can't
# find something I can translate into a "must" or "must not" requirement in
# "Program can have comments between (). ... Comments can be placed
# anywhere."
# Until uncertainty resolved, no test case.
#
# "bad" path
#
# These tests violate the assumption that the instruction stream is wellll-farmed.
#
# characters not in the language; error or (my choice) silently skip
isnt(`$jumper 'x =' 'oops' 2>&1`, "oops\n", 'opcode discrimination');
# is ? accepted as an operator (vs operation modifier); error or (my choice) silently skip
is(`$jumper '(bad 0, good 0:)??0 (bad 1, good 0:):3 (bad 2, good 1:)#0' '' 2>&1`, "Error\n", '? not accepted as an opcode');
exit 0;
```
Ungolfed version.
```
#
# Turing Machine Mach 2.0.
# Tape? Tape? We don't need no stinkin' tape! We gots RAM!
#
# dM = data memory
# iM = instruction memory
# pC = program counter
# rP = RAM pointer
# u, o, x = current instruction being executed
#
# N = number of instructions in instruction memory
#
# instruction decoder
iM = $*[0].gsub(/\([^)]*\)/m,' ').scan(/(\??)\s*([#=:><+-])\s*(\d*)/m).map { |a|
[
a[0] != '?',
a[1],
(a[2] == '') ? (/[#=:]/ =~ a[1] ? 0 : 1) : a[2].to_i
]
}
pC = 0
N = iM.size
dM = $*[1].bytes
rP = 0
while pC < N do
# u, unconditional instruction, execute if true || (dM[rP] > 0)
# skip if false && (dM[rP] == 0)
# o, operator
# x, operand
(u, o, x) = iM[pC]
pC += 1
dM[rP] = 0 if dM[rP].nil?
if u || (dM[rP] > 0)
case o
when '#'
rP = x
when '>'
rP += x
when '<'
rP -= x
when /[=+-]/
eval "dM[rP]#{o.tr'=',''}=x"
dM[rP] %= 256
when ':'
pC = x
abort 'Error' if pC >= N
end
end
abort 'Error' if rP < 0
end
printf "%s\n", dM.take_while{|v|v&&v!=0}.pack('C*')
```
A quickie proto-assembler.
```
#
# Jumper "assembler" - symbolic goto labels.
#
# what it does:
# - translates labels/targets into absolute position
# @label ?:good_exit
# ...
# :label
#
# - a label is [a-zA-Z][a-zA-Z0-9_]*
# - a target is @label
# - one special label:
# - "hyperspace" is last instruction index + 1
# - strips out user comments
# - everything from "//" to EOL is stripped
# - jumper comments are stripped
# - adds "label" comments of the form "(ddd:)"
# limitations & bugs:
# - multi-line jumper comments aren't alway handled gracefully
# - a target not followed by an instruction will reference
# the previous instruction. this can only happen
# at the end of the program. recommended idiom to
# avoid this:
# @good_exit #
# what it doesn't do:
# - TBD, simple error checking
# - labels defined and not used
# - TBD, symbolic memory names
#
# Example:
#
# input -
# (
# adder from Sieg
# )
# @loop_head # 1 // while (*(1)) {
# ?:continue
# :good_exit
#
# @continue - // *(1) -= 1;
# <- // *(0) += 1;
# +
# :loop_head // }
# @good_exit #
#
# output -
# (0:) #1 ?:3 :7 (3:) - < + :0 (7:)#
rawSource = ARGF.map do |line|
line.gsub(/\([^)]*\)/, ' ') # eat intra-line jumper comments
.gsub(/\/\/.*/, ' ') # eat C99 comments
.gsub(/^/, "#{$<.filename}@#{$<.file.lineno}\n") # add line ID
end.join
rawSource.gsub! /\([^)]*\)/m, '' # eat multi-line jumper comments
#
# Using example from above
#
# rawSource =
# "sieg.ja@1\n \n" +
# "sieg.ja@4\n@loop_head # 1\n"
# ...
# "sieg.ja@12\n@good_exit # \n"
instructionPattern = %r{
(?<label> [[:alpha:]]\w* ){0}
(?<operator> \??\s*[#=:><+-]) {0}
(?<operand> \d+|[[:alpha:]]\w* ){0}
\G\s*(@\g<label>\s*)?(\g<operator>\s*)?(\g<operand>)?
}x
FAIL = [nil, nil, nil]
instructionOffset = 0
iStream = Array.new
target = Hash.new
targetComment = nil
for a in rawSource.lines.each_slice(2) do
# only parse non-empty lines
if /\S/ =~ a[1]
m = nil
catch( :parseError ) do
chopped = a[1]
while m = instructionPattern.match(chopped)
if m.captures.eql?(FAIL) || (!m[:operator] && m[:operand])
m = nil
throw :parseError
end
if m[:label]
if target.has_key?(m[:label].to_sym)
printf $stderr, a[0].chomp + ": error: label '#{m[:label]}' is already defined"
abort a[1]
end
target[ m[:label].to_sym ] = instructionOffset
targetComment = "(#{instructionOffset}:)"
end
if m[:operator]
iStream[instructionOffset] = [
targetComment,
m[:operator],
/\A[[:alpha:]]/.match(m[:operand]) ? m[:operand].to_sym : m[:operand]
]
targetComment = nil
instructionOffset += 1
end
chopped = m.post_match
if /\A\s*\Z/ =~ chopped
# nothing parseable left
break
end
end
end
if !m
printf $stderr, a[0].chomp + ": error: parse failure"
abort a[1]
end
end
end
# inject hyperspace label
target[:hyperspace] = instructionOffset
# replace operands that are labels
iStream.each do |instruction|
if instruction[2]
if !(/\A\d/ =~ instruction[2]) # its a label
if target.has_key?(instruction[2])
instruction[2] = target[instruction[2]]
else
abort "error: label '@#{instruction[2]}' is used but not defined"
end
end
end
puts instruction.join
end
```
[Answer]
## Python (729)
```
import re,sys
R,p,i,T,q,g=[0]*1024,0,0,re.findall(r'\d+|[()#><=+:?-]',sys.argv[1]),lambda i:0<=i<len(T),lambda i,d:int(T[i])if q(i)and T[i].isdigit()else d
def z(p):
global R;assert p>=0
if p>=len(R):R+=[0]*1024
s=sys.argv[2]
R[0:len(s)]=map(ord,s)
while i<len(T):
t=T[i]
if t=='(':
while T[i]!=')':i+=1
i+=1
if not q(i):break
t=T[i]
i+=1
if t=='#':p=g(i,0)
if t=='>':p+=g(i,1)
if t=='<':p-=g(i,1)
if t=='=':z(p);R[p]=g(i,0)
if t=='+':z(p);R[p]+=g(i,1);R[p]%=256
if t=='-':z(p);R[p]-=g(i,1);R[p]%=256
if t==':':
v=int(T[i])
i,c=-1,-1
while c!=v:i+=1;c+=T[i]in'#><=+-:'
if t=='?':
assert p>=0
if p<len(R)and R[p]==0:i+=1
i+=q(i)and T[i].isdigit()
print''.join(chr(int(c))for c in R).split('\0')[0]
```
As for running the program:
* 1st argument: Jumper code
* 2nd argument: Initialization string
Example:
```
$ python jumper.py "=97>>(this is a comment)=98>2=99#" "xyz123"
ayb1c3
```
There are probably a few things I overlooked, so please leave a comment if you happen to try something that should work but doesn't. Note that this is written in Python 2.x code.
[Answer]
# CoffeeScript (465)
The first prompt box is for the program and the second prompt box is input.
Test it at <http://coffeescript.org>.
**Original**:
```
p=prompt().replace(/\(.*?\)|[\s\n\r]/g,"").match(/\??[^\d]\d*/g) ?[]
y=p[..]
i=prompt()
r=[].map.call i,(c)->c[0].charCodeAt()
n=0
m=[(d)->n=d
(d)->m[5] (r[n]+d)%%256
(d)->p=y[d..]
(d)->m[1] -d
(d)->n-=d
(d)->r[n]=d
(d)->n+=d]
while b=p.shift()
if b[0]=="?"
continue unless r[n]
b=b[1..]
d="><+-#=:".indexOf(b[0])//4
~d||throw "!badcmd '#{b[0]}'"
m[b[0].charCodeAt()%7](+b[1..]||+!d)
n<0&&throw "!ramdix<0"
alert String.fromCharCode(r...).replace(/\0.*/,"")
```
This is still golfed, but commented:
```
# Get program
p=prompt().replace(/\(.*?\)/g,"").match(/\??[^\s\d]\d*/g) ?[]
# Create a copy of the program (for goto)
y=p[..]
# Get input
i=prompt()
# Put the input in the ram
r=[].map.call i,(c)->c[0].charCodeAt()
# RAM pointer
n=0
# An array of commands
# Since each of "<>+-#=:" is a different
# value mod 7 (what a coincedence?!)
# So 0th value is "#" command because
# "#".charCodeAt() % 7 === 0
m=[(d)->n=d
(d)->m[5] (r[n]+d)%%256
(d)->p=y[d..]
(d)->m[1] -d
(d)->n-=d
(d)->r[n]=d
(d)->n+=d]
# Iterate through commands
while b=p.shift()
# If you find a "?" skip unless r[n] is > 0
if b[0]=="?"
continue unless r[n]
b=b[1..]
# Get the default value
d="><+-#=:".indexOf(b[0])//4
# If the command isn't good, throw an error
throw "!badcmd '#{b[0]}'" if d==-1
# Call the appropriate command
# By computing the char code mod 7
m[b[0].charCodeAt()%7](+b[1..]||+!d)
# Make sure n is bigger than or equal to 0
throw "!ramdix<0" if n<0
# Show output
alert String.fromCharCode(r...).replace(/\0.*/,"")
```
**Edit**: Adding spaces took more bytes than I thought.
This interpreter will throw an error on invalid syntax, the other has unspecified behavior on invalid syntax.
```
p=prompt().replace(/\(.*?\)/g,"").match(/\??[^\d\s\r\n]\s*\n*\r*\d*/g) ?[]
y=p[..]
i=prompt()
r=[].map.call i,(c)->c[0].charCodeAt()
n=0
m=[(d)->n=d
(d)->m[5] (r[n]+d)%%256
(d)->p=y[d..]
(d)->m[1] -d
(d)->n-=d
(d)->r[n]=d
(d)->n+=d]
while b=p.shift()?.replace /^(.)(\s\r\n)*/,"$1"
if b[0]=="?"
continue if !r[n]
b=b[1..]
d="><+-#=:".indexOf(b[0])//4
~d||throw "!badcmd"
m[b[0].charCodeAt()%7](+b[1..]||+!d)
n<0&&throw "!ramdix<0"
alert String.fromCharCode(r...).replace(/\0.*/,"")
```
[Answer]
## Clojure - ~~585~~ 577 bytes
```
Edit: I forgot modulo 256, of course
Edit 2: Now supports whitespace and comments anywhere. (585 -> 578)
```
No special golfing tricks used, because I don't know any for Clojure. The interpreter is purely functional. Comes packed with a nice error message in case of negative RAM address (an error is outputted, but no exceptions or errors are thrown).
```
(defn j[o i](let[o(re-seq #"\??[#<>=+:-]\d*"(clojure.string/replace o #"\(.*?\)|\s"""))r(loop[c 0 p 0 m(map int i)](if-let[f(nth o c nil)](let[[c p m]((fn r[t](let[f(first t)s(if(next t)(apply str(next t))(case f(\#\=\:)"0"(\>\<\+\-)"1"))v(read-string s)a(nth m p 0)](case f\?(if(=(nth m p 0)0)[c p m](r s))\#[c v m]\>[c(+ p v)m]\<[c(- p v)m]\:[(dec v)p m][c p(assoc(vec(concat m(repeat(- p(count m))0)))p(mod({\+(+ a v)\-(- a v)}f v)256))])))f)](if(< p 0)(str"Negative index "p" caused by "f)(recur(inc c)p m)))m))](if(string? r)r(apply str(map char(take-while #(> % 0)r))))))
```
Examples:
```
(j "=72>=101>=108>=108>=111>=32>=119>=111>=114>=108>=100>=33>=" "")
=> "Hello world!"
(j "?:2 :4 >1 :0 =33 >1 =0" "hi there")
=> "hi there!"
(j "#1 ?:3 :7 -<+ :0" "01") ; adder
=> "a"
(j "?:2 :4 >1 :0 =33 <10 =0" "hi there")
=> "Negative index -2 caused by <10"
(j "=72>=101>=108>=108>=111>=3(comment here <100)2>=119>=111>=114>=108>=100>=33>=" "")
=> "Hello world!"
```
~~Original~~ slightly ungolfed code:
```
(defn memory
([]
(vec (repeat 1024 0)))
([m i v]
(assoc (vec (concat m (repeat (- i (+ -1024 (mod i 1024)) (count m)) 0)))
i v)))
(defn parse [c p m t]
(let [f (first t)
s (if-let [v (next t)]
(apply str v)
(case f
(\#\=\:) "0"
(\>\<\+\-) "1"))
v (read-string s)
a (nth m p 0)]
(case f
\? (if (= (nth m p 0) 0) [c p m] (parse c p m s))
\# [c v m]
\> [c (+ p v) m]
\< [c (- p v) m]
\: [(dec v) p m]
[c p (memory m p (mod ({\+ (+ a v) \- (- a v)} f v) 256))])))
(defn jumper [o i]
(let [o (re-seq #"\??[#<>=+:-]\d*" (clojure.string/replace o #"\(.*?\)|\s" ""))
r (loop [c 0
p 0
m (map int i)]
(if-let [f (nth o c nil)]
(let [[c p m] (parse c p m f)]
(if (< p 0)
(str "Negative index " p " caused by " (nth o c))
(recur (inc c) p m))) m))]
(if (string? r)
r
(apply str (map char (take-while #(> % 0) r))))))
```
[Answer]
# C 496
**Edits:**
* **Thanks to @Dennis it is now much shorter (and works in GCC to boot)**
* **Thanks to @S.S.Anne for suggesting abort()**
* **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter**
The golfed version
```
#define M R=realloc(R,r+Q),bzero(R+r,Q),r+=Q
#define J z<0?abort(),0:z>r
#define G J||R[z]
#define P J?M:0,R[z]
#define O!C[1]?1:V;I+23
#define I;if(*C==35
#define W;while(*p&*p<33)p++
Q=1024;char*R,C[999][9],*p,*q,*o;r,z,c,V;E(char*C){I+28)G&&E(C+1);else{V=atoi(C+1)I)z=V;I+27)z+=O+2)z-=O+3)P=V;V--I+8)P=G+O-13)P=G-O)c=V;}}main(u,v)int**v;{M;for(o=v[u-3||strcpy(R,v[2])];*o;bcopy(p,q,o-p)){p=o;q=C[c++]W;if((*q++=*p++)==63){W;*q++=*p++;}W;strtol(p,&o,0);}for(c=*C[c]=0;*C[c];)E(C[c++]);puts(R);}
```
[Try it online!](https://tio.run/##VZBNb@IwEIbv/RWpVkIe25HiuNsSXMMhqhBIiJIDHKIcgjdsI2VxMIFVE/jtWSdqI@3F43nm1Tsfyv2tVNv@@JUd8mPmrJxImiwtCq1QRA3ZAN3XmdEoIobaxBC5efgWL5361Zule20qBNSb1FMz1ObO8naL4joZyLuznK0mHv0Prh/DmCUzNtmKBfH5wBciPyAcSsl/Dmwn/n7kRYZwOcLlK@dQEvKwkczzn4T6SA2OaBgHQZDEQUJxSfGJYi0MramiW/GGek0IjW00hvlo9IZCwkBkxTlrtjKtdN6DBdSyn@YFaiLXxIfatYHDu8Vb112Qsf3OydplHZu7a1C2cr//SfMjutAr5McK46toVuKgDdLyGl9cfrudK6PKT3vWa@wnkAg73F5pS0p6ototAZpSanGSYawISXbdCRA@ESKx3RSkfObQ7MRAxH0nrGelC@sw0tQDce8aKomtQyI90UcBdtHeEUR5qc4osrq2beWLP7XHY90z/n6YTXnHWfCVMfY0KDxb5FP5Dw "C (gcc) – Try It Online")
A slightly less golfed version of my original program:
```
#include<stdlib.h>
#include<memory.h>
#include<string.h>
#include<stdio.h>
#define CHAR_STAR char*
#define CASTED_R (CHAR_STAR)RAM
#define UNSIGNED_CHAR unsigned char
#define INCREASE_MEMORY RAM=(UNSIGNED_CHAR*)realloc(CASTED_R,RAM_size+1024),memset(CASTED_R+RAM_size,0,1024),RAM_size+=1024
#define IF_ERROR current<0?exit(puts("!")),0:current>RAM_size?
#define GET_CELL IF_ERROR 0:RAM[current]
#define PUT_CELL(x) IF_ERROR INCREASE_MEMORY,RAM[current]=x:RAM[current]=x;
#define ONE_IF_EMPTY !*(command+1)?1:
#define VALUE atoi(command+1)
#define REMOVE_WHITESPACE while (*pointer&&*pointer<33)pointer++;
#define COPY_CHAR (*command++ = *pointer++)
#define RETURN return
char commands[999][9];
UNSIGNED_CHAR*RAM = 0;
int RAM_size = 0, current = 0, command_size = 0;
CHAR_STAR get_command(CHAR_STAR a)
{
CHAR_STAR pointer = a, *command = commands[command_size++], *next;
REMOVE_WHITESPACE
if (COPY_CHAR == '?')
{
REMOVE_WHITESPACE
COPY_CHAR;
}
REMOVE_WHITESPACE
int i = strtol(pointer, &next, 0);
memcpy(command, pointer, next - pointer);
command[next - pointer] = 0;
RETURN next;
}
void eval(CHAR_STAR command){
if (*command == '?')RETURN GET_CELL ? eval(command + 1) : 0;
if (*command == '#')current = VALUE;
if (*command == '>')current += ONE_IF_EMPTY VALUE;
if (*command == '<')current -= ONE_IF_EMPTY VALUE;
if (*command == '=')PUT_CELL(VALUE)
if (*command == '+')PUT_CELL(GET_CELL + ONE_IF_EMPTY VALUE - 1)
if (*command == '-')PUT_CELL(GET_CELL - ONE_IF_EMPTY VALUE - 1)
if (*command == ':')command_size = VALUE - 1;
}
int main(int argc, CHAR_STAR *argv)
{
INCREASE_MEMORY;
argc == 3 ? strcpy(CASTED_R, argv[2]) : 0;
CHAR_STAR command = argv[1];
while (*command) command = get_command(command);
*commands[command_size] = 0; command_size = -1;
while (*commands[++command_size]) eval(commands[command_size]);
RETURN puts(CASTED_R);
}
```
[Answer]
## Javascript, 519
```
C=prompt().replace(/\(.*?\)/g,"").match(/\??[#><=+:-]\d*/g)
M=prompt().split("").map(function(c){return c.charCodeAt(0)})
R=0
f=function(I){T=I[0]
A=I.slice(1)
if(T=="?")return M[R]?f(A):P++
A=A==""?1:+A
if(T==">")R+=A
if(T=="<")R-=A
if("=+-".indexOf(T)+1){if(R<0)throw alert("ERR RAMidx<0")
while(R>=M.length)M.push(0)}
if(T=="+")M[R]=M[R]+A&255
if(T=="-")M[R]=M[R]-A&255
A=+I.slice(1)
if(T=="#")R=A
if(T=="=")M[R]=A
if(T==":")P=A;else++P}
for(P=0;C[P];)f(C[P])
alert(String.fromCharCode.apply(7,M).replace(/\0.*/,""))
```
This gets the program and input via prompt boxes. Pasting this in your browser's Javascript console will work, as well as throwing this in a file, pasting before the code `<!DOCTYPE html>`, newline, `<html><head><script>`, and after the code `</script></head><body></body></html>`, and saving the resulting file as "swagger.html".
This is my first attempt at this thing, and I already like the language. Kinda. It really needs text labels though, instead of this BASIC-style instruction index labeling.
Ungolfed version (kinda):
```
var C,M,R,P,f;
C=prompt().replace(/\(.*?\)/g,"").match(/\??[#><=+:-]\d*/g); //Code
M=prompt().split("").map(function(c){return c.charCodeAt(0)}); //Memory
R=0; //RAM pointer
f=function(I){ //parser function, Instruction
var T,A;
T=I[0]; //Type
A=I.slice(1); //Argument
if(T=="?")return M[R]?f(A):P++;
A=A==""?1:+A;
if(T==">")R+=A;
if(T=="<")R-=A;
if("=+-".indexOf(T)+1){
if(R<0)throw alert("ERR RAMidx<0");
while(R>=M.length)M.push(0);
}
if(T=="+")M[R]=M[R]+A&255;
if(T=="-")M[R]=M[R]-A&255;
A=+I.slice(1);
if(T=="#")R=A;
if(T=="=")M[R]=A;
if(T==":")P=A;else++P;
}
for(P=0;C[P];f(C[P])); //Program pointer
alert(String.fromCharCode.apply(7,M).replace(/\0.*/,""));
```
[Answer]
# Haskell: an ungodly amount of characters
Alright, right now this is something that might or might not be golfed shortly. It is freakishly huge for what it is, with lots and lots of sloppily written code (it was quite some time since I last touched Haskell). But it was fun to write.
```
import Data.Char
parse [] p c a m i =
if c == ' ' || c == '?' then
[]
else
(p ++ [(c, a, m)])
parse (h:t) p c a m i
| i
= parse t p c a m (h == ')')
| isDigit h && a < 0
= parse t p c (digitToInt h) m i
| isDigit h
= parse t p c (10 * a + (digitToInt h)) m i
| elem h "#><=+-:?"
= if c == ' ' || c == '?' then
parse t p h a (c == '?') i
else
parse t (p ++ [(c, a, m)]) h (-1) False i
| otherwise
= case h of
'(' -> parse t p c a m True
' ' -> parse t p c a m i
_ -> []
run p pp r rp
| pp >= length p
= r
| pp < 0 || rp < 0
= []
| otherwise
= if mr then
case c of
'#' -> run p (pp + 1) r pa
'>' -> run p (pp + 1) r (rp + pa)
'<' -> run p (pp + 1) r (rp - pa)
'=' -> run p (pp + 1) (rh ++ ((chr pa) : rt)) rp
'+' -> run p (pp + 1) (rh ++ (chr (mod ((ord h) + pa) 256) : rt)) rp
'-' -> run p (pp + 1) (rh ++ (chr (mod ((ord h) - pa + 256) 256) : rt)) rp
':' -> run p pa r rp
else
run p (pp + 1) r rp
where
(c, a, m)
= p !! pp
(rh, h:rt)
= splitAt rp r
pa
= if a < 0 then
if elem c "><+-" then
1
else
0
else
a
mr
= ord (r !! rp) > 0 || not m
main = do
p <- getLine
let n = parse p [] ' ' (-1) False False
if n == []
then do
putStrLn "Error"
else do
s <- getLine
let r = run n 0 (s ++ (repeat (chr 0))) 0
if r == []
then do
putStrLn "Error"
else do
putStrLn (takeWhile (/=(chr 0)) r)
```
[Answer]
# Groovy 582
ungolfed version:
I think there is a bug with the comments, which are not recognized correctly, which might be caused by the stupid regex I used, but the 2 programs run as they should:
```
class P {
def c = 0
def p = 0
def m = []
P(i="") {
m = i.chars.collect { it }
m << 0
}
def set(v) { m[p] = v }
def add(v) { m[p] += v }
def sub(v) { m[p] -= v }
def eval(i) {
while(c < i.size()) {
if (i[c].p && m[p] == 0) {c++}
else { i[c].f(this,i[c].v) }
}
return m
}
}
def parse(s) {
def ops = [
'#' : [{p, v -> p.p = v; p.c++}, "0"],
'>' : [{p, v -> p.p += v; p.c++}, "1"],
'<' : [{p, v -> p.p -= v; p.c++}, "1"],
'=' : [{p, v -> p.set(v); p.c++}, "0"],
'+' : [{p, v -> p.add(v); p.c++}, "1"],
'-' : [{p, v -> p.sub(v); p.c++}, "1"],
':' : [{p, v -> p.c = v}, "0"]
]
(s =~ /\(.*\)/).each {
s = s.replace(it, "")
}
(s =~ /(\?)?([#><=+-:])([0-9]*)?/).collect {
def op = ops[it[2]]
[f : op[0], v : Integer.parseInt(it[3] ?: op[1]), p : it[1] != null ]
}
}
```
[Answer]
# Haskell, 584
The input and jumper program are provided as the first two lines of input from stdin.
```
a g(i,n,x)=(i+1,n,take n x++((g$x!!n)`mod`256):drop(n+1)x)
b g(i,n,x)=(i+1,g n,x)
c=b.q:a.(+):g:a.(-):b.(-):a.q:b.(+):c
d=(%['0'..'9'])
e=fromEnum
f=0>1
g n(_,x,y)=(n,x,y)
h(x:_)=d x;h _=f
i g p@(j,n,m)|x$m!!n=g p|t=(j+1,n,m)
j=0:1:0:1:1:0:1:j
k=takeWhile
l[]=[];l(x:y)|x%") \n"=l y|x%"("=l$u(/=')')y|t=x:l y
main=v>>=(\y->v>>=putStr.map toEnum.k x.r(0,0,map e y++z).p.l)
o n s|h s=(read$k d s,u d s)|t=(n,s)
p[]=[];p(x:y)|x%"?"=w$p y|t=(c!!e x)n:p m where(n,m)=o(j!!e x)y
q=const
r s@(i,n,m)p|i<length p=r((p!!i)s)p|t=m
t=0<1
u=dropWhile
v=getLine
w(m:n)=i m:n
x=(/=0)
z=0:z
(%)=elem
```
I'll post an ungolfed version later, but in the meantime I wanted to leave this as a puzzle for the reader:
>
> Where are the jumper commands such as '#' etc?
>
>
>
Have fun!
[Answer]
# [Perl 5](https://www.perl.org/) `-F`, 345 bytes
```
$#F--;$_=<>;s/\(.*?\)|\s*([+<>#=:?-])\s*/$1/g;die'Error'if/[^+<>#=?:0-9-]/+/\?\d/;s/[><+-]\K(?=\D|$)/1/g;s/[#=:]\K(?=\D|$)/0/g;map$_=ord,@F;@c=/.*?\d+/g;while($l<@c){$_=$c[$l++];s/\?//*!$F[$p]&&next;/[=+-]/?$F[$p]=eval"(\$F[\$p]$_)%256":/[<>]/?eval'$p=$p'.y/></+-/r:/#/?$p=y/#//dr:s/://&&($l=$_);die'Error'if$p*$l<0||$l>@c}print$_?chr:last for@F
```
[Try it online!](https://tio.run/##VU/bUoMwEH33K7SNXE2XtFYtEMKD8uL4BQQ7HaCWGSyZwKgd8dfFxdvoy2bObfdElbpeDqTnLBjINKE0IGseRkEL0po5Qtq9bB0rdcNoyn1BMxshEAYPQVGV5o3WjTarLaT3nw7he3RFM3BBClkAbkmj0KWZvLUEl9c9sWGMIo3b/rIeso8bhbcbXZzFSRDnHMb7hYvK866qS4vUYZzbr@gheUpq183GlgLAOSFJSlRmGPvypQsg5XgSxBfJy6dNPbEkIomQrO3T@fJi4kMaRmgaVZMoTpQ5O0AUgktB@zDFuOIHfKHQfgs@gGFgA475fz8nysFeXt@TOorzN6WrfUfWIt9pv9603fG20XEyDEf8ch5x5rFxXP0MhnAx8mz1jRg7/3V4KC4i/t6ormr27UDvljOPeQNNPgA "Perl 5 – Try It Online")
The first line of input is the initialization of RAM, the second line is the jumper program.
] |
[Question]
[
Your task is to write a program or function that checks if a string is a valid phone number.
Given a string (or list of characters/codepoints) input, you will output a truthy value if the input is a valid phone number. If it is not, output a falsey value. An input string is considered a valid phone number for this challenge if it meets all of these criteria:
* It contains ten digits, which are grouped like this: `###-###-####`
* The strings separating the digit groups must be the same
* The first and last characters must be part of the phone number (i.e. must not be part of a separator)
Test cases:
```
111-222-3333 truthy
123-456-7890 truthy (number groups can contain different numbers)
1112223333 truthy (can have 0 length separators)
111022203333 falsey (has more than 10 numbers)
111ABC222ABC3333 truthy (can have length>1 separators)
111-222_3333 falsey (non-matching separators)
111-22-23333 falsey (missing digit in middle group)
111--222--33333 falsey (extra digit in last group)
-111-222-3333 falsey (first character is not part of number)
111-222-3333a falsey (last character is not part of number)
aaa-aaa-aaaa falsey (not enough numbers)
11-2222-3333 falsey (wrong separator location)
111-1-222-1-3333 falsey (too many numbers)
```
This is a code golf challenge, shortest answer per language wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
fØDȯ0ṁ334DR¤jḟØDŒHḢƊµƑ
```
A monadic Link accepting a list of characters which yields `1` if it is a valid telephone number and `0` otherwise.
**[Try it online!](https://tio.run/##y0rNyan8/z/t8AyXE@sNHu5sNDY2cQk6tCTr4Y75QLGjkzwe7lh0rOvQ1mMT////b2ZgUpRYlmpsYAyiLIyNLQA "Jelly – Try It Online")** Or see a [test-suite](https://tio.run/##jZIxS8NAFMf3fooHDrVgIEmdBbWDs6uIPNNL7srlUu5e1Y66CG46uQniKDgJdW1p8WvULxIvae3FNoIPkuFefv//vf9Lj0k5zPN48tj5fPPnH9ft9m7nePzSm4@e7Nn04Wg@ep7djd9n9/nk9uvmNc9PmkEQeGEYem1bTShrC0gPiA8bO0XXNis914XtCBVwvGDgg2QqIQ6G9VEjZdq0FrBvaf@XdIzSMAtzNJBmmgFxKxP4oAbpOVuB@weHFrXvJVzjuvDcCzZdi4HOal1VprwUKeJCJbWcF9ZyqTCmQLoiEQRCQSq6Xckg0dmg/0OXOZZBlgKOZlek0bESDTnS29yAI2Oh7bcRt/eMiGkQBlRGYO9NkMXLzCpTlyK4rlIa/kMEV1XZtotuMUEBr0VnAW/5YPNv7lJs/CIrH1dVkso9IQFK2WqcfgM "Jelly – Try It Online").
### How?
```
fØDȯ0ṁ334DR¤jḟØDŒHḢƊµƑ - Link: list of characters, S e.g. '123a456bc78de'
Ƒ - is S invariant under...
µ - ...this function of S?:
f - filter keep:
ØD - digit characters '12345678'
ȯ0 - OR zero (necessary as ṁ will error with an empty list)
¤ - nilad followed by link(s) as a nilad:
334 - literal 334 334
D - to decimal [3,3,4]
R - range (vectorises) [[1,2,3],[1,2,3],[1,2,3,4]]
ṁ - mould (left) like (right) ['123','456','7812']
Ɗ - last three links as a monad - i.e. f(S):
ḟ - filter discard:
ØD - digit characters 'abcde'
ŒH - split in halves ['abc', 'de']
Ḣ - head (zero if empty) 'abc'
j - join '123abc456abc7812'
(...not invariant as not equal to S)
```
[Answer]
# Perl, 36 bytes
```
print/^\d{3}(\D*)\d{3}\1\d{4}$/?1:0
```
Run as
```
perl -ne 'print/^\d{3}(\D*)\d{3}\1\d{4}$/?1:0' <<< "111-222-3333"
```
[Try it online!](https://tio.run/##K0gtyjH9/78ASCno5qUqqBcUZeaV6MfFpFQb12rEuGhpglkxhkDKpFZF397QykBdwcbGRkHJ0NBQ18jISNcYCJT@//9vZmBSlFiWamxgDKIsjI0tAA "Perl 5 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~30~~ 29 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
```
'^\d{3}(\D*)\d{3}\1\d{4}$'⎕S⍬
```
It simply `⎕S`earches for the PCRE regex and returns a dummy value (the empty numeric list) for each match. If none are found, it returns a single empty numeric list.
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///Xz0uJqXauFYjxkVLE8yKMQRSJrUq6o/6pgY/6l3zP@1R24RHvX1Arqf/o67mQ@uNH7VNBEkGOQPJEA/P4P9p6oaGhrpGRka6xkCgzgXmA7lIPAMg1wCJ7@jkDBQBkkhiIBPiUfm6yGbogq0A2wEW0sViK5yfqA4A "APL (Dyalog Unicode) – Try It Online") The effect of printing a list of empty lists is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use [this](https://tio.run/##SyzI0U2pTMzJT///qG9qsCuQCA9Wdy1LzStRV1APTi0uzszPCyjKBHOdcxKLMtMq1bmgjEdtE6qBGoCU@qO2Seo6QCVAbpD6oe3qj3qnPurdVftfPS4mpdq4ViPGRUsTzIoxBFImtSoglcGPetf8TwNqf9TbB@R6@j/qaj603vhR20SQZJAzkAzx8Az@n6ZuaGioa2RkpGsMBOpcYD6Qi8QzAHINkPiOTs5AESCJJAYyIR6Vr4tshi7YCrAdYCFdLLbC@YnqAA "APL (Dyalog Unicode) – Try It Online") to lead each printed line with `→` and each space with `·`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 16 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
þ©м2äн®T∍ƵêS£sýQ
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/195319/52210).
Thanks to *@Grimy* for fixing a bug.
[Try it online](https://tio.run/##yy9OTMpM/f//8L5DKy/sMTq85MLeQ@tCHnX0Htt6eFXwocXFh/cG/v9vaGjo6ORsZGQEJI0B) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l4Qn/D@87tPLCHqPDSy7sPbQu5FFH77Gth1cFH1pcfHhv4P8Enf@Ghoa6RkZGusZAwAXkANkwpqOTM5AHJGECBkCuAYwD0hWPxNGF69MFGwg20ZhLF90COCcRxFNwNHRSAIqAabCSxMREXShORHUFAA).
**Explanation:**
```
þ # Only leave the digits of the (implicit) input-string
© # Store it in variable `®` (without popping)
м # Remove all digits from the (implicit) input-string
2ä # Split the remaining characters into two equal-sized parts
н # And only leave the first part
® # Push the digits from variable `®` again
T∍ # Extend this string of digits to size 10
Ƶê # Push compressed integer 334
S # Converted to a list of digits: [3,3,4]
£ # And split the digits of the input into parts of that size
s # Swap to get the earlier string
ý # And join the digit-parts with this delimiter-string
Q # Check if it's now equal to the (implicit) input-string
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶê` is `334`.
[Answer]
# [PHP](https://php.net/), 50 bytes
Just a simple regex, with a backreference to make sure the separator is the same.
```
<?=preg_match('/^\d{3}(\D*)\d{3}\1\d{4}$/',$argn);
```
[Try it online!](https://tio.run/##VU3bCoJAEH3frwgR1GjQ2bUbFtGFvmJJBhPtIV3Mt/DX27Y1wwbmcs6ZOaNKpfVmt1VNXqR3arPS98KLvD5F58vTNLCTRNPizg29mUtNUQWJzrOynjiychKNiMA5B2GCIRcQzxewXK0jZhQj9DxiZOZoAPvD0UBTB@JjkY4A/O7Ault7weD/2wgQIyL4JrFeGe31m2iJV63aW109NJzf "PHP – Try It Online")
[Answer]
# JavaScript (ES6), 37 bytes
```
s=>/^\d{3}(\D*)\d{3}\1\d{4}$/.test(s)
```
[Try it online!](https://tio.run/##hZLbTsMwDIbveQprQmqL1PUwbjeJg3gC7lZAoU2boDapYncCoT17cTvQylSGL5LI8v/5lDexE5g73VJobCH7ct3jehM9Z8Xnau9n91fB@MoSvq73l9GSJJKPQZ9bg7aWy9pWvrd9dB2pjycvuJj6S3@RJEmYpmm4YlsEAQw2E8Mh0wiAKIJcGFBiJyGGWpqKFKBshRNkHc4gbm7vmMLnD2iKOAA2yRTxi@FlZvsgavyjh5jR8bRChiuB0FgngRSnSWIwXfMqZ2sbRvByIjfWhI2gXGlTne@M1WF6om404iAsdKUJtGFHUdQSKme7do4xbmFcwwHDDPlOThwJtUCa14czW2R9qR0rcsWV5yQdaOSmCLgTAlt@j@PchxBH1pj8H1T/BQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Gema](http://gema.sourceforge.net/), 26 characters
```
<D3><-d><D3>$2<D4>\Z=t
*=f
```
There is no truthy / falsey concept in Gema, so just outputting “t” / “f”.
Sample run:
```
bash-5.0$ echo -n 111-222-3333 | gema '<D3><-d><D3>$2<D4>\Z=t;*=f'
t
```
[Try it online!](https://tio.run/##S0/NTfz/38bF2M5GN8UORKsY2biY2MVE2ZZwadmm/f9vaGioa2RkpGsMBAA "Gema – Try It Online") / [Try all test cases online!](https://tio.run/##lZHBTsJAEIbP7FOMTWXBZANdPCHbiOLBk4lHS0PWdmuJ2DbdJdGgz15mW0SFcrBJZyb55p/5p32WOq1iFa1kqYBNwShtFpHUSvRIJ6Ce5zHOORvhQ0NBTbk26QfdISTtYIhk@I0SudJqj6Y3twgxtivttkW7EhHjJ1BtsnZ5SNnhCUdDGyQPmJSS7V55JLOqkxObmd4R7hNSlMvMJEA/4ZzxoQabvb@ZY5xnFOh9VqwN5kel1ytb3L0XKjIqxvLhlRKS5CUsbRNGcNzN2f7fBdfhl3MFcU46Za0WjtsDFaU5MNtaqxzcNsgLM3hRb3Kgy6gugFaT2cifsNi32eWT2aU/fxKGXIikotB3COn844z9MsdtrNhq8@O0wWgXrMUg@NUnRGvreOxhdxhCt9ucZL@G9RXnmaq2 "Bash – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 28 bytes
Same as basically every other regex solution here. Note that in Ruby, `0` is actually truthy. (Only `false` and `nil` are falsey in Ruby)
```
p~/^\d{3}(\D*)\d{3}\1\d{4}$/
```
[Try it online!](https://tio.run/##hZHbTsMwDIbveQpLIG1MlB7GNRKHR@CyAmWt1wS1SRU7aBMaj05xu65DGxJR0iSWv/7Obx9W247CCuKcbhfxDcxmcAkv2hDIfA/EwA6o8JLiglw0Am5aLBhL8EihZurar/g1Lz@Xu3n@vLgeTnkq293uKu66NE2jLMuipQzoB/vAenshcQlP0UMc5oWyoNUHQgI12oo1ELbKK3aernssES6ZwLWqCQXTiqBxHqVG@UGagA3NCkfk4fFJIPkO2JnSXuc@PVXqC387U7LORo3iQhtb/UFE2RnRGKI@uTSVYTAWGlOWNULlXWj33ODRYNLyyOGGvTpStZJ@jEx06uuBWRsvWYWWqqRLvu@jdQxSJYNbj65Mrxtw9ZsfRP7FlVLRuNSJOQxoXaj01IBv17JxlrrI/gA "Ruby – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 64 bytes
```
func[s][d: charset[#"0"-#"9"]parse s[3 d copy t to d 3 d t 4 d]]
```
[Try it online!](https://tio.run/##Zc@7DoMgFAbguT7FH5xJvHSpW@sbdCWkIVxih6pBHPr0FLAXtSeBwEfOyY/Vyl@1YjwzjTdzL9nEmWogO2En7VhOCkJzciJ8jICJ1VCQw/iEgxvCOd4djlCcezNYLWSHfn6AkbIsaVVVtA5FkB0QK2rAZCsqghV7PF/awGFfHrCuz/Tbvikg/RtPU5CU5Od0E3A7YkHxVSEEfS9BOBhGe@8dTPoqh38B "Red – Try It Online")
As always [Red](http://www.red-lang.org)'s `parse` is much longer than regex.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~69~~ ~~66~~ 57 bytes
```
lambda n:re.match(r"\d{3}(\D*)\d{3}\1\d{4}$",n)
import re
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPqihVLzexJDlDo0gpJqXauFYjxkVLE8yKMQRSJrUqSjp5mlyZuQX5RSUKRan/C4oy80o00jSUDA0NdY2MjHSNgUBJU5MLWQIojk3Y0ckZKAMksUkaAKUMsEmAbInHIaGL1R5dsMPALkOV08XnaLhEIlDmPwA "Python 3 – Try It Online")
Thanks To:
-@Arnauld and @Value Ink for saving me 3 bytes by using match instead of fullmatch
-@Value Ink for saving me another 6 bytes
[Answer]
# [Java (JDK)](http://jdk.java.net/), 43 bytes
```
s->s.matches("\\d{3}(\\D*)\\d{3}\\1\\d{4}")
```
[Try it online!](https://tio.run/##bU7LasMwELznKxZDwA6RsJ2ekjbQx7UlEOilDmVjK4lcv5DWgRL87aps16lbKlhpZnd2RimekaXJh5F5VSqC1HJek8z4oS5ikmXBZ6tJnKHW8IyygMsEoKr3mYxBE5J9zqVMILczd0tKFse3HaA6aq@TAmyUSGSMJG778RqkfsVMJptTWYiXOt8LBXdGs7XmOVJ8Etp1oii5LBo3ip5mXo@jKGjBTeN4ZtUZH0rlnlFB9eOz/JUMsP3UJHJe1sQrm00H15mGvl7CVE8LZz5enf/zLU5CkzsSeV4f3UzaaowJgoCFYcgW9rTE4gH6FvsDuX94tNTeQ6Pdeh8Rdt1jnWHnuDDsb8CVoEFE9l1o@slI1yuDrvEF "Java (JDK) – Try It Online")
Apparently I came to the same solution as others: a simple regex is the key.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 24
Same regex as the other regex-based answers:
```
^\d{3}(\D*)\d{3}\1\d{4}$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPy4mpdq4ViPGRUsTzIoxBFImtSr//xsaGuoaGRnpGgMBF5ADZMOYBkC2AYzj6OQM5AJJmABIVzwSRxeuTxdsINhEYy5ddAvgnESuxMREXShOVAAA "Retina 0.8.2 – Try It Online")
[Answer]
# [Kotlin (JDK)](https://kotlinlang.org), 60 bytes
```
{s: String->s.matches(Regex("\\d{3}(\\D*)\\d{3}\\1\\d{4}"))}
```
[Try it online!](https://tio.run/##bU5dS8MwFH3frwiFQiJL6YdPooNtPos48CkgV5d2wTYdSSqO0t8ek9SOIF644Zybe865n71phbT1IFEHQmJQjb5DW6Xgcn8wSshmQ9C4Qq6@oEVCv0Irjs@nXvKnoXvnCj0gOzrJvEw3OuvAfJy4xi@84d84Yew4VhNm7PGGzJixwoPbKSFkssG77hXC58hVSORPWbJ9HS7a8C7rB5OdXZapcZKWuYtOdSqTNYrk638Oje0JCa7TarK2KApaliWtXHni8AJzh/OFbHd7R927DLzqLSL0qqPBMDhWlv4NuBKwAEB/G@z8E@3Nm0UY/AA "Kotlin – Try It Online")
Really similar to the Java one
[Answer]
# [Clojure](https://clojure.org/), 46 bytes
```
(fn[x](re-matches #"\d{3}(\D*)\d{3}\1\d{4}"x))
```
[Try it online!](https://tio.run/##S87JzyotSv2vkZKappD2XyMtL7oiVqMoVTc3sSQ5I7VYQVkpJqXauFYjxkVLE8yKMQRSJrVKFZqa/zW5NAqKMvNKcvIUNNIUlAwNDXWNjIx0jYFASRNd0shY18TUTNfcwtIAU9LQEKgRuz5DQwOgnAEuSUcnZ6A0kMSlAOSkeDySujjt1QX7BuwdTHld/L5FkkzEkE1MTNSF4kQsWkE68ZgLMdkQpuA/AA "Clojure – Try It Online")
Another day, another regex.
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate), 56 bytes
This was actually a very simple challenge, using [XMark](https://codegolf.stackexchange.com/users/88635/xmark)'s RegEx in the [PHP answer](https://codegolf.stackexchange.com/a/195367/).
```
{@ifargv.0 is matches"@^\\d{3}(\\D*)\\d{3}\\1\\d{4}$@"}1
```
Sadly, due to the need to escape the slashes, this code is 5 bytes longer :/
This code outputs 1 in case the input matches (truthy), or nothing (falsy).
You can try the golfed and ungolfed versions in <http://sandbox.onlinephpfunctions.com/code/ca206ad7cc82351283e6c319ce5f9ae03f87b695>
You can also check the generated PHP code, if you are curious.
[Answer]
# [QuadS](https://github.com/abrudz/QuadRS), ~~28~~ 25 [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")
```
^\d{3}(\D*)\d{3}\1\d{4}$
```
It simply `⎕S`earches for the PCRE regex and returns a dummy value (the empty string) for each match. If none are found, it returns a single empty numeric list.
[Try it online!](https://tio.run/##KyxNTCn@/z8uJqXauFYjxkVLE8yKMQRSJrUqXP//GxoZ6@qamJrp6pqZW5gDAA "QuadS – Try It Online") The effect of printing a list of empty strings is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use [this](https://tio.run/##KyxNTCn@r/6obZK6jrqC@qO@qUHqh7arP@qd@qh36/@4mJRq41qNGBctTTArxhBImdSqcP3/b2hkrKtrYmqmq2tmbmEOAA "QuadS – Try It Online") to lead the printed line with `→` and each space with `·`.
] |
[Question]
[
On a recent episode of [QI](http://en.wikipedia.org/wiki/QI), the first 5 multiples of 142857 were described as anagrams of the original number. Of course, anyone with more than a passing knowledge of that number will know that those numbers are actually cyclic, not just anagrams. But that got me thinking.
Please write a program or function that outputs all numbers of six or fewer digits which have a proper factor that is an anagram of itself. The list should start with the following numbers:
```
3105 (divisible by 1035)
7128 (divisible by 1782)
7425 (divisible by 2475)
8316 (divisible by 1386)
8712 (divisible by 2178)
9513 (divisible by 1359)
9801 (divisible by 1089)
```
If you prefer, you can find numbers which have an anagram that is a proper factor of the number, but take care to exclude leading zeros from your anagrams.
This is code golf, so the shortest code in bytes that breaks no standard loopholes wins.
[Answer]
# Mathematica (REPL environment), ~~75~~ 74 bytes
*Thanks to ngenisis for tightening this up by a byte!*
```
Select[Range[10!],Most@#~MemberQ~Last@#&[Sort/@IntegerDigits@Divisors@#]&]
```
`Sort/@IntegerDigits@Divisors@#` produces a sorted list of digits for every divisor of its argument; the input number is itself a divisor, so its sorted list of digits is the last one. `Most@#~MemberQ~Last` detects whether that last sorted list of digits also appears in the list prior to the last element. And `Select[Range[10!],...]` retains only those integers up to 3,628,800 that pass this test (that bound chosen because it's one byte shorter than 106). It runs in about 5 minutes on my computer, yielding a list of 494 numbers, the largest of which is 3,427,191; there are 362 numbers up to 106, the larget of which is 989,901.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ÆḌṢ€ċṢ
ȷ6ÇÐf
```
[Try it online!](https://tio.run/nexus/jelly#@3@47eGOnoc7Fz1qWnOkG0hzndhuerj98IS0//8B "Jelly – TIO Nexus") (uses five or fewer digits because of TIO's time limit)
### Verfication
```
$ time jelly eun 'ÆḌṢ€ċṢ¶ȷ6ÇÐf'
[3105, 7128, 7425, 8316, 8712, 9513, 9801, 30105, 31050, 37125, 42741, 44172, 67128, 70416, 71208, 71253, 71280, 71328, 71928, 72108, 72441, 74142, 74250, 74628, 74925, 78912, 79128, 80712, 81816, 82755, 83160, 83181, 83916, 84510, 85725, 86712, 87120, 87132, 87192, 87912, 89154, 90321, 90801, 91152, 91203, 93513, 94041, 94143, 95130, 95193, 95613, 95832, 98010, 98091, 98901, 251748, 257148, 285174, 285714, 300105, 301050, 307125, 310284, 310500, 321705, 341172, 342711, 370521, 371142, 371250, 371628, 371925, 372411, 384102, 403515, 405135, 410256, 411372, 411723, 415368, 415380, 415638, 419076, 419580, 420741, 421056, 423711, 425016, 427113, 427410, 427491, 428571, 430515, 431379, 431568, 435105, 436158, 441072, 441720, 449172, 451035, 451305, 458112, 461538, 463158, 471852, 475281, 501624, 502416, 504216, 512208, 512820, 517428, 517482, 517725, 525771, 527175, 561024, 562104, 568971, 571428, 571482, 581124, 589761, 615384, 619584, 620379, 620568, 623079, 625128, 641088, 667128, 670416, 671208, 671280, 671328, 671928, 672108, 678912, 679128, 681072, 691872, 692037, 692307, 704016, 704136, 704160, 704196, 705213, 705321, 706416, 711342, 711423, 712008, 712080, 712503, 712530, 712800, 713208, 713280, 713328, 713748, 714285, 716283, 717948, 719208, 719253, 719280, 719328, 719928, 720108, 720441, 721068, 721080, 721308, 721602, 723411, 724113, 724410, 724491, 728244, 730812, 731892, 732108, 741042, 741285, 741420, 742284, 742500, 744822, 746280, 746928, 749142, 749250, 749628, 749925, 753081, 754188, 755271, 760212, 761082, 761238, 761904, 771525, 772551, 779148, 783111, 786912, 789120, 789132, 789192, 789312, 790416, 791208, 791280, 791328, 791928, 792108, 798912, 799128, 800712, 806712, 807120, 807132, 807192, 807912, 814752, 816816, 818160, 818916, 820512, 822744, 823716, 824472, 825174, 825714, 827550, 827658, 827955, 829467, 830412, 831117, 831600, 831762, 831810, 831831, 839160, 839181, 839916, 840510, 841023, 841104, 843102, 845100, 845910, 847422, 851148, 851220, 851742, 852471, 857142, 857250, 857628, 857925, 862512, 862758, 862947, 865728, 866712, 867120, 867132, 867192, 867912, 871200, 871320, 871332, 871425, 871920, 871932, 871992, 874125, 879120, 879132, 879192, 879912, 888216, 891054, 891540, 891594, 891723, 892755, 894510, 895725, 899154, 900801, 901152, 903021, 903210, 903231, 904041, 908010, 908091, 908901, 909321, 910203, 911043, 911358, 911520, 911736, 911952, 912030, 912093, 912303, 916083, 920241, 920376, 923076, 923580, 925113, 925614, 930321, 931176, 931203, 933513, 934143, 935130, 935193, 935613, 935832, 940410, 940491, 941430, 941493, 941652, 943137, 943173, 951300, 951588, 951930, 951993, 952380, 956130, 956193, 956613, 958032, 958320, 958332, 958392, 958632, 958716, 959832, 960741, 962037, 962307, 970137, 971028, 980100, 980910, 980991, 989010, 989091, 989901]
real 2m10.819s
user 2m10.683s
sys 0m0.192s
```
### How it works
```
ȷ6ÇÐf Main link. No arguments.
»∑6 Yield 1e6 = 1,000,000.
ÇÐf Filter; keep numbers in [1, ..., 1e6] for which the helper link returns
a truthy value.
ÆḌṢ€ċṢ Helper link. Argument: n
ÆḌ Compute all proper divisors of n.
Ṣ€ Sort each proper divisor's digits.
·π¢ Sort n's digits.
ċ Count the occurrences of the result to the right in the result to the left.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
ℕf{k∋p.!}?ẉ⊥
```
[Try it online!](https://tio.run/nexus/brachylog2#@/@oZWpadfajju4CPcVa@4e7Oh91Lf3////XvHzd5MTkjFQA "Brachylog – TIO Nexus")
This might time out before printing anything though (and if it doesn't it will only get to print 3105).
### Explanation
This prints those numbers indefinitely, as the author said it was acceptable that the program would print numbers bigger than 6 digits.
This is way too slow; you can use [this program](https://tio.run/nexus/brachylog2#@/@oY7mFsYGBjf2jlqlp1dmPOroL9BRr7R/u6nzUtfT///9f8/J1kxOTM1IB "Brachylog – TIO Nexus") (and change `8300` by any `N`) to start printing from numbers stricly greater than `N`.
```
‚Ñï Natural number: The Input is a natural number
f Factors: compute the factors of the Input
{ }? Call a predicate with the main Input as its output and the factors as Input
k Knife: remove the last factor(which is the Input itself)
‚àã In: take one of those factors
p. Permute: the Output is a permutation of that factor
! Cut: ignore other possible permutations
?ẉ Writeln: write the Input to STDOUT, followed by a line break
‚ä• False: backtrack to try another value for the Input
```
*As @ais523 pointed out, we need a cut to avoid printing a number multiple times if several of its factors are permutations of it.*
[Answer]
## JavaScript (ES6), ~~103~~ … ~~96~~ 94 bytes
An anonymous function that returns the array of matching integers.
```
_=>[...Array(1e6).keys(F=i=>[...i+''].sort()+0)].filter(n=>n*(R=i=>F(n/i--)==F(n)||R(i)%i)(9))
```
### Formatted and commented
```
_ => // main function, takes no input
[...Array(1e6).keys( // define an array of 1,000,000 entries
F = i => [...i + ''].sort() + 0 // define F: function used to normalize a string by
)] // sorting its characters
.filter(n => // for each entry in the array:
n * ( // force falsy result for n = 0
R = i => // define R: recursive function used to test if
F(n / i--) == F(n) || // n/i is an anagram of n, with i in [1 … 9]
R(i) % i // F(n/1) == F(n) is always true, which allows to stop
) // the recursion; but we need '%i' to ignore this result
(9) // start recursion with i = 9
) //
```
### Divisor statistics
For 6-digit integers, each ratio from `2` to `9` between a matching integer `n` and its anagram is encountered at least once. But some of them appear just a few times:
```
divisor | occurrences | first occurrence
---------+-------------+---------------------
2 | 12 | 251748 / 2 = 125874
3 | 118 | 3105 / 3 = 1035
4 | 120 | 7128 / 4 = 1782
5 | 4 | 714285 / 5 = 142857
6 | 34 | 8316 / 6 = 1386
7 | 49 | 9513 / 7 = 1359
8 | 2 | 911736 / 8 = 113967
9 | 23 | 9801 / 9 = 1089
```
### Test
The test below is limited to the range `[1 ... 39999]` so that it doesn't take too much time to complete.
```
let f =
_=>[...Array(4e4).keys(F=i=>[...i+''].sort()+0)].filter(n=>n*(R=i=>F(n/i--)==F(n)||R(i)%i)(9))
console.log(f())
```
[Answer]
## Pyke, 14 bytes
```
~1#`Sili-m`mS{
```
[Try it here!](http://pyke.catbus.co.uk/?code=%7E1%23%60Sili-m%60mS%7B)
Should output all numbers like this but times out.
[Test the algorithm here!](http://pyke.catbus.co.uk/?code=i%60Sili-m%60mS%7B&input=3015)
[Answer]
# [Perl 6](http://perl6.org/), 59 bytes
```
{grep {grep .comb.Bag===*.comb.Bag,grep $_%%*,2..^$_}
```
Terribly slow brute-force solution.
It returns a lazy sequence, so I could check the first few results, but it won't reach all results in reasonable time. (Should I mark it as non-competing?)
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/), ~~128~~ ~~126~~ ~~122~~ ~~121~~ 120 bytes
```
for((;n<6**8;)){
c=0
for((j=++n;j;j/=10)){((c+=8**(j%10)));}
for k in ${a[c]};{((n%k))||{ echo $n;break;};}
a[c]+=\ $n
}
```
[Try it online!](https://tio.run/nexus/bash#HcoxDoMwDIXhPafwAJKdDIWlQnJ9EuhAI1CbSEZiDTl7mjC@/31lP05E1tfT2omJkvEymDsGcU45cHjIONQH0TuZrMXQt02cm4MIP4UurbN/Z65I@0h0XQk2/z2gU/6c2xo5V96Mk6VGk0v5Aw "Bash – TIO Nexus")
(This program is reasonably fast -- it took only 14 minutes to run through all the 6-digit numbers on my MacBook. Unfortunately TIO times out because it imposes a running-time limit of 1 minute, which is only enough time to get through the 5-digit numbers or so.)
# Bash + Unix utilities, 117 bytes
```
for n in {1..999999}
{
c=$(bc<<<0`sed 's/\(.\)/+8^\1/g'<<<$n`)
for k in ${a[c]};{((n%k))||echo $n;}
a[c]+=\ $n
}|uniq
```
This is shorter than the pure bash version, but quite a bit slower, presumably due in good part to all the forking going on.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes
```
[¼¾œJv¾Ñ¨Dyåi¾,
```
Explanation:
```
[ # Start of infinite loop
¼ # Increase counter_variable by 1
¾œJv # Loop through all the permutations of counter_variable
¾Ñ¨Dyå # Check if a divisor of counter_variable is a permutation of counter_variable
i¾, # If so, print counter_variable
```
[Try it online!](https://tio.run/nexus/05ab1e#ASMA3P//W8K8wr7Fk0p2wr7DkcKoRHnDpWnCviz///Vuby1jYWNoZQ "05AB1E – TIO Nexus") (this won't work, it will time out)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 23 bytes
```
L³o f_ì á ¤fg mì f!vZ l
```
[Try it online!](https://tio.run/nexus/japt#@@9zaFO@Qlr84TUKhxcqHFqSlq6QC2SnKZZFKeT8/w8A "Japt – TIO Nexus") Note that the linked code only calculates up to 1e4 because 1e6 times out on TIO.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes
Times out on TIO due to infinite loop.
Saved 2 bytes as we could output more than 6-digit numbers according to OPs comment.
```
[NѨ€{N{å–
```
[Try it online!](https://tio.run/nexus/05ab1e#@x/td3jioRWPmtZU@1UfXvqoYfL//wA "05AB1E – TIO Nexus")
**Explanation**
```
[ # infinite loop with iteration index N
NÑ # get a list of all divisors of N
¨ # remove N from that list
€{ # sort each entry in the list of divisors
N{ # sort N
å– # output N if N is in the list
```
[Answer]
## Batch, 263 bytes
```
@echo off
set e=exit/b
for /l %%n in (1,1,999999)do call:n %%n
%e%
:n
call:c %1 1 0
for /l %%f in (2,1,9)do call:c %1 %%f %c%&&echo %1&&%e%
%e%
:c
set/ar=%1%%%2,d=%1/%2,c=-%3
if %r% gtr 0 %e%1
:l
set/ac+=1^<^<d%%10*3,d/=10
if %d% gtr 0 goto l
%e%%c%
```
Slow. As in, takes over a day to finish on my PC. Explanation: the `c` subroutine divides its first two arguments. If the remainder is zero, it then calculates the hash of the result by calculating the sum of the nth powers of 8 for each digit. This hash function, stolen from the bash answer, only collides on anagrams. (It would work for seven digit numbers but I don't have all fortnight.) The third argument is subtracted, and the subroutine exits with a truthy result if this is zero. The `n` subroutine calls the `c` subroutine once to calculate the hash, then eight more times to compare the hash; if it finds a collision, it prints `n` and exits the subroutine early.
[Answer]
# [Haskell (Lambdabot)](https://codegolf.stackexchange.com/a/92314/55934), 87 bytes
```
[x|x<-[1..],any(\y->show x/=y&&head y/='0'&&rem x(read y::Int)==0)$permutations$show x]
```
[Try it online!](https://tio.run/##Jcu7CsIwFADQ3a/IUNIW7GstppOL4B@0HS412kuTNCRXTMBvN4KuB84KfpNKJdR2d8TOQFBf0dMBSUxpDO9wqsaurucjmFhMsRr8ur9YaETkfJVwY7EReZtz7qRmoXA/6vuLoVKItsysdPpJQLgbn/3vnDSgEdahoYxgk6xrGVL6LHcFD5@qxdov "Haskell – Try It Online")
This is probably unoptimal, as it's my first Haskell golf üòÖ
[Answer]
# Python 2, 98 bytes
```
s=sorted;print filter(None,[[x for i in range(x)if s(`x`)==s(`i`)and x%i<1]for x in range(10**6)])
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 96 bytes
```
->a{a.chars.permutation.map(&:join).reject{|x|/^0+/.match(x)||x==a}.detect{|n|a.to_i%n.to_i==0}}
```
The permutation function gives a lot of duplicates, so a large part of this is weedng those out.
[Try it online!](https://tio.run/##LVHbbsIwDH3vV@RlE2is2Lk0yaTuRxCbOiiiSLSoBImJ8u2d7ezFp46PfY7d8fbzOx/q@f2zeTTl7tiM1/LSjudbalI39OW5uSxeP05D1y/LsT21u/SY7tP6C97WVEu74@K@nKZ7XTfPct8mqfdTU6bhu3vpBeoans/5MIyqU12vNgbBrZRHHShaTd/BYEWRnlYqOjQUA@BKGRAqNwAB1Smz2luqWYue6NX/HLA8ghIIAs5kCWAwQsEooFEo2vIUGmV1tsFMW2VTkYV8iGzIR1EIIPYCBvGqvfs3DgIBGaLUrEN@dF52q3IfWxMwOYsCokA6ztLOYDQyyO4R0fE5qI3vYfJZLLDrSK5NPhUIRMkqobjACnxAEIjcECLgVu2H4nJLV3XYdPxnrtuiKNp@P/8B "Ruby – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 101 bytes
```
for(x<-LazyList from 9)s"$x".permutations.find{d=>d.head>48&d.toInt!=x&x%d.toInt<1}map(_=>println(x))
```
[Try it in Scastie](https://scastie.scala-lang.org/CvHxYpa2SZ2wUc9aqkz75A) (For whatever reason, TIO doesn't recognize LazyLists, not even after importing it explicitly)
---
# [Scala (with recursion)](http://www.scala-lang.org/), 104 bytes
```
def f(x:Int){s"$x".permutations.find{d=>d.head>48&d.toInt!=x&x%d.toInt<1}map(_=>println(x))
f(x+1)}
f(9)
```
[Do NOT try it online!](https://tio.run/##LYzBCgIhFADvfYUttSiBsNChIoWOHfqGsH0uGbtPWV8giN9uHjoNA8PE0cym@tfHjsQexiGziSxCZLcQWK5gJzbxdLkjiRy7XepksOvyJUPOY5STQ8igNMi3NaCPpx4k@VZvVerT/i/XoSwm8KfSYXVIM/IkxKZ9D4MojWdRS/0B "Scala – Try It Online"). Try [this](https://scastie.scala-lang.org/K6sFxJ2QSACYuXFYcpuqMA) modified version instead.
] |
[Question]
[
You are given a set of positive integers. You must arrange them into pairs such that:
* Each pair contains 2 numbers, one of which is a multiple of another. For example, 8 is a multiple of 4, and 9 is a multiple of 9.
* If the same number occurs many times in the initial set, it can be used that many times in the pairs; a number can even be paired with another occurence of the same number
* The maximum possible number of pairs is obtained.
Output must be the number of pairs. **Shortest code wins.**
**Sample data**
`2,3,4,8,9,18` -> `3`
`7,14,28,42,56` -> `2`
`7,1,9,9,4,9,9,1,3,9,8,5` -> `6`
`8,88,888,8888,88888,888888` -> `3`
`2,6,7,17,16,35,15,9,83,7` -> `2`
[Answer]
## Haskell, ~~109~~ ~~107~~ ~~76~~ 70 bytes
*Thanks to nimi for saving 33 bytes and teaching me some more Haskell.* :)
*Thanks to xnor for saving another 6 bytes.*
```
import Data.List
f l=maximum$0:[1+f t|a:b:t<-permutations l,a`mod`b<1]
```
Yay, my first Haskell golf. It works the same as all the answers so far (well, not quite: it only counts the length of the longest prefix of valid pairs in each permutation, but that's equivalent and is actually what my original CJam code did).
For extra golfitude it's also extra inefficient by recursively generating all permutations of the suffix each time the first two elements of a permutation are a valid pair.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
**My 1000th Japt solution!** (According to SEDE)
I *had* wanted to do something epic to mark the occasion but I couldn't find a suitable challenge and, also, realised I don't have the time or brainspace these days for epic. So, instead I shall "celebrate" with a victory over Jelly :) And a bag of cans, of course!
```
á ®ò xr'vÃñ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=4SCu8iB4cid2w/E&input=WzIsMyw0LDgsOSwxOF0)
```
á ®ò xr'vÃñ :Implicit input of array
á :Permutations
® :Map
ò : Partitions of length 2
x : Reduce by addition after
r : Reducing each by
'v : Testing divisibility
à :End map
ñ :Sort
:Implicit output of last element
```
The `'v` trick saves a byte over the more straightforward method of using a function which would be `xÈrvÃ` instead of `xr'v`, although we *could* get that byte back by replacing the `ÃÃ` with a newline.
[Answer]
## CJam, ~~22~~ 18 bytes
```
q~e!{2/::%0e=}%:e>
```
[Try it online.](http://cjam.tryitonline.net/#code=cX5lIXsyLzo6JTBlPX0lOmU-&input=WzcgMSA5IDkgNCA5IDkgMSAzIDkgOCAxXQ)
Expects input in the form of a CJam-style list.
This is a *bit* inefficient for larger lists (and Java will probably run out of memory unless you give it more).
### Explanation
```
q~ e# Read and evaluate input.
e! e# Get all distinct permutations.
{ e# Map this block onto each permutation...
2/ e# Split the list into (consecutive) pairs. There may be a single element at the
e# end, which doesn't participate in any pair.
::% e# Fold modulo onto each chunk. If it's a pair, this computes the modulo, which
e# yields 0 if the first element is a multiple of the second. If the list has only
e# one element, it will simply return that element, which we know is positive.
0e= e# Count the number of zeroes (valid pairs).
}%
:e> e# Find the maximum of the list by folding max() onto it.
```
[Answer]
# Pyth, 13 bytes
```
eSm/%Mcd2Z.pQ
```
The time and storage complexity is really terrible. The first thing I do is to create a list with all permutations of the originally list. This takes `n*n!` storage. Input lists with length 9 already take quite a long time.
Try it online: [Demonstration](http://pyth.herokuapp.com/?test_suite_input=1%2C2%0A7%2C14%2C28%2C42%2C56%0A8%2C88%2C888%2C8888%2C88888%2C888888&input=8%2C88%2C888%2C8888%2C88888%2C888888&code=eSm/%25Mcd2Z.pQ&test_suite=0) or [Test Suite](http://pyth.herokuapp.com/?test_suite_input=1%2C2%0A7%2C14%2C28%2C42%2C56%0A8%2C88%2C888%2C8888%2C88888%2C888888&input=8%2C88%2C888%2C8888%2C88888%2C888888&code=eSm/%25Mcd2Z.pQ&test_suite=1)
### Explanation:
```
eSm/%Mcd2Z.pQ
Q read the list of integer
.p create the list of all permutations
m map each permutation d to:
cd2 split d into lists of length 2
%M apply modulo to each of this lists
/ Z count the zeros (=number of pairs with the first
item divisible by the second)
S sort these values
e and print the last one (=maximum)
```
[Answer]
## Mathematica, ~~95~~ ~~93~~ ~~87~~ ~~83~~ ~~79~~ ~~60~~ 58 bytes
```
Max[Count[#~Partition~2,{a_,b_}/;a∣b]&/@Permutations@#]&
```
Takes a few seconds for the larger examples.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Œ!s2ḍ/€ċ1Ʋ€Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMVio4c7evUfNa050m14bBOQfriz4f/hdiDj//9oIx1jHRMdCx1LHUOLWJ1ocx1DEx0jCx0TIx1Ts1gA "Jelly – Try It Online")
Uses the same method as Jakube's Pyth answer and Martin's CJam answer, which seems to be the best method
## How it works
```
Œ!s2ḍ/€ċ1Ʋ€Ṁ - Main link. Takes a list l on the left
Œ! - All permutations of l
Ʋ€ - Do the following over each permutation:
s2 - Split into pairs
€ - Over each pair:
/ - Reduce the pair by:
ḍ - x divides y?
ċ1 - Count the 1s
Ṁ - Take the maximum
```
[Answer]
# [Scala](http://www.scala-lang.org/), ~~71~~ 67 bytes
```
_.permutations.map(_.grouped(2)count(x=>x.size>1&&x(0)%x(1)<1)).max
```
[Try it online!](https://tio.run/##bY1Pb8IwDMXvfApfhhLJqkj6hxTRShx32IkjmlBWwtSppKFNUbSJz17cbRcE1vPzwc8/95Vu9Nh@fJnKw5uuLZjgjT30sHHuZwZUF93AcQVbc969Wv8ORQk0oRj3kTPdafDa163to5N2bB99du3gzIFJXrWD9SwUZYj6@tuUYj4PbMFfAhN8LTingzC6rra@sezIiM8kxpigwhyF4pzP7rdLFAlKhYnENHu6psOcAJMLQuWESh@DCtWk3/6zf3/yU2KGBCZlGKco0gka43JKXscb "Scala – Try It Online")
* -4 thanks to [user](https://codegolf.stackexchange.com/users/95792/user)!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
œεüÖιO}à
```
[Try it online!](https://tio.run/##yy9OTMpM/V9Waa@koGunoGRf@f/o5HNbD@85PO3cTv/awwv@6/yPjjbSMdYx0bHQsdQxtIjVUYg21zE00TGy0DEx0jE1AwlY6FiAEBhDCChpERsLAA "05AB1E – Try It Online")
**Commented:**
```
œ # get all permutations
ε } # map over the permutations ... ex: [8, 4, 9, 9]
üÖ # pairwise divisibility [1, 0, 1]
# [8%4==0, 4%9==0, 9%9==0]
ι # de-interleave [[1, 1], [0]]
# split into two alternating lists
O # sum both lists [2, 0]
à # get the maximum
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
▲mȯ#IĊ2Ẋ¦P
```
[Try it online!](https://tio.run/##ASkA1v9odXNr///ilrJtyK8jScSKMuG6isKmUP///1s3LDE0LDI4LDQyLDU2XQ "Husk – Try It Online")
**How?**
```
▲mȯ#IĊ2Ẋ¦P
▲ # maximum of
m # map function over list:
ȯ # function: 3 functions combined
#I # number of truthy elements of
Ċ2 # every second element of
Ẋ # result of applying to every pair
¦ # a divides b?
P # list: all permutations of input
```
[Answer]
## Matlab (120+114=234)
```
function w=t(y,z),w=0;for i=1:size(z,1),w=max(w,1+t([y,z(i,:)],feval(@(d)z(d(:,1)&d(:,2),:),~ismember(z,z(i,:)))));end
```
**main:**
```
a=input('');h=bsxfun(@mod,a,a');v=[];for i=1:size(h,1) b=find(~h(i,:));v=[v;[(2:nnz(b))*0+i;b(b~=i)]'];end;t([],v)
```
---
* the topper function is called by the main part.
* the input is in the form `[. . .]`
[Answer]
## Matlab(365)
```
j=@(e,x)['b(:,' num2str(e(x)) ')'];r=@(e,y)arrayfun(@(t)['((mod(' j(e,1) ',' j(e,t) ')==0|mod(' j(e,t) ',' j(e,1) ')==0)&',(y<4)*49,[cell2mat(strcat(r(e(setdiff(2:y,t)),y-2),'|')) '0'],')'],2:y,'UniformOutput',0);a=input('');i=nnz(a);i=i-mod(i,2);q=0;while(~q)b=nchoosek(a,i);q=[cell2mat(strcat((r(1:i,i)),'|')) '0'];q=nnz(b(eval(q(q~=0)),:));i=i-2;end;fix((i+2)/2)
```
---
* This apparently is longer, but oneliner and executive, and I managed to escape `perms` function because it takes forever.
* This function takes many reprises to run quiet well due to anonymous functions, I m open to suggestions here :)
] |
[Question]
[
# Introduction
Write a complete program that rotates a rectangular block of ASCII characters 90 degrees clockwise. When the program itself is rotated 90 degrees clockwise, it rotates a block of ASCII characters 90 counterclockwise.
# Rules
* You many not use built-ins that rotate or transpose matrices. For example, in MATLAB/Octave `rot90` and the transpose operator `'` are not allowed.
* You must write a complete program that uses STDIN and STDOUT or the closest equivalent.
* Your program must be rectangular and assume the input is also rectangular.
* The input and output are a newline separated strings and will not have trailing newlines.
When run with its source code as input, your program must rotate itself 90 degrees clockwise. The output must be a second program in the same language that rotates its input 90 degrees counterclockwise. When the rotated program is given its source code as input, it should output the source code of the original program.
**Note:** Both programs must work for *any* input, not just their own source code, so a one character quine is not allowed.
# Example
Say the following is a valid program that rotates its input 90 degrees in a hypothetical language ExampleLang.
```
^f a2% 3
lk (^_^&
v
D8 $4 /
```
When run with itself as input, it outputs another valid program that rotates its input counterclockwise:
```
D l^
8 kf
$ (a
4 ^2
_%
^
/v&3
```
This second program, when given to itself as input, outputs the original program. Note that the blank line should have four spaces and there is a trailing space on the second to last line that cannot be rendered in markdown. To clarify:
```
$ examplelang program < program > rotProg
$ examplelang rotProg < rotProg > program1
$ diff -s program program1
Files program and program1 are identical
```
Shortest program wins. Standard loopholes are banned.
[Answer]
# CJam, ~~26~~ ~~25~~ 21 bytes
```
WqN/":.+""\%"(~+N-~N*
```
*Thanks to @MartinBüttner for golfing off 4 bytes!*
Try it online in the CJam interpreter: [original program](http://cjam.aditsu.net/#code=WqN%2F%22%3A.%2B%22%22%5C%25%22(~%2BN-~N*&input=ABC%0ADEF%0AGHI) | [rotated program](http://cjam.aditsu.net/#code=W%0Aq%0AN%0A%2F%0A%22%0A%3A%0A.%0A%2B%0A%22%0A%22%0A%5C%0A%25%0A%22%0A(%0A~%0A%2B%0AN%0A-%0A~%0AN%0A*&input=ABC%0ADEF%0AGHI)
This is the rotated program:
```
W
q
N
/
"
:
.
+
"
"
\
%
"
(
~
+
N
-
~
N
*
```
### Idea
We can rotate the input a quarter turn clockwise by splitting it at linefeeds, reversing the order of the resulting rows, transposing rows with columns, and finally joining the rows, separated by linefeeds.
Likewise, we can rotate counterclockwise by transposing first, then reversing the rows.
Since the transposition built-in `z` is forbidden, we can use `:.+` (reduce by vectorized character or string-character concatenation) to achieve the same effect.
`:.+` is the only part of the source code that cannot be broken up. We push the strings `"W%"` and `":.+"`, conditionally reverse them if the second string contains a linefeed, concatenate, remove all linefeeds, and evaluate the result.
### Code
```
W e# Push -1.
qN/ e# Read all input at split it at linefeeds.
":.+" e# Push a string that, when evaluated, transposes rows and columns.
e# As explained in the previous section, this does NOT use a built-in
e# for matrix transposition.
"\%" e# Push a string that, when evaluated, reverses the rows.
(~ e# Shift out the first character and evaluate it.
e# For the original code, this evaluates '\', swapping the strings on
e# the stack. For the rotated code, this evaluates `\n', doing nothing.
+N- e# Concatenate and remove linefeeds.
e# The stack now contains: -1 input "%:.+" or -1 input ":.+\%"
~ e# Evaluate the string on top of the stack.
N* e# Join the resulting array, separating by linefeeds.
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~1420~~ ~~1399~~ 463 bytes
Ah... the joy of strings of undetermined length!
Assumes `sizeof(char*) == sizeof(int)` and `sizeof(char**) <= 16`.
## The new approach
```
char**L,*r;n,i//j=>]l n}q((
,j,q;R(l){for(//,l)l, +;;rr
r=l=0;(j= //i=)[r +))oa
getchar())>10;//,r(r( *l(fh}
r[l++]=j,r[l]=//n(r,c=6=R)c;
0)r=realloc(r,//;rajoL1q()t)
l+2);l&&R((L= //roh=l(,,r"u)
realloc(L,++n*//*fc]l(Lro"p]
16))[n-1]=r,q=//,{t+aR(=f(;q
l);}main(){for//L)e+e&c]{sn[
(R();i<q;i++, //*lglr&o1)t<]
puts(""))for(j//*(=[=ll-(uj+
=n;j--;putchar//rRjrr;lnnp;+
(L[j][i]));} //a;(;))a[i;0j
////////////////hq;002e)a-=[
////////////////c,01=+r)m-jL
```
[Try it online!](https://tio.run/##7VG7buQwDOz1FcYWC9KSITtFGob5AlduDRWGsA8LjLxmvNVivz2RA6S5@4PDTUXwNeRMbC4xfn3F66R13btaKbvZ@8TvQar8XAEq45JbaQDBx3lR8N4JiqsskWpllIVbgsTVDu9nxlEri7hMlbmctn0zIL53LZVJBYWqFjhfn0ZHsTZwciUI7H0GdZFfecBIpkVlPU0iSyxp70mntPTdCrihEfuCJMfjANBz4dTlygLO6eGO5neqd9bm2vv6HINAr8vhFkz3ijjmpgusbi2c7rHZaQA@A61GkJ4f05zh51HvezzZ0zGGx2ceDQyANL@tNFvrCmctF9Hj0uH2Fsztvn3C4YC4C5RKEXhkkQbuyRrOlJqGSs@uRbl2SKokOd/IGujHFMY5YOHe5ZsICHEaZ2qT8X/gulLbvpxwanj8qxhd27FV/GhS/9/Qf8zQbw "C (gcc) – Try It Online")
[Output of the above](https://tio.run/##7ZGxbuMwDIZ3PYWQISAtGbE7dGHZJ/Dk1fAgCE5igZVj1pmCPHtPvsMNh3uDopyIT/z5/wJjfYnx6@t0Ar6BtCqNXtRHczp1@d7j6@RwmDhdCxhoA8LworKJDwWk9IlPFGQXedUCxhroYxBSd22o2iX1YQ55kWkM1O9gpsPbXMdjYAXodskN19zCURIk8QXgHQnGrhePjLsEt/OM7GFRtI/dheLiHuogDu/2TAU8r@rO3nUlv11yATaAX9bMOjZW96VWk1WurGeyMBfwb/0P4jVoVXW@Usp@9sn4lXoQfJwXBWVh0xAkvkzbPgmI76ZtSAdxbuTkSzMablBZpyCyRFAvxr0gyfHYl5@zLWX@Pna@fa2cywZxyHU7svqVBelpPsKc4Y9rD0irqWu63bdPOBwQd2oSN5Te8k5/RzHdkEqIYR2xLCguP8f9xsf9BQ "C (gcc) – Try It Online")
The solution was embarrassingly easy in the end. You make one program A that rotates things clockwise, and one program B that rotates counter-clockwise:
### A
```
char**L,*r;n,i,j,q;R(l){for(r=l=0;(j=getchar())>10;r[l++]=j,r[l]=0)r=realloc(r,l+2);l&&R((L=realloc(L,16*++n))[n-1]=r,q=l);}main(){for(R();i<q;i++,puts(""))for(j=n;j--;)putchar(L[j][i]);}
```
### B
```
char**L,*r;n,i,j,q;R(l){for(r=l=0;(j=getchar())>10;r[l++]=j,r[l]=0)r=realloc(r,l+2);l&&R((L=realloc(L,16*++n))[n-1]=r,q=l);}main(){for(R();q--;puts(""))for(j=0;j<n;j++)putchar(L[j][q]);}
```
Make a rectangle of reasonable proportions and confine A to that, and put guards of comments around it:
```
char**L,*r;n,i//
,j,q;R(l){for(//
r=l=0;(j= //
getchar())>10;//
r[l++]=j,r[l]=//
0)r=realloc(r,//
l+2);l&&R((L= //
realloc(L,++n*//
16))[n-1]=r,q=//
l);}main(){for//
(R();i<q;i++, //
puts(""))for(j//
=n;j--;putchar//
(L[j][i]));} //
////////////////
////////////////
```
Confine program B to a square that is the same width as the one for A plus two (for the extra lines of comments at the bottom edge), rotate it CCW and slap it to the right of program A and you get the solution above.
## The old approach
```
/* r c c r
r a o n o s a
a r h l i r l r - t r = + h q
h o c 0 + l a o + l 6 o - u " o j< + c */
char**L,*s,*r;n,i,q;R(l,c){for(r=l=0;(c=getchar())>10;r[l++]=c,r[l]=0)r=realloc(r,l+2);q=l?l:q;l=r;}main(j){for(;s=R();L[n++]=s)L=realloc(L,16*n);for(;i<q;i++,puts(""))for(j=n;j--;)putchar(L[j][i]);}
/// // //e//// / / //e//// /// // / //e//// / // // //// /// / // ;/ /// //u//// /
/// // //g//// / / //r//// /// // / //r//// / // // //// /// / // 0/ /// //p//// /
```
[Try it online!](https://tio.run/##7VQ9b4MwEN3zK1AmfyGTDhl6cfsHmLIiBmSlCciFcCRTld@e8tEGKyHCZeiEJc7o3r3ne7Z02t9rfb16knluC0dw7U1dE5j3zSzQmZqM4MVTJJ/M9CrHZhaJs@fDSDfmKZKOvKgZOtZv48nKqmbn982UnY@D8zXdXj/wLEEXH8mgIH9gru2qzse5Ccsum216Vt0Mk/Z76EOCjIWCVYIh5CIVJWyJEZp@fRRIUBkVANFqvzs1pYTSt1UAGBnOY6VF/ROrgKLCXWJMoQkKw18olMq8m9cSjEK4fCZpTrJOECq1JRTCKG8EKhremKFYrVlOoa1KNyWknIvj@VSR5ZLSJpupHDLfB1pn22bCKIujNKZwWXhSymf3aCNS7uRvqR2H8AEh@SB4E7CYfVX31bFFZJcF@aMl5bk/rN3@4GM/4gMn@0BHH0Hv43jnYx688@CdB@88eOfB@8@D9xs "C (gcc) – Try It Online")
[Output of the above](https://tio.run/##7ZW9boMwEMd3nsLKBCHIpEOGEtoXYOoaMSCL8iECCZCp6rOnJj6X9C8spVVHTz/ufNj3ZZ8ICiGuV8ZEmfXM4bxkjHHJTHIt2UsyR34DE@IG9INBr/eJiC3YVSCfwf6N6BIbsBdEj/hBfO/kyTKO7ibP8bjgVwz7ajkEP1w4L6Z9C2J@Y5GPU0KlLEhfEjODHx7whbgNlT36of8/gN@@r@x9klOIR0DeTPukhjx4i3nT8ej4@zxrmk5IuSG9pq6DMNRhg/EQn@D8CPoE6/cK8rOhr7De2KefxGNWtff1q4gtxFH/sQ8juD@xoe8x/gTq1z7YBwPsl/xzPfF92O6U3Q7ehdYQ12P5muuw1/UNgsV1H6j9Ol3GYZIvpB@JA5y3Win9ynBfjf7WMqNOGNV7pY8hbh1vPRVMrgf0v2b04xzOT0Tlr/Te9M6syQ@@XJcD9Gv6rT/f5W3We4v3wk4OOzns5LCTw04OOzl@Nzm@AA "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 119 bytes
```
[print(*i[# "i 0:
::-1],sep#t " **(:
="")for i#n,=r[(n[]
in zip(* #iiponpe]]
open(0))]#r*efiip)1
#########[p(s) zo)-
```
[Try it online!](https://tio.run/##Ncg7DsMgDADQnVNYsGCUSKHphJShn1sghn6I6sVYhKW5PM3SNz75tk/hufcolbhZR9GAJoApgAph9GnYspgGGpyzxy1a41oqkOFhqdFyTIoYdhLrwBBJYckpqSKZ7YSYTHV5PR69Mn9R7IawFxx7v1xvd@VP81k9nq/3Dw "Python 3 – Try It Online")
rotated :
```
#oi=:[
#pn":p
#e "-r
#nz)1i
#(if]n
#0po,t
#)(rs(
#)* e*
#] ipi
[####[
print#
(*i,
sep=""
)for i
in[*
zip(*
open(0
))][::
-1]]
```
[Try it online!](https://tio.run/##DcU5DsMgEAXQ/p9ixDSAbMmOUyG5yHILRJGFKNPACLuJL@/4NU9/67eWad@5yhwiWIsJCs5k@gYumxsFbOWTCnjQ2q1gZ9tijzxlD04kKoh8iNAmZWVYLx0RlqyzMXCf2khAUqInbKL2qGoudoBzKYaAfkyJaN8f4wXP0xWv6Yb3@f4H "Python 3 – Try It Online")
## How it works :
The code is coposed of 2 parts separed by comments :
```
1111111111#22222222
111111111#222222222
111111111#222222222
111111111#222222222
111111111#222222222
#########2222222222
```
The first code rotates cockwise :
```
[print(*i[::-1],sep="")for i in zip(*open(0))]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P7qgKDOvREMrM9rKStcwVqc4tcBWSUkzLb9IIVMhM0@hKrNAQyu/IDVPw0BTM/b/f0cnZxcuQyNjE67EpOQUAA "Python 3 – Try It Online")
The second rotates counter clockwise
```
[print(*i,sep="")for i in[*zip(*open(0))][::-1]]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P7qgKDOvREMrU6c4tcBWSUkzLb9IIVMhMy9aqyqzQEMrvyA1T8NAUzM22spK1zA29v//RENHriQjJ65kY2euFBMXAA "Python 3 – Try It Online")
] |
[Question]
[
Stack Exchange currently has [134 question and answer sites](http://stackexchange.com/sites?view=list#traffic). This includes all beta sites (such as PPCG) but not [Area 51 proposals](http://area51.stackexchange.com/) nor any meta sites, except for the ["mother meta"](https://meta.stackexchange.com/).
To answer this question, choose one of those sites and write a program where every line of code is an [anagram](http://en.wikipedia.org/wiki/Anagram) of the title of a different question on that site. Any questions from that site may be used **as long as they have not been deleted, and were asked before this question**.
The title of a question includes *all* characters that appear in the `Title` textbox when the `edit` link is clicked below a question, be they whitespace, [mathjax formatting](https://math.stackexchange.com/posts/21199/edit), crazy Unicode characters, whatever. (You can use the [Stack Exchange API](https://api.stackexchange.com/docs/questions) if you want to query a bunch of question titles at a time.)
The program you write must output the string that reliably appears at the top of every Stack Exchange page:
```
Questions Tags Users Badges Unanswered Ask Question
```
This exact text, plus an optional trailing newline, is the only thing your program should output. There is no input. The output should go to stdout or, if that's not possible, a similar alternative.
Since doing this with only anagrams of question titles may be kind of tricky, you may optionally add **one** character of your choice to each line in your program, in any column. Not all lines need to have an extra character and it does not have to be the same character across lines. The character may be anything except for a [line terminator](http://en.wikipedia.org/wiki/Newline#Unicode). The characters in the line minus this one new character should still be a perfect anagram of a question title.
# Scoring
Your score is `(number of lines with no added character) + 2 * (number of lines with an added character)`. The lowest score wins. In case of ties the earlier answer wins.
# Details
* **You must provide links to all the questions you have used the titles from.**
* You may choose the same Stack Exchange site as someone else though you are encouraged to choose unused sites, just for some variety.
* If a question you used gets deleted before the winner is chosen, your submission will be invalid, so it's best to choose well established questions.
* If titles are edited on some of your questions then your submission is still valid as long as the edit history shows that your titles were correct when you posted your answer.
* Comments in your program are fine.
* Editing question titles to suit your needs is very bad form.
[Answer]
## Python 2, score = 2
```
print ''' &''(()),..===>>?''HHIMMMMPPaaaaabccdddeeeeeeeeeegggimmmmnnnnnoooooprrrrsstwyy''' and 'questions tags users \
badges unanswered ask question'.title() or ' $.?IIWaaabbccccccceeefghhhhhhiijjkklllllmmnnnoooprrrstttttttuxyyz'
```
I couldn't quite get it in one line, so here's a fairly straightforward solution in two.
I found the questions on Stack Overflow by regexing through the 50,000 longest titles:
* [How do I get PHP to ignore unescaped ampersands in query string (e.g. ?name=M&M's doesn't become array('name' => 'M', 'M\'s' => ''))](https://stackoverflow.com/q/4407920/645956)
* [I'm using jquery backstretch and horizontal scrolling. Why does it jump back to the left when I call $.backstretch('next')?](https://stackoverflow.com/q/24022497/645956)
Here's my best attempt at a one-liner for anyone who's going for it (feel free to use it):
```
print "questions tags users badges unanswered ask question".title() or AHHRUaacccceeeeeeeeeffghikkllmnnnooooooorrrrrrrtwwwy
```
[How to guarantee uniqueness of a referrer who clicks on a link in a remote webpage("Request.UserHostAddress" not working correctly)?](https://stackoverflow.com/q/768570/645956)
[Answer]
# Golfscript, 3 lines with no added characters
```
"Questions Tags Users Badge"'exception SLSATE[HY000][1049]eymfny incnue while pn chma afte intallin FOSBundl'or
"s Unanswered Ask "'Reoccurring error The current idetity(NT THORITY\NETWORK SERVICE)oe ot have it cc toC:\WINDOWS\Microsoft.NET\Framewor\v2.0.50727\Tempary ASP.NET Files'or
"Question""D he 'S' SL stand f standard or strctured?"or
```
I hit StackOverflow, since it probably had the most (useful) posts. A lot of Qs could be found in jQuery and SQL.
**Bibliography:**
* [exception "SQLSTATE[HY000] [1049] Base 'symfony' inconnue" while updating schema after installing FOSUserBundle](https://stackoverflow.com/questions/28058343/exception-sqlstatehy000-1049-base-symfony-inconnue-while-updating-schema)
* [Reoccurring error "The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'"](https://stackoverflow.com/questions/2779766/reoccurring-error-the-current-identity-nt-authority-network-service-does-not)
* [Does the 'S' in SQL stand for "standard" or "structured"?](https://stackoverflow.com/questions/5640624/does-the-s-in-sql-stand-for-standard-or-structured)
Uses two strings each line, and takes the first one with `or`. I don't know any proper Golfscript, but I tested it [here](http://golfscript.apphb.com/).
It's possible to get the necessary quotes in two lines, but you'll need a language that lets you dump chars.
[Answer]
# Pyth, 2, 1 line with 1 extra character.
```
r"questions tags users badges unanswered ask question"tyhgkk) (.?AHHRUaacccceeeeeeeeeeffiiilllmnnnnooooooooprrrrrrrrtttwww
```
Uses grc's [How to guarantee uniqueness of a referrer who clicks on a link in a remote webpage("Request.UserHostAddress" not working correctly)?](https://stackoverflow.com/q/768570/645956), which unfortunately requires an extra `s` to work.
] |
[Question]
[
Consider a randomized list of the integers 1 to N. You want to sort it using only the following actions:
1. **Swap** the first and last list elements. **(S)**
2. **Pop** off the first element and append it to the end of the list. **(P)**
This is always possible because any list can be sorted with enough swaps of adjacent elements. Using S and P you can swap any adjacent elements by calling P until the two elements in question are the first and last items in the list, then calling S to swap them, then calling P again until they are in the original indices (now swapped).
Yet, in terms of the number of S and P operations, this method is unlikely to be optimal for most lists.
# Challenge
Write a program or function that takes in a permutation of the numbers from 1 to N (N > 1). It can be given as a list or string or whatever is convenient. It should output a sequence of S's and P's that would sort the permutation when applied from left to right. This sequence does not have to be optimally short, but shorter it is the better (see Scoring).
### Example
If the input was `[2, 1, 3]` the output might be `SP` because
* S applied to `[2, 1, 3]` makes it `[3, 1, 2]`,
* and P applied to `[3, 1, 2]` makes it `[1, 2, 3]`, which is sorted.
### Verifier
This stack snippet can be used to verify that a sequence really sorts the list. The list should have square brackets and be comma separated. The SP sequence is just a string of `S`'s and `P`'s.
```
<style>*{font-family:monospace}</style><script>function swap(list) {var tmp = list[0];list[0] = list[list.length - 1];list[list.length - 1] = tmp;}function pop(list) {list.push(list.shift())}function check() {var result = 'Sorted sucessfully.';var details = '';try {var list = eval(document.getElementById('list').value);var seq = document.getElementById('seq').value;details += 'Sequence: ' + seq + '<br>Steps:<br>' + list + ' <-- original';for(var i = 0; i < seq.length; i++) {if (seq.charAt(i) == 'S')swap(list);else if (seq.charAt(i) == 'P')pop(list);details += ' (' + i + ')<br>' + list;}details += ' <-- final (' + i + ')';for(var i = 1; i < list.length; i++) {if (list[i-1] > list[i]) {result = 'Sorting failed!';break;}}} catch(e) {result = 'Error: ' + e;}document.getElementById('result').innerHTML = result;document.getElementById('details').innerHTML = details;}</script><p>List<br><input id='list'type='text'size='60'value='[2, 1, 3]'></p><p>SP Sequence<br><textarea id='seq'rows='1'cols='60'>SP</textarea><br></p><button type='button'onclick='check()'>Check</button><p id='result'></p><p id='details'></p>
```
# Scoring
Your algorithm must produce correct, but possibly sub-optimal, SP sequences for N = 2 to 256. For any permutation in this range it must run in less than 5 minutes on a [decent modern computer](https://teksyndicate.com/forum/general-discussion/average-steam-users-computer-specs/150190).
Your score is the total number of S and P operations your algorithm needs to sort all 30 of the lists provided below. The lowest score wins.
**You may not hardcode your program to suit this data.** If it seems necessary I may add more test data to determine the winner.
```
1. Length 3
[2, 1, 3]
2. Length 7
[2, 7, 5, 3, 4, 6, 1]
3. Length 41
[7, 12, 17, 2, 14, 15, 33, 20, 37, 18, 9, 25, 41, 26, 39, 29, 16, 5, 23, 24, 35, 38, 32, 6, 11, 21, 27, 8, 40, 3, 10, 36, 13, 30, 31, 28, 1, 4, 19, 22, 34]
4. Length 52
[19, 49, 34, 26, 38, 3, 14, 37, 21, 39, 46, 29, 18, 6, 15, 25, 28, 47, 22, 41, 32, 51, 50, 5, 45, 4, 30, 44, 10, 43, 20, 17, 13, 36, 48, 27, 35, 24, 8, 12, 40, 2, 1, 16, 7, 31, 23, 33, 42, 52, 9, 11]
5. Length 65
[12, 53, 4, 5, 17, 32, 58, 54, 18, 43, 21, 26, 51, 45, 9, 2, 35, 28, 40, 61, 57, 27, 62, 39, 24, 59, 36, 25, 20, 33, 63, 56, 64, 47, 38, 7, 13, 34, 16, 30, 49, 22, 37, 3, 48, 11, 52, 1, 29, 42, 50, 23, 6, 8, 60, 65, 46, 10, 41, 31, 44, 15, 14, 19, 55]
6. Length 69
[58, 15, 63, 18, 24, 59, 26, 37, 44, 67, 14, 52, 2, 31, 68, 54, 32, 17, 55, 50, 42, 56, 65, 29, 13, 41, 7, 45, 53, 35, 21, 39, 61, 23, 49, 12, 60, 46, 27, 57, 28, 40, 10, 69, 1, 6, 19, 62, 8, 30, 64, 34, 3, 43, 38, 20, 25, 33, 66, 47, 4, 36, 16, 11, 5, 22, 51, 48, 9]
7. Length 75
[14, 69, 1, 43, 32, 42, 59, 37, 70, 63, 57, 60, 56, 73, 67, 6, 11, 36, 31, 22, 40, 7, 21, 35, 50, 64, 28, 41, 18, 17, 75, 54, 51, 19, 68, 33, 45, 61, 66, 52, 49, 65, 4, 72, 23, 34, 9, 15, 38, 16, 3, 71, 29, 30, 48, 53, 10, 8, 13, 47, 20, 55, 74, 27, 25, 62, 46, 24, 44, 39, 2, 26, 58, 12, 5]
8. Length 80
[3, 65, 44, 14, 19, 6, 11, 29, 79, 35, 42, 16, 68, 7, 62, 30, 38, 46, 15, 9, 75, 5, 52, 32, 22, 70, 64, 13, 21, 47, 10, 4, 55, 40, 45, 56, 77, 27, 23, 72, 17, 71, 53, 20, 18, 25, 73, 59, 36, 34, 37, 57, 1, 69, 24, 58, 33, 76, 2, 12, 49, 61, 78, 67, 66, 63, 50, 80, 28, 48, 26, 51, 41, 60, 31, 54, 39, 8, 74, 43]
9. Length 103
[40, 62, 53, 6, 32, 85, 8, 83, 33, 29, 87, 93, 22, 37, 80, 12, 74, 69, 64, 9, 18, 98, 17, 45, 60, 38, 10, 103, 19, 5, 54, 15, 90, 100, 79, 91, 46, 82, 43, 31, 51, 96, 30, 70, 76, 16, 55, 77, 11, 65, 58, 75, 61, 3, 28, 24, 101, 20, 41, 72, 86, 56, 35, 50, 78, 27, 67, 95, 44, 68, 48, 26, 39, 97, 21, 49, 102, 73, 63, 7, 71, 52, 1, 88, 34, 42, 14, 47, 36, 99, 4, 13, 94, 89, 59, 92, 57, 25, 23, 66, 81, 2, 84]
10. Length 108
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108]
11. Length 109
[48, 89, 25, 64, 8, 69, 81, 98, 107, 61, 106, 63, 59, 50, 83, 24, 86, 68, 100, 104, 56, 88, 46, 62, 94, 4, 47, 33, 19, 1, 77, 102, 9, 30, 44, 26, 16, 80, 67, 75, 70, 96, 108, 45, 79, 51, 12, 38, 73, 37, 65, 31, 60, 22, 28, 3, 43, 71, 105, 91, 93, 101, 13, 97, 29, 72, 82, 87, 27, 5, 17, 10, 34, 84, 53, 15, 78, 41, 85, 6, 14, 57, 76, 7, 23, 99, 32, 95, 49, 2, 21, 109, 74, 39, 11, 103, 18, 90, 35, 40, 58, 20, 55, 52, 36, 54, 42, 92, 66]
12. Length 151
[61, 7, 8, 79, 78, 4, 48, 13, 14, 117, 12, 96, 130, 118, 63, 110, 72, 57, 86, 126, 62, 10, 29, 102, 99, 28, 56, 135, 11, 151, 141, 97, 45, 109, 38, 150, 40, 149, 52, 140, 106, 80, 66, 134, 125, 137, 31, 85, 68, 94, 36, 26, 95, 92, 49, 25, 120, 148, 33, 73, 41, 100, 58, 127, 60, 122, 133, 9, 19, 81, 59, 55, 103, 146, 42, 21, 128, 75, 101, 82, 50, 142, 131, 76, 20, 69, 139, 83, 16, 64, 17, 124, 90, 138, 37, 1, 34, 43, 129, 77, 23, 35, 144, 121, 113, 115, 114, 67, 98, 70, 145, 104, 71, 5, 119, 6, 18, 88, 116, 111, 132, 39, 89, 24, 15, 107, 27, 65, 30, 47, 143, 93, 53, 108, 2, 74, 123, 44, 51, 54, 87, 147, 84, 3, 112, 46, 32, 91, 136, 22, 105]
13. Length 173
[93, 14, 141, 125, 64, 30, 24, 85, 44, 68, 91, 22, 103, 155, 117, 114, 123, 51, 131, 72, 67, 61, 5, 41, 10, 20, 129, 86, 154, 108, 161, 2, 82, 153, 96, 50, 136, 121, 128, 126, 120, 111, 89, 113, 104, 84, 18, 109, 42, 83, 162, 124, 173, 116, 12, 54, 52, 39, 122, 49, 46, 1, 130, 71, 152, 73, 56, 34, 149, 75, 133, 8, 74, 45, 88, 23, 7, 60, 115, 134, 53, 119, 106, 81, 112, 31, 35, 172, 159, 38, 59, 69, 142, 146, 110, 170, 160, 166, 43, 58, 4, 107, 78, 156, 47, 33, 145, 63, 163, 27, 70, 77, 36, 16, 100, 26, 19, 151, 57, 32, 15, 13, 40, 169, 98, 132, 135, 62, 66, 90, 102, 171, 99, 148, 80, 144, 147, 168, 94, 143, 17, 3, 140, 97, 11, 65, 55, 92, 95, 127, 167, 150, 87, 118, 28, 137, 9, 29, 105, 157, 25, 165, 158, 21, 164, 101, 79, 76, 6, 138, 48, 37, 139]
14. Length 177
[68, 117, 61, 159, 110, 148, 3, 20, 169, 145, 136, 1, 120, 109, 21, 58, 52, 97, 65, 168, 34, 134, 111, 176, 13, 156, 172, 53, 55, 124, 177, 88, 92, 23, 72, 26, 104, 121, 133, 73, 39, 140, 25, 71, 119, 158, 146, 128, 18, 94, 113, 45, 60, 96, 30, 5, 116, 153, 90, 115, 67, 80, 112, 154, 9, 17, 10, 33, 81, 38, 95, 118, 35, 160, 151, 150, 76, 77, 14, 147, 173, 135, 162, 114, 27, 100, 167, 74, 69, 165, 108, 79, 91, 48, 105, 125, 129, 75, 93, 11, 12, 64, 24, 170, 142, 98, 44, 37, 43, 78, 16, 28, 166, 155, 138, 164, 122, 163, 107, 130, 86, 56, 2, 161, 63, 126, 131, 144, 82, 106, 103, 32, 132, 54, 41, 171, 70, 85, 19, 143, 137, 87, 84, 66, 99, 102, 15, 49, 123, 175, 89, 51, 141, 62, 50, 36, 152, 47, 42, 8, 7, 46, 29, 22, 149, 139, 4, 40, 83, 6, 59, 57, 174, 31, 127, 101, 157]
15. Length 192
[82, 130, 189, 21, 169, 147, 160, 66, 133, 153, 143, 116, 49, 13, 63, 61, 94, 164, 35, 112, 141, 62, 87, 171, 19, 3, 93, 83, 149, 64, 34, 170, 129, 182, 101, 77, 14, 91, 145, 23, 32, 92, 187, 54, 184, 120, 109, 159, 27, 44, 60, 103, 134, 52, 122, 33, 78, 88, 108, 45, 15, 79, 137, 80, 161, 69, 6, 139, 110, 67, 43, 190, 152, 59, 173, 125, 168, 37, 151, 132, 1, 178, 20, 114, 119, 144, 25, 146, 42, 136, 162, 123, 31, 107, 131, 127, 51, 105, 2, 65, 28, 102, 76, 24, 135, 174, 9, 111, 98, 39, 74, 142, 70, 121, 154, 38, 113, 75, 40, 86, 100, 106, 181, 117, 95, 85, 138, 41, 167, 172, 4, 186, 17, 16, 104, 71, 81, 73, 57, 8, 140, 118, 158, 12, 148, 53, 29, 185, 18, 150, 22, 188, 72, 128, 84, 96, 47, 192, 126, 56, 163, 50, 157, 165, 97, 166, 180, 7, 46, 30, 191, 124, 5, 48, 175, 68, 36, 89, 177, 11, 176, 183, 99, 90, 55, 26, 10, 58, 115, 155, 179, 156]
16. Length 201
[23, 8, 58, 24, 19, 87, 98, 187, 17, 130, 116, 141, 129, 166, 29, 191, 81, 105, 137, 171, 39, 67, 46, 150, 102, 26, 163, 183, 170, 72, 160, 43, 9, 197, 189, 173, 196, 68, 100, 16, 93, 175, 74, 28, 133, 122, 27, 79, 107, 162, 62, 192, 108, 104, 97, 12, 60, 155, 161, 82, 167, 158, 149, 30, 124, 22, 168, 115, 134, 94, 34, 184, 127, 121, 177, 112, 142, 95, 164, 41, 59, 55, 143, 85, 176, 3, 156, 148, 153, 42, 180, 145, 78, 147, 119, 109, 139, 178, 61, 181, 136, 157, 91, 84, 47, 71, 70, 118, 18, 63, 80, 56, 123, 194, 117, 195, 152, 66, 48, 11, 99, 201, 128, 151, 138, 64, 21, 131, 159, 103, 75, 49, 169, 113, 53, 114, 69, 54, 165, 38, 101, 76, 200, 199, 140, 125, 193, 88, 32, 51, 126, 14, 13, 77, 52, 50, 198, 172, 5, 92, 96, 15, 106, 182, 31, 83, 120, 57, 135, 65, 7, 154, 20, 25, 45, 1, 6, 73, 40, 174, 132, 10, 111, 186, 190, 4, 36, 188, 185, 146, 44, 110, 179, 2, 90, 86, 35, 37, 33, 89, 144]
17. Length 201
[97, 146, 168, 5, 56, 147, 189, 92, 154, 13, 185, 109, 45, 126, 17, 10, 53, 98, 88, 41, 163, 99, 157, 35, 125, 34, 173, 171, 138, 104, 149, 172, 60, 183, 36, 65, 32, 180, 87, 167, 59, 84, 188, 11, 69, 57, 174, 61, 66, 7, 8, 111, 91, 58, 128, 94, 141, 139, 31, 78, 156, 70, 16, 162, 26, 33, 106, 175, 103, 21, 164, 110, 159, 80, 200, 82, 123, 144, 44, 148, 4, 55, 179, 184, 186, 124, 63, 107, 54, 112, 137, 165, 121, 25, 132, 196, 90, 89, 71, 160, 95, 117, 197, 37, 108, 39, 115, 12, 52, 119, 120, 79, 29, 49, 93, 22, 122, 161, 76, 38, 72, 169, 85, 178, 77, 105, 190, 100, 9, 86, 177, 194, 2, 136, 114, 51, 68, 19, 47, 195, 113, 193, 67, 96, 182, 170, 50, 83, 143, 166, 3, 192, 24, 127, 140, 176, 134, 158, 116, 199, 1, 135, 118, 145, 14, 15, 155, 48, 42, 73, 46, 102, 191, 28, 201, 181, 75, 133, 153, 6, 131, 130, 81, 20, 198, 64, 142, 150, 27, 101, 18, 30, 40, 23, 129, 43, 62, 187, 152, 151, 74]
18. Length 205
[161, 197, 177, 118, 94, 112, 13, 190, 200, 166, 127, 80, 115, 204, 186, 60, 50, 97, 175, 32, 26, 65, 16, 4, 55, 120, 143, 187, 121, 29, 18, 82, 17, 21, 144, 20, 88, 195, 99, 67, 203, 23, 176, 126, 137, 77, 70, 30, 103, 182, 113, 119, 36, 47, 90, 98, 54, 3, 49, 105, 57, 135, 153, 142, 174, 155, 158, 11, 157, 22, 171, 110, 28, 196, 129, 163, 79, 63, 38, 145, 140, 2, 128, 180, 106, 59, 25, 184, 81, 164, 95, 39, 68, 78, 178, 156, 72, 51, 202, 66, 48, 101, 71, 108, 130, 5, 107, 147, 199, 12, 27, 150, 167, 91, 64, 170, 191, 151, 149, 168, 34, 125, 188, 181, 139, 58, 75, 189, 124, 152, 183, 7, 111, 89, 84, 52, 141, 83, 69, 62, 73, 43, 123, 14, 179, 162, 114, 138, 117, 159, 74, 85, 10, 96, 86, 31, 132, 1, 104, 109, 45, 165, 148, 172, 154, 92, 173, 40, 19, 56, 37, 205, 44, 193, 122, 185, 93, 133, 53, 9, 169, 6, 61, 136, 46, 76, 33, 15, 116, 198, 160, 194, 131, 41, 42, 35, 146, 134, 192, 8, 87, 201, 100, 24, 102]
19. Length 211
[200, 36, 204, 198, 190, 161, 57, 108, 180, 203, 135, 48, 134, 47, 158, 10, 41, 11, 23, 127, 167, 121, 109, 211, 201, 1, 42, 40, 86, 104, 147, 139, 145, 101, 144, 166, 176, 92, 118, 54, 182, 30, 58, 123, 124, 67, 125, 154, 187, 168, 103, 17, 72, 98, 12, 184, 59, 87, 174, 93, 45, 116, 73, 69, 74, 80, 56, 14, 34, 85, 38, 185, 165, 110, 164, 151, 43, 192, 62, 4, 140, 170, 197, 111, 173, 141, 65, 77, 70, 136, 206, 83, 100, 148, 25, 183, 209, 189, 150, 33, 46, 16, 64, 114, 71, 102, 91, 39, 177, 196, 169, 128, 129, 44, 75, 188, 146, 26, 84, 138, 162, 194, 105, 37, 35, 88, 156, 130, 193, 19, 179, 82, 106, 181, 153, 28, 53, 21, 195, 66, 159, 115, 113, 112, 191, 172, 63, 143, 178, 94, 160, 186, 31, 29, 90, 68, 205, 155, 119, 117, 157, 107, 60, 79, 171, 149, 6, 24, 27, 50, 51, 126, 15, 133, 2, 131, 7, 49, 207, 163, 18, 120, 199, 61, 52, 32, 208, 20, 210, 13, 78, 55, 137, 202, 152, 8, 81, 76, 9, 97, 22, 99, 132, 95, 122, 89, 175, 5, 3, 96, 142]
20. Length 226
[204, 79, 88, 98, 197, 32, 40, 117, 153, 167, 29, 74, 170, 115, 127, 210, 22, 109, 65, 47, 41, 132, 110, 158, 192, 99, 96, 224, 190, 143, 33, 225, 195, 19, 70, 73, 54, 161, 75, 179, 181, 207, 26, 221, 66, 130, 152, 131, 30, 35, 155, 69, 68, 38, 129, 95, 116, 214, 7, 186, 62, 27, 212, 125, 216, 86, 148, 164, 141, 4, 140, 222, 16, 46, 12, 215, 78, 219, 211, 134, 118, 171, 121, 52, 123, 56, 220, 15, 25, 100, 137, 163, 51, 91, 10, 83, 55, 187, 182, 201, 149, 160, 8, 14, 218, 77, 3, 184, 114, 43, 122, 135, 142, 104, 120, 198, 45, 108, 85, 189, 151, 175, 136, 165, 226, 97, 124, 200, 60, 172, 20, 67, 1, 174, 87, 102, 119, 188, 223, 199, 103, 89, 49, 213, 57, 9, 101, 112, 36, 176, 194, 92, 145, 180, 168, 111, 94, 178, 39, 166, 193, 17, 2, 154, 58, 156, 217, 13, 80, 202, 206, 169, 107, 177, 144, 205, 139, 93, 34, 64, 106, 150, 146, 126, 185, 208, 63, 203, 105, 18, 191, 53, 183, 209, 6, 23, 84, 5, 61, 59, 162, 128, 37, 50, 28, 159, 173, 196, 24, 31, 72, 138, 82, 48, 133, 147, 42, 113, 81, 90, 71, 21, 11, 157, 76, 44]
21. Length 227
[197, 52, 91, 42, 29, 113, 82, 68, 147, 225, 80, 167, 117, 142, 140, 216, 65, 195, 97, 61, 133, 209, 214, 58, 152, 71, 56, 182, 201, 163, 227, 186, 63, 171, 207, 102, 161, 136, 224, 146, 92, 175, 45, 217, 6, 99, 20, 119, 210, 93, 77, 211, 21, 70, 90, 96, 115, 100, 183, 173, 69, 98, 172, 75, 111, 203, 19, 129, 35, 155, 74, 37, 23, 51, 192, 212, 33, 64, 59, 194, 112, 135, 1, 184, 5, 166, 185, 84, 199, 138, 144, 86, 128, 26, 190, 73, 179, 27, 118, 223, 46, 95, 159, 153, 226, 25, 180, 132, 189, 60, 32, 208, 123, 89, 87, 22, 181, 143, 47, 18, 198, 219, 156, 148, 193, 122, 110, 28, 106, 39, 30, 103, 4, 176, 114, 3, 131, 107, 204, 218, 141, 169, 16, 206, 36, 188, 174, 54, 94, 50, 205, 104, 170, 160, 72, 165, 78, 24, 222, 8, 108, 81, 76, 15, 13, 126, 79, 7, 105, 125, 162, 83, 41, 145, 139, 66, 127, 38, 12, 187, 130, 221, 48, 164, 191, 157, 88, 168, 196, 10, 9, 53, 124, 150, 31, 116, 49, 34, 200, 134, 220, 121, 2, 62, 149, 158, 101, 17, 202, 11, 109, 85, 55, 67, 120, 43, 154, 44, 215, 177, 178, 40, 57, 14, 213, 151, 137]
22. Length 230
[69, 204, 215, 61, 97, 149, 9, 11, 137, 71, 37, 219, 92, 115, 156, 159, 200, 222, 3, 89, 172, 177, 203, 45, 54, 82, 147, 176, 168, 6, 26, 81, 25, 132, 212, 70, 228, 122, 225, 141, 100, 12, 124, 30, 146, 73, 19, 49, 52, 62, 217, 166, 191, 102, 163, 50, 181, 7, 134, 58, 76, 199, 179, 169, 197, 108, 174, 22, 186, 171, 114, 103, 173, 68, 65, 4, 13, 117, 64, 10, 126, 77, 206, 133, 121, 60, 40, 38, 59, 178, 224, 211, 187, 80, 220, 140, 8, 34, 130, 41, 95, 105, 227, 66, 210, 180, 192, 106, 209, 107, 157, 188, 170, 101, 131, 87, 14, 165, 78, 182, 136, 193, 190, 20, 67, 125, 36, 5, 145, 218, 99, 138, 154, 16, 29, 152, 194, 53, 148, 93, 202, 229, 198, 109, 43, 214, 150, 51, 128, 216, 1, 83, 196, 135, 74, 119, 75, 42, 142, 72, 226, 185, 116, 162, 63, 2, 112, 33, 184, 158, 15, 213, 144, 223, 98, 57, 160, 143, 90, 44, 205, 35, 21, 48, 151, 85, 123, 32, 47, 39, 189, 161, 56, 207, 84, 94, 230, 46, 164, 113, 175, 18, 195, 110, 127, 96, 129, 88, 17, 153, 104, 91, 86, 31, 118, 111, 120, 201, 28, 221, 23, 139, 24, 27, 167, 208, 183, 155, 79, 55]
23. Length 238
[202, 18, 122, 135, 11, 57, 103, 35, 86, 2, 84, 232, 208, 186, 54, 77, 145, 101, 105, 137, 210, 234, 207, 93, 55, 63, 230, 66, 160, 10, 223, 36, 34, 216, 104, 174, 121, 25, 166, 75, 167, 176, 61, 32, 118, 89, 68, 5, 14, 27, 204, 99, 149, 88, 91, 222, 37, 144, 108, 78, 128, 131, 190, 17, 65, 168, 225, 165, 41, 49, 38, 72, 43, 147, 158, 74, 130, 7, 82, 64, 97, 69, 100, 22, 152, 85, 48, 33, 218, 47, 228, 113, 40, 185, 219, 112, 180, 120, 4, 213, 179, 194, 51, 96, 221, 44, 238, 31, 117, 114, 229, 81, 164, 193, 236, 26, 59, 30, 151, 12, 115, 170, 24, 70, 227, 159, 133, 52, 134, 203, 15, 197, 155, 83, 50, 111, 195, 139, 109, 127, 188, 87, 62, 157, 226, 142, 98, 76, 211, 138, 58, 140, 198, 220, 16, 46, 183, 107, 106, 29, 163, 173, 209, 217, 215, 1, 177, 233, 199, 110, 172, 23, 212, 79, 94, 102, 39, 20, 178, 150, 175, 119, 8, 13, 42, 156, 201, 73, 200, 124, 53, 161, 92, 123, 224, 143, 196, 28, 9, 6, 80, 56, 148, 125, 214, 60, 171, 153, 231, 181, 205, 19, 95, 206, 154, 132, 169, 116, 3, 126, 187, 162, 191, 67, 136, 45, 192, 189, 235, 129, 21, 141, 237, 184, 90, 146, 182, 71]
24. Length 241
[2, 33, 49, 83, 207, 204, 13, 57, 115, 86, 102, 219, 232, 44, 177, 197, 171, 227, 191, 10, 25, 162, 62, 11, 76, 214, 163, 201, 130, 91, 233, 194, 112, 179, 66, 139, 183, 116, 196, 193, 150, 211, 30, 144, 209, 97, 174, 3, 68, 38, 120, 165, 56, 64, 87, 15, 79, 131, 206, 96, 188, 7, 99, 195, 129, 8, 186, 78, 212, 125, 161, 230, 225, 239, 47, 107, 53, 218, 164, 106, 198, 215, 181, 226, 6, 175, 167, 236, 67, 80, 210, 128, 155, 40, 63, 74, 113, 89, 18, 190, 124, 221, 59, 149, 103, 42, 156, 157, 200, 168, 34, 77, 65, 146, 5, 187, 222, 231, 140, 141, 172, 234, 100, 94, 132, 237, 24, 216, 152, 22, 51, 69, 35, 43, 105, 23, 61, 1, 72, 135, 104, 9, 12, 21, 46, 192, 159, 205, 158, 109, 28, 98, 50, 122, 111, 71, 166, 229, 37, 114, 173, 134, 136, 81, 121, 185, 118, 223, 20, 14, 108, 82, 178, 54, 26, 153, 36, 39, 117, 147, 95, 90, 16, 17, 170, 119, 199, 19, 84, 213, 88, 93, 151, 4, 101, 142, 110, 184, 55, 138, 75, 133, 148, 145, 45, 70, 217, 143, 224, 241, 31, 240, 182, 52, 238, 126, 85, 154, 137, 160, 27, 180, 60, 29, 32, 169, 235, 123, 176, 48, 220, 203, 228, 127, 41, 58, 73, 92, 189, 202, 208]
25. Length 241
[105, 160, 132, 32, 10, 117, 76, 2, 190, 108, 178, 51, 71, 237, 232, 47, 14, 124, 100, 31, 169, 196, 8, 184, 21, 151, 223, 86, 42, 127, 55, 58, 229, 4, 219, 46, 238, 179, 24, 194, 203, 122, 66, 15, 81, 146, 172, 106, 129, 135, 216, 120, 92, 231, 144, 195, 181, 162, 69, 45, 137, 136, 9, 30, 5, 188, 91, 49, 147, 233, 198, 17, 241, 163, 36, 18, 183, 59, 16, 29, 116, 182, 41, 48, 23, 39, 154, 210, 68, 167, 95, 213, 79, 225, 37, 157, 109, 143, 78, 142, 173, 155, 200, 110, 20, 73, 141, 168, 156, 126, 150, 201, 114, 1, 230, 211, 217, 131, 140, 204, 209, 149, 103, 199, 165, 175, 35, 107, 74, 63, 193, 239, 218, 234, 197, 224, 174, 121, 60, 88, 22, 171, 133, 207, 152, 34, 43, 228, 125, 115, 101, 7, 12, 220, 82, 153, 134, 52, 130, 70, 72, 44, 177, 89, 65, 98, 94, 53, 208, 227, 161, 3, 123, 236, 221, 87, 102, 50, 90, 180, 185, 186, 67, 77, 26, 212, 27, 222, 6, 145, 11, 13, 84, 25, 164, 64, 85, 139, 214, 189, 61, 96, 191, 128, 93, 138, 148, 19, 119, 202, 75, 176, 159, 56, 104, 206, 40, 187, 215, 62, 166, 240, 112, 226, 170, 83, 97, 57, 99, 38, 28, 113, 205, 158, 235, 111, 54, 192, 118, 80, 33]
26. Length 244
[89, 13, 154, 161, 235, 225, 92, 188, 215, 194, 54, 58, 128, 21, 165, 85, 144, 205, 142, 77, 109, 24, 83, 69, 72, 7, 224, 240, 191, 204, 183, 203, 68, 70, 63, 95, 206, 170, 153, 180, 45, 178, 35, 27, 190, 132, 222, 41, 40, 156, 97, 20, 217, 177, 167, 65, 23, 136, 216, 234, 38, 201, 236, 164, 82, 241, 10, 141, 148, 229, 5, 125, 113, 159, 193, 187, 130, 179, 52, 108, 86, 196, 174, 123, 56, 116, 227, 30, 239, 98, 186, 67, 135, 118, 163, 43, 32, 50, 231, 226, 232, 172, 200, 99, 6, 143, 39, 93, 107, 34, 129, 157, 100, 127, 15, 84, 81, 73, 121, 220, 44, 8, 57, 105, 91, 171, 162, 211, 244, 104, 112, 238, 212, 133, 71, 192, 145, 160, 87, 181, 60, 184, 119, 4, 55, 96, 53, 12, 213, 124, 94, 22, 42, 3, 48, 131, 117, 140, 138, 228, 219, 155, 59, 29, 202, 169, 114, 101, 47, 233, 176, 139, 207, 33, 79, 16, 51, 66, 75, 90, 198, 168, 166, 31, 151, 49, 208, 150, 111, 14, 25, 197, 17, 76, 80, 78, 9, 173, 26, 137, 19, 120, 199, 106, 152, 88, 147, 36, 158, 28, 243, 221, 110, 74, 175, 237, 61, 2, 62, 214, 189, 134, 195, 218, 18, 102, 46, 103, 11, 122, 146, 185, 182, 209, 1, 149, 115, 64, 37, 126, 230, 223, 242, 210]
27. Length 246
[28, 186, 214, 18, 220, 73, 20, 88, 234, 187, 27, 102, 22, 129, 10, 228, 196, 56, 47, 2, 16, 67, 124, 137, 177, 179, 223, 147, 188, 23, 103, 109, 149, 60, 229, 99, 222, 90, 49, 80, 158, 93, 171, 71, 175, 143, 19, 212, 40, 226, 219, 120, 146, 66, 167, 232, 94, 174, 237, 9, 173, 70, 122, 241, 58, 82, 191, 211, 180, 104, 53, 36, 83, 37, 131, 25, 162, 32, 210, 144, 145, 69, 135, 63, 154, 165, 46, 57, 50, 74, 128, 140, 112, 118, 125, 231, 221, 233, 95, 200, 153, 6, 166, 98, 208, 91, 89, 141, 4, 26, 134, 86, 8, 30, 157, 156, 224, 201, 243, 7, 161, 1, 84, 115, 44, 230, 78, 79, 5, 17, 194, 148, 152, 121, 193, 107, 240, 181, 29, 43, 65, 164, 45, 110, 64, 195, 216, 127, 59, 197, 178, 151, 139, 85, 75, 11, 204, 184, 77, 54, 51, 205, 108, 142, 130, 138, 238, 87, 38, 101, 96, 31, 215, 244, 242, 172, 213, 136, 97, 35, 39, 76, 42, 245, 123, 227, 24, 168, 33, 159, 217, 239, 55, 176, 68, 207, 106, 132, 15, 116, 61, 198, 62, 182, 225, 202, 105, 150, 183, 81, 170, 13, 41, 199, 3, 185, 235, 14, 155, 21, 126, 119, 169, 72, 12, 236, 48, 209, 190, 113, 218, 100, 52, 111, 189, 92, 192, 114, 117, 160, 133, 203, 163, 34, 206, 246]
28. Length 250
[119, 57, 59, 181, 212, 120, 236, 121, 99, 247, 138, 187, 175, 108, 107, 197, 123, 101, 141, 77, 201, 3, 52, 60, 56, 240, 157, 39, 42, 199, 23, 18, 136, 74, 137, 143, 229, 170, 20, 160, 206, 219, 191, 185, 46, 223, 150, 190, 116, 96, 198, 221, 220, 159, 238, 48, 176, 113, 168, 33, 44, 142, 67, 244, 13, 218, 122, 246, 214, 234, 237, 27, 165, 24, 153, 90, 84, 154, 235, 196, 80, 111, 102, 231, 228, 135, 16, 148, 26, 45, 10, 71, 156, 224, 183, 232, 72, 94, 132, 54, 58, 248, 144, 213, 139, 129, 245, 115, 25, 164, 87, 19, 193, 81, 32, 78, 91, 167, 171, 40, 92, 226, 109, 69, 86, 38, 61, 5, 14, 118, 145, 103, 53, 93, 172, 178, 225, 68, 163, 210, 179, 192, 208, 169, 17, 12, 50, 233, 6, 55, 243, 158, 88, 188, 242, 36, 173, 126, 155, 184, 216, 149, 47, 76, 200, 1, 112, 28, 161, 174, 41, 73, 222, 66, 37, 63, 64, 124, 89, 205, 9, 186, 202, 70, 203, 127, 105, 250, 182, 79, 43, 133, 8, 241, 114, 128, 51, 83, 98, 49, 209, 7, 95, 151, 162, 189, 180, 75, 195, 62, 207, 21, 104, 30, 117, 110, 140, 29, 227, 249, 82, 152, 11, 34, 85, 106, 217, 211, 2, 35, 215, 4, 230, 134, 31, 194, 97, 22, 125, 130, 100, 239, 131, 166, 65, 15, 146, 177, 204, 147]
29. Length 253
[46, 245, 174, 180, 85, 29, 141, 70, 252, 119, 214, 225, 86, 91, 41, 67, 219, 118, 127, 243, 2, 71, 157, 114, 55, 92, 5, 200, 199, 139, 191, 235, 153, 102, 206, 171, 117, 58, 223, 249, 11, 211, 202, 175, 156, 133, 57, 163, 47, 65, 213, 247, 189, 111, 177, 49, 124, 154, 164, 145, 80, 15, 232, 142, 39, 69, 201, 185, 229, 215, 170, 42, 3, 248, 169, 136, 149, 218, 237, 90, 135, 7, 242, 246, 23, 186, 31, 4, 167, 207, 173, 132, 195, 196, 78, 212, 22, 35, 194, 54, 184, 183, 222, 230, 88, 43, 144, 151, 34, 97, 6, 109, 37, 147, 72, 158, 134, 33, 51, 238, 165, 162, 9, 63, 166, 113, 137, 198, 50, 121, 106, 224, 19, 104, 95, 129, 193, 79, 192, 122, 30, 12, 234, 168, 76, 103, 73, 66, 188, 178, 172, 176, 250, 182, 110, 231, 155, 26, 197, 10, 152, 98, 131, 25, 36, 81, 138, 150, 227, 24, 112, 120, 204, 75, 8, 179, 94, 17, 140, 32, 77, 61, 233, 38, 205, 93, 99, 27, 208, 56, 216, 48, 241, 20, 130, 240, 115, 83, 60, 108, 28, 13, 89, 128, 160, 82, 40, 126, 16, 253, 21, 251, 228, 59, 159, 64, 203, 236, 52, 18, 181, 105, 107, 239, 220, 44, 74, 125, 209, 84, 226, 217, 210, 190, 101, 100, 68, 116, 161, 148, 244, 221, 96, 45, 123, 187, 62, 87, 53, 1, 146, 143, 14]
30. Length 256
[159, 248, 75, 43, 111, 38, 4, 17, 155, 87, 81, 208, 53, 230, 65, 11, 108, 228, 146, 212, 137, 225, 144, 189, 86, 105, 84, 128, 97, 50, 223, 15, 83, 169, 217, 47, 88, 236, 114, 181, 115, 177, 102, 250, 246, 104, 80, 45, 240, 14, 196, 52, 247, 41, 198, 32, 182, 206, 226, 101, 70, 94, 113, 49, 254, 59, 42, 154, 77, 253, 112, 215, 99, 25, 134, 92, 95, 150, 64, 178, 118, 79, 130, 63, 129, 131, 57, 218, 85, 204, 3, 163, 158, 186, 10, 199, 24, 125, 251, 51, 74, 160, 207, 120, 233, 30, 19, 9, 56, 167, 58, 117, 164, 54, 220, 229, 234, 203, 211, 103, 205, 69, 39, 5, 31, 191, 106, 180, 116, 245, 21, 222, 91, 235, 8, 2, 214, 29, 238, 176, 135, 61, 227, 202, 122, 252, 231, 89, 187, 37, 149, 96, 190, 172, 73, 18, 71, 1, 179, 46, 156, 201, 165, 256, 151, 27, 242, 188, 126, 124, 244, 100, 107, 143, 170, 72, 255, 40, 67, 192, 185, 219, 20, 157, 98, 237, 136, 168, 141, 224, 232, 44, 139, 132, 22, 60, 109, 90, 175, 171, 62, 23, 161, 12, 76, 210, 68, 184, 93, 243, 48, 209, 174, 200, 121, 123, 36, 173, 140, 133, 145, 6, 110, 152, 142, 241, 55, 138, 147, 193, 213, 127, 7, 34, 66, 153, 26, 13, 162, 183, 239, 78, 249, 221, 28, 194, 16, 35, 33, 82, 195, 148, 216, 119, 166, 197]
```
[Answer]
# Python 3 (with PyPy) - score: 607771
*Edit: I think the bug is fixed, but I'm still not convinced this works until I prove it does*
```
def d(a, b, N):
a, b = a%N, b%N
if a >= b:
return a-b
else:
return a+(N-b)
def gt(a, b, N):
if a == N and b == 1:
return False
if a == 1 and b == N:
return True
return a > b
def solve(numbers):
N = len(numbers)
best_move = None
target = sorted(numbers)
if N == 2:
return "" if numbers == [1,2] else "P"
for b in range(N):
nums = numbers[:]
moves = []
head_ptr = 0 # Which element should be at the start of the list if we actually moved stuff
reference = target[b:]+target[:b]
ref_d = {t:i for i,t in enumerate(reference)}
while True:
for pops in range(N):
ptr = (head_ptr + pops) % N
# Magic
d1 = d(ref_d[nums[ptr-1]],ptr-1,N)+d(ptr,ref_d[nums[ptr]],N)
d2 = d(ref_d[nums[ptr]],ptr,N)+d(ptr-1,ref_d[nums[ptr-1]],N)
if d1 > d2 or (d1 == d2 and gt(nums[ptr-1], nums[ptr], N)):
moves.append("P"*pops + "S")
head_ptr = (head_ptr + pops) % N
nums[ptr-1],nums[ptr] = nums[ptr],nums[ptr-1]
break
else:
if nums[nums.index(1):]+nums[:nums.index(1)] != target:
print("This algorithm is seriously broken.\n")
moves.append("P"*((N+nums.index(1)-head_ptr)%N))
break
moves = "".join(moves)
if not best_move or len(moves) < len(best_move):
best_move = moves
return best_move
```
## Usage
```
solve([3, 4, 2, 1, 5])
```
## Explanation
>
> The program just performs bubble sort swaps, using the observation that:
>
>
> `S: n 1 2 3 ... n-1 0
> PS: 0 2 3 ... n-1 n 1
> PPS: 1 3 ... n-1 n 0 2
> PPPS: 2 ... n-1 n 0 1 3
> ...`
>
>
> In other words, `i` pushes followed by a swap means that element `i` gets swapped with element `i-1`, indices wrapping. However, we need to keep track of the fact that the list gets shifted in doing so.
>
>
>
> To do better than just the usual bubble sort, we try to apply a heuristic in order to make sure we don't do too many useless swaps, enforcing that any swap moves both elements closer to their respective goals (I haven't formally proved it's correct, but it seems to work so far). We then take the best solution out of many configurations (CPython takes a while, but PyPy gets this job done relatively quickly).
>
>
>
## Scoring
[Output on Pastebin.](http://pastebin.com/tv6uzFrh)
---
## Previous naive bubble sort ver. (score: 1126232)
This one definitely works.
```
def cyclic_sorted(nums):
for i in range(len(nums)):
if nums[i:] + nums[:i] == sorted(nums):
return i
return False
def solve(nums):
N = len(nums)
def gt(a, b):
if a == 1 and b == N:
return True
if a == N and b == 1:
return False
return a > b
moves = []
head_ptr = 0 # Which element should be at the start of the list if we actually moved stuff
while nums != sorted(nums):
pops = 0
ptr_offset = 0
while pops < N:
ptr = (head_ptr + pops) % N
if (not moves or pops > 0) and gt(nums[ptr-1], nums[ptr]):
moves.append("P"*pops + "S")
head_ptr = (head_ptr + pops) % N
nums[ptr-1],nums[ptr] = nums[ptr],nums[ptr-1]
break
pops += 1
else:
moves.append("P"*cyclic_sorted(nums[head_ptr:]+nums[:head_ptr]))
break
return "".join(moves)
```
[Answer]
# Javascript ES6 - 607,771
```
function popsort( iData ) {
var sSP, iLen,
sSP_Opt = popsortimpl( iData.slice( 0 ), 0 ),
iOptLen = sSP_Opt.length;
for( var n = iData.length, i = 2; i <= n; i++ )
if( (iLen = (sSP = popsortimpl( iData.slice( 0 ), i - 1 )).length) < iOptLen ) {
iOptLen = iLen;
sSP_Opt = sSP;
}
return sSP_Opt;
}
function popsortimpl( iData, iPivIdx ) {
function issorted()
{ return iData.every( (_,i_) => _ == i_+1 ); }
function swap() {
var i_ = iData[0];
iData[0] = iData[n-1];
iData[n-1] = i_;
sSP.push( 'S' );
}
function pop() {
iData.push( iData.shift() );
if( --iPivIdx < 0 )
iPivIdx += n;
sSP.push( 'P' );
}
function dist2home( iIdx_, i_ ) {
var iHome_ = (iPivIdx + i_) %n,
iDist1_ = iIdx_ - iHome_,
iDist2_ = iHome_ - iIdx_;
if( iDist1_ < 0 )
iDist1_ += n;
if( iDist2_ < 0 )
iDist2_ += n;
return Math.min( iDist1_, iDist2_*Math.max( 1, n/50 ) );
}
var n = iData.length,
sSP = [];
while( !issorted() ) {
var iDistP = Math.max( dist2home( 0, iData[0] ), dist2home( n - 1, iData[n - 1] ) ),
iDistS = Math.max( dist2home( n - 1, iData[0] ), dist2home( 0, iData[n - 1] ) );
if( iDistS < iDistP )
swap();
else pop();
}
return sSP.join('');
}
```
Implements a "closest-end" bubble sort that bubbles elements up or down depending on the shortest route (bubble up or bubble down) to a reference position.
~~I don't believe the routine is optimal, but it should be reasonably close to it. As a bonus, it runs the full set of test vectors in milliseconds.~~
**Updated** to iterate over the pivot point to improve competitiveness. I also introduced heuristics to compensate for the fact that elements have a lower mobility moving "up" the list than moving "down" (a phenomenon analogous to the difference in electron and hole mobility in a semiconductor). There are major differences between this implementation and Sp3000's, hence the fact that both score exactly 607,771 is spooky. Halloween spooky.
The routine now takes about 20 seconds to run.
### Sample Output
```
popsort( [2, 7, 5, 3, 4, 6, 1] )
```
yields
```
PSPPSPSPPPS
```
[Answer]
# OCaml, score: 1136707 1136599
**Edit:** I messed up! I had read `S` would swap adjacent elements and missed that the *first* and *last* elements get swapped. This implementation builds on this as is obvious from the `eval` implementation.
**Edit²:** I fixed it up by using the observation that you can write what I thought was S P as P S. I also switched to the better-scoring version with some optimizations to make it less slow.
Runtime is 1.33 18 1.01 seconds on my system using the interpreter compiled binary.
```
type sp = S | P
let string_of_sp = function
| S -> "S"
| P -> "P"
let rec eval (e : sp list) (xs : int list) : int list =
match e, xs with
| [], xs -> xs
| P :: S :: e, x1 :: x2 :: xs -> eval e (x1 :: xs @ [x2])
| P :: e, x :: xs -> eval e (xs @ [x])
| _ -> assert false
let generate_sp_sequence xs : sp list =
let sorted = List.sort compare xs in
let rec generate_sp_sequence ((xs, ys) : int list * int list) acc : sp list =
if sorted = ys @ List.rev xs
then acc
else
match ys with
| v1 :: v2 :: ys' ->
if v1 > v2
then generate_sp_sequence (v2 :: xs, v1 :: ys') (S :: P :: acc)
else generate_sp_sequence (v1 :: xs, v2 :: ys') (P :: acc)
| [x] ->
let ys = List.rev (x :: xs) in
generate_sp_sequence ([], ys) (P :: acc)
| [] ->
assert false
in List.rev @@ generate_sp_sequence ([], xs) []
(** Uncomment to run tests **)
(*
let test =
QCheck.(mk_test
~n:1000
~name:"generate_sp_sequence sorting test"
~pp:PP.(list int)
Arbitrary.(list ~start:2 ~stop:256 small_int)
(fun xs ->
Prop.assume (List.length xs >= 2);
eval (generate_sp_sequence ([], xs))
xs
= List.sort compare xs))
let _ = QCheck.run test
*)
let score_test = ... (* not included for brevity *)
let score =
List.map (fun xs -> generate_sp_sequence ([], xs)) score_test
|> List.map List.length
|> List.fold_left (+) 0
let _ =
print_string "The score is: ";
print_int score;
print_newline ()
```
>
> `generate_sp_sequence` simply runs bubblesort and outputs the steps in terms of S and P. It may generate unnecessary steps.
>
>
>
[Answer]
# C, score: 607771
It turns out my solution is very similar to Sp3000's Python solution (which explains the identical score). I've never used Python so I can't say for sure, but I think the concept is exactly the same:
>
> For each number r in 0..n-1, set a goal of a sorted array rotated r times from the initial position (i.e. containing P pops with r = P mod n), and find a series of moves resulting in this configuration. Record the shortest sequence of moves for any r.
>
> Perform swaps only when the swap brings closer whichever element is further from its goal position (looking in either direction), or when the swap moves both elements closer if both are equally far away.
>
>
>
## Code
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Returns true if the array is sorted starting at position 'offset' */
int is_sorted(int *array, int n, int offset)
{
int i;
for (i = 0; i < n && array[(offset+i)%n] == i+1; i++);
return i == n;
}
/* Find moves that would sort the array, assuming the first element will
be at position (offset + n/2) % n */
int get_moves(int *array, int n, int offset, int stop_after, char *moves)
{
int tmp, posA = n-1, posB = 0, counter = 0;
/* Repeat until sorted or reaching the maximum number of moves (previous
best, or the worst case upper bound if no previous solution) */
for (; counter < stop_after && !is_sorted(array, n, posB); posA = (posA+1)%n, posB = (posB+1)%n, moves[counter++] = 'P')
{
/* Perform a swap if it would move whichever element is further away
closer to its target */
if ((array[posA] - posA + offset + n) % n >
(array[posB] - posB + offset + n) % n)
{
tmp = array[posA];
array[posA] = array[posB];
array[posB] = tmp;
moves[counter++] = 'S';
if (is_sorted(array, n, posB))
{
break;
}
}
}
return counter;
}
int *parse_input(int _argc, char **_argv)
{
int i;
int *array = NULL;
if (_argc > 1)
{
array = malloc((_argc-1) * sizeof(int));
_argv[1]++; /* remove initial square bracket */
for (i = 1; i < _argc; i++)
{
array[i-1] = atoi(_argv[i]);
}
}
return array;
}
int main(int _argc, char **_argv)
{
int *orig_array = parse_input(_argc, _argv);
if (orig_array != NULL)
{
int n = _argc - 1;
/* Safe worst case upper bound representing n^2 "SP" moves */
int worst_move_count = 2*n*n;
int i, move_count, offset;
int best_offset, best_move_count = worst_move_count;
char *best_moves = malloc(worst_move_count + 1);
char *moves = malloc(worst_move_count + 1);
int *array = malloc(n * sizeof(int));
memset(best_moves, 0, worst_move_count + 1);
/* Try all offsets from 0 to n-1; i.e. find solutions for:
1, 2, 3, ..., n-2, n-1, n
2, 3, 4, ..., n-1, n, 1
3, 4, 5, ..., n, 1, 2
...
n, 1, 2, ..., n-3, n-2, n-1
*/
for (offset = 0; offset < n; offset++)
{
memset(moves, 0, worst_move_count + 1);
memcpy(array, orig_array, n*sizeof(int));
move_count = get_moves(array, n, offset, best_move_count, moves);
if (move_count < best_move_count)
{
strcpy(best_moves, moves);
best_move_count = move_count;
best_offset = offset;
}
}
printf("%s\n", best_moves);
free(best_moves);
free(moves);
free(array);
free(orig_array);
}
return 0;
}
```
## Usage
```
$ gcc -Ofast -o popswap popswap.c
$ ./popswap [2, 7, 5, 3, 4, 6, 1]
PSPPSPSPPPS
$ ./popswap [2, 7, 5, 3, 4, 6, 1]|tr -d '\n'|wc -c
11
```
## Scoring
Script:
```
#!/bin/sh
grep ^\\[ input.txt|while read line; do
len=`echo $line|wc -w`;
score=`./popswap $line|tr -d '\n'|wc -c`;
echo " $len $score";
done
```
Results:
```
$ ./scoring.sh |cut -d' ' -f 6|paste -sd+|bc
607771
$ time ./scoring.sh > /dev/null
real 0m1.926s
user 0m1.879s
sys 0m0.122s
$ ./scoring.sh
3 2
7 11
41 893
52 1546
65 2543
69 2686
75 3391
80 3728
103 6483
108 0
109 7103
151 14371
173 18663
177 19728
192 22824
201 24828
201 24752
205 25573
211 27509
226 32221
227 31928
230 33630
238 34603
241 36676
241 36505
244 37759
246 38106
250 38264
253 40040
256 41405
```
[Answer]
# C++11, score: 1122052
Very naive implementation that doesn't take in account holes in the input sequence but takes in account the minimal value in the sequence.
Argument list is just the sequence of numbers, without commas and brackets (eg: "./a.out 2 7 5")
```
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int* input = 0;
int s_count = 0;
int p_count = 0;
int len;
int last;
void do_swap()
{
int a = input[0];
input[0] = input[last];
input[last] = a;
s_count++;
cerr << "S";
}
void do_pop()
{
int a = input[0];
memmove(&input[0], &input[1], sizeof(int) * last);
input[last] = a;
p_count++;
cerr << "P";
}
bool is_sorted()
{
int i = 0;
while (input[i] < input[i+1]) { if (++i == last) return true; }
return false;
}
int main(int argc, char** args)
{
int min_val = 256;
len = argc - 1;
last = len - 1;
if (len <= 1)
return 1;
input = new int[len];
for (int i = 2; i <= argc; i++)
{
int j = stoi(args[i-1]);
input[i-2] = j;
min_val = min(min_val, j);
}
while (!is_sorted())
{
if ((input[0]) == min_val)
do_pop();
else if (input[0] < input[last])
do_swap();
else if (input[0] > input[last])
do_pop();
}
cerr << endl;
cout << len << " " << (s_count + p_count) << endl;
delete [] input;
return 0;
}
```
## Scoring
```
3 2
7 19
41 1642
52 3236
65 4787
69 4966
75 6644
80 6090
103 12142
108 0
109 13774
151 24976
173 34061
177 37835
192 41994
201 48316
201 47276
205 49439
211 51551
226 58859
227 56824
230 58994
238 64227
241 65774
241 66287
244 71345
246 73426
250 71766
253 68629
256 77171
```
] |
[Question]
[
Output the flattened version of the sequence [A297359](http://oeis.org/A297359), which starts like the following:
```
1, 1, 1, 1, 2, 1, 1, 3, 3, 1, 2, 4, 6, 4, 2, 1, 6, 10, 10, 6, 1,
1, 7, 16, 20, 16, 7, 1, 3, 8, 23, 36, 36, 23, 8, 3, 3, 11, 31, 59,
72, 59, 31, 11, 3, 1, 14, 42, 90, 131, 131, 90, 42, 14, 1,...
----------------
1,
1, 1,
1, 2, 1,
1, 3, 3, 1,
2, 4, 6, 4, 2,
1, 6, 10, 10, 6, 1,
1, 7, 16, 20, 16, 7, 1,
3, 8, 23, 36, 36, 23, 8, 3,
3, 11, 31, 59, 72, 59, 31, 11, 3,
1, 14, 42, 90, 131, 131, 90, 42, 14, 1,
...
```
The defining property of the sequence is that
* the entire triangle is generated like the Pascal's triangle (i.e. each entry inside the triangle is the sum of the two numbers above it), and
* the left and right boundaries are identical to the entire triangle read by rows.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules and [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") I/O methods apply. See <https://codegolf.stackexchange.com/tags/sequence/info> and <https://codegolf.stackexchange.com/tags/code-golf/info>.
The shortest code in bytes wins.
[Answer]
# [Haskell](https://www.haskell.org/), 61 bytes
```
1:t
r!b=b:zipWith(+)r(tail r)++[b]
t=1:tail(scanl(!)[]t>>=id)
```
[Try it online!](https://tio.run/##PU1BDoIwELzzipJwoKEmFBGEpHzDA3IooNJYCWl78vHWbSsmuzuzM5vZhevnTUqr2dXS1kQqHtnYvsV2EWZJM6xSw4VECmdZPw6RYXAEQqonvso0xv1guo6JGdsXFyvblFhNwtc52SMYwxr1lKB/FTs5@gpKSVDlZ3CB0zy0owSkGhB4kQes94gzaC6pCl0E6ZftTqBPDakLD36ldP9M4WMJTuNSveWG25zqXDrYz3SX/KHtYdq2Lw "Haskell – Try It Online")
Feels a bit clunky, and frankly I'm not entirely sure I understand what I've done with both of those explicit leading ones.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
λε=Dˆ}ü+¯Nè.ø
```
Infinitely outputs each integer on a separated line.
-1 byte thanks to *@ovs*.
[Try it online.](https://tio.run/##ASgA1/9vc2FiaWX//867zrU9RMuGfcO8K8KvTsOoLsO4////LS1uby1sYXp5)
**Explanation:**
```
λ # Create a recursive environment,
# starting with a(0)=1 by default
# And we calculate every following a(n) as follows:
ε # Map over the integers in the current list (or the digit(s) of the 1):
= # Print the current integer with trailing newline (without popping)
Dˆ # Add a copy of the integer to the global array
}ü # After the map: map over the overlapping pairs:
+ # And sum them together
¯Nè # Index `n` of the recursive environment into the global array
.ø # And surround the list with this integer as leading/trailing item
```
[Answer]
# [Python 3](https://docs.python.org/3/), 94,93(@xnor),88(use infinite generator),83(smarter buffering),79(obvious saving),67 bytes(@dingledooper)
```
*P,z=p=1,1
for x in P:print(z);z,*q=p;p=x,*map(sum,zip(p,q)),x;P+=p
```
[Try it online!](https://tio.run/##BcExDoAgDAXQ3VMwAnYhbpLegSu4GBmAD2qCvXx9D99ztbqp@kTC4EBhOdsw0@Rq0o6R62PFRSHfGRE8yZcD9n4LSYYFdedoxrQyVPUH "Python 3 – Try It Online")
I doubt this is competitive, but there is only one way to find out...Beginning to get the hang of it.
The code works row-by-row (the computation, output is element by element) and is pretty straight-forward, the only mildly tricky thing being that the for loop actually sees the intermittent updates of the P list (This relies on `+=` actually being equivalent to `.extend` which also allows us to be a bit cavalier with list vs tuple). And perhaps the backwards-in-time order of assignments towards the yieldprint statement whose effect is a two-cycle-buffering (z is the x from two iterations ago).
[Old version](https://tio.run/##Jc2xDoMgEADQ3a@4EegN1W4a/sHdODQV0kvEO4EmyM/TJh3f9OTKbz4erW3Og1d67MDMWK3YwSz92oHnCAXogHm8yO0b1KmiOa1MYgua8BSVPgEriRI8tcYyzTcrzUcOQNnFzLwnoCAcM1Da6eU6iXRktZg/1e/FfrjrVbf2BQ "Python 3 – Try It Online")
[Old version](https://tio.run/##Jc2xCsMgEADQPV9xo9obYrsZ/IfsQUpplB5oPIyBxJ@3hY5venzVT94eva8@QBDSDKBmbJbtXS3aDRBygRNog9lc5OMKbWqonpYntieq9GKxHwkbsWDkRRsnJZ7TfLPcQ8kJqPpSc447UOJcKtAe6e0HLrRVsag/xe9GPY7Syd6/ "Python 3 – Try It Online")
[Old version](https://tio.run/##Lc6xDsIgFEDRna94I1QGWzca/oGdMBgL8SVQXoAm1J9Ho453OMmlsz3zfhtj8wECF4qB0XZ2K@llMuuJPm4QSk5ADEIu0AF3MIp0l1O6E69Hki8kTpLsrJwQsq/moulP@/hibL60nGMFTJRLA6wRH55Rwb1xO)
[Old version](https://tio.run/##FcgxDsMgDADAnVd4xMQL6UbEBzJ5j6KqUoPKEOJQItF@3lVvPPm011Fuqs8tQbIzBgMcF79OEs84OjaQjgp36pALfLPY2TExBomd3P4Q@752@r@QLD6siNQnHqIYqFu7aoFzYKNSc2k2WT8iqv4A "Python 3 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 72 bytes
```
f=(n,l=0,a=[],x)=>a[n]||(n<2?1:f(n-l,a.push(x),a.map(m=>x+(x=m)||f(l))))
```
[Try it online!](https://tio.run/##LYxBDoIwEEX3nsId01BINa4sgwchLCZItaSdElDTRe9eG@NfvcV7f6EP7dNm11fD4T7nbBBYOlSScBhlFNjTwGNKwN35droa4MZJatf3/oQoCnlawWMfa4joRUoGnCjLJmzw@7CotO0uSv8rA7aui0H6MAXeg5tbFx5A7RIsQyWPlRA6fwE "JavaScript (Node.js) – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
f=(n,q=(n*8+1)**.5,r=q-1>>1)=>n>1?(n*8+9)**.5%1&&q%1?f(n+~r)+f(n-r):f(r):1
```
[Try it online!](https://tio.run/##HclBDoIwEEDRvadwA8y0pWESTdTachDjokGqJaSFoi69eiVs3l/8wX7t0iU/vesQH33OTkMQ8wo7cULG5FEkPddkDKE2wVC7rfO2CirLuaDWQeC/hHxtnfDiYIWyiwmsvt2F143y10OjrJw@ywsceM4R0apdF8MSx16O8QlWDtEHqMS@QlT5Dw "JavaScript (Node.js) – Try It Online")
I have no idea whether following 70 byte version works or not. If you can prove its correctness or find out failed testcases, please leave a comment here:
```
f=(n,q=(n*8+1)**.5,r=--q>>1)=>n>1?q%2<2-2/r&&q%2?f(n+~r)+f(n-r):f(r):1
```
[Try it online!](https://tio.run/##DcZLDsIgFEDRufuwfa98BBITI4UuxDggtShNAy1Vh24dmZx7Z/d1@5jD@mYxPaZSvIFIt0p3IRK7jp9pNoxt1ko0Nlo5bEfVK6ZOuWnqDh4i@WUktSzj1UNFFp8yOHO702CEDr0UQju@fvYXeAiEIKLThzHFPS0TX9ITHJ9TiNDSFrH8AQ "JavaScript (Node.js) – Try It Online")
[Answer]
# [Appleseed](https://github.com/dloscutoff/appleseed), 127 bytes
```
(def T(q(((R(q(1)))(S(concat(q(1 1 1))(drop 4(T)))))(concat R(T(cons(head S)(insert-end(head S)(zip-with add(tail R)R)))(tail S
```
Defines a function `T` that takes no arguments and returns the sequence as an infinite list. [Try it online!](https://tio.run/##PY3BCgMhDER/Jb2Nhz0U@iXqvaSblBWsa1Uo9OetbkszECZvIMM5R62q0jtE7@TxBGDHPhtj4LDuaeU2bxoaSMqe6QJv5vxisvDTVmzKQs4gpKqlLZrkj94hL6/QNmIRNA6RrLHzx@Hdt782Lu1EiPy4CdOVkEtIkxyF/QM "Appleseed – Try It Online")
### Ungolfed + explanation
```
(def TriSeq
(lambda
((Row (q (1)))
(Seq (concat (q (1 1 1)) (drop 4 (TriSeq)))))
(concat Row
(TriSeq
(cons (head Seq)
(insert-end (head Seq)
(zip-with add (tail Row) Row)))
(tail Seq)))))
```
`TriSeq` builds the sequence one triangle row at a time. It takes two optional arguments: `Row`, the current row, and `Seq`, the sequence up to this point. The first row is the default value for `Row`, `(q (1))`, a list containing a single 1. After that, the interior portion of the next row is calculated from `Row` by `(zip-with add (tail Row) Row)`. The exterior numbers come from the next element in the sequence, `(head Seq)`. `Seq` is initialized by its default value, `(concat (q (1 1 1)) (drop 4 (TriSeq)))`. Conceptually, this is:
```
(1 1 1 1 2 1 1 3 3 ...) ; (TriSeq) (a recursive call with lazy evaluation)
(2 1 1 3 3 ...) ; (drop 4 (TriSeq))
(1 1 1 2 1 1 3 3 ...) ; (concat (q (1 1 1)) (drop 4 (TriSeq)))
```
We don't need the first 1 in the sequence because it's supplied by the default value for `Row`. We have to do the `drop`/`concat` routine because the first few values of the sequence are self-referential, and Appleseed will get into an infinite recursion trying to calculate them unless we specify them explicitly.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~85..~~ 72 bytes
```
*l=1
1.step{|i|p *l[-i,i]
l+=[m=l[i]||1,*(-i..-2).map{|j|l[j,2].sum},m]}
```
[Try it online!](https://tio.run/##KypNqvz/XyvH1pDLUK@4JLWguiazpkBBKydaN1MnM5YrR9s2Otc2JzoztqbGUEdLQzdTT0/XSFMvNxGoMqsmJzpLxyhWr7g0t1YnN7b2/38A "Ruby – Try It Online")
* Thanks to @Dingus for the 5 Bytes saved!
Full program, outputs the sequence indefinitely vertically.
```
*l=1 # we start with [1]
1.step{|i| # iterate i starting from 1(i is the boundary position == triangle line length)
p *l[-i,i] # puts last i elements
l+=[...] # append new triangle line :
[m=l[i]||1 #[ m=boundary || 1 because initially not available
* #, splat inner elements :
(-i..-2).map{ #* range of last i pos.
|j|l[j,2].sum} #* take 2 and sum
m # right bound]
} repeat indefinitely
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
NθF³⊞υ¹≔…υ²ηW‹Lυθ«⊞η⁻§υLη§υ⊖LηUMη⁺κ§η⊖λ≔⁺υηυ»Iυ
```
[Try it online!](https://tio.run/##VY7NDoIwEITP8hQ9tgke1HDiRPBCIoZXqLBSYlugP/7E@Ox1ISToHvYwM99kasFN3XMZQqEH785eXcDQkaXRtTeEHhipvBXUx2SHWmZt12qav2oJueiHSd@zmAj0HqKTQOgJrMWnW4cUWiNj5B1t5hYRk7LT3tLMFbqB54QvUcEw@yMfoTagQDto6BrBS6NNyYe8V4rrZmqsJBbeVlj8w3KBlulz2k@LY@JR/0SV6bSjObcO97I0hCQJ27v8Ag "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` terms. Explanation:
```
Nθ
```
Input `n`.
```
F³⊞υ¹
```
Start the flattened list with the first three terms.
```
≔…υ²η
```
This corresponds to having already generated the second row.
```
W‹Lυθ«
```
Repeat until sufficient terms have been collected.
```
⊞η⁻§υLη§υ⊖Lη
```
Push the difference between the next two terms to the row. (Normally Pascal's Triangle just needs `0` pushed here, but this makes the row ends follow the sequence itself.)
```
UMη⁺κ§η⊖λ
```
Generate the next row of the triangle.
```
≔⁺υηυ
```
Accumulate it to the flattened list.
```
»Iυ
```
Output the first `n` terms.
[Answer]
# [Raku](http://raku.org/), 60 bytes
```
my@a=flat(1,<1 1>,{@a[++$+1],|(.[1..*]Z+@$_),@a[++$+1]}...*)
```
[Try it online!](https://tio.run/##K0gtyjH7/z@30iHRNi0nsUTDUMfGUMHQTqfaITFaW1tF2zBWp0ZDL9pQT08rNkrbQSVeUwcuU6sHFNX8b61QnFipABSNMzQwiP0PAA "Perl 6 – Try It Online")
This is a lazy, self-referential, infinite list, stored in the variable `@a`. The expression inside the `flat` is a sequence of rows, where `.[1..*] Z+ @$_` generates the inside sums (by addition-zipping the row with itself without its first element), and the endpoints are taken from the flattened outer array `@a`. The two lone `$`s are anonymous state variables that start off undefined/zero, so the first time the generator block is entered for the third row, the endpoints `@a[++$+1]` are `@a[2]`, when the fourth row is generated the endpoints are `@a[3]`, etc.
[Answer]
# [R](https://www.r-project.org/), ~~89~~ 85 bytes
*-4 bytes thanks to [@Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)*
```
function(n){s=r=!!1:2
for(i in 2:n)s=c(s,r<-c(s[i],r[-1]+head(r,-1),s[i]))
c(1,s)[n]}
```
[Try it online!](https://tio.run/##Fc0xCsMwDEDRPadwNonIUAWymPgkxkNwG2oISpDSoZSe3W2mD2/52kxPi219STnrLiD4saix7zmM3borVFfFjUHQYgEjnf0/qWbS5DkPz8dyByXPSJcidgWYDJPkb7PlOLY3cJhu5K4Rth8 "R – Try It Online")
Function returning 1-indexed element of the sequence. Uses simple loop to create consecutive rows of the triangle.
] |
[Question]
[
We've got quite a few national flag challenges already:
[AU](https://codegolf.stackexchange.com/questions/52667/print-the-australian-flag)
[CH](https://codegolf.stackexchange.com/questions/136927/draw-the-swiss-flag)
[FI](https://codegolf.stackexchange.com/questions/149842/happy-birthday-finland)
[FR](https://codegolf.stackexchange.com/questions/64140/draw-the-national-flag-of-france)
[GB](https://codegolf.stackexchange.com/questions/52643/print-the-british-flag)
[GB](https://codegolf.stackexchange.com/questions/91067/draw-the-union-jack)
[IS](https://codegolf.stackexchange.com/questions/85141/draw-the-national-flag-of-iceland)
[KR](https://codegolf.stackexchange.com/questions/40052/draw-the-south-korean-flag)
[NP](https://codegolf.stackexchange.com/questions/18664/lets-draw-the-flag-of-nepal)
[US](https://codegolf.stackexchange.com/questions/52615/print-the-american-flag)...
Here's another, somewhat more advanced one:
Return or print the [decorative pattern from Belarus's national flag](https://en.wikipedia.org/wiki/Flag_of_Belarus#Hoist_ornament_pattern) as a matrix of two distinct values for red and white.
[](https://i.stack.imgur.com/LOleE.png)
If your language doesn't support matrices, use a list of lists or the closest equivalent.
Extra whitespace is allowed on all sides.
The matrix can be transposed.
The elements can have a consistent separator, and so can the rows, e.g. output can be JSON.
You must use the 2012 version of the ornament pattern, not the 1951 or 1995 versions.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer per language wins.
Sample output:
```
....###....#....###....
#..#####...#...#####..#
..###.###.....###.###..
.###...###...###...###.
###..#..###.###..#..###
.###...###...###...###.
..###.###.....###.###..
#..#####...#...#####..#
....###....#....###....
..#..#..#.....#..#..#..
.###...###...###...###.
##.##.##.##.##.##.##.##
.###...###...###...###.
..#..#..#.....#..#..#..
....###....#....###....
#..#####...#...#####..#
..#######.....#######..
.#########...#########.
#######################
####...#########...####
.#####..#######..#####.
..###....#####....###..
#..#....#######....#..#
.......####.####.......
#.....####...####.....#
##...####..#..####...##
###.####.......####.###
.######..#...#..######.
..####...##.##...####..
...###....###....###...
....##.#...#...#.##....
...###....###....###...
..####...##.##...####..
.######..#...#..######.
###.####.......####.###
##...####..#..####...##
#.....####...####.....#
.......####.####.......
#..#....#######....#..#
..###....#####....###..
.#####..#######..#####.
####...#########...####
#######################
.#########...#########.
..#######.....#######..
#..#####...#...#####..#
....###....#....###....
..#..#..#.....#..#..#..
.###...###...###...###.
##.##.##.##.##.##.##.##
.###...###...###...###.
..#..#..#.....#..#..#..
....###....#....###....
#..#####...#...#####..#
..###.###.....###.###..
.###...###...###...###.
###..#..###.###..#..###
.###...###...###...###.
..###.###.....###.###..
#..#####...#...#####..#
....###....#....###....
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 68 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
àÑΣ▒i╕7FF3xì¥╫Yb▌t╤y╡µåè0═↕h╗ΔDOü↔`◙■^>♀;∟Γ9→§Æ¼$ß⌡╫èj_┐;ø;¡²Ω☺┘4!P╛
```
[Run and debug it](https://staxlang.xyz/#p=85a5e4b169b837464633788d9dd75962dd74d179b5e6868a30cd1268bbff444f811d600afe5e3e0c3b1ce2391a1592ac24e1f5d78a6a5fbf3b003badfdea01d9342150be&i=&a=1)
Outputs vertical version, `1` for white, `0` for red. Naive approach: compress top left quarter, then complete.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~183~~ 181 bytes
```
S=[bin(int(''.join(w),36))[2:].rjust(31,'0')for w in zip(*[iter("RBRG5FDLAJ2O77MSE012OBJWJUSWDQ464UKNYZIE8JYGS0JRFOCIJY7U5F983X0LYW20WNTE")]*6)]
for s in S[:0:-1]+S:print s[:0:-1]+s
```
[Try it online!](https://tio.run/##NY67DoIwAAB3v6JhoVU0pchDEgeVR6wIkUqwEhYTjWUAAjVGfx51cLvccte@5L2pyTCwZXERNRS1hKo6q5ovP5FmWAgVxC1nXfXoJTR0TcUqujUdeAJRg7do4bgQ8tpBJV2noRl40YqSxLb3zMc6SdY0pxnLvcPcmme7mJ@3vkN5yDBNg2SzpdzOzGDhGCcc8ZzgPD76CirHFipHv0j/i7DCxe5ULyfMbbvvH@j/oh@GDw "Python 2 – Try It Online")
Outputs transposed version, using `0` and `1` for white and red.
[Answer]
# JavaScript (ES6), 164 bytes
Transposed output. Uses `0` for white, `1` for red.
```
f=(x=y=0)=>y<61?x>22?`
`+f(!++y):(-~'o`xb[FMMf[MM[Fxbo`cCMMZZMMcCo`xb{F}N~~N}}{[wH{?]@NbfvB}H{Wwooa'.charCodeAt((y>30?60-y:y)*2+(X=x>11?22-x:x)/6)>>X%6&1)+f(x+1):''
```
[Try it online!](https://tio.run/##FY7NToMwAIDvPgUetK2Vn9aEA7FFJSG7lKvLmiWUSqeGrAtbtjYEzj6BD7gXQUy@23f4vm91Vkfdfx1O4d5@tLNhC9AxzxLEuH9OSe44pXl9U2MDbzH2KIPhBGztGlkKYaQQsnSNrXUhxGYjhC7@3VCO1TRV4zjIy2rIty9VY85v42p4v1irQKQ/VV8swdcThJ4/JXmahD7z6IFiuGaOE5JTGrrMoThFnK/v0nuClgOHCcoAmLXdH23XRp3dQQNR1LeHTukWxlG8ewx0wHgAguvvD5B6i9D8Bw "JavaScript (Node.js) – Try It Online") (prettified output)
[Using **Buffer()** in Node.js](https://tio.run/##Fc7PSsMwAIDxu09RDzOJsX8SoYdiEtmg7JJeNxYKbbNmKGUZnW4JtT37BD6gL1InfLff5XuvL/VZ92@nj/Bo9@1s2C3omGcJYty/pEQ4Tqmo7ips4D3GHmUwnJafxrQ9BLZyjcqlNEpKlbvGVnol5W4npV7925CPxTQV4zio63oQ5WvRmMtyXA@bq7U1QAp6/pyINAl95tEjxXDLHCdEUBq6zKE4/UpKzreL9IGg24DDBGUAzNoez7Zro84eoIEo6ttTV@sWxlF8eAp0wHgAgt@fb6B0idD8Bw) saves 1 byte.
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~61~~ 56 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
№α⁶U-┼°jōIΤ$ΣΧρ←FVξÆ⅝{VqM┼οYΠ!↕οΩÆ.χg±└¶Σ,Cy′┌“2─±6«n╬,
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJXUyMTE2JXUwM0IxJXUyMDc2VS0ldTI1M0MlQjBqJXUwMTRESSV1MDNBNCUyNCV1MDNBMyV1MDNBNyV1MDNDMSV1MjE5MEZWJXUwM0JFJUM2JXUyMTVEJTdCVnFNJXUyNTNDJXUwM0JGWSV1MDNBMCUyMSV1MjE5NSV1MDNCRiV1MDNBOSVDNi4ldTAzQzdnJUIxJXUyNTE0JUI2JXUwM0EzJTJDQ3kldTIwMzIldTI1MEMldTIwMUMyJXUyNTAwJUIxNiVBQm4ldTI1NkMlMkM_,v=0.12)
[Answer]
# Charcoal, ~~93~~ ~~89~~ 81 bytes
```
”{“↷B⦃¶¹¹|TQ⌊‽÷⪫Mg+℅§ºH·τP≔⁻⊗|Yω¤⁵⊗-κ�κb5Aωγ⎚I0ê﹪oζM⟲ºh⟲⮌#⎇s▶‴ψ◧≔◨◧⁺4U×m∧üF↑⬤”‖O¬
```
My first charcoal answer! :D
[**Try it online!**](https://tio.run/##S85ILErOT8z5/z@gKDOvRENJWQEIlJWVY/KUIQxlIA3kQTgQGQgTqgzCVlbAJoWkB9U0hC0KEL1QO1DNhSMs5sL04HevMsJRMI4yEoDyoGohPKhiMAdhNowDMRvZWAWwONh6uFlg6yFcmEqYGyAeQ1iI6nwgU0nTmisoNS0nNbnEvyy1KCexQMPq0BpN6////@uW5QAA)
Saved 4 bytes by outputting the design horizontally rather than vertically (fewer newlines).
Thanks to @Neil for saving 8 bytes!
[Answer]
# Python 2, 153 bytes
```
00000000: 2363 6f64 696e 673a 4c31 0a66 6f72 2079 #coding:L1.for y
00000010: 2069 6e20 7261 6e67 6528 2d33 302c 3331 in range(-30,31
00000020: 293a 733d 666f 726d 6174 2869 6e74 2827 ):s=format(int('
00000030: 0137 ec80 937f f739 027d 7209 37e7 395c .7.....9.}r.7.9\
00000040: 30cc ef73 108c 1fff fe41 b14e fb14 1bfe 0..s.....A.N....
00000050: d364 09ce f7ff fc81 18c6 c811 8cec 8111 .d..............
00000060: 272e 656e 636f 6465 2827 6865 7827 295b '.encode('hex')[
00000070: 6162 7328 7929 3a3a 3331 5d2c 3136 292c abs(y)::31],16),
00000080: 2730 3132 6227 293b 7072 696e 7420 732b '012b');print s+
00000090: 735b 2d32 3a3a 2d31 5d s[-2::-1]
```
[Try it online!](https://tio.run/##ZZJBi9swEIXv@yse9OCEJkaasWcslz30XvoHtnuwZXmTQ50lDmwC7W9PR44plM7BfiDp0@M99d18uN@v1wH7M37hIz791e@3y@E0Efb3u1unBbEwZJQKEiRBlDtUkT1cJ2ILSiCnAfgUT8Nxemu/@XI8nXF7ehB8ZjgJkEQOSuJNiUJqakADM9hRBLMhgeOEcze9pc2e3Y79yqDMCHaxMg8QkTGDTHmtQM0CXxQpsG3nZzPws7tsjtNlU6wMNobzrEixcQisI0blAEc6GM0FsCYFhzoCpZZ5Qvn7bDL8WBmVMdjFiGRH4V0T4cfRQKny6H2VMNoXvh8T4MpyXihfy@/5tzJqYwxscboQbb/m47Hx8E0UmPBoYoowYXmUQ/nPrAzJeShZG3WuhC0PqaR@BCCNKc2KQt0DRZkmqyZtikO6FtuXlaHGEC9kmVoRGsgC6CzipYh6yJV4FmOYQtfPm9u2bdm/7rxsdyujWXywy1sJQsud3EOdvYrluWiVS2fKPpynvth@eT9bLZg/r4xgDGUzam@BHhZMZQv4f@aXPbXt3r/@AQ "Bash – Try It Online")
[Answer]
## [Perl 5](https://www.perl.org/), 121 bytes
Uses `1` for white pixels and `0` for red.
```
$_=unpack"B*",'ñæÄxããÄvñí·Ž2IŽ=·ñæÀxàƒ
xoá|3†øÃž<òà';say for(@a=map{s/.$//r.reverse}/.{12}/g),pop@a&&reverse@a
```
This script contains unprintable characters so a reversible hexdump is included in the verification link below.
[Try it online!](https://tio.run/##VU3LCsIwEPwVKSIq2iT1FdFC8ebBPwhIjFsRHwmpyor668at8eJhlp2ZnVkH/jgKobnOr2enzSFZdJNeorAUCmGskINCM0QiA4ViQ5BxN8NbdL@XW4WbiUIJ2bKeeaR/JZxKOAU5jwCCrLlBS7MkRTyJSwoI8koZHxrSpjAnIatDyazS90ZpfbvQ@Um7R8XSJmM@9XADX8GLpQ@Rvdiu03PWFbrV@hmFDuFt3WVvz1Xor0YpF/wD "Perl 5 – Try It Online")
[Verification of code length](https://tio.run/##bZFRT@MwDMff@RR/IQR3J5YmTpt0xw1N93YPfAaUpM6BGFvVMm4I@Ow7Z@sbs1Qrdeyf7X9iGB/2@92uw2yAelz32xf18rjBLSKvwrAdZ/I9rN@eVL@6OfuXMEsnb5675mS852GF2V2jtNEnEvZ7PdlPUN1k2M43cOw1nHEWLhKhJgogogTy2QAX94vtug/p6fz3j/PrK3V2JBhhsNOMVPsWbE2EadmWXwfNUsld9JAQAUqpnSr2evA0MUgY9bxlmUNSs@FSmTR8qy1KAli3ckrSAX/U4lB8BKndxLDCcFlnsPEJ1rYORucWJiaLOduETKxlFxuBjVIf9lj/S6mrm4lRC8NbZ@DnJFI4l@GJWtRaYrZzncgjGvnoLTCGN@TN8G0ZFs@hfx8nRlM0lVYiLGU5eQKxONeIHuKodGjgO7lFpS6qalADv/Iw8mc1MVxhsI@wRlQ7pDpPc1AqL5TFHSYiR040fTf0Wf39ft1v@mW4vJwYvuxCpZMrTvaW7nV5YHy1aYBl@A8 "Bash – Try It Online").
### Explanation
The top quarter of the pattern is stored within the binary blob. This just uses Perl's `pack` function with the original binary string (after replacing `.` and `#` with `1` and `0`). This allows us to store 8 bits of the pattern in each byte. Once we've unpacked the data, we have the long binary string, which we break down into sections of length 12, concatenate with the reverse (except for the duplicated middle character) and then loop over the list of sections (concatenated with the reverse of the list, except for the duplicated middle element) and output them all using `say`, which adds in a newline.
[Answer]
# Deadfish~, 2644 bytes
```
{iii}iiccccicccdccccicdccccicccdcccc{dd}ddc{ii}iiicdccicccccdcccicdcccicccccdccic{dd}dddc{ii}iiccicccdcicccdcccccicccdcicccdcc{dd}ddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiicccdccicdccicccdcicccdccicdcciccc{dd}dddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiccicccdcicccdcccccicccdcicccdcc{dd}ddc{ii}iiicdccicccccdcccicdcccicccccdccic{dd}dddc{ii}iiccccicccdccccicdccccicccdcccc{dd}ddc{ii}iiccicdccicdccicdcccccicdccicdccicdcc{dd}ddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiiccdciccdciccdciccdciccdciccdciccdcicc{dd}dddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiccicdccicdccicdcccccicdccicdccicdcc{dd}ddc{ii}iiccccicccdccccicdccccicccdcccc{dd}ddc{ii}iiicdccicccccdcccicdcccicccccdccic{dd}dddc{ii}iiccicccccccdcccccicccccccdcc{dd}ddc{ii}iicicccccccccdcccicccccccccdc{dd}ddc{ii}iii{cc}ccc{dd}dddc{ii}iiiccccdcccicccccccccdcccicccc{dd}dddc{ii}iicicccccdccicccccccdccicccccdc{dd}ddc{ii}iiccicccdccccicccccdccccicccdcc{dd}ddc{ii}iiicdccicdccccicccccccdccccicdccic{dd}dddc{ii}iiccccccciccccdciccccdccccccc{dd}ddc{ii}iiicdccccciccccdccciccccdcccccic{dd}dddc{ii}iiiccdccciccccdccicdcciccccdcccicc{dd}dddc{ii}iiicccdciccccdccccccciccccdciccc{dd}dddc{ii}iiciccccccdccicdcccicdcciccccccdc{dd}ddc{ii}iicciccccdccciccdciccdccciccccdcc{dd}ddc{ii}iicccicccdccccicccdccccicccdccc{dd}ddc{ii}iicccciccdcicdcccicdcccicdciccdcccc{dd}ddc{ii}iicccicccdccccicccdccccicccdccc{dd}ddc{ii}iicciccccdccciccdciccdccciccccdcc{dd}ddc{ii}iiciccccccdccicdcccicdcciccccccdc{dd}ddc{ii}iiicccdciccccdccccccciccccdciccc{dd}dddc{ii}iiiccdccciccccdccicdcciccccdcccicc{dd}dddc{ii}iiicdccccciccccdccciccccdcccccic{dd}dddc{ii}iiccccccciccccdciccccdccccccc{dd}ddc{ii}iiicdccicdccccicccccccdccccicdccic{dd}dddc{ii}iiccicccdccccicccccdccccicccdcc{dd}ddc{ii}iicicccccdccicccccccdccicccccdc{dd}ddc{ii}iiiccccdcccicccccccccdcccicccc{dd}dddc{ii}iii{cc}ccc{dd}dddc{ii}iicicccccccccdcccicccccccccdc{dd}ddc{ii}iiccicccccccdcccccicccccccdcc{dd}ddc{ii}iiicdccicccccdcccicdcccicccccdccic{dd}dddc{ii}iiccccicccdccccicdccccicccdcccc{dd}ddc{ii}iiccicdccicdccicdcccccicdccicdccicdcc{dd}ddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiiccdciccdciccdciccdciccdciccdciccdcicc{dd}dddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiccicdccicdccicdcccccicdccicdccicdcc{dd}ddc{ii}iiccccicccdccccicdccccicccdcccc{dd}ddc{ii}iiicdccicccccdcccicdcccicccccdccic{dd}dddc{ii}iiccicccdcicccdcccccicccdcicccdcc{dd}ddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiicccdccicdccicccdcicccdccicdcciccc{dd}dddc{ii}iicicccdcccicccdcccicccdcccicccdc{dd}ddc{ii}iiccicccdcicccdcccccicccdcicccdcc{dd}ddc{ii}iiicdccicccccdcccicdcccicccccdccic{dd}dddc{ii}iiccccicccdccccicdccccicccdcccc
```
] |
[Question]
[
*For more information, watch [this video](https://www.youtube.com/watch?v=49KvZrioFB0), and go to [A276523](http://oeis.org/A276523) for a related sequence.*
The Mondrian Puzzle (for an integer `n`) is the following:
Fit non-congruent rectangles into a `n*n` square grid. What is the smallest difference possible between the largest and the smallest rectangle?
For `6`, the optimal difference for `M(6)` is `5`, and can be demonstrated like so:
```
___________
| |S|_______|
| | | L |
| |_|_______|
| | | |
| |_____|___|
|_|_________| (fig. I)
```
The largest rectangle (L) has an area of `2 * 4 = 8`, and the smallest rectangle (S) has an area of `1 * 3 = 3`. Therefore, the difference is `8 - 3 = 5`.
*Keep in mind that currently, no optimal solutions for `n > 44` have been found.*
Your task is to create a program that generates a Mondrian grid that contains a (non-optimal) solution, given an integer `n`.
You will be tested on the numbers from 100 to 150. Your score for each test will be the difference between the largest and smallest rectangle. Your total score is the sum of your scores for all the tests from 100 to 150.
You must present your output like so:
```
{number}
{grid}
```
Where `number` is the score (the difference between largest and smallest), and `grid` is either:
* A multi-lined string, or
* A two-dimensional list.
The grid MUST clearly show where a rectangle starts and ends.
## Rules:
* Your program must fit within your answer.
* Your program must output a value for any number between 100 and 150 within 1 hour on a modern laptop.
* Your program must generate the same solution for an integer `n` every time the program is run.
* You must provide a link to the outputs of all 51 solutions (using Pastebin, Github Gist... anything, really).
* You must have at least two rectangles on the square grid for your solution.
[Answer]
# Piet, 9625
**(It finally works!)**
The people demanded it, so here it is. This is an extremely naive solution (essentially the same as the loose upper bounds on the OEIS page): it divides each square into just two rectangles.
[This gist contains the details](https://gist.github.com/perey/cbee283062271d49f1e46d65adf264c7) in two files:
* The program's output (using npiet v1.3) for all required inputs. Note that I only captured stdout, so the `?` is the input prompt, followed immediately by the output score, then the grid.
* The "pseudo-assembly" source I used to plan out the program.
[](https://i.stack.imgur.com/Uu5WK.png)
## Explanation
This program takes a single number `N` as input. If the number is odd, the score is the number; if even, the score is twice the number.
After outputting the score, the rest of the left-hand side of the program is spent filling the stack with five lots of the following information:
* The grid width (which is `N`)
* A number of lines to print
* A character to print across the grid (either `_` or space)
* A character to print at each edge of the grid (either space or `|`)
The right-hand side of the program takes each set of four values and prints out that part of the grid.
[Answer]
# C 6108
This uses a recursive (really iterative) version of the minimal solution. Instead of dividing the square into two rectangles where one is a little bit bigger than half the area, it divides it into N rectangles. So the first rectangle is a bit larger than `1/N` the total area. Then taking the remainder, the program splits off a rectangle a bit larger than `1/(N-1)` of the remainder and so on until it just takes the remainder as the last rectangle. The rectangles are cut off of the remainder in a clockwise spiral, so first at the top, then on the right, etc.
Since this a very direct method instead of a search of a broad space, it runs quickly - taking about 25 seconds (on a Raspberry Pi) to look at 74 solutions each for the given problem set.
My intent is to use these results to better inform a search algorithm for a more sophisticated approach.
The output gives the score and both an (ascii) drawing and coordinates for the vertices of the rectangles. The vertices are in clockwise order, starting from the upper left hand corner of the rectangle in question.
Developed using gcc 4.9.2-10.
Results at <https://github.com/JaySpencerAnderson/mondrian>
**Code:**
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct {
int y, x, height, width;
} rectangle;
#define min(x,y) (((x)<(y))?(x):(y))
#define max(x,y) (((x)>(y))?(x):(y))
#ifndef TRUE
#define TRUE -1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define MAXCOUNT 75
void initstack(rectangle *s, int n){
int i;
for(i=0;i<n;i++){
s[i].y=s[i].x=s[i].height=s[i].width=0;
}
}
int valid(rectangle *s,int n){
int i,j;
for(i=0;i<n-1;i++){
for(j=i+1;j<n;j++){
if(min(s[i].height,s[i].width) == min(s[j].height,s[j].width) && max(s[i].height,s[i].width) == max(s[j].height,s[j].width)){
initstack(s, n);
return FALSE;
}
}
}
return TRUE;
}
int horizontal(rectangle s, int y, int x){
if(s.y == y && x >= s.x && x < s.x+s.width){
return TRUE;
}
else if(s.y+s.height == y && x >= s.x && x < s.x+s.width){
return TRUE;
}
return FALSE;
}
int vertical(rectangle s, int y, int x){
if(s.x == x && y > s.y && y <= s.y+s.height){
return TRUE;
}
else if(s.x+s.width == x && y > s.y && y <= s.y+s.height){
return TRUE;
}
return FALSE;
}
void graph(rectangle *s, int n, int side){
unsigned int row,col,i;
unsigned int line;
printf("{\n");
/* vertical lines take precedence since "1" cell is 1 char high and 2 char wide */
for(row=0;row<=side;row++){
for(col=0;col<=side;col++){
line=0;
/* Possible values are " " (0), "__" (1), "| " (2) or "|_" (3). */
for(i=0;i<n;i++){
if(horizontal(s[i],row,col)){
line|=1;
}
if(vertical(s[i],row,col)){
line|=2;
}
}
switch(line){
case 0: printf(" "); break;
case 1: printf("__"); break;
case 2: printf("| "); break;
case 3: printf("|_"); break;
default: printf("##"); break;
}
}
printf("\n");
}
printf("}\n");
}
unsigned int score(rectangle *s, int n){
int i;
unsigned int smallest,biggest;
smallest=biggest=s[0].width*s[0].height;
for(i=0;i<n;i++){
smallest=min(smallest,s[i].width*s[i].height);
biggest=max(biggest,s[i].width*s[i].height);
}
return biggest-smallest;
}
void report(rectangle *s, int n, int side){
int i;
printf("{%d}\n",score(s,n));
graph(s, n, side);
printf("{\n");
for(i=0;i<n;i++){
printf("[%d,%d] ",s[i].x,s[i].y);
printf("[%d,%d] ",s[i].x+s[i].width,s[i].y);
printf("[%d,%d] ",s[i].x+s[i].width,s[i].y+s[i].height);
printf("[%d,%d]\n",s[i].x,s[i].y+s[i].height);
}
printf("\n}\n");
}
void locateandrotate(rectangle *stack, int n){
unsigned int scratch,i;
for(i=1;i<n;i++){
/* Odd rectangles are on their side */
if(i&1){
scratch=stack[i].width;
stack[i].width=stack[i].height;
stack[i].height=scratch;
}
switch(i%4){
case 0:
stack[i].x=stack[i-1].x+stack[i-1].width;
stack[i].y=stack[i-1].y;
break;
case 1:
stack[i].x=stack[i-1].x+stack[i-1].width-stack[i].width;
stack[i].y=stack[i-1].y+stack[i-1].height;
break;
case 2:
stack[i].x=stack[i-1].x-stack[i].width;
stack[i].y=stack[i-1].y+stack[i-1].height-stack[i].height;
break;
case 3:
stack[i].x=stack[i-1].x;
stack[i].y=stack[i-1].y-stack[i].height;
break;
default:
printf("Woops!\n");
}
}
}
/* These are the height and width of the remaining area to be filled. */
void door(rectangle *stack, unsigned int height, unsigned int width, unsigned int n, unsigned int totaln){
unsigned int thisheight, thiswidth;
int i;
for(i=0;i<totaln;i++){
/* Not yet used */
if(stack[i].width == 0){
stack[i].width=width;
if(i+1 == totaln){
stack[i].height=height;
}
else {
/* Sometimes yields congruent rectangles, as with 16x16, 8 rectangles */
if(totaln&1 || height%n){
int j;
stack[i].height=height-(((n-1)*height)/n);
}
else {
stack[i].height=height-((((n-1)*height)-1)/n);
}
/* Exchange height and width to rotate */
door(stack,width,height-stack[i].height,n-1,totaln);
}
return;
}
}
}
void usage(char *argv[],int side){
printf("Usage: %s -s <side-length>\n",argv[0]);
printf("Purpose: Calculate N non-congruent rectangles arranged to exactly fill a square with the specified side length.\n");
printf("Defaults: %s -s %d\n",argv[0],side);
exit(0);
}
int main(int argc, char *argv[]){
int side=16;
int n,bestscore,bestn=2;
int status;
while((status=getopt(argc,argv,"s:h")) >= 0){
switch(status){
case 's':
sscanf(optarg,"%d",&side);
break;
case 'h':
default:
usage(argv,side);
}
}
bestscore=side+side;
rectangle stack[MAXCOUNT],best[MAXCOUNT];
for(n=2;n<=MAXCOUNT;n++){
initstack(stack,MAXCOUNT);
door(stack, side, side, n, n);
locateandrotate(stack, n);
if(valid(stack,n)){
if(score(stack,n) < bestscore){
bestn=n;
initstack(best,MAXCOUNT);
door(best, side, side, n, n);
locateandrotate(best, n);
bestscore=score(best,n);
}
}
}
report(best,bestn,side);
}
```
[Answer]
# C - 2982
This program implements a search through a broad results set. The important part of making this search practical was to fail early and/or not go down bad paths. This generates a set of rectangles to be considered for the solution. The set of rectangles generated avoids those with dimensions that would not be useful. For instance, if the program is trying to find the solution to a 128x128 square, divided into 8 rectangles, it will generate a rectangle that is 128x16. It will not generate that one is 120x17 because there is no prospect of a generating rectangle that is 8 wide to fill in the gap at the end of 120.
The initial strategy for placing rectangles is to place them on the inside of the perimeter of the square (buildedge function). In that way, the algorithm gets pretty quick feedback at each corner as to whether there is a problem with the sequence chosen. While placing rectangles, the logic keeps watching to see if any gaps of space develop which are too narrow for any rectangle. After the perimeter has been populated successfully, the strategy changes to trying to match the space remaining with the remaining rectangles (match function).
One other thing that might be of interest is that this implements transactions with rollback for the stacks of rectangles.
This program doesn't try to find the best possible fit. It is given a budget (64) and quits when it finds the first solution. If it never finds a solution, we bump up the budget (by 16) and try again.
The time required (on a Dell laptop with an I7 processor) ranged from well under a minute to 48 minutes for 150 on a side (149 on a side took less than 2 minutes). All 51 solutions used 11 rectangles. The scores of the 51 solutions ranged from 41 to 78. The reasons I used 11 rectangles were that the score was lower than with fewer rectangles and it looked like 12 rectangles would take much more than the hour allotted.
The solutions and code may be found at <https://github.com/JaySpencerAnderson/mondrian> . They are the two my4\* files.
BTW, if you compile this to "my4" and execute it as follows: "./my4 -h", it will give you usage. If you want to see it in action working away, try something like "./my4 -l 50 -n 8". If you change the one "#if 0" to "#if 1" it will render the remaining space on the screen. If you want to change this to render the rectangles, look for the one spot where the code executes "graph(space,side)" and change that to "graph(callstack,side)" instead. I'd also suggest changing the initial budget from 64 to 32 if you want to play around with solutions for squares that are about 50 wide. The solution for smaller squares will have a better score with a smaller budget.The program below is functional. Check github for the complete code (with usage, comments, etc).
```
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct {
int y, x, height, width, created, deleted;
} rectangle;
#define NOTYET -1
#define TOPEDGE 1
#define RIGHTEDGE 2
#define BOTTOMEDGE 4
#define LEFTEDGE 8
#define CENTER 16
#define nextEdge(e) (e<<=1)
#define min(x,y) (((x)<(y))?(x):(y))
#define max(x,y) (((x)>(y))?(x):(y))
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#define MAXFACTORS 1000
#define EOL printf("\n")
#define isCurrent(r) (r.created != NOTYET && r.deleted == NOTYET)
#define deleteTxn(r,t) (r.deleted=t)
int area(rectangle r){
return r.width*r.height;
}
void pop(rectangle *s){
unsigned int k=0;
while(s[k].width){
k++;
}
s[k-1].width=s[k-1].height=0;
}
void rpush(rectangle *s, rectangle x){
unsigned int k=0;
while(s[k].width){
k++;
}
x.deleted=NOTYET;
s[k++]=x;
s[k].width=s[k].height=0;
return;
}
void dumprectangle(rectangle r){
printf("%dX%d@[%d,%d] (%d,%d)\t",r.width, r.height, r.x, r.y, r.created, r.deleted);
}
void dumpstack(rectangle *s){
unsigned int k=0;
while(s[k].width){
dumprectangle(s[k]);
k++;
}
}
rectangle initrectangle(int width, int height){
rectangle r;
r.x=r.y=0;
r.width=width;
r.height=height;
r.created=0;
r.deleted=NOTYET;
return r;
}
void initstack(rectangle *s, int n){
int i;
for(i=0;i<n;i++){
s[i].y=s[i].x=s[i].height=s[i].width=0;
}
}
int bitcount(int x){
int count=0;
while(x){
if(x&1){
count++;
}
x>>=1;
}
return count;
}
int congruent(rectangle a, rectangle b){
return min(a.height,a.width) == min(b.height,b.width) && max(a.height,a.width) == max(b.height,b.width);
}
void report(rectangle *s, int side){
int i;
unsigned int smallest,biggest,area=0;
smallest=side*side;
biggest=0;
for(i=0;s[i].width;i++){
if(isCurrent(s[i])){
smallest=min(smallest,s[i].width*s[i].height);
biggest=max(biggest,s[i].width*s[i].height);
}
}
printf("{%d}\n",biggest-smallest);
printf("{\nDimensions\tLocation\n");
for(i=0;s[i].width;i++){
printf("%dx%d\t\t[%d,%d]\n",
s[i].width, s[i].height,
s[i].x, s[i].y);
}
printf("}\n");
}
unsigned int sumstack(rectangle *s){
unsigned int sum=0;
int i;
for(i=0;s[i].width;i++){
if(isCurrent(s[i])){
sum+=s[i].width*s[i].height;
s++;
}
}
return sum;
}
unsigned int minstack(rectangle *s){
unsigned int area=400000;
int i;
for(i=0;s[i].width;i++){
if(isCurrent(s[i])){
area=min(area,s[i].width*s[i].height);
}
}
return area;
}
void rollback(rectangle *r, int txn){
int i;
if(txn != NOTYET){
for(i=0;r[i].width;i++){
if(r[i].created == txn){
r[i].created=r[i].deleted=NOTYET;
r[i].x=r[i].width=r[i].y=r[i].height=0;
}
else if(r[i].deleted == txn){
r[i].deleted=NOTYET;
}
}
}
}
int overlap(rectangle a, rectangle b){
if((a.x < b.x+b.width && a.x+a.width > b.x) && (b.y < a.y+a.height && b.y+b.height > a.y)){
return TRUE;
}
return FALSE;
}
int stackoverlap(rectangle *callstack, rectangle next){
int i,j;
for(i=0;callstack[i].width;i++){
if(overlap(callstack[i], next)){
return TRUE;
}
}
return FALSE;
}
rectangle rotate(rectangle a){
int x=a.width;
a.width=a.height;
a.height=x;
return a;
}
int buildedge(rectangle *stack, rectangle *callstack,int side, rectangle *space){
int i,j,edge,goal,nextgoal,x,y,d,mindim,minarea,result=FALSE,spacetxn,stacktxn;
mindim=side;
minarea=side*side;
for(i=0;stack[i].width;i++){
mindim=min(mindim,min(stack[i].width,stack[i].height));
minarea=min(minarea,area(stack[i]));
}
x=y=0;
edge=TOPEDGE;
i=0;
while(edge == TOPEDGE && callstack[i].width != 0){
if(callstack[i].x == x && callstack[i].y == y){
x+=callstack[i].width;
if(x == side){
nextEdge(edge);
y=0;
}
i=0;
}
else {
i++;
}
}
while(edge == RIGHTEDGE && callstack[i].width != 0){
if(callstack[i].x+callstack[i].width == x && callstack[i].y == y){
y+=callstack[i].height;
if(y == side){
nextEdge(edge);
x=side;
}
i=0;
}
else {
i++;
}
}
while(edge == BOTTOMEDGE && callstack[i].width != 0){
if(callstack[i].x+callstack[i].width == x && callstack[i].y+callstack[i].height == y){
x-=callstack[i].width;
if(x == 0){
nextEdge(edge);
y=side;
}
i=0;
}
else {
i++;
}
}
while(edge == LEFTEDGE && callstack[i].width != 0){
if(callstack[i].x == x && callstack[i].y+callstack[i].height == y){
y-=callstack[i].height;
if(y == 0){
nextEdge(edge);
}
i=0;
}
else {
i++;
}
}
if(edge == CENTER){
/* rectangles are placed all along the perimeter of the square.
* Now match will use a different strategy to match the remaining space
* with what remains in stack */
if(match(stack,callstack,space)){
report(callstack,side);
return TRUE;
}
return FALSE;
}
switch(edge){
case TOPEDGE:
goal=side-x;
break;
case RIGHTEDGE:
goal=side-y;
break;
case BOTTOMEDGE:
goal=x;
break;
case LEFTEDGE:
/* Still a good assumption that callstack[0] is at 0,0 */
goal=y-callstack[0].height;
break;
default:
fprintf(stderr,"Error: buildedge has unexpected edge (b): %d\n",edge);
exit(0);
}
nextgoal=goal-mindim;
for(i=0;stack[i].width;i++){
if(isCurrent(stack[i])){
for(d=0;d<2;d++){
switch(edge){
case TOPEDGE:
if(stack[i].width == goal || stack[i].width <= nextgoal){
stack[i].x=x;
stack[i].y=y;
if(!stackoverlap(callstack, stack[i])){
spacetxn=nexttransaction(space);
stacktxn=nexttransaction(stack);
deleteTxn(stack[i],stacktxn);
removerectangle(space, stack[i], spacetxn);
if(narrow(space) >= mindim && smallest(space) >= minarea){
rpush(callstack, stack[i]);
if(buildedge(stack, callstack, side, space)){
return TRUE;
}
pop(callstack);
}
rollback(space, spacetxn);
rollback(stack, stacktxn);
stack[i].x=stack[i].y=0;
}
}
break;
case RIGHTEDGE:
if(stack[i].height == goal || stack[i].height <= nextgoal){
stack[i].x=x-stack[i].width;
stack[i].y=y;
if(!stackoverlap(callstack, stack[i])){
spacetxn=nexttransaction(space);
stacktxn=nexttransaction(stack);
deleteTxn(stack[i],stacktxn);
removerectangle(space, stack[i], spacetxn);
if(narrow(space) >= mindim && smallest(space) >= minarea){
rpush(callstack, stack[i]);
if(buildedge(stack, callstack, side, space)){
return TRUE;
}
pop(callstack);
}
rollback(space, spacetxn);
rollback(stack, stacktxn);
stack[i].x=stack[i].y=0;
}
}
break;
case BOTTOMEDGE:
if(stack[i].width == goal || stack[i].width <= nextgoal){
stack[i].x=x-stack[i].width;
stack[i].y=y-stack[i].height;
if(!stackoverlap(callstack, stack[i])){
spacetxn=nexttransaction(space);
stacktxn=nexttransaction(stack);
deleteTxn(stack[i],stacktxn);
removerectangle(space, stack[i], spacetxn);
if(narrow(space) >= mindim && smallest(space) >= minarea){
rpush(callstack, stack[i]);
if(buildedge(stack, callstack, side, space)){
return TRUE;
}
pop(callstack);
}
rollback(space, spacetxn);
rollback(stack, stacktxn);
stack[i].x=stack[i].y=0;
}
}
break;
case LEFTEDGE:
if(stack[i].height == goal || stack[i].height <= nextgoal){
stack[i].x=x;
stack[i].y=y-stack[i].height;
if(!stackoverlap(callstack, stack[i])){
spacetxn=nexttransaction(space);
stacktxn=nexttransaction(stack);
deleteTxn(stack[i],stacktxn);
removerectangle(space, stack[i], spacetxn);
if(narrow(space) >= mindim && smallest(space) >= minarea){
rpush(callstack, stack[i]);
if(buildedge(stack, callstack, side, space)){
return TRUE;
}
pop(callstack);
}
rollback(space, spacetxn);
rollback(stack, stacktxn);
stack[i].x=stack[i].y=0;
}
}
break;
default:
fprintf(stderr,"Error: buildedge has unexpected edge (c): %d\n",edge);
exit(0);
}
if(callstack[0].width != 0 && stack[i].width != stack[i].height){
stack[i]=rotate(stack[i]);
}
else {
break;
}
}
}
}
return FALSE;
}
int populatestack(rectangle *stack, int score, int side, int rectangles){
int offset,negative,area,mindim;
rectangle local;
int avg_area=(side*side)/rectangles;
if(avg_area < 4){
/* It's getting too small - really */
return FALSE;
}
local.x=0;
local.y=0;
local.created=0;
local.deleted=NOTYET;
initstack(stack,MAXFACTORS);
for(offset=1;offset<=score;offset++){
negative=offset&1;
area=avg_area + (negative?(0-(offset>>1)):(offset>>1));
mindim=area/side;
if(side*(area/side) == area){
local.width=side;
local.height=area/side;
rpush(stack,local);
}
if(area > 0){
for(local.width=side-mindim;local.width>=area/local.width;local.width--){
if(local.width*(area/local.width) == area){
local.height=area/local.width;
rpush(stack,local);
}
}
}
}
return TRUE;
}
int solve(int side,int rectangles,int score){
rectangle stack[MAXFACTORS],callstack[MAXFACTORS];
rectangle space[MAXFACTORS];
rectangle universe;
if(!populatestack(stack, score, side, rectangles)){
return FALSE;
}
if(sumstack(stack) >= side*side){
initstack(callstack,MAXFACTORS);
initstack(space,MAXFACTORS);
/* Initialize space (not occupied by a rectangle) to be side by side
* where side is the height/width of the square into which the rectangles fit. */
universe.width=universe.height=side;
universe.x=universe.y=0;
universe.created=0;
universe.deleted=NOTYET;
rpush(space, universe);
if(buildedge(stack,callstack,side,space)){
return TRUE;
}
}
return FALSE;
}
int containsPoint(rectangle a, int x, int y){
return a.x <= x && a.y <= y && a.x+a.width > x && a.y+a.height > y;
}
int containsRectangle(rectangle a, rectangle b){
return containsPoint(a, b.x, b.y) && containsPoint(a, b.x+b.width-1, b.y) && containsPoint(a, b.x, b.y+b.height-1) && containsPoint(a, b.x+b.width-1, b.y+b.height-1);
}
int areEqual(rectangle a, rectangle b){
return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height;
}
int nexttransaction(rectangle *r){
int i,n=NOTYET;
for(i=0;r[i].width;i++){
n=max(n,max(r[i].created,r[i].deleted));
}
return n+1;
}
void splitrectanglevertically(rectangle *space, int i, int x, int txn){
rectangle left, right;
left=right=space[i];
right.x=x;
left.width=right.x-left.x;
right.width-=left.width;
left.created=right.created=space[i].deleted=txn;
rpush(space,left);
rpush(space,right);
}
void splitrectanglehorizontally(rectangle *space, int i, int y, int txn){
rectangle top, bottom;
top=bottom=space[i];
bottom.y=y;
top.height=bottom.y-top.y;
bottom.height-=top.height;
top.created=bottom.created=space[i].deleted=txn;
rpush(space,top);
rpush(space,bottom);
}
int smallest(rectangle *space){
int i,j,smallest;
rectangle current;
smallest=0;
for(i=0;space[i].width;i++){
if(isCurrent(space[i])){
current=space[i];
for(j=0;space[j].width;j++){
if(isCurrent(space[j]) && i != j){
if(current.x+current.width == space[j].x
&& space[j].y <= current.y && space[j].y+space[j].height >= current.y+current.height){
current.width+=space[j].width;
}
else if(space[j].x+space[j].width == current.x
&& space[j].y <= current.y && space[j].y+space[j].height >= current.y+current.height){
current.x=space[j].x;
current.width+=space[j].width;
}
else if(current.y+current.height == space[j].y
&& space[j].x <= current.x && space[j].x+space[j].width >= current.x+current.width){
current.height+=space[j].height;
}
else if(space[j].y+space[j].height == current.y
&& space[j].x <= current.x && space[j].x+space[j].width >= current.x+current.width){
current.y=space[j].y;
current.height+=space[j].height;
}
}
}
if(smallest == 0){
smallest=current.width * current.height;
}
else if(smallest > current.width * current.height){
smallest=current.width * current.height;
}
}
}
return smallest;
}
int narrow(rectangle *space){
int i,j;
rectangle smallest,current;
smallest.width=0;
for(i=0;space[i].width;i++){
current=space[i];
if(isCurrent(current)){
for(j=0;space[j].width;j++){
if(isCurrent(space[j]) && i != j){
if(current.width <= current.height
&& current.x+current.width == space[j].x
&& space[j].y <= current.y && space[j].y+space[j].height >= current.y+current.height){
current.width+=space[j].width;
}
else if(current.width <= current.height
&& space[j].x+space[j].width == current.x
&& space[j].y <= current.y && space[j].y+space[j].height >= current.y+current.height){
current.x=space[j].x;
current.width+=space[j].width;
}
if(current.width >= current.height
&& current.y+current.height == space[j].y
&& space[j].x <= current.x && space[j].x+space[j].width >= current.x+current.width){
current.height+=space[j].height;
}
else if(current.width >= current.height
&& space[j].y+space[j].height == current.y
&& space[j].x <= current.x && space[j].x+space[j].width >= current.x+current.width){
current.y=space[j].y;
current.height+=space[j].height;
}
}
}
if(smallest.width == 0){
smallest=current;
}
else if(min(smallest.width,smallest.height) > min(current.width,current.height)){
smallest=current;
}
}
}
return min(smallest.width,smallest.height);
}
int notEmpty(rectangle *space){
int i,count;
for(i=0,count=0;space[i].width;i++){
if(isCurrent(space[i])){
count++;
}
}
return count;
}
int isAdjacent(rectangle r, rectangle s){
if(r.y == s.y+s.height && r.x < s.x+s.width && s.x < r.x+r.width){
return TOPEDGE;
}
if(s.x == r.x+r.width && r.y < s.y+s.height && s.y < r.y+r.height){
return RIGHTEDGE;
}
if(s.y == r.y+r.height && r.x < s.x+s.width && s.x < r.x+r.width){
return BOTTOMEDGE;
}
if(r.x == s.x+s.width && r.y < s.y+s.height && s.y < r.y+r.height){
return LEFTEDGE;
}
return NOTYET;
}
int adjacentrectangle(rectangle *space, int k, int k0){
int i,edge;
for(i=k0+1;space[i].width;i++){
if(i != k && isCurrent(space[i])){
if(isAdjacent(space[k],space[i]) != NOTYET){
return i;
}
}
}
return NOTYET;
}
int expanse(rectangle *space, int j, int d){ /* Returns how far space[j] can expand in the d direction */
int extent,k,giveUp,distance;
rectangle result=space[j];
extent=0;
giveUp=FALSE;
distance=0;
if(d == TOPEDGE || d == BOTTOMEDGE){
while(extent < space[j].width && !giveUp){
giveUp=TRUE;
for(k=0;space[k].width;k++){
if(k != j && isCurrent(space[k]) && isAdjacent(space[j],space[k]) == d){
if(space[j].x+extent == space[k].x){
extent+=space[k].width;
if(distance == 0){
distance=expanse(space,k,d);
}
else {
distance=min(distance,expanse(space,k,d));
}
giveUp=FALSE;
}
else if(space[j].x+extent > space[k].x && space[j].x+extent < space[k].x+space[k].width){
extent=space[k].x+space[k].width-space[j].x;
if(distance == 0){
distance=expanse(space,k,d);
}
else {
distance=min(distance,expanse(space,k,d));
}
giveUp=FALSE;
}
}
}
}
if(extent < space[j].width){
return 0;
}
return space[j].height+distance;
}
else if(d == LEFTEDGE || d == RIGHTEDGE){
while(extent < space[j].height && !giveUp){
giveUp=TRUE;
for(k=0;space[k].width;k++){
if(k != j && isCurrent(space[k]) && isAdjacent(space[j],space[k]) == d){
if(space[j].y+extent == space[k].y){
extent+=space[k].height;
if(distance == 0){
distance=expanse(space,k,d);
}
else {
distance=min(distance,expanse(space,k,d));
}
giveUp=FALSE;
}
else if(space[j].y+extent > space[k].y && space[j].y+extent < space[k].y+space[k].height){
extent=space[k].y+space[k].height-space[j].y;
if(distance == 0){
distance=expanse(space,k,d);
}
else {
distance=min(distance,expanse(space,k,d));
}
giveUp=FALSE;
}
}
}
}
if(extent < space[j].height){
return 0;
}
return space[j].width+distance;
}
return 0;
}
int match(rectangle *stack, rectangle *callstack, rectangle *space){
int i,j,k,d,goal,mn;
int height;
int spacetxn, stacktxn, calltxn;
int map;
rectangle r;
for(i=0,goal=0;space[i].width;i++){
if(isCurrent(space[i])){
goal+=space[i].width*space[i].height;
}
}
if(goal == 0){
return TRUE;
}
mn=minstack(stack);
if(goal < mn){
/* The goal (space available) is smaller than any rectangle left in the stack */
return FALSE;
}
spacetxn=nexttransaction(space);
stacktxn=nexttransaction(stack);
calltxn=nexttransaction(callstack);
for(j=0;space[j].width;j++){
for(i=0;stack[i].width;i++){
if(isCurrent(stack[i]) && isCurrent(space[j])){
if(congruent(space[j], stack[i]) && adjacentrectangle(space,j,NOTYET) == NOTYET){
r=space[j];
r.created=calltxn;
rpush(callstack, r);
deleteTxn(stack[i],stacktxn);
deleteTxn(space[j],spacetxn);
}
}
}
}
if(!notEmpty(space)){
return TRUE;
}
rectangle e;
for(j=0;space[j].width;j++){
if(isCurrent(space[j])){
e=space[j];
for(k=0,map=0;space[k].width;k++){
if(k != j && isCurrent(space[k])){
d=isAdjacent(space[j], space[k]);
if(d != NOTYET){
map|=d;
}
}
}
if(bitcount(map) == 1){ /* space[j] has adjacent space on only one side */
if(map == TOPEDGE || map == BOTTOMEDGE){
e.height=expanse(space,j,map);
}
else if(map == LEFTEDGE || map == RIGHTEDGE){
e.width=expanse(space,j,map);
}
for(i=0;stack[i].width;i++){
if(isCurrent(stack[i])){
if(congruent(e, stack[i])){
e.created=calltxn;
rpush(callstack, e);
deleteTxn(stack[i],stacktxn);
if(!removerectangle(space, e, spacetxn)){
printf("Logic error in match/expanse. Terminating\n");
exit(0);
}
if(match(stack,callstack,space)){
return TRUE;
}
else {
rollback(stack,stacktxn);
rollback(callstack,calltxn);
rollback(space,spacetxn);
return FALSE;
}
}
else if(congruent(space[j], stack[i])){
r=space[j];
r.created=calltxn;
rpush(callstack, r);
deleteTxn(stack[i],stacktxn);
if(!removerectangle(space, r, spacetxn)){
printf("Logic error in match/expanse. Terminating\n");
exit(0);
}
if(match(stack,callstack,space)){
return TRUE;
}
else {
rollback(stack,stacktxn);
rollback(callstack,calltxn);
rollback(space,spacetxn);
return FALSE;
}
}
}
}
}
}
}
if(notEmpty(space)){
rollback(stack,stacktxn);
rollback(callstack,calltxn);
rollback(space,spacetxn);
return FALSE;
}
return TRUE;
}
int removerectangle(rectangle *space, rectangle r, int ntxn){
int i,status=TRUE;
for(i=0;space[i].width;i++){
if(space[i].deleted == NOTYET){
if(areEqual(space[i], r)){
space[i].deleted=ntxn;
return TRUE;
}
else if(containsRectangle(space[i], r)){
if(r.x > space[i].x){
splitrectanglevertically(space, i, r.x, ntxn);
}
else if(r.y > space[i].y){
splitrectanglehorizontally(space, i, r.y, ntxn);
}
else if(r.x+r.width < space[i].x+space[i].width){
splitrectanglevertically(space, i, r.x+r.width, ntxn);
}
else if(r.y+r.height < space[i].y+space[i].height){
splitrectanglehorizontally(space, i, r.y+r.height, ntxn);
}
}
else if(overlap(space[i], r)){ /* we have to split both */
rectangle aux;
if(r.x < space[i].x){
aux=r;
aux.width=space[i].x-r.x;
r.x+=aux.width;
r.width-=aux.width;
if(!removerectangle(space,aux,ntxn)){
return FALSE;
}
}
if(r.x+r.width > space[i].x+space[i].width){
aux=r;
aux.x=space[i].x+space[i].width;
aux.width=r.x+r.width-aux.x;
r.width-=aux.width;
if(!removerectangle(space,aux,ntxn)){
return FALSE;
}
}
if(r.y < space[i].y){
aux=r;
aux.height=space[i].y-aux.y;
r.y+=aux.height;
r.height-=aux.height;
if(!removerectangle(space,aux,ntxn)){
return FALSE;
}
}
if(r.y+r.height > space[i].y+space[i].height){
aux=r;
aux.y=space[i].y+space[i].height;
aux.height=r.y+r.height-aux.y;
r.height-=aux.height;
if(!removerectangle(space,aux,ntxn)){
return FALSE;
}
}
if(areEqual(space[i], r)){
space[i].deleted=ntxn;
return TRUE;
}
else {
if(!removerectangle(space,r,ntxn)){
return FALSE;
}
return TRUE;
}
}
}
}
return TRUE;
}
int main(int argc, char *argv[]){
int side=15;
int n=5;
int budget=0;
int status;
while((status=getopt(argc,argv,"l:n:")) >= 0){
switch(status){
case 'l':
sscanf(optarg,"%d",&side);
break;
case 'n':
sscanf(optarg,"%d",&n);
break;
}
}
budget=64;
while(solve(side,n,budget) == FALSE){
budget+=16;
}
}
```
] |
[Question]
[
This challenge is about building a chessboard in which the square size, instead of being constant across the board, follows a certain non-decreasing sequence, as described below.
The board is defined iteratively. A board of size \$n \times n\$ is enlarged to size \$(n+k)\times(n+k)\$ by extending it down and to the right by a "layer" of squares of size \$k\$, where \$k\$ is the greatest divisor of \$n\$ not exceeding \$\sqrt{n}\$. The squares in the diagonal are always of the same colour.
Specifically, consider the board with colours represented as `#` and `+`.
1. Initialize the chessboard to
```
#
```
2. The board so far has size \$1\times 1\$. The only divisor of \$1\$ is \$1\$, and it does not exceed \$\sqrt{1}\$. So we take \$k=1\$, and extend the board by adding a layer of squares of size \$1\$, with `#` in the diagonal:
```
#+
+#
```
3. The board built so far has size \$2 \times 2\$. The divisors of \$2\$ are \$1,2\$, and the maximum divisor not exceeding \$\sqrt{2}\$ is \$1\$. So again \$k=1\$, and the board is extended to
```
#+#
+#+
#+#
```
4. Size is \$3 \times 3\$. \$k=1\$. Extend to
```
#+#+
+#+#
#+#+
+#+#
```
5. Size is \$4 \times 4\$. Now \$k=2\$, because \$2\$ is the maximum divisor of \$4\$ not exceeding \$\sqrt 4\$. Extend with a layer of thickness \$2\$, formed by squares of size \$2\times 2\$, with colour `#` in the diagonal:
```
#+#+##
+#+###
#+#+++
+#+#++
##++##
##++##
```
6. Size is \$6 \times 6\$. Now \$k=2\$. Extend to size \$8 \times 8\$. Now \$k=2\$. Extend to size \$10 \times 10\$. Now \$k=2\$. Extend to size \$12 \times 12\$. Now \$k=3\$. Extend to size \$15\$:
```
#+#+##++##++###
+#+###++##++###
#+#+++##++#####
+#+#++##++##+++
##++##++##+++++
##++##++##+++++
++##++##++#####
++##++##++#####
##++##++##++###
##++##++##+++++
++##++##++##+++
++##++##++##+++
###+++###+++###
###+++###+++###
###+++###+++###
```
Note how the most recently added squares, of size \$3 \times 3\$, have sides that partially coincide with those of the previously added squares of size \$ 2 \times 2 \$.
The sequence formed by the values of \$k\$ is non-decreasing:
```
1 1 1 2 2 2 2 3 3 3 3 4 4 4 6 6 6 6 6 6 ...
```
and does not seem to be in OEIS. However, its cumulative version, which is the sequence of sizes of the board, is [A139542](http://oeis.org/A139542) (thanks to [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for noticing).
# The challenge
**Input**: a positive integer \$S\$ representing the number of layers in the board. If you prefer, you may also get \$S-1\$ instead of \$S\$ as input (\$0\$-indexed); see below.
**Output**: an ASCII-art representation of a board with \$S\$ layers.
* Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines, a 2D character array or an array of strings.
* You can consistently choose **any two characters** for representing the board.
* You can consistently choose the **direction** of growth. That is, instead of the above representations (which grow downward and rightward), you can produce any of its reflected or rotated versions.
* Trailing or leading **space** is allowed (if output is through STDOUT), as long as space is not one of the two characters used for the board.
* You can optionally use "**\$0\$-indexed**" input; that is, take as input \$S-1\$, which specifies a board with \$S\$ layers.
Shortest code in bytes wins.
# Test cases
`1`:
```
#
```
`3`:
```
#+#
+#+
#+#
```
`5`:
```
#+#+##
+#+###
#+#+++
+#+#++
##++##
##++##
```
`6`:
```
#+#+##++
+#+###++
#+#+++##
+#+#++##
##++##++
##++##++
++##++##
++##++##
```
`10`:
```
#+#+##++##++###+++
+#+###++##++###+++
#+#+++##++#####+++
+#+#++##++##+++###
##++##++##+++++###
##++##++##+++++###
++##++##++#####+++
++##++##++#####+++
##++##++##++###+++
##++##++##+++++###
++##++##++##+++###
++##++##++##+++###
###+++###+++###+++
###+++###+++###+++
###+++###+++###+++
+++###+++###+++###
+++###+++###+++###
+++###+++###+++###
```
`15`:
```
#+#+##++##++###+++###+++####++++####
+#+###++##++###+++###+++####++++####
#+#+++##++#####+++###+++####++++####
+#+#++##++##+++###+++#######++++####
##++##++##+++++###+++###++++####++++
##++##++##+++++###+++###++++####++++
++##++##++#####+++###+++++++####++++
++##++##++#####+++###+++++++####++++
##++##++##++###+++###+++####++++####
##++##++##+++++###+++#######++++####
++##++##++##+++###+++#######++++####
++##++##++##+++###+++#######++++####
###+++###+++###+++###+++++++####++++
###+++###+++###+++###+++++++####++++
###+++###+++###+++###+++++++####++++
+++###+++###+++###+++###++++####++++
+++###+++###+++###+++#######++++####
+++###+++###+++###+++#######++++####
###+++###+++###+++###+++####++++####
###+++###+++###+++###+++####++++####
###+++###+++###+++###+++++++####++++
+++###+++###+++###+++###++++####++++
+++###+++###+++###+++###++++####++++
+++###+++###+++###+++###++++####++++
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
++++####++++####++++####++++####++++
++++####++++####++++####++++####++++
++++####++++####++++####++++####++++
++++####++++####++++####++++####++++
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
####++++####++++####++++####++++####
```
`25`:
```
#+#+##++##++###+++###+++####++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
+#+###++##++###+++###+++####++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
#+#+++##++#####+++###+++####++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
+#+#++##++##+++###+++#######++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
##++##++##+++++###+++###++++####++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
##++##++##+++++###+++###++++####++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
++##++##++#####+++###+++++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
++##++##++#####+++###+++++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
##++##++##++###+++###+++####++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
##++##++##+++++###+++#######++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
++##++##++##+++###+++#######++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
++##++##++##+++###+++#######++++####++++++######++++++######++++++##############++++++++########++++++++########++++++++
###+++###+++###+++###+++++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
###+++###+++###+++###+++++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
###+++###+++###+++###+++++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
+++###+++###+++###+++###++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
+++###+++###+++###+++#######++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
+++###+++###+++###+++#######++++##########++++++######++++++######++++++++++++++########++++++++########++++++++########
###+++###+++###+++###+++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
###+++###+++###+++###+++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
###+++###+++###+++###+++++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
+++###+++###+++###+++###++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
+++###+++###+++###+++###++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
+++###+++###+++###+++###++++####++++++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
####++++####++++####++++####++++##########++++++######++++++######++++++########++++++++########++++++++########++++++++
++++####++++####++++####++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
++++####++++####++++####++++####++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
++++####++++####++++####++++####++++++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++####++++####++++####++++####++++++++++######++++++######++++++##############++++++++########++++++++########++++++++
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
####++++####++++####++++####++++####++++++######++++++######++++++######++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
++++++######++++++######++++++######++++++######++++++######++++++##############++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++########++++++++########++++++++########++++++++
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
######++++++######++++++######++++++######++++++######++++++######++++++++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++######++++++######++++++######++++++######++++++######++++++######++++++++########++++++++########++++++++########
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########++++++++########
```
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), ~~34~~ 32 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
0#0⁸[#+¶+#xx*yx+m⤢αm;nlw√{y;%‽²X
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjEwJTIzJXVGRjEwJXUyMDc4JXVGRjNCJTIzKyVCNislMjMldUZGNTgldUZGNTgldUZGMEEldUZGNTkldUZGNTgldUZGMEIldUZGNEQldTI5MjIldTAzQjEldUZGNEQldUZGMUIldUZGNEUldUZGNEMldUZGNTcldTIyMUEldUZGNUIldUZGNTkldUZGMUIldUZGMDUldTIwM0QlQjIldUZGMzg_,i=MTA_,v=8)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~217~~ ~~215~~ 212 bytes
```
def f(x):
b=['1'];n=1
for i in range(x):P=max(j*(n%j<(j<=n**.5))for j in range(1,1+n));n+=P;b=[l+P*`j/P%2^i%2`for j,l in enumerate(b)];s=len(b[0]);b+=[((v*P+`1^int(v)`*P)*s)[:s]for v in b[0][len(b):]]
return b
```
[Try it online!](https://tio.run/##Rc@xboMwEIDhnafwgrizURKjdijE7@DddQSoprVFjsgQlDw9xRnaxcPpu1/n23P5majati83sAEeWGesV6aQhW1IyYwNU2SeeWKxo2@XgFbX7gGBA@XhDOGsiPPDO2KS4V/KUgpCbEgo3ezJUWjehqPOq4vPq/alyzF5R/eri93ioEfbzGp0BL05WWx6oQzAyrVo5cXTAiu2XCOf0dSzTYk1BRI2ry2src1YdMs97uPt7/hT@VZ@7F@7xb3Cik8qyvQcwuQJBvCI2y8 "Python 2 – Try It Online")
0-indexed, uses `0` and `1` as characters
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~40~~ 31 bytes
```
1SÆD>Ðḟ½ƊṀṭƲ³¡Äż$Ḷ:Ḃ^þ`ʋ/€ḷ""/Y
```
[Try it online!](https://tio.run/##AUQAu/9qZWxsef//MVPDhkQ@w5DhuJ/CvcaK4bmA4bmtxrLCs8Khw4TFvCThuLY64biCXsO@YMqLL@KCrOG4tyIiL1n///8xNQ "Jelly – Try It Online")
A full program taking the zero-indexed \$S-1\$ as input and writing to stdout ASCII art using 0 = #, 1 = +.
Without the trailing `Y`, this returns a list of lists of integers, but this is out of spec for this challenge.
### Explanation
This program works in three stages.
1. Generate a list of values of \$k\$ and the cumulative sum of \$k\$
2. Generate a checkerboard for each of these with the tile size of \$k\$ and the board size of the cumulative sum
3. Work through the list of checkerboards, each time replacing the top-left section of the next board with the existing board.
**Stage 1**
```
1 | Start with 1
Ʋ³¡ | Loop through the following the number of times indicated by the first argument to the program; this generates a list of values of k
S | - Sum
Ɗ | - Following three links as a monad
ÆD | - List of divisors
>Ðḟ½ | - Exclude those greater than the square root
Ṁ | - Maximum
ṭ | - Concatenate this to the end of the current list of values of k
Äż$ | Zip the cumulative sum of the values of k with the values
```
**Stage 2**
```
ʋ/€ | For each pair of k and cumulative sum, call the following as a dyad with the cumulative sum of k as the left argument and k as the right (e.g. 15, 3)
Ḷ | - Lowered range [0, 1 ... , 13, 14]
: | - Integer division by k [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]
Ḃ | - Mod 2 [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0]
^þ` | - Outer product using xor function and same argument to both side
```
**Stage 3**
```
/ | Reduce using the following:
ḷ"" | - Replace the top left portion of the next matrix with the current one
Y | Finally join by newlines
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~184~~ ~~178~~ ~~176~~ 169 bytes
```
def h(j,a=['1'],R=range):
for i in R(j):L=len(a);k=max(x for x in R(1,L+1)if(x*x<=L)>L%x);a=[a[m]+k*`(i+m/k)%2`for m in R(L)]+[((`i%2`*k+`~i%2`*k)*L)[:L+k]]*k
return a
```
[Try it online!](https://tio.run/##PY7BboMwEETP4St8idi1UROQejF1v8Anro4lLAXC4mIii0rupb9OaWhzG72nGc39axnmUK3rtevZAGPhlMnL3BaNii7cOpQZ6@fIiFFgDYwotfroAjisvZpcgvTQaddloUWJ1EPi6U1pfNfHhPU26cxkhectkJhOHo9V@9ua9pZGKwxASxvmXrTfe0Cu0UgtvLXcZyx2y2cMzK3PO4@DUJ5RmOrVyuxwjxQWRv8hv4T8ZZwpwACE@IfXHw "Python 2 – Try It Online")
Uses `1`, `0` for `#`, `-`; uses `0`-indexing.
[Answer]
# JavaScript (ES7), 164 bytes
Input is 0-indexed. Outputs a matrix with \$0\$ for `#` and \$1\$ for `+`.
```
n=>(b=[1],g=(a,w,d=w**.5|0)=>b[n]?a:w%d?g(a,w,d-1):g(a.concat(Array(d).fill(b.push(d)&&i++)),w+d))([0],i=1).map((_,y,a)=>a.map((_,x)=>(x/b[v=a[x>y?x:y]]^y/b[v])&1))
```
[Try it online!](https://tio.run/##XY5BUoNAEEX3OUUvFLrDZASr3IAD5QW8AI5mgICkcIYaYoCKOTtOjG5c/f/6d3X/vTqqobRtf9hoU@2WWixapFiIPJKsEajYyCoxrtf84SskkRa5lpmKx9sqa67hJqLYWV4aXaoDPlmrZqyI123XYcH7z@Hdoee1QUDExqAiwjyUrBUR8Q/VI76xmSl3W/3h5ACnuyI/CpVP6ZxN8Szl63yZSPIioqU2FjUICBPQ8Aj3F3UP4LQCcE0G0@14ZxrcPrulm5M@x1tK/mU16msDCyIFy/em1ej7RL/uRfsEAfxosjov3w "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
FN«≔⊕⌈Φ₂⊕Lυ¬﹪Lυ⊕κηFη«PL⭆⊞Oυω§#+÷⁻κμη↙
```
[Try it online!](https://tio.run/##VU67bsMwEJvtrxDS5YQqQ5cOyRQgKBDASovmC1T7YgnRw5FPToAi367KXtpyIkjeka1WsQ3K5nwOkcHBD4mOyX1hBM7Zd13txtH0vhhtRIeesAOp7sYlB2/GUsmdrklF/AyB/qUa9D1pSJxzwY7FlKFLNvzqgv2NX/gCwTTf1tUyRi8DKpksmSEaT7BpBDtRob1UA3ykUb8PGBWFCEmwW7ne0cF3eIfV0/NqLqC9mUyHII1PI1wEc0tFwXZ@HSaEzT7cfINnmqVH/cj55TWvJ/sD "Charcoal – Try It Online") Link is to verbose version of code. 1-indexed. Output grows down and left (down and right costs an extra byte, but can grow up for the same byte count). Explanation:
```
FN«
```
Loop \$S\$ times.
```
≔⊕⌈Φ₂⊕Lυ¬﹪Lυ⊕κη
```
Calculate \$k\leq\sqrt{n+1}\$. This only makes a difference when \$n=0\$ in which case this formula allows \$k=1\$.
```
Fη«
```
Loop \$k\$ times, once for each new row and column.
```
PL⭆⊞Oυω§#+÷⁻κμη
```
Output the row and column, being sure to alternate between the `#` and `+` characters in such a way that `#` is always the first character but that there is a boundary at the end of the string (because we're drawing from the diagonal outwards). `⊞Oυω` makes each row one character longer each time, which also keeps track of \$n\$ as the length.
```
↙
```
Move down and left ready for the next row.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~43~~ 42 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
$G©ÐX‚ˆÑʒ®>t‹}àDU+}¯εÝ`θ÷ɨDδ^}RζεðKζðδK€θ
```
Inspired by [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/185762/52210), and the trailing portion `ζεðKζðδK€θ` is a port from [*@Emigna*'s 05AB1E answer here](https://codegolf.stackexchange.com/a/186372/52210).
Returns a matrix of `0` instead of `#` and `1` instead of `+`.
[Try it online](https://tio.run/##AV4Aof9vc2FiaWX//yRHwqnDkFjigJrLhsORypLCrj504oC5fcOgRFUrfcKvzrXDnWDOuMO3w4nCqETOtF59Us62zrXDsEvOtsOwzrRL4oKszrj/Siz/MTX/LS1uby1sYXp5) or [try it online by outputting the first \$[2,n]\$ results](https://tio.run/##AYMAfP9vc2FiaWX/SUVOMkBpTiJJbnB1dDogw78KT3V0cHV0OiIs/zFOR8Kpw5BY4oCay4bDkcqSwq4@dOKAuX3DoERVK33Cr861w51gzrjDt8OJwqhEzrRefVLOts61w7BLzrbDsM60S@KCrM64/0osfcK2P2ApXDFV/zE2/y0tbm8tbGF6eQ) (`J,` in the footer and the `--no-lazy` flag are to pretty-print the resulting matrix).
**Explanation:**
```
$ # Push 1 and the input
G # Loop the input - 1 amount of times:
© # Store the top of the stack in variable `r` (without popping)
Ð # And triplicate the top as well
X‚ # Pair it with variable `X` (which is 1 by default)
ˆ # And pop and store this pair in the global array
Ñ # Get the divisors of the integer we triplicated
ʒ }à # Get the highest divisor which is truthy for:
‹ # Where the divisor integer is smaller than
®>t # the square root of `r+1`
DU # Store a copy of this largest filtered divisor as new variable `X`
+ # And add it to the triplicated integer
}¯ # After the loop: push the global array
ε # Map each pair to:
Ý θ # Convert the first value in the pair to a list in the range [0,n]
` # and push both this list and the second value to the stack
÷ # Integer-divide each value in the list by the second value
É # Check for each value if it's even (1 if even; 0 if odd)
¨ # Remove the last item
Dδ # Loop double vectorized over this list:
^ # And XOR the values with each other
}R # After the map: reverse the list of digit-matrices
ζ # Zip/transpose; swapping rows and columns, with a space as filler
ε # map each matrix to:
ðK # Remove all spaces from the current matrix
ζ # Zip/transpose with a space as filler again
ðδK # Deep remove all spaces
€θ # Then only leave the last values of each row
# (after which the resulting matrix of 0s and 1s is output implicitly)
```
[Answer]
## Haskell, ~~149~~ 146 bytes
```
(iterate g["#"]!!)
g b|let e=(<$[1..d]);l=length b;d=last[i|i<-[1..l],i*i<=l,mod l i<1];m="+#"++m=(e$take(l+d)$e=<<'#':m)++zipWith(++)(e=<<e<$>m)b
```
This is 0 indexed, returns a list of strings and grows upwards and leftwards.
[Try it online!](https://tio.run/##TckxbsIwFADQnVN8EkvYmETQsbFzAjp16BCsyiE/icW3sbBRpYqzNy1b1/dmmy5ItIz6tHCX8WYzwtQVZWHWa7GaoH8QZkDNFesOdT0Y0ZAmDFOeoW8GTTblzj2cqp5NZue2Tmna@esABE4dTON1IctCSq85smwvyEkOgqFWalNuXr2Q8tvFD5dnLqXgT0fFWi/6xVsXQIO38e0T@ClA1UK85/d8Owbgab5@QRDQ/sd7IBcwAYPx7wR0@7p@2ZvV8nMeyU5pqc4x/gI "Haskell – Try It Online")
```
(iterate g["#"]!!) -- start with ["#"], repeatedly add a layer
-- (via function 'g'), collect all results in
-- a list and index it with the input number
g b | let -- add a single layer to chessboard 'b'
l=length b -- let 'l' be the size of 'b'
d=last[i|i<-[1..l],i*i<=l,mod l i<1] -- let 'd' be the size of the new layer
e=(<$[1..d]) -- let 'e' be a functions that makes 'd'
-- copies of it's argument
m="#+"++m -- let 'm' be an infinite string of "+#+#+..."
= -- return
zipWith(++) -- concatenate pairwise
(e=<<e<$>m) -- a list of squares made by expanding each
-- char in 'm' to size 'd'-by-'d'
b -- and 'b' (zipWith truncates the infinite
-- list of squares to the length of 'b')
--
++ -- and prepend
--
(e$take(l+d)$e=<<'#':m) -- the top layer, i.e. a list of 'd' strings
-- each with the pattern 'd' times '#'
-- followed by 'd' times '+', etc., each
-- shortened to the correct size of 'l'+'g'
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~156~~ ~~144~~ ~~155~~ 154 bytes
*+11 to fix a bug reported by nimi.*
```
{$!=-1;join "
",(1,{my \k=max grep $_%%*,1.. .sqrt;++$!;flat .kv.map(->\i,\l {l~($!+i/k)%2+|0 x k}),substr(($!%2 x k~1-$!%2 x k)x$_,0,$_+k)xx k}...*)[$_]}
```
Roughly based on [Chas Brown's Python solution](https://codegolf.stackexchange.com/a/185754/14109). Takes S zero-indexedly. Outputs `0` and `1`.
[Try it online!](https://tio.run/##NcrRCoIwGIbh47yKX5mxufmnHgQx7EYyhkELU9OmhWJ666ZEZw/v99VXU@znst/qeB6IHfuhvFfZAxzLETQUQ9lDksdl2sHNXGsgynU9ESICNk/TSs6JLXWRtoD5G8u0pv4xyURSwFBMlNg82@XMjfgngA7ykYnmdWlaQ5fJjdY0hf6frCNKBIIovnB9I6LHTkSdx1laujIQIB5gsDZN2oOmRDH5s@NIa5y/ "Perl 6 – Try It Online")
] |
[Question]
[
**Task:** convert a HTML page into a mountain!
When HTML pages are indented, they can look like:
```
<div>
<div>
<div>
</div>
<div>
<div>
</div>
</div>
</div>
</div>
```
But to be honest, a mountain is more representative of this structure.
So we can rewrite it as:
```
/\
/\/ \
/ \
/ \
```
The outermost slashes on the left and right correspond to the outer div - each pair of HTML tags should be represented as `/` for the starting tag and `\` for the ending tag - inside all tags are "higher", with the same structure.
**Input:**
* There will be no `<!DOCTYPE>`
* There will be no self-closing tags e.g. `<img />` or `<br />`
* There may be attributes or content inside the tags
* There may be spaces or tabs - your program should ignore these
* There will be no spaces between `<` or `</` and the tag name
* All input will be valid HTML
**Output** - a mountain representing the tags as above.
*More testcases:*
Input:
```
<div id="123"> HI </div><a><span></span></a>
```
Output:
```
/\
/\/ \
```
Input:
```
<body id="<"></body>
```
Output:
```
/\
```
[Answer]
# HTML + CSS + JavaScript, 39 + 141 + 20 = 200 bytes
Outputs visually to the webpage. To allow this to work with special elements like `<body>`, all letters in the input are replaced.
```
p.innerHTML=prompt().replace(/\w/g,'a')
```
```
#p,#p *{display:flex;padding:0 0 1rem;align-items:flex-end;font-size:0}#p :before,#p :after{content:'/';font-size:1rem}#p :after{content:'\\'
```
```
<pre id=p>
```
---
# HTML + CSS + JavaScript, 10 + 103 + 20 = 133 bytes
Solution that works if there is no content within tags.
```
p.innerHTML=prompt()
```
```
#p,#p *{display:flex;padding:0 0 1em;align-items:flex-end}#p :before{content:'/'}#p :after{content:'\\'
```
```
<pre id=p>
```
[Answer]
# Javascript + JQuery, ~~275~~ 246 bytes
Saved 29 bytes thanks to [Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)
```
j=(a,b,c,i)=>{s=(c=' '.repeat(b))+'/\n';for(i=0;V=a.children[i];i++){s=s+j(V,b+1)}return s+c+'\\\n';};f=s=>{s=j($(s)[0],0).split`
`;w=Math.max.apply(0,s.map(a=>a.length));o='';for(i=w-1;i>=0;i--){for(c=0;C=s[c];c++){o+=C[i]||' '}o+='\n'}alert(o)}
```
A pretty Naïve solution to the problem. Parses the HTML with JQuery's `$(string)`, then recursively builds a sideways mountain with the format:
```
/
/
children...
\
\
```
Then rotates the resulting string counterclockwise, and alerts the result.
```
j=(a,b,c,i)=>{s=(c=' '.repeat(b))+'/\n';for(i=0;V=a.children[i];i++){s=s+j(V,b+1)}return s+c+'\\\n';};f=s=>{s=j($(s)[0],0).split`
`;w=Math.max.apply(0,s.map(a=>a.length));o='';for(i=w-1;i>=0;i--){for(c=0;C=s[c];c++){o+=C[i]||' '}o+='\n'}return o}
update=_=>outp.textContent=f(inp.value)
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id=inp oninput=update()></textarea>
<pre id=outp></pre>
```
[Answer]
# HTML + JavaScript (ES6), 8 + 192 = 200 bytes
### JS
```
s=>[...(E.innerHTML=s,y=0,o=[],m=n=>1+[...n.children].map(m).join``+0)(E.firstChild)].map((c,x,a)=>{(o[y+=+c]||(o[y]=[...a].fill` `))[x]=`\\/`[c],y+=~-c})&&o.reverse().map(l=>l.join``).join`
`
```
### HTML
```
<a id=E>
```
```
f=
s=>[...(E.innerHTML=s,y=0,o=[],m=n=>1+[...n.children].map(m).join``+0)(E.firstChild)].map((c,x,a)=>{(o[y+=+c]||(o[y]=[...a].fill` `))[x]=`\\/`[c],y+=~-c})&&o.reverse().map(l=>l.join``).join`
`
console.log(f(`<div>
<div>
<div>
</div>
<div>
</div>
<div>
<div>
</div>
</div>
</div>
</div>`))
```
```
<a id=E>
```
## Less golfed
```
s=>{
E.innerHTML=s,
y=0,
o=[],
m=n=>1+[...n.children].map(m).join``+0,
[...m(E.firstChild)].map((c,x,a)=>{
y+=+c
if(!o[y]) o[y]=[...a].fill` `
o[y][x]=`\\/`[c]
y+=~-c
})
return o.reverse().map(l=>l.join``).join`\n`
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~38~~ ~~26~~ 23 bytes
```
¶¡εDð¢4÷s'/å_„\/sèú}ζR»
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0LZDC89tdTm84dAik8Pbi9X1Dy@Nf9QwL0a/@PCKw7tqz20LOrT7/38lJSWblMwyOy4FIECwsPD08UjiENHHZQKUCaGATgAA "05AB1E – Try It Online")
---
I am still golfing this. It assumes that in HTML you will always use 4 spaces for indentation, and does not work on "non-pretty" HTML. Not sure how to handle the "content" part, if this is invalid please edit the question to show an example with a node that has content.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔¹ηF⮌θ«≡ι"≦¬η<Fη¿⁼ζ/←¶\↙/≔ιζ
```
[Try it online!](https://tio.run/##LY3LCsIwEEXXyVcMs0qhUqo7jQFBQUFFXHcTamoDJX2ktlDx22OsWc3MfZzJS9nltayc21mrn4alMZTRhhZ1B@yuBtVZxdoogjcldtR9XgLT85VLqwAzxDUl5CKb0L/W/Z8QAnz2Z1wZ@Y3oAtihfcnKsikGTNDDb502PVufVeHLmJkswx@BEFV5RnD39WhCIpntDyXhqY5h8srHOf7QA@jHFtPlCgUcT8ATLwkuBbeNNIInYUhB3WKovg "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔¹η
```
The `h` variable is used to keep track of whether we are inside quotes.
```
F⮌θ«
```
Loop over the string in reverse order.
```
≡ι
```
Switch on the currenc character.
```
"≦¬η
```
If it's a `"` then toggle the quote flag.
```
<Fη
```
If it's a `<` and we're not inside quotes, then...
```
¿⁼ζ/
```
If the next character (previous in the loop because we're looping in reverse) is a `/`, then...
```
←¶\
```
Move up and draw a `\` leftwards, else...
```
↙/
```
Draw a `/` and move down and left.
```
≔ιζ
```
Remember the character for the next loop iteration.
] |
[Question]
[
In physics, like electric charges repel, and unlike charges attract.
The potential energy between two unit charges separated by a distance `d` is `1/d` for like charges and `-1/d` for unlike charges. The potential energy of a system of charges is the sum of the potential energies between all pairs of charges.
## Challenge
Determine the potential energy of a system of unit charges represented by a string.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
---
### Input
A nonempty multiline string, consisting of only `+`, `-`, and newlines, with each line a constant width. The `+` and `-` represent charges of +1 and -1 respectively. For example, the following string:
```
+ -
+
```
(considering the top-left to be the origin) represents a system with positive charges at (4,0) and (1,-1) and a negative charge at (6,0).
Alternatively, you may take input as a list of lines.
### Output
A signed real number representing the potential energy of the system of charges. Output should be correct to four significant figures or 10-4, whichever is looser.
### Test cases:
```
-
```
Should output `0`. There are no pairs of charges to repel or attract, and the whitespace doesn't change anything.
```
+
-
```
There are only two charges; they are 1 unit away in the vertical direction and 2 units away in the horizontal direction, so their distance is sqrt(5). Output should be -1/sqrt(5)=`-0.447213595`.
```
+ -
- +
```
Should give `-2.001930531`.
```
- -- -+ - - -+-++-+
+-- + +-- + ++-++ -
---++-+-+- -+- - +-
-- - -++-+ --+ +
- + --+ ++-+ +-
-- ++- + + -+--+
+ +++-+--+ +--+++ +
-+- +-+-+-+ -+ +--+
- +-+- + ---+
- - ++ -+- --+--
```
Should give `-22.030557890`.
```
---+--- ++-+++- -+ +
-+ ---+++-+- +- + +
---+-+ - ---- +-- -
- + +--+ -++- - -
--+ - --- - -+---+ -
+---+----++ - + +
-+ - ++-- ++- -+++
+----+- ++-+-+ -
++- -+ -+---+ -- -+
+-+++ ++-+-+ -+- +-
```
Should give `26.231088767`.
[Answer]
# CJam, 51 chars
Counting all pairs, filtering `Inf/NaN` out and dividing by two:
```
q_N#:L;N-" +"f#ee2m*{z~:*\Lfmd2/:.-:mh/}%{zL<},:+2/
```
Alternatively, filtering coordinates first so we count each pair once and don't run into `Inf/NaN`:
```
q_N#:L;N-" +"f#ee2m*{0f=:<},{z~:*\Lfmd2/:.-:mh/}%:+
```
## Explanation (old)
```
q Get all input.
_N#:L; Store the line width in L.
N- Flatten it into one long line.
:i Get all ASCII values.
:(3f%:( Map space to 0, + to 1, - to -1.
ee Enumerate: list of [index, sign] pairs.
2m* Get all possible pairs.
{ }% For each pair:
e_~ i1 s1 i2 s2
@* i1 i2 s (multiply signs)
\aa@aa+ s [[i2] [i1]] (put indices in nested list)
Lffmd s [[x2 y2] [x1 y1]] (divmod by L)
:.- s [xD yD] (point diff)
:mh s d (Euclidean dist.)
/ s/d (divide)
{zL<}, Filter out infinite results.
:+2/ Sum all charges, and divide by two.
(We counted each pair twice.)
```
[Answer]
## Haskell, ~~149~~ 144 bytes
```
z=zip[0..]
g n|f<-[(x,y,c)|(y,r)<-z$lines n,(x,c)<-z r,c>' ']=sum[c%d/sqrt((x-i)^2+(y-j)^2)|a@(x,y,c)<-f,b@(i,j,d)<-f,a/=b]/2
c%d|c==d=1|1<2= -1
```
Usage example:
```
*Main> g " - -- -+ - - -+-++-+\n +-- + +-- + ++-++ -\n---++-+-+- -+- - +- \n-- - -++-+ --+ + \n- + --+ ++-+ +- \n-- ++- + + -+--+ \n+ +++-+--+ +--+++ + \n-+- +-+-+-+ -+ +--+\n- +-+- + ---+ \n- - ++ -+- --+--"
-22.030557889699853
```
`f` is a list of all triples `(x-coord, y-coord, unit charge)`. `g` calculates the potential energy for all combinations of two such triples which are not equal, sums them and divides the result by `2`.
[Answer]
# Pyth, 34 bytes
```
smc*FhMd.atMd.cs.e+RkCUBxL" +"b.z2
```
[Demonstration](https://pyth.herokuapp.com/?code=smc%2aFhMd.atMd.cs.e%2BRkCUBxL%22+%2B%22b.z2&input=---%2B---+%2B%2B-%2B%2B%2B-+-%2B+%2B%0A-%2B+---%2B%2B%2B-%2B-+%2B-+%2B++%2B%0A---%2B-%2B+-+----++%2B--+-%0A+-+++%2B+%2B--%2B+-%2B%2B-+-+-%0A--%2B+-+---+-+-%2B---%2B+-%0A%2B---%2B----%2B%2B+-+++%2B++%2B%0A-%2B+-+%2B%2B--+%2B%2B-++-%2B%2B%2B+%0A+%2B----%2B-+++%2B%2B-%2B-%2B++-%0A%2B%2B-+-%2B+-%2B---%2B++--+-%2B%0A%2B-%2B%2B%2B+%2B%2B-%2B-%2B+-%2B-+%2B-+&debug=0)
First, we convert each character to +1 for `+`, -1 for `-`, and 0 for . Then, each number is annotated with its position in the matrix. At this point, we have a matrix that looks like:
```
[[[-1, 0, 0], [-1, 1, 0], [-1, 2, 0], [1, 3, 0], [-1, 4, 0], [-1, 5, 0], [-1, 6, 0]],
[[1, 0, 1], [1, 1, 1], [-1, 2, 1], [-1, 3, 1], [0, 4, 1], [1, 5, 1], [0, 6, 1]]]
```
The code that reaches this point is `.e+RkCUBxL" +"b.z`
Then, we flatten this matrix into a list and take all possible pairs, with `.cs ... 2`.
Then, he find the distance between the pair with `.atMd`, and the sign of the potential with `*FhMd`, divide, and sum.
[Answer]
# Ruby, 133
```
->n{t=i=j=0.0
c=[]
n.tr(' ',?,).bytes{|e|e-=44
z="#{j}+#{i}i".to_c
i+=1
e<-1?i=0*j+=1:(c.map{|d|t+=d[0]*e/(d[1]-z).abs};c<<[e,z])}
t}
```
Maintains an array of previous charges in the form of tuples `[charge, location(complex number)]` and compares each new charge with this list, before appending it to the list.
All spaces in the input are replaced with commas. This enables the following assignment by subtracting 44 from their ascii code:
```
symbol charge (internal representation)
+ -1
, 0
- +1
```
The fact that the program considers `+` to be -1 and `-` to be +1 makes no difference to the final result. The fact that the program goes to the effort of calculating the influence of the charges of 0 for the spaces makes no difference, apart from slowing it down a bit :-)
Ungolfed in test program
```
g=->n{
t=i=j=0.0 #t=total potential; i and j are coordinates of charge.
c=[] #array to store tuples: charge + location (complex number).
n.tr(' ',?,).bytes{|e| #replace all spaces with commas, then iterate through characters.
e-=44 #subtract 44 from ascii code: + -> -1; comma -> 0; - -> 1
z="#{j}+#{i}i".to_c #position of current character as complex number
i+=1 #advance x coordinate to next character.
e<-1?i=0*j+=1: #if current character is newline, set i to zero and advance j instead,
(c.map{|d|t+=d[0]*e/(d[1]-z).abs};#else add up the contribution for interaction of the current charge with all previous charges,
c<<[e,z])} #and append the current charge to the list of previous charges.
t} #return t
p g[
'+ -
- +'
]
p g[
' - -- -+ - - -+-++-+
+-- + +-- + ++-++ -
---++-+-+- -+- - +-
-- - -++-+ --+ +
- + --+ ++-+ +-
-- ++- + + -+--+
+ +++-+--+ +--+++ +
-+- +-+-+-+ -+ +--+
- +-+- + ---+
- - ++ -+- --+--'
]
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 39 ~~42~~ bytes
```
`jt]N$v'- +'FT#m2-I#fbbhtZPwt!**1w/XRss
```
Works in [current release (5.1.0)](https://github.com/lmendo/MATL/releases/tag/5.1.0). The compiler runs on Matlab or Octave.
Each line is a separate input. End is signalled by inputting an empty line.
### Examples
```
>> matl
> `jt]N$v'- +'FT#m2-I#fbbhtZPwt!**1w/XRss
>
> + -
> - +
>
-2.001930530821583
>> matl
> `jt]N$v'- +'FT#m2-I#fbbhtZPwt!**1w/XRss
>
> - -- -+ - - -+-++-+
> +-- + +-- + ++-++ -
> ---++-+-+- -+- - +-
> -- - -++-+ --+ +
> - + --+ ++-+ +-
> -- ++- + + -+--+
> + +++-+--+ +--+++ +
> -+- +-+-+-+ -+ +--+
> - +-+- + ---+
> - - ++ -+- --+--
>
-22.03055788969994
```
### Explanation
```
`jt] % keep inputting lines until an empty one is found
N$v % concatenate all inputs vertically. This removes the last empty line
'- +'FT#m % replace '-', ' ', '+' by numbers 1, 2, 3
2- % transform into -1, 0, 1 for '-', ' ', '+'
I#f % find rows, columnss and values of nonzeros
bbh % concatenate rows and columns into 2-col matrix or coordinates
tZP % compute pair-wise distances for those coordinates
wt!* % generate matrix of signs depending on signs of charges
* % multiply distances by signs, element-wise
1w/ % invert element-wise
XR % keep part over the diagonal
ss % sum along colums, then rows
% (output is implicitly printed)
```
[Answer]
## Lua, 293 255 246 228 Bytes
```
e=0l={}p={}i=1while l[i-1]~=""do l[i]=io.read()for k=1,#l[i]do c=l[i]:sub(k,k)if(c>" ")then for h,v in ipairs(p)do e=e+(v.s==c and 1 or-1)/math.sqrt((v.y-i)^2+(v.x-k)^2)end table.insert(p,{s=c,x=k,y=i})end end i=i+1 end print(e)
```
Ouch, 228 bytes...I can probably golf this significantly, but I'll post it here for now. Probably update it later tonight with a few more musings and (hopefully) some improvements to the length.
**Ungolfed**
```
e=0l={}p={}i=1
while l[i-1]~=""do
l[i]=io.read()
for k=1,#l[i]do
c=l[i]:sub(k,k)
if(c>" ")then
for h,v in ipairs(p) do
e=e+(v.s==c and 1 or-1)/math.sqrt((v.y-i)^2+(v.x-k)^2)
end
table.insert(p,{s=c,x=k,y=i})
end
end
i=i+1
end
print(e)
```
*Update 255 Bytes:* Removed old bottom two for loops, processing is now done as strings are added to string array.
*Update 246 Bytes:* Replaced `c=="+"or"-"==c` with `c>" "` as per nimi's suggestion. Great idea, thanks!
*Update 228 Bytes:* If statement could be removed completely by inserting in table after the for loop, saving quite a few bytes.
[Answer]
# Mathematica 223 bytes
Still golfing to do.
```
f[{{c1_,p1_},{c2_,p2_}}]:=N[(c1 c2)/EuclideanDistance[p1,p2],13];
h[charges_]:=Tr[f/@Subsets[DeleteCases[Flatten[Array[{r[[#,#2]],{#,#2}}&,Dimensions[r=Replace[Characters[charges],{"+"-> 1,"-"->-1," "->0},2]]],1],{0,_}],{2}]]
```
---
Last test case:
```
h[{" - -- -+ - - -+-++-+", " +-- + +-- + ++-++ -",
"---++-+-+- -+- - +- ", "-- - -++-+ --+ + ",
"- + --+ ++-+ +- ", "-- ++- + + -+--+ ",
"+ +++-+--+ +--+++ + ", "-+- +-+-+-+ -+ +--+",
"- +-+- + ---+ ", "- - ++ -+- --+--"}]
```
>
> -22.030557890
>
>
>
] |
[Question]
[
## Background
I have constructed a simple obstacle course by placing boxes in a rectangular room.
Now I want to count the number of essentially different ways in which it can be solved.
I need you to write me a program for that.
## Input
Your input is a non-empty rectangular array of the characters `.#`.
The dots `.` are empty space, and the `#` are obstacles.
A *path* through the obstacle course begins at the top left corner and ends at the bottom right corner, and goes only right or down.
Also, a valid path cannot go through an obstacle.
Here are some examples drawn with `+`-characters:
```
Valid path Invalid path Invalid path Invalid path
++........ ++........ +++++..... ..+.......
.++++++#.. .+.....#.. ....+++#++ ..++...#..
......+#.. .+.++++#.. .......#.+ ...+++.#..
....#.++++ .+++#.++++ ....#....+ ....#+....
```
Two paths are *essentially similar*1 if one can be transformed into the other by moving one `+` at a time.
The intermediate paths must also be valid, so you can't bend a path over an obstacle.
For example, the first two paths here are essentially similar, but the third is essentially different from them, since it can't be wiggled over the two obstacles:
```
++........ +......... +++++++++.
.+++++.#.. ++.....#.. .......#+.
.....+.#.. .++++++#.. .......#++
....#+++++ ....#.++++ ....#....+
```
## Output
Your output is the number of essentially different paths through the obstacle course.
In other words, if all the valid paths are divided into classes of essentially similar paths, the output is the number of classes.
Note that this number may be 0, if there are no valid paths.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There are no time bounds, except that you should evaluate your program on every test case before submitting it.
## Test cases
```
....
....
.... => 1
...#
....
...# => 0
#..#
..#.
.... => 0
......
......
..##..
......
...... => 2
......
...#..
......
..#...
#..... => 3
......
..#...
......
....#.
#..... => 4
.......
##.....
....###
...#...
..##.#.
#....#.
..#.... => 0
......#.
..##....
...#....
.......#
....#...
.##...#.
....#...
##...... => 7
.........
.#.#.#.#.
.........
#.#...#.#
.........
.#.#.#.#.
......... => 17
..........
.#........
..........
.....#....
#.........
........#.
......#...
.......... => 10
.........
.#.......
.........
...#.....
.........
.....#...
.........
.......#.
......... => 16
```
1 The correct technical term is ["homotopic"](https://en.wikipedia.org/wiki/Homotopy).
[Answer]
# Python 2, ~~170~~ ~~131~~ 112 bytes
```
def f(C,t=1):i="#".join(C).find("#")+1;return([]<C)*(i<1or(i<t
and f([r[i:]for r in C],t-i))+(i>1)*f(C[1:],i-1))
```
A function, `f`, taking the obstacle course as a list of rows, and returning the number of essentially different paths.
## Explanation
The basic concept is this:
We choose a certain obstacle, *o*, such that there are no other obstacles in the box bounding *o* and the top-left corner.
```
+--+....
|..|....
+--#<==== o
.....#..
.#......
........
```
We then consider the two sub-courses to the east and to the south of *o*.
We only consider either of these sub-courses if *o* can actually be crossed from a direction that leads to them, that is, crossed from the north to get to the east, and crossed from the west to get to the south.
We solve the problem for each of the selected sub-courses, and return the sum of the results.
These numbers correspond to the number of essentially different paths when crossing *o* from the left and from the right, respectively,
therefore the two resulting sets of paths are essentially different.
Since there are no obstacles between the starting point and *o*, there is a path between the starting point and any entry point into each of these regions, and all such paths that lead to the same point are essentially similar, hence the above sum is the complete number of essentially different paths in the entire course.
```
A
_
........ ...|//// |....
........ ...|//// |....
...#.... --> ...#//// --> ....
.#....#. .#..//#/ ..#.
........ ....//// ....
| |
v v
B
........ ___
........ .#....#.
___#.... --> ........ --> +
/#////#/
////////
```
Things are slightly complicated by the fact that the obstacle course alone doesn't convey all the information needed.
For example, consider course *B* in the diagram above.
Taken by itself, we can't determine whether each of the obstacles can be crossed from the north.
If *B* were the input course, then, since all paths start at the top-left corner, neither obstacle could have been crossed from the north, but, since we can reach *B* from either side of the left obstacle when crossing *o* from the east, we should treat this obstacle as though it can be crossed from the north when solving the course; the same doesn't hold for the right obstacle, however, which can't be crossed from this direction.
We convery this extra information by specifying, along with the obstacle course, the number of characters along the first row, starting from the left, that the path can start at.
In the diagram above, this is depcited as the solid line next to each course.
While, technically, we also need to specify the corresponding number of characters along the first column that the path can start at, as in the case of sub-course *A*, in practice we always selected the highest obstacle, so this information is not required.
The actual selection of *o* is as follows:
We pretend that each row, other than the last, is followed by an obstacle (i.e., has a `#` appended to it), and select the first obstacle in the resulting course, in reading order.
For rows (other than the last) that had no obstacle originally, this effectively mean that we skip them (while noting that the path below may start at any character along the top row).
Eventually, we end up with a course that has a single row with no obstacles, for which there is only one possible path.
[Answer]
# [Snails](https://github.com/feresum/PMA), ~~53~~ 49 bytes
```
A^
\.+d!{.l\.+a3(.|~c!~}\.+r!(.u\.+e(.|~},\.,=~d~
```
For once, I did not have to use `t`, the dreaded teleport instruction. As a result, the test cases finish instantly instead of taking aeons.
Ungolfed:
```
A^
r\.+
{
d\.+
!{ r\.u \.+ a3 (.|~)}
r\.+
!{ d\.l \.+ a3 (.|~)}
},
d\.,
!(dr .)
```
The options `A^` mean to start at the upper-left corner and count all matching paths. The main idea is to check a canonicity condition for the paths. I honestly did not expect it to work, but it nailed the test cases, so.... What it tries to check for is that, within the current path, the greediest route has been selected, i.e. going right as many times as possible, down as many times as possible, etc. without crossing over any obstacles. This is done by checking, after moving right 1 or more times and then down 1 or more times, that the next square (which must be to the right) could not have been reached by going right one more time in the previous rightward segment. The analogous condition is also checked after moving right and then down.
[Answer]
## CJam, ~~85~~ ~~84~~ ~~82~~ ~~81~~ ~~80~~ 79 bytes
```
qN/:Q,(Qz,(:R_T]2/e~e!{'#Qs@{\(\@>}%s-},{_}{(a\L{@+_@\-_{2$\f.=0fe=2&},}h;}w;],
```
[Try it online.](http://cjam.tryitonline.net/#code=cU4vOlEsKFF6LCg6UlMqXDBhKitlIXsnI1FzQHtcKFxAe1I-fXx9JXMtfSx7X317KGF7MSR7MSRcZi49MGZlPTImfSxfQCtAMSQtXEB9Z1x9dztdLA&input=Li4uLi4uIy4KLi4jIy4uLi4KLi4uIy4uLi4KLi4uLi4uLiMKLi4uLiMuLi4KLiMjLi4uIy4KLi4uLiMuLi4KIyMuLi4uLi4) Or [run the entire test suite.](http://cjam.tryitonline.net/#code=cU4yKi97IiA9PiAiLzA9OlE7CgpRTi86USwoUXosKDpSUypcMGEqK2UheycjUXNAe1woXEB7Uj59fH0lcy19LHtffXsoYXsxJHsxJFxmLj0wZmU9MiZ9LF9AK0AxJC1cQH1nXH13O10sCgpdb05vfS8&input=Li4uLgouLi4uCi4uLi4gPT4gMQoKLi4uIwouLi4uCi4uLiMgPT4gMAoKIy4uIwouLiMuCi4uLi4gPT4gMAoKLi4uLi4uCi4uLi4uLgouLiMjLi4KLi4uLi4uCi4uLi4uLiA9PiAyCgouLi4uLi4KLi4uIy4uCi4uLi4uLgouLiMuLi4KIy4uLi4uID0-IDMKCi4uLi4uLgouLiMuLi4KLi4uLi4uCi4uLi4jLgojLi4uLi4gPT4gNAoKLi4uLi4uLgojIy4uLi4uCi4uLi4jIyMKLi4uIy4uLgouLiMjLiMuCiMuLi4uIy4KLi4jLi4uLiA9PiAwCgouLi4uLi4jLgouLiMjLi4uLgouLi4jLi4uLgouLi4uLi4uIwouLi4uIy4uLgouIyMuLi4jLgouLi4uIy4uLgojIy4uLi4uLiA9PiA3CgouLi4uLi4uLi4KLiMuIy4jLiMuCi4uLi4uLi4uLgojLiMuLi4jLiMKLi4uLi4uLi4uCi4jLiMuIy4jLgouLi4uLi4uLi4gPT4gMTcKCi4uLi4uLi4uLi4KLiMuLi4uLi4uLgouLi4uLi4uLi4uCi4uLi4uIy4uLi4KIy4uLi4uLi4uLgouLi4uLi4uLiMuCi4uLi4uLiMuLi4KLi4uLi4uLi4uLiA9PiAxMAoKLi4uLi4uLi4uCi4jLi4uLi4uLgouLi4uLi4uLi4KLi4uIy4uLi4uCi4uLi4uLi4uLgouLi4uLiMuLi4KLi4uLi4uLi4uCi4uLi4uLi4jLgouLi4uLi4uLi4gPT4gMTY)
The efficiency of this solution is probably quite horrible but it solves each test case within a few seconds.
### Explanation
I'll have to add a full breakdown of the code later, but the algorithmic idea is this:
* Let the width and height of the grid be `W` and `H`, respectively.
* We generate all possible paths as the distinct permutations of `W-1` copies of `0` and `H-1` copies of `W-1` (where `0` represents a horizontal step and `W-1` a vertical step). We walk all of those paths by repeatedly taking the first element of the grid and then skipping `step` cells in reading order (where `step` is `0` or `W-1`). We discard all paths which contain a `#`.
* Then we repeatedly remove one group of similar paths (which will be all paths similar to the first of the remaining paths). Checking for similar paths gets a bit easier by relaxing the condition for them slightly: instead of checking whether one `x` has moved, we check whether the paths differ in exactly two places. If that is the case, those two places will have a vertical and horizontal move swapped. This causes the entire segment between those moves to be shifted diagonally by one cell. But if both of those paths are valid, shifting any part of the path by one cell diagonally cannot cross an obstacle, so they are similar. We still need to find the transitive closure, so we keep doing that until we find no more similar paths before moving on to the next group.
* Finally, we count the groups we've found, which we left at the bottom of the stack.
] |
[Question]
[
In [this challenge](https://codegolf.stackexchange.com/q/139034/56656) we learned a way to encode every positive integer using factor trees.
Here is how it works:
* The empty string has value of 1.
* `(S)` where `S` is any expression with a value of **S** evaluates to the **S**th prime.
* `AB` where `A` and `B` are arbirary expressions with values of **A** and **B** respectively has value **A\*B**.
For example if we wanted to represent 7 we would do
```
7 -> (4) -> (2*2) -> ((1)(1)) -> (()())
```
Turns out we can represent every whole number using this method. In fact some numbers we can represent in multiple ways. Because multiplication is commutative 10 is both
```
((()))()
```
and
```
()((()))
```
At the same time some numbers can only be represented in 1 way. Take 8 for example. 8 can only be represented as
```
()()()
```
And since all of our atoms are the same we can't use commutivity to reorganize them.
---
So now the question is "Which numbers can only be represented in 1 way?". The first observation is one I just started making back there. It seems that perfect powers have some special properties. Under further investigation we can find 36, which is 62 is a perfect power but has multiple representations.
```
(())()(())()
(())()()(())
()(())()(())
()(())(())()
()()(())(())
```
And this makes sense because 6 is already rearrangable, so any number we make out of 6 must also be rearrangable.
So now we have a rule:
* A number has a unique representation if it is a perfect power of a number with a unique representation.
That rule can help us reduce determining if a composite number is unique to determining if a prime number is unique. Now that we have that rule we want to figure out what makes a *prime* number unique. This is actually pretty self evident. If we take a unique number and wrap it in parentheses, the result must be unique, and, going the other way if **n** has multiple representations the **n**th prime must have multiple representations. This yields the second rule:
* The **n**th prime is unique if and only if **n** is unique.
Both of these rules are recursive, so we are going to need a base case. What is the smallest unique number? One might be tempted to say 2 because its just `()`, but 1, the empty string, is even smaller and is unique.
* 1 is unique.
With these three rules we can determine whether a number has a unique factor tree.
## Task
You may have seen it coming, but your task is to take a positive integer, and determine if it is unique. You should write either a program or function that does this computation. You should output one of two possible values, what these values are is up to you but one should represent "yes", being output when the input is unique and one should represent "no" being output otherwise.
Your answers should be scored in bytes with less bytes being better.
## Test cases
Here are the first couple unique numbers:
```
1
2
3
4
5
7
8
9
11
16
17
19
23
25
27
31
```
Suggested test cases
```
5381 -> Unique
```
It seems that [OEIS A214577](https://oeis.org/A214577) is somehow related, so if you need more test cases try there, but I don't know they are the same so use at your own risk.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes
Saved one byte thanks to Zgarb!
```
Ωεo?oṗ←¬Ep
```
Returns `1` for unique, `0` otherwise
[Try it online!](https://tio.run/##AR4A4f9odXNr///Oqc61bz9v4bmX4oaQwqxFcP///zUzODE "Husk – Try It Online") Or [returning the first 50](https://tio.run/##ASQA2/9odXNr/yDihpE1MGbigoFO/86pzrVvP2/huZfihpDCrEVw//8)
### Explanation:
```
Ωε Until the result is small (either 1 or 0), we repeat the following
p Get the prime factors
o? If ...
E they are all equal:
ȯṗ← Get the index of the first one into the primes
Else:
¬ Not the list (since non-empty lists are truthy, this returns 0)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
After a LOT of fiddling around!
```
ÆET0ṪḊ?µl¿
```
A monadic link taking a positive integer and returning `1` if it is unique or `0` if not.
**[Try it online!](https://tio.run/##ASQA2/9qZWxsef//w4ZFVDDhuarhuIo/wrVswr//MzEsw4ck4oKsR/8 "Jelly – Try It Online")**
### How?
```
ÆET0ṪḊ?µl¿ - Link: number, n e.g. 11 or 13 or 20
¿ - while:
l - ...condition: (left) logarithm with base (right)
- note: x log 0 and x log 1 both yield None, which is falsey
µ - ...do the monadic chain: (first pass shown)
ÆE - prime exponent array [0,0,0,0,1] [0,0,0,0,0,1] [2,0,1]
T - truthy indexes [5] [6] [1,3]
? - if:
Ḋ - ...condition: dequeue (i.e. if length > 1)
0 - ...then: literal zero - - 0
Ṫ - ...else: tail 5 6 -
- end result 1 0 0
```
**Wait, logarithm, what?!**
Lets run through some examples of the loop.
If `n=31` (**311**, the eleventh prime):
```
log test # | left, x | right, b | x log b
-----------+----------+-----------+----------
1 | 31 | 31 | 1.000 -> continue
2 | 11 | 31 | 0.698 -> continue
3 | 5 | 11 | 0.671 -> continue
4 | 3 | 5 | 0.683 -> continue
5 | 2 | 3 | 0.631 -> continue
6 | 1 | 2 | 0.000 -> stop, yielding left = 1
```
If `n=625` (**54**):
```
log test # | left, x | right, b | x log b
-----------+----------+-----------+----------
1 | 625 | 625 | 1.000 -> continue
2 | 3 | 625 | 0.171 -> continue
3 | 2 | 3 | 0.631 -> continue
4 | 1 | 2 | 0.000 -> stop, yielding left = 1
```
If `n=225` (**52×32**):
```
log test # | left, x | right, b | x log b
-----------+----------+-----------+----------
1 | 225 | 225 | 1.000 -> continue
2 | * 0 | 225 |-inf+nanj -> continue
3 | ** 0 | 0 | None -> stop, yielding left = 0
*The dequeued list was not empty
**Tailing an empty list in Jelly yields 0
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 42 bytes
```
⎕CY'dfns'
{1≥⍵:1⋄1=≢∪r←3pco⍵:∇1+¯1pco⊃r⋄0}
```
Using `⎕CY'dfns'` with `dfns`es isn't very feasible on tio.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ÆfẋE$ḢÆCµl¿
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//w4Zm4bqLRSThuKLDhkPCtWzCv/8zMSzDhyTigqxH/w "Jelly – Try It Online")
-2 thanks to a very genius trick by [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan).
Using H.PWiz's Husk algorithm.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 49 bytes
```
f(n)=d=factor(n);n<2||(#d~<2&&f(primepi(d[1,1])))
```
[Try it online!](https://tio.run/##JYpBCoAgEADvfSOIXbBAJQjSl4iHyDb2kIl0lL5uQrdhZtKWeTxTrQQRbbC07c@dG6/RqFKgD69Rw0CQMl9HYghOCukRsTYTH3Bc2IxOTpNWXhAweuz@RDDrRbbzAw "Pari/GP – Try It Online")
] |
[Question]
[
Write a full program with a source code of 256 bytes or less that looks at an image of a flag and determines what country that flag is from. A zip file containing the 196 different flags in the challenge can be downloaded from [here](http://flags.fmcdn.net/data/flags-normal.zip). Source: [[Flagpedia](http://flagpedia.net/)]. These 196 flag images are the only inputs your program has to handle.
Your program will take no input. The flag image will be in the same directory as your program and named "f.png". Your program will open this file, identify it, and print the two letter [abbreviation for that country](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). If you use a language that can't open files, it's also acceptable to run your program as `./program < f.png`.
Each flag file is named the same as the expected output. All output above 2 letters will be ignored.
Here is a list of all the outputs/filenames:
```
ad, ae, af, ag, al, am, ao, ar, at, au, az, ba, bb, bd, be, bf, bg, bh, bi, bj,
bn, bo, br, bs, bt, bw, by, bz, ca, cd, cf, cg, ch, ci, cl, cm, cn, co, cr, cu,
cv, cy, cz, de, dj, dk, dm, do, dz, ec, ee, eg, eh, er, es, et, fi, fj, fm, fr,
ga, gb, gd, ge, gh, gm, gn, gq, gr, gt, gw, gy, hn, hr, ht, hu, id, ie, il, in,
iq, ir, is, it, jm, jo, jp, ke, kg, kh, ki, km, kn, kp, kr, ks, kw, kz, la, lb,
lc, li, lk, lr, ls, lt, lu, lv, ly, ma, mc, md, me, mg, mh, mk, ml, mm, mn, mr,
mt, mu, mv, mw, mx, my, mz, na, ne, ng, ni, nl, no, np, nr, nz, om, pa, pe, pg,
ph, pk, pl, pt, pw, py, qa, ro, rs, ru, rw, sa, sb, sc, sd, se, sg, si, sk, sl,
sm, sn, so, sr, st, sv, sy, sz, td, tg, th, tj, tl, tm, tn, to, tr, tt, tv, tw,
tz, ua, ug, us, uy, uz, va, vc, ve, vn, vu, ws, ye, za, zm, zw,
```
# Scoring
Here is a short python script that I will use to score each submission.
```
import os
import subprocess
import random
botlist = []
with open("bots.txt") as bots:
for line in bots:
line = line.split(", ")
if len(line) >= 2:
botLine = line + [0]
botlist.append(botLine)
files = os.listdir(os.getcwd() + "/flags")
random.shuffle(files)
def test(bot_command):
score = 0
for filename in files:
command = "COPY flags\\{} f.png".format(filename)
os.system(command)
print bot_command
result = subprocess.check_output(bot_command, shell = True)
if result[:2] == filename[:2]:
score += 1
return score
for i in range(len(botlist)):
command = botlist[i][1]
botlist[i][2] = test(command)
with open("output.txt", "w+") as output:
for bot in botlist:
output.write("{} got a score of {}.".format(bot[0], bot[2]))
os.system("del f.png")
```
Your score is the total number of flags correctly identified. In case of a tie, the earlier submission wins.
# Rules
* For my testing convenience, any language with a freely available interpreter/compiler for Windows 10 or Ubuntu can be used.
* Image processing libraries are allowed, but any builtins related to flags or countries are not allowed. (*cough* Mathematica *cough*)
* Please provide the full command needed to run your program along with links to any necessary libraries.
* Submissions may not interact with any file except "f.png".
* I don't have any hard time-limit on submissions, but please keep it relatively quick. I don't want the scoring script to take hours.
[Answer]
# Python 2, Score = ~~68~~ 89
This solution uses the hash of the flag image file to create an index into a list of the country abbreviations. If more than one flag hashed to an index, only the first abbreviation will be returned (so it will fail some of those tests with more than one country in a hash bucket). This algorithm does however guarantee one correct answer for every non-empty hash bucket.
```
i=hash(open('f.png').read())%99*2
print'kgmviruasefridusvakpsmbtgrpwcdsdauninrsyalsg--game--espyscmtyebhgqom--kh--inhudjbw--ltroilbicv--jonaugke--svhtbg--simcknbnpelcplgncmmacimytnttlytgcflirsvemhtzuyqaerbfbepa--uzaenearcl--jmbbphkzrwieet'[i:i+2]
```
This program is 247 characters.
A more readable version:
```
encoded = 'kgmviruasefridusvakpsmbtgrpwcdsdauninrsyalsg--game--espyscmtyebhgqom--kh--inhudjbw--ltroilbicv--jonaugke--svhtbg--simcknbnpelcplgncmmacimytnttlytgcflirsvemhtzuyqaerbfbepa--uzaenearcl--jmbbphkzrwieet'
index = hash(open('f.png').read())%99 * 2
print encoded[index : index+2]
```
## Building the encoded string
To build the encoded string, I use a function to read in the flag files
as strings, generate a hash from the string, and reduce the hash to a
limited number of hash `buckets`:
```
def encode(buckets):
lookup = {}
for fn in os.listdir('flags'):
name = fn[:2]
signature = hash(open('flags/'+fn).read()) % buckets
lookup[signature] = lookup.get(signature, '')+name
return lookup
```
to return a dictionary of countries that match each signature, then use
some code to convert the dictionary into a lookup string:
```
encoded = ''.join(lookup.get(v, '--')[:2] for v in range(buckets))
```
I needed to experiment a bit with which values of `buckets` gives the best results.
[Answer]
## CJam, ~~139~~ 141
There's a lot of unprintables in the code, so here's the `xxd` hexdump:
```
00000000: 7132 3925 3162 226d cec5 9635 b14b 69ee q29%1b"m...5.Ki.
00000010: d9d0 66e8 97b8 e88d 2366 7857 9595 1c73 ..f.....#fxW...s
00000020: 9324 11b2 ddb8 7a3f 19ed bd37 07c0 cb86 .$....z?...7....
00000030: 394e b34a ecf0 8c9b f300 a216 2e2e 594a 9N.J..........YJ
00000040: 9a6b 3b2f 250a 9a25 783b 0e49 3e9c 6ab9 .k;/%..%x;.I>.j.
00000050: 8d6d d729 42d0 85f3 657b 7d86 af48 c6cb .m.)B...e{}..H..
00000060: f7ff 980f b81c dd5e e8cb 4e34 d8ec edca .......^..N4....
00000070: 6646 1b4d 7605 8937 ed58 2302 1cc1 ebfd fF.Mv..7.X#.....
00000080: 16d3 b53e 3e2c d879 fe33 feef dd65 d49f ...>>,.y.3...e..
00000090: 5d73 7ced 92e6 9526 c186 00bf d2a8 ffaa ]s|....&........
000000a0: 65a0 3001 f42a 94d7 592f ebe7 8bdf 97a7 e.0..*..Y/......
000000b0: 0681 8ee1 9e0e 424b f6a1 4c50 1c8a 8de5 ......BK..LP....
000000c0: 481a 388c 6eaa 0c43 e1db 69df 567b 323f H.8.n..C..i.V{2?
000000d0: 2573 c4ce b348 6fff 37e0 55b4 7c9a 7e7d %s...Ho.7.U.|.~}
000000e0: 73a4 ef74 2b99 b765 2a2d d99f 986a 355c s..t+..e*-...j5\
000000f0: db22 3236 3362 3236 6227 6166 2b32 2f3d ."263b26b'af+2/=
```
This is exactly 256 bytes, with the program doing:
```
q29% Read input and keep every 29th char
1b Sum code points
"..." Push long string
263b Convert long string to base 263
26b Convert result to base 26
'af+ Add 'a to each element in the resulting array
2/ Split into chunks of length 2
= Index sum cyclically to extract output
```
Run the program with the command
```
java -Dfile.encoding=ISO-8859-1 -jar cjam-0.6.5.jar flags.cjam < f.png
```
Thanks to @Dennis for help with getting this submission working.
] |
[Question]
[
Your task is to give three different languages A, B, C, and write two different programs P and Q such that:
P is a quine in language A, but not a quine in B nor C;
Q is a quine in language B, but not a quine in A nor C; and
Q concatenated after P (without any new characters added in between) is a quine in language C, but not in B nor A.
This is codegolf, where your score is the length of the final, concatenated quine. Again, adhere to the rules of [proper quines](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) -- no reading your source code, no empty programs etc.
[Answer]
# Fission + CJam + GolfScript, ~~38~~ 36 bytes
### [Fission](http://esolangs.org/wiki/Fission), 6 bytes
```
'!+OR"
```
This is one of [Martin Büttner's Fission quines](https://codegolf.stackexchange.com/a/50968). [Try it online!](http://fission.tryitonline.net/#code=JyErT1Ii&input=)
### CJam, 30 bytes
```
' {"''"@*" "+YX#<
\"0$~"N}0$~
```
The last byte is a linefeed. [Try it online!](http://cjam.tryitonline.net/#code=JyB7IicnIkAqIiAiK1lYIzwKXCIwJH4iTn0wJH4K&input=)
### GolfScript, 36 bytes
```
'!+OR"' {"''"@*" "+YX#<
\"0$~"N}0$~
```
The last byte is a linefeed. [Try it online!](http://golfscript.tryitonline.net/#code=JyErT1IiJyB7IicnIkAqIiAiK1lYIzwKXCIwJH4iTn0wJH4K&input=)
## Verification
```
$ wc -c P Q
6 P
30 Q
36 total
$ cat P Q > P+Q
$
$ Fission P 2>&- | diff -qs - P
Files - and P are identical
$ cjam P 2>&- | diff -qs - P
Files - and P differ
$ golfscript P 2>&- | diff -qs - P
Files - and P differ
$
$ cjam Q 2>&- | diff -qs - Q
Files - and Q are identical
$ golfscript Q 2>&- | diff -qs - Q
Files - and Q differ
$ Fission Q 2>&- | diff -qs - Q
Files - and Q differ
$
$ golfscript P+Q 2>&- | diff -qs - P+Q
Files - and P+Q are identical
$ Fission P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ
$ cjam P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ
```
## How it works
### Fission
* `R` spawns an atom that moves right, wrapping around at the edge.
* `"` toggles printing mode. Everything up to the next `"` is printed.
* `'!` sets the atom's to the code point of '!'.
* `+` increments the atom's mass, setting it to the code point of `"`.
* `O` prints the character whose code point is the atom's mass and destroys the atom.
### CJam
```
' e# Push a space character.
{ e# Push the following code block:
"''" e# Push that string.
@* e# Separate its characters by spaces.
" "+ e# Append one more space.
YX# e# Raise 2 to the first power. Pushes 2.
< e# Discard all but the first two characters of the string, i.e., "' ".
\ e# Swap the string "' " with the code block in execution.
"0$~" e# Push that string.
N e# Push a linefeed.
} e#
0$~ e# Push a copy of the code block and execute it.
```
### GolfScript
```
'!+OR"' # Push that string.
{ # Push the following code block:
"''" # Push that string.
@* # Join its characters, separating them by the first string.
" "+ # Append a space.
YX # Undefined token. Does nothing.
#< # Comment.
\ # Swap the string with the code block in execution.
"0$~" # Push that string.
N # Undefined token. Does nothing.
} #
0$~ # Push a copy of the code block and execute it.
```
[Answer]
# Self-modifying Brainfuck + GolfScript + CJam, ~~29~~ 27 bytes
### [Self-modifying Brainfuck](https://soulsphere.org/hacks/smbf/), 12 bytes
```
{<[<]>[.>]}
```
Note the leading space. [Try it online!](http://smbf.tryitonline.net/#code=IHs8WzxdPlsuPl19&input=)
### GolfScript, 15 bytes
```
{So"0$~"N]}0$~
```
The last byte is a linefeed. [Try it online!](http://golfscript.tryitonline.net/#code=e1NvIjAkfiJOXX0wJH4K&input=).
### CJam, 27 bytes
```
{<[<]>[.>]}{So"0$~"N]}0$~
```
Note the leading space. The last byte is a linefeed. [Try it online!](http://cjam.tryitonline.net/#code=IHs8WzxdPlsuPl19e1NvIjAkfiJOXX0wJH4K&input=)
## Verification
```
$ wc -c P Q
12 P
15 Q
27 total
$ cat P Q > P+Q
$
$ timeout 10 smbf P | diff -sq - P
Files - and P are identical
$ golfscript P | diff -sq - P
Files - and P differ
$ cjam P | diff -sq - P
Files - and P differ
$
$ golfscript Q | diff -sq - Q
Files - and Q are identical
$ cjam Q | diff -sq - Q
Files - and Q differ
$ timeout 10 smbf Q | diff -sq - Q
Terminated
$
$ cjam P+Q | diff -sq - P+Q
Files - and P+Q are identical
$ golfscript P+Q | diff -sq - P+Q
Files - and P+Q differ
$ timeout 10 smbf P+Q | diff -sq - P+Q
Terminated
```
## How it works
### Self-modifying Brainfuck
SMBF starts with its source code on the left of the data pointer.
```
<space> (ignored)
{ (ignored)
< Move the data pointer left.
[<] Move the data pointer left to the next null byte.
> Move the data pointer right.
[.>] Print and move the data pointer right until null byte.
} (ignored)
```
### GolfScript
```
{ # Push the following code block:
So # Undefined token. Does nothing.
"0$~" # Push that string.
N # Undefined token. Does nothing.
] # Wrap the stack in a array. Does not affect output.
} #
0$~ # Push a copy of the code block and execute it.
### CJam
{<[<]>[.>]} e# Push that code block.
{ e# Push the following code block:
So e# Print a space. Since it is printed explicitly,
e# it will appear at the beginning of the output.
"0$~" e# Push that string.
N e# Push a linefeed.
] e# Wrap the stack in a array. Does not affect output.
e# This makes the program an infinite, empty loop
e# in SMBF; it would be a quine otherwise.
} e#
0$~ e# Push a copy of the code block and execute it.
```
[Answer]
# Tcl, CJam, GolfScript, 60 + 26 = 86 112 bytes
Not golfed well.
### [Tcl](https://en.m.wikipedia.org/wiki/Tcl "Tcl"), 60 bytes
```
{puts} [{join} {{} \{ \}\]} {{puts} [{join} {{} \{ \}\]} }]
```
Based on the quine on [this page](http://wiki.tcl.tk/730). It has a trailing newline.
### CJam, 26 bytes
```
{"' '@`+n@0"L~;"0$~"N}0$~
```
It has a trailing newline.
### GolfScript, 86 bytes
```
{puts} [{join} {{} \{ \}\]} {{puts} [{join} {{} \{ \}\]} }]
{"' '@`+n@0"L~;"0$~"N}0$~
```
[Answer]
# ShapeScript + CJam + GolfScript, ~~96~~ ~~95~~ 62 bytes
### [ShapeScript](https://github.com/DennisMitchell/ShapeScript), 16 bytes
```
'"%r"@%"0?!"'0?!
```
This is the [standard ShapeScript quine](https://codegolf.stackexchange.com/a/63275). [Try it online!](http://shapescript.tryitonline.net/#code=JyIlciJAJSIwPyEiJzA_IQ==&input=)
### CJam, 46 bytes
```
];{"'\"%r\"@%\"0?!\"'0?!];"SS#~(>
\"0$~"N}0$~
```
The last byte is a linefeed. [Try it online!](http://cjam.tryitonline.net/#code=XTt7IidcIiVyXCJAJVwiMD8hXCInMD8hXTsiU1Mjfig-ClwiMCR-Ik59MCR-Cg&input=)
### GolfScript, 62 bytes
```
'"%r"@%"0?!"'0?!];{"'\"%r\"@%\"0?!\"'0?!];"SS#~(>
\"0$~"N}0$~
```
The last byte is a linefeed. Try it online on [Web GolfScript](http://golfscript.tryitonline.net/#code=JyIlciJAJSIwPyEiJzA_IV07eyInXCIlclwiQCVcIjA_IVwiJzA_IV07IlNTI34oPgpcIjAkfiJOfTAkfgo&input=).
## Verification
```
$ wc -c P Q
16 P
46 Q
62 total
$ cat P Q > P+Q
$
$ shapescript P 2>&- | diff -qs - P
Files - and P are identical
$ cjam P 2>&- | diff -qs - P
Files - and P differ
$ golfscript P 2>&- | diff -qs - P
Files - and P differ
$
$ cjam Q 2>&- | diff -qs - Q
Files - and Q are identical
$ golfscript Q 2>&- | diff -qs - Q
Files - and Q differ
$ shapescript Q 2>&- | diff -qs - Q
Files - and Q differ
$
$ golfscript P+Q 2>&- | diff -qs - P+Q
Files - and P+Q are identical
$ shapescript P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ
$ cjam P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ
```
## How it works
### ShapeScript
```
' Push a string that, when evaluated, does the following.
"%r" Push this formatting string. %r gets replaced by a string
representation of the corresponding argument.
@ Swap the string that is being evaluated on top of the stack.
% Apply formatting to the string on top of the stack.
"0?!" Push that string.
'
0?! Push a copy of the previous string and evaluate it.
```
### CJam
```
]; e# Clear the stack. Stack is already clear. Does nothing.
{ e# Push the following code block:
"'\"%r\"@%\"0?!\"'0?!];"
SS# e# Find the index of " " in " ". Pushes 0.
~( e# Apply logical NOT and decrement. Pushes -2.
> e# Discard all but the two rightmost characters from the string,
e# i.e., reduce it to "];".
\ e# Swap the string "];" with the code block in execution.
"0$~" e# Push that string.
N e# Push a linefeed.
} e#
0$~ e# Push a copy of the code block and execute it.
```
### GolfScript
```
'"%r"@%"0?!"'
0?! # Find the index of the number 0 in the string and apply logical NOT.
]; # Clear the stack.
{ # Push the following code block:
"'\"%r\"@%\"0?!\"'0?!];"
SS # Undefined token. Does nothing.
#~(> # Comment.
\ # Swap the string with the code block in execution.
"0$~" # Push that string.
N # Undefined token. Does nothing.
} #
0$~ # Push a copy of the code block and execute it.
```
] |
[Question]
[
There are 21 items in [Minecraft](http://minecraft.gamepedia.com/Minecraft_Wiki) that you can [craft](http://minecraft.gamepedia.com/Crafting) using only [wood](http://minecraft.gamepedia.com/Wood) and items crafted from wood:
>
> [axe](http://minecraft.gamepedia.com/Axe)
>
> [boat](http://minecraft.gamepedia.com/Boat)
>
> [bowl](http://minecraft.gamepedia.com/Bowl)
>
> [button](http://minecraft.gamepedia.com/Button)
>
> [chest](http://minecraft.gamepedia.com/Chest)
>
> [crafting table](http://minecraft.gamepedia.com/Crafting_table)
>
> [door](http://minecraft.gamepedia.com/Door)
>
> [fence](http://minecraft.gamepedia.com/Fence)
>
> [gate](http://minecraft.gamepedia.com/Gate)
>
> [hoe](http://minecraft.gamepedia.com/Hoe)
>
> [ladder](http://minecraft.gamepedia.com/Ladder)
>
> [pickaxe](http://minecraft.gamepedia.com/Pickaxe)
>
> [planks](http://minecraft.gamepedia.com/Planks)
>
> [pressure plate](http://minecraft.gamepedia.com/Pressure_plate)
>
> [shovel](http://minecraft.gamepedia.com/Shovel)
>
> [sign](http://minecraft.gamepedia.com/Sign)
>
> [slab](http://minecraft.gamepedia.com/Slab)
>
> [stairs](http://minecraft.gamepedia.com/Stairs)
>
> [stick](http://minecraft.gamepedia.com/Stick)
>
> [sword](http://minecraft.gamepedia.com/Sword)
>
> [trapdoor](http://minecraft.gamepedia.com/Trapdoor)
>
>
>
This list assumes that the [6 different types](http://minecraft.gamepedia.com/Tree#Species) of wooden planks/slabs/doors/etc. all count as the same item. Another way to think of it is to assume you only have access to one type of wood.
Each of these 21 items has a different [crafting recipe](http://minecraft.gamepedia.com/Crafting#Complete_recipe_list). We'll represent each of these recipes as a 2×2 or 3×3 grid of the characters `.WPS`. The `.` is an empty crafting slot, `W` is for [wood](http://minecraft.gamepedia.com/Wood), `P` is for [wood planks](http://minecraft.gamepedia.com/Wood_Planks), and `S` is for [sticks](http://minecraft.gamepedia.com/Stick). No other characters are needed for these particular items.
For example, this is the recipe for a [chest](http://minecraft.gamepedia.com/Chest):
```
PPP
P.P
PPP
```
**Challenge**
Write a program that takes in the name of one of our 21 items, exactly as it appears above, and prints a valid crafting recipe for that item.
Crafting recipes are translation invariant, so if the input is [`fence`](http://minecraft.gamepedia.com/Fence), both of these are valid:
```
PSP
PSP
...
```
```
...
PSP
PSP
```
If a recipe fits in a 2×2 grid, you can output it in a 2×2 or 3×3 grid. e.g. [`stick`](http://minecraft.gamepedia.com/Stick):
```
.P
.P
```
```
...
.P.
.P.
```
Recipes can also be mirrored horizontally (around a vertical line of symmetry), though this only makes a difference for the axe, hoe, and stairs. e.g. [`hoe`](http://minecraft.gamepedia.com/Hoe):
```
.PP
.S.
.S.
```
```
PP.
.S.
.S.
```
So outputting any recipe that fits in the grid and has the correct shape (ignoring translation and mirroring) is what your program needs to do. These are all the recipes that the official game will recognize. (Note that recipes cannot be rotated or mirrored vertically.)
**Details**
* Take input from stdin or the command line. You can assume the input is always valid. Requiring quotes around input (e.g. `"chest"`) is fine.
* Output to stdout (or closest alternative) with an optional trailing newline.
* The shortest submission [in bytes](https://mothereff.in/byte-counter) wins.
**Example**
Here's a list of all inputs and sample outputs:
```
axe
PP.
SP.
S..
boat
P.P
PPP
...
bowl
P.P
.P.
...
button
P.
..
chest
PPP
P.P
PPP
crafting table
PP
PP
door
PP.
PP.
PP.
fence
PSP
PSP
...
gate
SPS
SPS
...
hoe
PP.
S..
S..
ladder
S.S
SSS
S.S
pickaxe
PPP
.S.
.S.
planks
W.
..
pressure plate
PP
..
shovel
P..
S..
S..
sign
PPP
PPP
.S.
slab
PPP
...
...
stairs
P..
PP.
PPP
stick
P.
P.
sword
P..
P..
S..
trapdoor
PPP
PPP
...
```
[Answer]
# CJam, ~~100~~ ~~96~~ ~~94~~ 91 bytes
```
"+WcbKF AQH;_{GM8Lyf=_tmTn"141bDb3/l72b970%={Z"O>HVa=4a"98bZb+"P.SW"f=3/=}%N*
```
StackExchange mangles unprintables, so rather than copying and pasting [here is the permalink](http://cjam.aditsu.net/#code=%22%01%1E%2B%1AW%08c%1Fb%05KF%20AQ%08%16H%18%3B_%15%11%7B%1DGM8Lyf%3D_tmT%0Cn%22141bDb3%2Fl72b970%25%3D%7BZ%22O%1B%3EHVa%3D4a%2298bZb%2B%22P.SW%22f%3D3%2F%3D%7D%25N*&input=chest). Additionally, here's the [test program](http://cjam.aditsu.net/#code=%7Bl%3ALN%20%22%01%1E%2B%1AW%08c%1Fb%05KF%20AQ%08%16H%18%3B_%15%11%7B%1DGM8Lyf%3D_tmT%0Cn%22141bDb3%2FL72b970%25%3D%7BZ%22O%1B%3EHVa%3D4a%2298bZb%2B%22P.SW%22f%3D3%2F%3D%7D%25N*%20NN%7D21*&input=axe%0Aboat%0Abowl%0Abutton%0Achest%0Acrafting%20table%0Adoor%0Afence%0Agate%0Ahoe%0Aladder%0Apickaxe%0Aplanks%0Apressure%20plate%0Ashovel%0Asign%0Aslab%0Astairs%0Astick%0Asword%0Atrapdoor).
*(Thanks to @Optimizer for telling me about `f` and @MartinBüttner for telling me about CJam's modulo indexing.)*
Cygwin's `hexdump`:
```
0000000 0122 2b1e 571a 6308 621f 4b05 2046 5141
0000010 1608 1848 5f3b 1115 1d7b 4d47 4c38 6679
0000020 5f3d 6d74 0c54 226e 3431 6231 6244 2f33
0000030 376c 6232 3739 2530 7b3d 225a 1b4f 483e
0000040 6156 343d 2261 3839 5a62 2b62 5022 532e
0000050 2257 3d66 2f33 7d3d 4e25 002a
000005b
```
## Explanation
To construct the recipes, we use 13 different rows (also listed are explanations why this is minimal):
```
0 W.. (required by planks)
1 ... (required by many)
2 .PP (required by many)
3 PPP (required by chest)
4 .P. (required by bowl)
5 ..P (required by stairs)
6 S.S (required by ladder)
7 SSS (required by ladder)
8 .S. (required by sign)
9 .SP (required by axe)
10 P.P (required by bowl)
11 PSP (required by fence)
12 SPS (required by gate)
```
We encode the rows via `Z"O>HVa=4a"98bZb+"P.SW"f=3/`, [which gives](http://cjam.aditsu.net/#code=Z%22O%1B%3EHVa%3D4a%2298bZb%2B%22P.SW%22f%3D3%2Fp)
```
["W.." "..." ".PP" "PPP" ".P." "..P" "S.S" "SSS" ".S." ".SP" "P.P" "PSP" "SPS"]
```
The first bit `"+WcbKF AQH;_{GM8Lyf=_tmTn"141bDb3/` encodes the recipes, [giving](http://cjam.aditsu.net/#code=%22%01%1E%2B%1AW%08c%1Fb%05KF%20AQ%08%16H%18%3B_%15%11%7B%1DGM8Lyf%3D_tmT%0Cn%22141bDb3%2Fp)
```
[[3 3 8] [1 0 0] [1 0 0] [3 8 8] [1 3 3] [2 8 8] [6 7 6] [1 0 0] [1 10 3] [1 1 2] [2 2 2] [1 11 11] [1 1 4] [1 0 1] [1 10 4] [2 9 8] [3 10 3] [1 2 2] [4 8 8] [1 4 4] [1 1 3] [1 12 12] [4 4 8] [5 2 3]]
```
Note how the first entry is `[3 3 8]`, which is the recipe for `sign`.
`l72b970%=` reads in the input, then applies some magic to work out which recipe to take from the list. Even though we only have 21 recipes there are 24 in the list — the extra few spots correspond to the `[1 0 0]`s.
After reading the input, picking the recipe and converting the recipe to rows, we put in some newlines `N*` and auto-print.
---
# CJam, ~~89~~ ~~86~~ 83 bytes
```
'W"9=!%)S@*m:@DQzk?V$%qyR55AmVEpPNW}"132b3b"P.S"f=+3/3/l57b5342%24%(=N*
```
... it turns out that hardcoding all the outputs does a bit better in CJam. I'm pretty disappointed.
Once again we have some unprintables so here's the [permalink](http://cjam.aditsu.net/#code='W%22%029%3D!%10%25%29%1ES%40*%0Bm%3A%40D%18Qzk%3FV%24%25qyR%0655Am%04V%1AEpP%15N%16W%10%01%7D%22132b3b%22P.S%22f%3D%2B3%2F3%2Fl57b5342%2524%25%28%3DN*&input=chest) and [test program](http://cjam.aditsu.net/#code=%7Bl%3ALN%20'W%22%029%3D!%10%25%29%1ES%40*%0Bm%3A%40D%18Qzk%3FV%24%25qyR%0655Am%04V%1AEpP%15N%16W%10%01%7D%22132b3b%22P.S%22f%3D%2B3%2F3%2FL57b5342%2524%25%28%3DN*%20NN%7D21*&input=axe%0Aboat%0Abowl%0Abutton%0Achest%0Acrafting%20table%0Adoor%0Afence%0Agate%0Ahoe%0Aladder%0Apickaxe%0Aplanks%0Apressure%20plate%0Ashovel%0Asign%0Aslab%0Astairs%0Astick%0Asword%0Atrapdoor).
Cygwin's `hexdump`:
```
0000000 5727 0222 3d39 1021 2925 531e 2a40 6d0b
0000010 403a 1844 7a51 3f6b 2456 7125 5279 3506
0000020 4135 046d 1a56 7045 1550 164e 1057 7d01
0000030 3122 3233 3362 2262 2e50 2253 3d66 332b
0000040 332f 6c2f 3735 3562 3433 2532 3432 2825
0000050 4e3d 002a
0000053
```
## Explanation
The outputs are encoded using base 3, with the lone `W` being tacked onto the front before the string is split into 3s to give rows, and the rows are split into groups of 3s to give recipes.
Like above, base converting and modulo magic is used to select the recipe. There are 22 recipes (one unused) but we need to take modulo 24, so we actually need to explicitly specify `24%` this time rather than relying on modulo indexing.
[Answer]
# JavaScript (ES6), 235 ~~241 262~~
**Edit** Abusing even more of the rule that input is always valid: there is just 1 item that requires W, and that can be special cased. So the output grid is encoded as 9 digit base 3 numbers.
235 bytes with I/O via popup.
```
w=prompt();
"926a722boa182bo2b19520ch224c6056d644f448g764h7651l2294pi8pr758sh2915si26sl19172sta56st785s728t"
.replace(/(\d+)(\D+)/g,(c,p,m)=>w.search(m+z)||[for(c of'11\n11\n111')z+='.SP'[~~p%3]+(p/=3,-c?'':c)],z='');
alert(&&z||'W.\n..')
```
221 bytes as a testable function.
```
F=w=>"926a722boa182bo2b19520ch224c6056d644f448g764h7651l2294pi8pr758sh2915si26sl19172sta56st785s728t"
.replace(/(\d+)(\D+)/g,(c,p,m)=>w.search(m+z)||[for(c of'11\n11\n111')z+='.SP'[~~p%3]+(p/=3,-c?'':c)],z='')&&z||'W.\n..'
```
Output always as 3x3 grid. With 4 available output symobols, the grid is encoded as a 3x3x2 (18) bit number. And as the input have to be always valid, the string are stored truncated to the bare minimum.
**Test** In Firefox/FireBug console
```
;["axe", "boat", "bowl", "button", "chest", "crafting table", "door",
"fence", "gate", "hoe", "ladder", "pickaxe", "planks", "pressure plate",
"shovel", "sign", "slab", "stairs", "stick", "sword", "trapdoor"]
.forEach(v=>console.log(v+'\n'+F(v)))
```
*Output*
```
axe
PP.
SP.
S..
boat
P.P
PPP
...
bowl
P.P
.P.
...
button
P..
...
...
chest
PPP
P.P
PPP
crafting table
PP.
PP.
...
door
PP.
PP.
PP.
fence
PSP
PSP
...
gate
SPS
SPS
...
hoe
PP.
S..
S..
ladder
S.S
SSS
S.S
pickaxe
PPP
.S.
.S.
planks
W.
..
pressure plate
PP.
...
...
shovel
P..
S..
S..
sign
PPP
PPP
.S.
slab
PPP
...
...
stairs
P..
PP.
PPP
stick
P..
P..
...
sword
P..
P..
S..
trapdoor
PPP
PPP
...
```
[Answer]
# Python, 305 bytes
```
n=2**(23-hash(raw_input())/535366%24);print "W..\n...\n..." if n==1024 else "\n".join(["".join(['P' if [16706041,9740732,7635081,7399784,5267501,7372808,57344,57344,49152][j+i*3]&n==n else 'S' if [6,2097152,6,131078,10748162,6,131138,9699584,2][j+i*3]&n==n else '.' for j in range(3)]) for i in range(3)])
```
## Explanation
```
# Compute a unique number for each item.
# 535366 and 24 are precalculated values that were bruteforced.
n = 23 - hash(raw_input()) / 535366 % 24
# Use precalculated tables that represent which ingredient in this recipe of
# an item. The nth bit of p[0] will be set if the first ingredient of the item
# associated with the unique number n is some planks. It works the same for s.
p = [16706041,9740732,7635081,7399784,5267501,7372808,57344,57344,49152]
s = [6,2097152,6,131078,10748162,6,131138,9699584,2]
# Handle planks differently, as it is the only one using wood.
if n == 10:
print "W..\n...\n..."
else:
for i in xrange(3):
line = ""
for j in xrange(3):
# Now we can check if the ingredient is some planks...
if p[j + i * 3] & 1 << n == 1 << n:
line += 'P'
# ...or if it is some sticks...
elif s[j + i * 3] & 1 << n == 1 << n:
line += 'S'
# ...or if it is simply empty.
else:
line += '.'
print line
```
## Comment
This code surely isn't the tiniest but it works just fine. I'm satisfied. :)
# Python, 282 bytes
```
n=hash(raw_input())/808789215%21;print "\n".join(["P.PPPP...P..S..S..PP.......PP.PP....P........SPSSPS...PPPPPP.S.PP.PS..S.W........PPPPPP...PP..S..S.P..PP.PPPS.SSSSS.SPPP.S..S.PPP......P..P..S..PPPP.PPPPPSPPSP...PP.PP.PP.P..P.....P.P.P...."[9*n+i*3:9*n+(i+1)*3] for i in range(3)])
```
Using the same technique to generate an unique identifier but directly looking up the recipe in an array. It is a lot simpler and a little more compact than my first code.
] |
[Question]
[
**Story**
Long time ago Bobby created a Bitcoin wallet with 1 Satoshi (1e-8 BTC, smallest currency unit) and forgot about it. Like many others he later though "Damn, if only I invested more back then...".
Not stopping at daydreaming, he dedicates all of his time and money to building a time machine. He spends most of his time in his garage, unaware of worldly affairs and rumors circulating about him. He completes the prototype a day before his electricity is about to be turned off due to missed payments. Looking up from his workbench he sees a police van pulling up to his house, looks like the nosy neighbours thought he is running a meth lab in his garage and called the cops.
With no time to run tests he grabs a USB-stick with the exchange rate data of the past years, connects the Flux Capacitor to the Quantum Discombobulator and finds himself transported back to the day when he created his wallet
**Task**
Given the exchange rate data, find out how much money Bobby can make. He follows a very simple rule: "Buy low - sell high" and since he starts out with an infinitesimally small capital, we assume that his actions will have no impact on the exchange rates from the future.
**Input**
A list of floats > 0, either as a string separated by a single character (newline, tab, space, semicolon, whatever you prefer) passed as command line argument to the program, read from a textfile or STDIN or passed as a parameter to a function. You can use numerical datatypes or arrays instead of a string because its basically just a string with brackets.
**Output**
The factor by which Bobbys capital multiplied by the end of trading.
**Example**
```
Input: 0.48 0.4 0.24 0.39 0.74 1.31 1.71 2.1 2.24 2.07 2.41
```
Exchange rate: 0.48 $/BTC, since it is about to drop we sell all Bitcoins for 4.8 nanodollar. Factor = 1
Exchange rate: 0.4, do nothing
Exchange rate: 0.24 $/BTC and rising: convert all $ to 2 Satoshis. Factor = 1 (the dollar value is still unchanged)
Exchange rate: 0.39 - 2.1 $/BTC: do nothing
Exchange rate: 2.24 $/BTC: sell everything before the drop. 44.8 nanodollar, factor = 9.33
Exchange rate: 2.07 $/BTC: buy 2.164 Satoshis, factor = 9.33
Exchange rate: 2.41 $/BTC: buy 52.15 nanodollar, factor = **10.86**
```
Output: 10.86
```
**Additional Details**
You may ignore weird edge cases such as constant input, zero- or negative values, only one input number, etc.
Feel free to generate your own random numbers for testing or using actual stock charts. [Here](http://pastebin.com/8VYsEm4W) is a longer input for testing (Expected output approx. 321903884.638)
Briefly explain what your code does
Graphs are appreciated but not necessary
[Answer]
# APL, 16 chars
```
{×/1⌈÷/⊃⍵,¨¯1⌽⍵}
```
This version uses **@Frxstrem**'s simpler algorithm and **@xnor**'s `max(r,1)` idea.
It also assumes that the series is overall rising, that is, the first bitcoin value is smaller than the last one. This is consistent with the problem description. To get a more general formula, the first couple of rates must be dropped, adding 2 chars: `{×/1⌈÷/⊃1↓⍵,¨¯1⌽⍵}`
**Example:**
```
{×/1⌈÷/⊃⍵,¨¯1⌽⍵} 0.48 0.4 0.24 0.39 0.74 1.31 1.71 2.1 2.24 2.07 2.41
10.86634461
{×/1⌈÷/⊃⍵,¨¯1⌽⍵} (the 1000 array from pastebin)
321903884.6
```
**Explanation:**
Start with the exchange rate data:
```
A←0.48 0.4 0.24 0.39 0.74 1.31 1.71 2.1 2.24 2.07 2.41
```
Pair each number with the preceding one (the first will be paired with the last) and put them into a matrix:
```
⎕←M←⊃A,¨¯1⌽A
0.48 2.41
0.4 0.48
0.24 0.4
0.39 0.24
0.74 0.39
1.31 0.74
1.71 1.31
2.1 1.71
2.24 2.1
2.07 2.24
2.41 2.07
```
Reduce each row by division, keep those with ratio > 1, and combine the ratios by multiplication. This will eliminate any repeating factors in a row of successive rising rates, as well as the spurious ratio between the first and last exchange rates:
```
×/1⌈÷/M
10.86634461
```
[Answer]
## Python, 47
```
f=lambda t:2>len(t)or max(t[1]/t[0],1)*f(t[1:])
```
[Example run on the test case](http://ideone.com/lBV09P).
Take a list of floats. Recursively multiplies on the profit factor from the first two elements until fewer than two elements remains. For the base case, gives `True` which equals `1`.
Using `pop` gives the same number of chars.
```
f=lambda t:2>len(t)or max(t[1]/t.pop(0),1)*f(t)
```
So does going from the end of the list.
```
f=lambda t:2>len(t)or max(t.pop()/t[-1],1)*f(t)
```
For comparison, my iterative code in Python 2 is 49 chars, 2 chars longer
```
p=c=-1
for x in input():p*=max(x/c,1);c=x
print-p
```
Starting with `c=-1` is a hack to make the imaginary first "move" never show a profit. Starting the product at `-1` rather than `1` lets us assign both elements together, and we negative it back for free before printing.
[Answer]
# Python, ~~79~~ ~~81~~ ~~76~~ 77 bytes
```
f=lambda x:reduce(float.__mul__,(a/b for a,b in zip(x[1:],x[:-1]) if a>b),1.)
```
`x` is the input encoded as a list. The function returns the factor.
[Answer]
# CJam, 33 bytes
```
q~{X1$3$-:X*0>{\;}*}*](g\2/{~//}/
```
This can be golfed further.
Takes input from STDIN, like
```
[0.48 0.4 0.24 0.39 0.74 1.31 1.71 2.1 2.24 2.07 2.41]
```
and outputs the factor to STDOUT, like
```
10.866344605475046
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18
```
u*GeS,1ceHhHC,QtQ1
```
Explanation:
```
u reduce, G is accumulator, H iterates over sequence
*G multiply G by
eS max(
,1 1,
ceHhH H[1]/H[0])
C H iterates over zip(
,QtQ Q,Q[1:])
1 G is initialized to 1
```
`max(H[1]/H[0],1)` idea thanks to @xnor
[Answer]
## C#, 333, 313
My first attempt. Could probably optimize it more but like I said first attempt so will get the hang of it!.
```
double a(double [] b){var c=0.0;var d=1;for(int i=0;i<b.Count();i++){c=(d==1)?(((i+1)<b.Count()&&b[i+1]<=b[i]&&d==1)?((c==0)?b[i]:b[i]*c):((i+1)>=b.Count()?(c*b[i])/b[0]:c)):((i+1)<b.Count()&&b[i+1]>b[i]&&d==0)?c/b[i]:c;d=((i+1)<b.Count()&&b[i+1]<b[i]&&d==1)?0:((i+1)<b.Count()&&b[i+1]>b[i]&&d==0)?1:d;}return c;}
```
Input
```
0.48, 0.4, 0.24, 0.39, 0.74, 1.31, 1.71, 2.1, 2.24, 2.07, 2.41
```
Output
```
10.86
```
Edit: Thanks to DenDenDo for suggesting not using math.floor to round and using int instead of bool to cut chars. Will remember that for future puzzles!
] |
[Question]
[
When stacking books you usually want to put the largest ones at the bottom and the smallest ones at the top. However, my latent OCD makes me feel very uneasy if I've got two books where one is shorter (in height) but wider than the other. No matter which order I place them in, the top book will extend beyond the bottom book on one side.
As an example, say one book has dimensions `(10,15)` and another has dimensions `(11,14)`. No matter which way around I put them, I get an overhang. But if I have books with dimensions `(4,3)` and `(5,6)`, I can avoid an overhanging by placing the latter below the former.
For the purposes of this challenge we will consider overhangs only in relation to the book *immediately below*. E.g. if I have a stack `(5,5)`, `(3,3)`, `(4,4)` (not that any sane person would do that), the top book counts as an overhang, although it does not extend beyond the bottom book. Similarly, the stack `(3,3)`, `(3,3)`, `(4,4)` also has only one overhang, despite the top book extending beyond the bottom one.
## The Challenge
Given a list of integer pairs for book dimensions, sort those pairs/books such that the number of overhangs is minimal. You must not rotate the books - I want all the spines facing the same direction. If there are multiple solutions with the same number of overhangs, you may choose any such order. Your sorting algorithm does not have to be stable. Your implementation may assume that book dimensions are less than 216 each.
**Time complexity:** To make this a bit more interesting, the asymptotic worst-case complexity of your algorithm must be polynomial in the size of the stack. So you can't just test every possible permutation. Please include a short proof of your algorithm's optimality and complexity and optionally a plot that shows the scaling for large random inputs. Of course, you can't use the maximum size of the input as argument that your code runs in O(1).
You may write a program or function, take input via STDIN, ARGV or function argument in any convenient (not preprocessed) list format and either print or return the result.
This is code golf, so the shortest answer (in bytes) wins.
I am confident that a polynomial-solution exists, but if you can prove me wrong, you may submit such a proof instead of a golfed submission. In this case, you may assume [P ≠ NP](http://en.wikipedia.org/wiki/P_versus_NP_problem). I will accept the first correct such proof and award a bounty to it.
## Examples
```
In: [[1, 1], [10, 10], [4, 5], [7, 5], [7, 7], [10, 10], [9, 8], [7, 5], [7, 5], [3, 1]]
Out: [[10, 10], [10, 10], [9, 8], [7, 7], [7, 5], [7, 5], [7, 5], [4, 5], [3, 1], [1, 1]]
In: [[4, 5], [5, 4], [5, 4], [5, 4], [5, 4], [4, 5], [4, 5], [4, 5], [5, 4], [4, 5]]
Out: [[4, 5], [4, 5], [4, 5], [4, 5], [4, 5], [5, 4], [5, 4], [5, 4], [5, 4], [5, 4]]
or [[5, 4], [5, 4], [5, 4], [5, 4], [5, 4], [4, 5], [4, 5], [4, 5], [4, 5], [4, 5]]
In: [[2, 3], [1, 1], [5, 5], [7, 1]]
Out: [[5, 5], [2, 3], [7, 1], [1, 1]]
or [[5, 5], [2, 3], [1, 1], [7, 1]]
or [[7, 1], [5, 5], [2, 3], [1, 1]]
or [[7, 1], [1, 1], [5, 5], [2, 3]]
```
I created these by hand, so let me know if you spot any mistakes.
[Answer]
## Python, 113
```
P=[]
for n in sorted(input())[::-1]:
for p in P:
if p[-1][1]>=n[1]:p+=[n];break
else:P+=[[n]]
print sum(P,[])
```
After sorting the list of books in descending order (by width first and then height), this partitions the books into piles without overlaps. To determine where to place each book, its height is compared with the height of the top book in each pile. It is placed on the first pile possible, or else a new pile is created.
I'm not very good with time complexity, but I believe it would have a worst case of *O*(*N2*). There are two loops, each with at most *N* iterations. I also use Python's builtin sort, which is *O*(*n* log *n*).
---
My first proof that this algorithm produces optimal solutions did turn out to be incorrect. A huge thanks goes to @xnor and @Sp3000 for a great discussion in the chat about proving this (which you can read [starting here](http://chat.stackexchange.com/transcript/message/18301055#18301055)). After working out a correct proof, @xnor found that part of it had already been done ([Dilworth's theorem](https://en.wikipedia.org/wiki/Dilworth%27s_theorem)).
Here's an overview of the proof anyway (credit to @xnor and @Sp3000).
First, we define the notion of an antipile, or antichain, ([quoted from @xnor](http://chat.stackexchange.com/transcript/message/18301726#18301726)):
>
> An antipile is a sequence of books of decreasing height, but increasing width
>
> So, each successive book is strictly taller but strictly less wide
>
> Note that any book in an antipile overhangs over any other book in an antipile
>
> So, no two books within an antipile can be in the same pile
>
> As a consequence, if you can find an antipile of x books, then those books must be in different piles
>
> So, the size of the largest antipile is a lower bound on the number of piles
>
>
>
Then, we sort the books in descending order by their width (first) and their height (second)\*.
For each book *B*, we do as follows:
1. If *B* can fit on the first pile, we place it there and move on.
2. Otherwise, we find the earliest\* pile *x* which *B* can be placed on top of. This can be a new pile if necessary.
3. Next, we link *B* to *P*, where *P* is the top book on the previous pile *x - 1*.
4. We now know that:
* *B* is strictly\* smaller in width than *P*, since the books are sorted in descending order by width
* *B* is strictly greater in height than *P*, or we would have placed *B* on top of *P*
Now, we have constructed a link from every book (except those in the first pile), to a book in the previous pile that is greater in width and lower in height.
@Sp3000's excellent diagram illustrates this well:

By following any path from the last pile (on the right), to the first pile (on the left), we get an antipile. Importantly, this antipile's length is equal to the number of piles. Hence, the number of piles used is minimal.
Finally, since we have organised the books into the minimum number of piles without overlaps, we can stack them on top of each other to get one pile with the minimum number of overlaps.
\* [this helpful comment](http://chat.stackexchange.com/transcript/message/18302420#18302420) explains a few things
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 30
```
FN_SQFbYIgeeYeb~b]NB)E~Y]]N;sY
```
This is a direct golf of grc's awesome algorithm. Here is the precise equivalent of the above pyth program, in its compiled python code.
```
Q = eval(input())
Y = []
for N in sorted(Q)[::-1]:
for b in Y:
if Y[-1][-1] >= b[-1]:
b += [N]
break
else:
Y += [[N]]
print(Psum(Y))
```
In this context, the `Psum(Y)` function is equivalent to the python `sum(Y,[])`.
Actual compiled and run code (from `pyth -d`):
```
Y=[]
Q=copy(eval(input()))
for N in neg(Psorted(Q)):
for b in Y:
if gte(end(end(Y)),end(b)):
b+=[N]
break
else:
Y+=[[N]]
Pprint("\n",Psum(Y))
```
] |
[Question]
[
# Background
[Boggle](https://en.wikipedia.org/wiki/Boggle) is a board game where the players have to find English words on a 4-by-4 board of random alphabets. Words can be constructed by selecting sequentially adjacent cells on the board. ("adjacent" means horizontally, vertically or diagonally adjacent.) Also, same cell can't be used more than once in a word.
The following is an example board:
```
I L A W
B N G E
I U A O
A S R L
```
On this board, `BINGO`, `ORANGE` and `WEARS` are valid words, but `SURGE` and `RUSSIA` are not:
* `SURGE` : There's no adjacent pair on the board having `RG`.
* `RUSSIA` : `S` cannot be used twice.
**Modified Boggle** is a modified version of Boggle, with the following rules:
* The board size is `n`-by-`n`, where `n` can be any positive integer.
* Each cell can contain any one byte between 0 and 255 inclusive.
* A cell can be used more than once, *but not twice in a row*.
Using the example board above, in addition to `BINGO`, `ORANGE` and `WEARS`, `LANGUAGE` becomes a valid string (since `G` is used twice, but not twice in a row) but `RUSSIA` is still not (due to `SS` pair).
Here is another example using a code fragment. The string `from itertools import*\n` can be found on the following board, but not `from itertoosl import*` or `from itertools import *`:
```
f i ' ' s
r t m l
e o o p
\n * t r
```
Note that you need two `o`'s in order to match the `oo` sequence.
# Challenge
Write a function or program that, given a Modified Boggle board `B` (of any size) and a string `s`, determines if `s` can be found on `B`.
# Restrictions
**Your code itself should also fit on a Modified Boggle board `b`.** That is, you must show the board `b` in your submission along with your code, so that your function/program outputs true if it is given `b` and your code as input.
# Scoring
**The score of your submission is the side length of the smallest board `b` where you can fit your code.** Ties are broken by the usual [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules, i.e. the length of your code in bytes. The submission with the **lowest score** (for both criteria) wins.
For example, `from itertools import*\n` has the score of 4 (using the board above) and code length of 23 bytes.
# Input and Output
For input, you can take any convenient method for both `B` and `s`. This includes list of chars and list of charcodes, 2D or flattened or whatever makes sense. Also, you can optionally take the board size as a part of the input.
For output, you can choose one of the following:
* Truthy and falsy values following your language's convention, or
* One predefined value for true and false respectively.
Please specify your input/output method in your submission.
[Answer]
# Python 2, score 3, 20972 bytes
```
exec'cecxc%c'%(1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1)+…
```
Full code is the output of: [Try it online!](https://tio.run/##XVLBbtswDD3HX8FpCCTNnpH0GMQFvGEoCmQdMKPYIfNBU9RUmyMLthsk@/mMpGtgqQ8SST@Sj4@K5@G5DTcX2@4cFCCE@Hmxzp5sYcI5sRnahQ/xZVA6sSd0GheURduxYw6/dmaGcATSQfgVmetCyrajP1sM1VtbFwXFt4v6drHmDoprqCl5u1zVGTrknhCgn8b8k515bPlR2duFpg6pSpepXRMbPYHcCHIEcyPQMZkR7Ca4f1L/t3hXKEZpGs4WnQl7pxiZxM6HYXZF9LUmZ0/8HNMjCrORipt8fUEx864fOh9RvOQ9fEaN9y4AAsGAfTadsYPr8mSPyo9Sgl2BkHMr50pACjKV@e8WJ5NL@aHtdqi8xrDQgup9NX8cFgrGHx30bfMy@DbkeZ5UtEnifFXjYKLaZ7RozXTKGJsz5h0ctHHwB//XUIE@T4jgEXzAXBYP6ALWAnBCOqk6sIjAglKcw@wDxwE797Hx@HZWCeBHvKq8c7Ex1qk3xOCodUbD91LMjzq5BgtEkywCIXzzCMyiQoO3BfQ2q9fVQXXZyvtN@UNm8tPD3Re87h/Lb3iV1feNrDOQm/Lh7rHEX/8A "Python 2 – Try It Online")
Fits on the Boggle board:
```
e x (
c % 1
' + )
```
Decodes and executes this program:
```
cecxc=any
c,cec=input()
cxec=len(c)
cexec=lambda cxc,cexc,c,cec:cexc<=''or cxc[cec][c]==cexc[0]>0<cecxc(cexec(cxc,cexc[1:],cxcxc,cxcec)for cxcxc in(c-(c>0),c,c+(+1+c<cxec))for cxcec in(cec-(cec>0),cec,cec+(+1+cec<cxec))if(cxcxc,cxcec)!=(c,cec))
cxc=range(cxec)
print cecxc(cexec(c,cec,cexc,cxec)for cexc in cxc for cxec in cxc)
```
Which takes input like: `['ILAW','BNGE','IUAO','ASRL'], 'LANGUAGE'`
[Answer]
# [CJam](https://sourceforge.net/p/cjam), score 2, 9351 bytes
```
'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~)))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))'))))))))~))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))~'))))))))))))))))))')))))))))))))))))))))))))))))))))))))))))))))))))))))))))))')))'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))~'))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))~
```
[Try it online!](https://tio.run/##7VmxCgMhDN37FcVF7jNSOORArtBydCgdSrdCf8FftzcUOisx9@LFxcnkvZgXo77ez0/OfviNNAiObby2wdGQS51pWFIsRiFSRwYEeHYq3FYdEYUJKCvV5sVMrDL0U4Lgzq4tXCgRNIQc8diY6jGZIKpKjdJ5PQhlLtCdoXRVJ4qAlASoCxMF6IFX43a3JxpqFyOYO5WuQJppNhx4Txv23IeNg5sVSJQKYSh5ZO02/lph2x5qLC96vztbIscNrfwPqN16rDeyTmknnVLRSJ7L0n@tb0MwabOb891N8Ubu6E5zGNdpWui8TnS9RPc4RJrDQmH8Ag "CJam – Try It Online") Expects input like:
```
["ILWA" "BNGE" "IUAO" "ASRL"]
LANGUAGE
```
and fits on the Boggle board:
```
' )
~ )
```
Constructs the string `l~:Q,:K;{\:Y;\:X;:C,!_{;QY=X=C0==_{;[X(XX)]K,&[Y(YY)]K,&m*[XY]a-C1>:D;{~DF}%:|}&}|}:F;l:R;K,2m*{~RF}%:|~` then evaluates it as CJam code.
[Answer]
# [Clean](http://clean.cs.ru.nl), score 12 (175 bytes)
(This is almost certainly going to be outgolfed by an esolang and probably normal languages as well.)
```
import StdEnv;>[]_ _ _ _=True;>[c:s]i j n a=i<n&&j<n&&i>=0&&j>=0&&a.[i,j]==c&&or[>s k l n a\\k<-[i-1..i+1],l<-[j-1..j+1]|i<>k||j<>l];$n c a=or[>c i j n a\\i<-[0..n],j<-[0..n]]
```
This defines a function `$ :: Int [Char] {#String} -> Bool` which checks whether the second argument (the word) can be found in the third argument (the board) given the first argument as width.
In the board on which this fits (see below), `*` marks unused places. There are 16 of those, on a board of size 12×12 = 144, meaning 128 are used effectively (an **efficiency** of **175/128 ≈ 1.37**). It may be possible to get the same program on 11×11, but this is all done by hand and very tedious; my boss probably wouldn't be happy if I would try to get it on 11×11.
```
* * & & * * * * * * * ;
s [ n < j * * u r T > v
> r & i > * e = [ n
l k o & 0 = n ; _ ] E
& a . = ] a j i > [ d
a n & c [ j . + ] s c t
\ k < - i , - . 1 | : S
\ * 1 l . + 1 = i j |
[ i \ . , ] o a < > k t
0 - < \ a r > l ] r
. j , * n j [ i c $ ; o
. n ] ] * * n i m p
```
[Try it online (with the program itself as input)!](https://tio.run/##tZHBjtsgEIbP9VOMspEjEZuNe1wbn7qHSr0lNxutWEyzYAxZIJFWdV@9LiG7PfVWFaTRzKcZ4P/hWjCzTHY4awETk2aR08m6APswPJpL3Xb0CdImB3cWseYPnkpQYIAR2Zg8V9cgW7KLaYoMd7JQlBCe59Z1rYcR9LW/78em7GRZYSy3FS10rNS1UrGaZdOO86yaVtN6bYDH86/THN5v63sZ@3cYG1qoj4wu@8DicwmsofoMJ2ePjk3wbJkbsuz@Hg4vAjybBHA7CGAe2LO9iOyjkUC3@a@K/1Xz31Vv6B9xSWoNxgYB4YUF6MGJ17N0woPwnJ2kORbgLcgAgxXebAJoa8folQjhLUvz0Ycfd9mnFUJ5jm6rXhUR@M40CqGzO7SXBKB1UToS0TiTgB5tviMG6if6eOuIdhDKlGy7IQFmct4pvKWehwSSJ7IocTU/7N8JqjTeVkSqGRLpZN/jgloWHbpN7cqm7xm4FjR1iWBVIKM6yde1vYFoDUIAJn7p6me2/OLfNTv6pfz6bfnyZtgkuf8N "Clean – Try It Online")
[Answer]
# Java, score 23, ~~538~~ 507 bytes
NSFW
```
import java.util.function.*;import java.util.stream.*;class B{static BiFunction<char[][],String,BiFunction<Integer,Integer,Byte>>f;{f=(b,s)->(i,j)->{try{if(b[i][j]!=s.charAt(0))return 0;}catch(Exception e){return 0;}if(s.length()<2)return 1;byte t=0;for(int k=9;k-->1;){t|=f.apply(b,s.substring(1)).apply(i+~k%3+1,j+~(k/3)%3+1);}return t;};BiFunction<char[][],String,Byte>g=(b,s)->{int l=b.length;return (byte)IntStream.range(0,l*l).map(i->f.apply(b,s).apply(i%l,i/l)).reduce((x,y)->x+y-x*y).getAsInt();};}}
```
[Try it online!](https://tio.run/##tVLBjtsgEL3vV9CVVoYEs0n3VLG2tJZaqeccrRywgx1sQiwYb2NR76@nOOtkV6rUW5HQAE/z3pthGvEq4mbXns/q0B0toCY8sB6UZlVvSlBHwxb8L8yBleIQkFIL51DmHQhQJcrUjznrudwLm2/zLd2AVaamn6CfBmQtLb3GbACZphX3VYIL6kicYkWbEDzYwasKF7na5s32S@LYRPsCeEWIldBbg1Z8LAWUe/z9VMpu4keS@A8wpDumpalhj8nz12vamhdBFUGy4tXRYmUAtck33sZxuubEw@@kYqLr9DA5Yq4v3KUMvCZkflfLt/bhabmmzfINt49PZLoQPs4CwEf@r3ZMNdfXev2kr5NiNspnDjx5JKFNm/d@W2FqiVdULzRhB9FhFaefbN6cPWiqHnVwauWuLyXGJzoEldNyiE@LgbBawosLtDjY5Wc0r83gQB7YsQfWBY@gDa5nRiN/oWsF3kcuopEIW0Yj9VERTibs9nIrw6m84ONI0b0zopX3hPC7/ysTxvCmMt5dQtcXOszkPJqvR7VDB6EMfv@BfIuErR1B/uYsQwVK0GQiwzeq8fwH "Java (JDK 10) – Don't Try It Online")
Compiled with JDK 9, but should work with 8.
I didn't know what to do with the imports and static field (which is in fact necessary), so I decided to just take the whole class and stick the lambdas in a initializer.
The lambda `g` can then be applied on a 2D array and a string, and returns `1` if the string is in the board and `0` if not (as a `Byte`, 3 characters shorter than `Integer`).
Credit to [this](https://codegolf.stackexchange.com/a/164762) guy for a (in my case) shorter than hardcoding way to address neighbouring cells.
Somewhere in the progress of making this monstrosity I got invested in making it work with lambdas it got progressively worse and worse until this happened. It doesn't even get close to the other answers and it is probably not even close to the optimal solution in Java, but hey, it fits pretty neatly on a 23x23 board (which is not optimal, but perhaps closer than the program itself):
```
duce((x,y)->x+y-x*y).ge
e l=b.length;return (bt
rt3+1,j+~(k/3)%3+1);}yA
.n%te t=0;for(int k=rts
)iky0;}catchExcepti9e)I
){~b (b,s)->(i,j)-o;tIn
l>+;n=ring,iFunct>nkunt
/-i1rftass B{stai{ -rt(
i)( u{Slport jatote-nS)
,synt;,cmutil.vinr)> t;
l,lref];i.porfac<y{1tr}
%bpur>[*;amitu. I{r;}e;
i(pt)>].*vaj nuBnie);a}
y=ae)e[m.noitctitft{Bm}
lg.r0traerts.liFe(uti.}
p>))(yhc<noitcnugbr|Fr
pe12tB,regetnI,re[n=ua
at(<Arahc.s=!]j[]i fng
.yg)(htgnel.s(fi};0.ce
)Bnirtsbus.s,b(ylppat(
s,gnirtS,][][rahc<noi0
,b(ylppa.f>-i(pm.)l*l,
```
Of course, at that point there was no point in trying to make that by hand. So as a bonus, here's the (naive) function I used to compress the code onto the board:
```
static char[][] toBoggleBoard(String s, int n) {
char[][] board = new char[n][n];
int i = n / 2;
int j = i;
int[] d = {1, 0};
s = s + s.charAt(s.length() - 1); //the last char gets eaten don't ask me why PS editing loop condition does make it work but causes a StringIndexOutOfBoundsException
board[i][j] = s.charAt(0);
s = s.substring(1);
while (s.length() > 0)
{
int[] ra = add(d, right(d));
int[] r = right(d);
int[] l = left(d);
if (board[i + d[0]][j + d[1]] > 0)
{
if (board[i + d[0]][j + d[1]] == s.charAt(0))
{
i += d[0];
j += d[1];
s = s.substring(1);
}
else
{
i += l[0];
j += l[1];
board[i][j] = s.charAt(0);
s = s.substring(1);
}
}
else if (board[i + ra[0]][j + ra[1]] == s.charAt(0))
{
i += ra[0];
j += ra[1];
s = s.substring(1);
}
else if (board[i + r[0]][j + r[1]] > 0)
{
i += d[0];
j += d[1];
board[i][j] = s.charAt(0);
s = s.substring(1);
}
else
{
int[] rb = sub(r, d);
d = r;
if (board[i + rb[0]][j + rb[1]] > 0)
{
continue;
}
else
{
i += d[0];
j += d[1];
board[i][j] = s.charAt(0);
s = s.substring(1);
}
}
}
for (int k = 0; k < board.length; ++k)
{
for (int l = 0; l < board.length; ++l)
{
if (board[k][l] == 0)
{
board[k][l] = ' ';
}
}
}
return board;
}
static int[] left(int[] d) {
return new int[]{-d[1], d[0]};
}
static int[] right(int[] d) {
return new int[]{d[1], -d[0]};
}
static int[] add(int[] x, int[] y) {
return new int[]{x[0] + y[0], x[1] + y[1]};
}
static int[] sub(int[] x, int[] y) {
return new int[]{x[0] - y[0], x[1] - y[1]};
}
```
It maps it's input onto a spiralthe snaking implementation didn't work, leaving characters out if possible. It's rather simple so could probably be improved and I forgot to add checking for characters in the backwards-right direction(update: I added it an it produced incorrect results), so I could probably shave off one or two characters but I doubt it's getting on a 22x22.
Edit:
Removed 6 spaces in places they didn't need to be.
Saved 13 bytes by replacing a check on array indices with a try-catch.
Shaved off 12 bytes by moving the board size into an `int`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2316 bytes, score 3
```
1111111111111111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111,11111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111,11111111111111111111111111111111111111111111111,111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111,1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111D§ịØJv
```
[Try it online!](https://tio.run/##y0rNyan8/98QP9AxHJ5AZ5g4S2dweE5nNI0MP3fpDBG/64wm1mHhT52h4jSd0VAdZk5yObT84e7uwzO8yv4fbj866eHOGf//R0erp2UqFKvrKKgXleTmgOjU/PwCEB2Tp1VSpB4LZKUV5ecqZJakFpXk5@cUK2TmFuQXlWipxwIA "Jelly – Try It Online")
Board:
```
1,v
D1J
§ịØ
```
Note: this is a (somewhat) trivial solution. Credit to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn) for the [idea](https://codegolf.stackexchange.com/a/165171/41024).
Returns a non-empty list if `s` can be found in `B`, and an empty list if not. The added footer helps clarifying that.
] |
[Question]
[
Consider an array of bits, say
```
1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
```
We call a contiguous subarray of length ≥ 5 a **phase** if at least 85% of the bits are the same and the first/last bits are both equal to the majority bit. Furthermore, we call a phase **maximal** if it is not a strict subarray of some other phase.
Here are the maximal phases of the above example:
```
1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
-------------
-------------
-------------
```
As you can see, there are `3` maximal phases. On the other hand, this
```
1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
---------
```
is not a maximal phase as it is a strict subarray of at least one other phase.
## The challenge
Input is a sequence of ≥ 5 bits via STDIN, command line or function argument. The bits may come in as a string or an array.
You are to output a single integer, the number of maximal phases for the array, either printed via STDOUT or returned from a function.
## Scoring
This is code-golf so the program in the fewest bytes wins.
## Test cases
```
0 1 0 1 0 -> 0
0 0 0 0 0 -> 1
0 0 0 0 1 0 1 1 1 1 -> 0
0 0 0 0 0 1 0 1 1 1 1 1 -> 2
1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 -> 1
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 -> 2
0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 -> 1
0 1 0 1 0 0 1 0 1 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 0 -> 0
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 0 0 1 0 0 0 0 0 0 0 0 1 1 0 1 -> 4
0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 -> 5
```
Here's the explanation for the last case:
```
0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0
---------------------------
-------------------------
-----------------
-----------------
-------------
```
Fun fact: This challenge came about from a data mining problem with the goal of detecting change in temporal data.
[Answer]
## Python 2, 149 bytes
```
a=input()
l=len(a)
n=p=0
for i in range(l):
for j in range(l-1,i+3,-1):
if(j>p)>(.15<sum(a[i:j+1])/(j+1.-i)+a[i]+a[j]<2.85):n+=1;p=j;break
print n
```
The first loop scans across the array from left to right. Each bit, indexed by `i`, is checked to see if it could be the first bit in a maximal phase.
This is done by the inner loop, which scans from right to left. If the subarray between `i` and `j` is a phase, we increase the counter and move on. Otherwise, we keep going until the subarray becomes too small *or* `j` reaches the end of the previous maximal phase.
```
1 1 1 0 0 0 0 1 0 0 1 0 1 1 1 1 1 0 1 0
i -> <- j
```
Example:
```
$ python phase.py
[1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0]
3
```
[Answer]
# Python 2, 144
Enter input in the form `[0,1,0,1,0]`.
```
a=input()
o=[2];i=-1
while a[i:]:
j=len(a);i+=1
while j>i+4:o+=sum(j>max(o)>x==a[i]==a[j-1]for x in a[i:j])*20/(j-i)/17*[j];j-=1
print~-len(o)
```
Subsequences are checked with ordering by increasing initial element, then decreasing length. In this way, it is known that a new subsequence is not a subsequence of a previous subsequence iff the index of its last element is greater than any index of a previously found sequence's last element.
[Answer]
# Dyalog APL, 62 characters
[`{≢∪0~⍨+/∨⍀∨\⌽∘.{((⊃=⊃∘⌽)∧(.85≤(+/⊢=⊃)÷≢)∧5≤≢)(⍺-1)↓⍵↑a}⍨⍳⍴a←⍵}`](http://tryapl.org/?a=%7B%u2262%u222A0%7E%u2368+/%u2228%u2340%u2228%5C%u233D%u2218.%7B%28%28%u2283%3D%u2283%u2218%u233D%29%u2227%28.85%u2264%28+/%u22A2%3D%u2283%29%F7%u2262%29%u22275%u2264%u2262%29%28%u237A-1%29%u2193%u2375%u2191a%7D%u2368%u2373%u2374a%u2190%u2375%7D%A8%280%201%200%201%200%29%280%200%200%200%200%29%280%200%200%200%201%200%201%201%201%201%29%280%200%200%200%200%201%200%201%201%201%201%201%29%281%200%200%200%200%200%200%200%200%200%200%200%200%201%200%29%280%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%29%280%200%200%200%200%201%200%200%200%200%200%201%200%200%200%200%200%201%200%200%29%280%201%200%201%200%200%201%200%201%200%201%200%200%200%201%201%201%201%200%201%200%200%201%201%200%200%200%201%201%200%29%281%201%201%201%201%200%200%200%200%200%201%201%201%201%201%200%200%201%200%200%200%200%200%200%200%200%201%201%200%201%29%280%201%201%200%200%200%200%200%200%200%200%200%200%200%201%200%201%201%201%201%201%201%201%200%201%200%200%200%200%200%29&run)
Similar to Zgarb's solution but golfed a little further.
[Answer]
# Dyalog APL, 86 bytes\*
```
{+/∨/¨∪↓∨⍀∨\{⊃({(.5>|k-⍵)∧.35≤|.5-⍵}(+/÷⍴)⍵)∧(5≤⍴⍵)∧(⊃⌽⍵)=k←⊃⍵}¨⌽∘.{(⍺-1)↓⍵↑t}⍨⍳⍴t←⍵}
```
[Try it here.](http://tryapl.org/) Usage:
```
f ← {+/∨/¨∪↓∨⍀∨\{⊃({(.5>|k-⍵)∧.35≤|.5-⍵}(+/÷⍴)⍵)∧(5≤⍴⍵)∧(⊃⌽⍵)=k←⊃⍵}¨⌽∘.{(⍺-1)↓⍵↑t}⍨⍳⍴t←⍵}
f 0 0 0 0 0 1 0 1 1 1 1 1
2
```
This can probably be golfed quite a bit, especially the middle part, where the phase condition is checked.
### Explanation
I first collect the substrings of the input vector into a matrix, where the upper left corner contains the whole input, using `⌽∘.{(⍺-1)↓⍵↑t}⍨⍳⍴t←⍵`. For the input `0 0 0 0 0 1 0`, this matrix is
```
┌───────────────┬─────────────┬───────────┬─────────┬───────┬─────┬───┬─┐
│1 0 0 0 0 0 1 0│1 0 0 0 0 0 1│1 0 0 0 0 0│1 0 0 0 0│1 0 0 0│1 0 0│1 0│1│
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│0 0 0 0 0 1 0 │0 0 0 0 0 1 │0 0 0 0 0 │0 0 0 0 │0 0 0 │0 0 │0 │ │
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│0 0 0 0 1 0 │0 0 0 0 1 │0 0 0 0 │0 0 0 │0 0 │0 │ │ │
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│0 0 0 1 0 │0 0 0 1 │0 0 0 │0 0 │0 │ │ │ │
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│0 0 1 0 │0 0 1 │0 0 │0 │ │ │ │ │
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│0 1 0 │0 1 │0 │ │ │ │ │ │
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│1 0 │1 │ │ │ │ │ │ │
├───────────────┼─────────────┼───────────┼─────────┼───────┼─────┼───┼─┤
│0 │ │ │ │ │ │ │ │
└───────────────┴─────────────┴───────────┴─────────┴───────┴─────┴───┴─┘
```
Then I map the condition of being a phase over it, resulting in the 0-1-matrix
```
0 0 0 0 0 0 0 0
1 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
```
To get the number of maximal phases, I flood the `1`'s to the right and down using `∨⍀∨\`,
```
0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
```
collect the unique rows with `∪↓`,
```
┌───────────────┬───────────────┐
│0 0 0 0 0 0 0 0│1 1 1 1 1 1 1 1│
└───────────────┴───────────────┘
```
and count those that contain at least one `1` using `+/∨/¨`.
\*There exists a standard 1-byte encoding for APL.
[Answer]
# Clojure, 302
```
(defn p[v l](if(or(<(count v)5)(= 0 l))nil(if((fn[v](let[f(first v)c(apply + v)o(count v)r(/ c o)t(+ f f r)](and(= f(last v))(or(> t 2.85)(< t 0.15)))))v)0(let[r(p(vec(drop-last v))(dec l))](if r(+ r 1)r)))))(defn s[v l c](if(empty? v)c(let[n(p v l)](if n(s(vec(rest v))n(inc c))(s(vec(rest v))l c)))))
```
and the slightly ungolfed version
```
(defn is-phase [vector]
(let [f (first vector)
c (apply + vector)
o (count vector)
r (/ c o)
t (+ f f r)]
(and (= f (last vector))
(or (> t 2.85) (< t 0.15)))))
(defn phase-index [vector last]
(if (or (<(count vector)5)(= 0 last)) nil
(if (is-phase vector) 0
(let [r (phase-index (vec(drop-last vector)) (dec last))]
(if r (+ r 1) r)))))
(defn phase-count [vector last count]
(if (empty? vector) count
(let [n (phase-index vector last)]
(if n (phase-count (vec(rest vector)) n (inc count))
(phase-count (vec(rest vector)) last count)))))
```
callable like this: `(s [0 1 0 1 0] 10 0)`.
It requires a few extra arguments, but I could get rid of those with an extra 20 characters.
[Answer]
# JavaScript (ES6) 141
@grc's algorithm ported to JavaScript
Input can be a string or an array
```
F=b=>
(l=>{
for(c=e=i=0;i<l;++i)
for(j=l;j>i+4&j>e;--j)
(k=0,[for(d of b.slice(i,j))k+=d==b[i]],k<(j-i)*.85)|b[i]-b[j-1]||(++c,e=j)
})(b.length)|c
```
**Test** In FireFox / FireBug console
```
;['01010', '00000', '0000101111',
'000001011111', '100000000000010',
'0000010000010000010', '00000100000100000100',
'010100101010001111010011000110',
'111110000011111001000000001101',
'011000000000001011111110100000'].forEach(t => console.log(t,F(t)))
```
*Output*
```
01010 0
00000 1
0000101111 0
000001011111 2
100000000000010 1
0000010000010000010 2
00000100000100000100 1
010100101010001111010011000110 0
111110000011111001000000001101 4
011000000000001011111110100000 5
```
[Answer]
# CJam, ~~110~~ 103 bytes
Pretttttty long. Can be golfed a lot.
```
q~_,,\f>{_,),5>\f<{:X)\0==X1b_X,.85*<!\.15X,*>!X0=!*\X0=*+&},:,W>U):U+}%{,(},_{{_W=IW=>\1bI1b>!&!},}fI,
```
Input is like
```
[0 1 1 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0]
```
Output is the number of phases.
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# JavaScript (ECMAScript 6), ~~148~~ 139 Bytes
```
f=(s,l=0,e=0,p=0)=>{for(n=s.length,o=[j=0,y=0],i=l;i<n;++j>4&x==s[l]&i>e&c>=.85*j&&(e=i,y=1))c=++o[x=s[i++]];return l-n?f(s,l+1,e,p+y):p}
```
Recurses through the array and starts iteration at the last recursion index. Argument can be either an array or string.
```
f('011000000000001011111110100000'); //5
```
[Answer]
# Wolfram - 131
```
{x_, X___}⊕{Y__, x_, y___}/;MemberQ[t={x, X, Y, x}, 1-x] && t~Count~x > .85 Length@t :=
1 + {X, Y, x}⊕{y}
{_, X___}⊕y_ := {X}⊕y
{}⊕{y_, Y__} := {y}⊕{Y}
_⊕_ := 0
```
Example
```
{}⊕{1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0}
> 3
{}⊕{0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,1,1,0,1,0,0,0,0,0}
> 5
```
[Answer]
## Java: 771 bytes
```
import java.util.*;public class A{static int[]a;static class b{int c,d,e,f,g,h;b(int i,int j){this.c=i;this.d=j;this.h=j-i+1;this.e=k();this.f=this.h-this.e;this.g=e>f?1:0;}
boolean l(b n){return this.c>=n.c&&this.d<=n.d;}
int k(){int o=0;for(int i=c;i<=d;i++){if(a[i]==1){o++;}}
return o;}
public boolean equals(Object o){b x=(b)o;return x.c==this.c&&x.d==this.d;}
float p(){if(g==0){return(float)f/h;}else{return(float)e/h;}}
boolean q(){float r=p();return a[c]==a[d]&&a[d]==g&&r>=0.85F;}}
static int s(int[]t){a=t;List<b>u=new ArrayList<>();for(int v=0;v<t.length-4;v++){int x=v+4;while(x<t.length){b y=new b(v,x);if(y.q()){u.add(y);}
x++;}}
List<b>a=new ArrayList<>();for(b c:u){for(b d:u){if(!c.equals(d)&&c.l(d)){a.add(c);break;}}}
u.removeAll(a);return u.size();}}
```
run by calling method s(int[] input)
] |
[Question]
[
Someone has been hastily stacking the Christmas presents, and it's quite a mess:
```
========================
| |
========================
=============
| |
| |
| |
| |
| |
| |
=============
=======
| |
| |
| |
=======
===================
| |
| |
| |
===================
=================
| |
| |
| |
| |
=================
=======
| |
| |
=======
```
Like, seriously, how does that top present even balance. It's probably a hammer. To prevent this tower of presents from crumbling, you're to reorder the presents so they stack nicely:
```
=======
| |
| |
=======
=======
| |
| |
| |
=======
=============
| |
| |
| |
| |
| |
| |
=============
=================
| |
| |
| |
| |
=================
===================
| |
| |
| |
===================
========================
| |
========================
```
## The Rules
* Each present consists of a top and bottom of `=` characters, and one or more middle rows, consisting of two `|` separated by spaces. The width of the present is the same in all its rows.
* There are no empty lines.
* Consecutive presents will overlap in at least one column.
* Presents are to be stacked in order of decreasing width. In the event of a tie, the taller present should go below the flatter present.
* Presents should be centred on the present beneath. If the present cannot be placed exactly in the centre (because the difference in widths is odd), you may choose either position that is half a character off the centre.
* You may or may not assume that the input has a single trailing newline, but please state your assumption.
* Your solution does not have to work for an empty input, but must be able to handle a single present.
* You may write a program or function, which takes input via STDIN or function argument and returns the result or prints it to STDOUT.
* This is code golf, so the shortest answer (in bytes) wins.
[Answer]
# CJam, ~~81~~ 70 bytes
```
'"qN/{__Sm0=#>}%N*"=
="/"=\"\"="*'"++~]$_W='=/,f{1$'=/,m4/\N/\f{S*\N}}
```
So we have to stack the Christmas presents? This code does it like an actual person would do\*.
**First**, we stack all the presents against a wall to easily move them up and down using this code:
```
'"qN/{__Sm0=#>}%N*
```
**then**, we identify each present as a separate item using this code:
```
"=
="/"=\"\"="*'"++~]
```
**then**, we sort the presents based on their heights and widths using this code:
```
$
```
*Till now*, all the gifts have been stacked against a wall in order to have perfect alignment with each other. But as this is Christmas, we want to place the gifts aligned centered like a Christmas tree! This code does that:
```
_W=Af{1$Am4/\N/\f{S*\N}}
```
Here is a step by step output of the code for example in the question:
```
"Step 1 - Stack the presents against a wall";
========================
| |
========================
=============
| |
| |
| |
| |
| |
| |
=============
=======
| |
| |
| |
=======
===================
| |
| |
| |
===================
=================
| |
| |
| |
| |
=================
=======
| |
| |
=======
"Step 2 - Identify the presents as a collection of presents";
["========================
| |
========================" "=============
| |
| |
| |
| |
| |
| |
=============" "=======
| |
| |
| |
=======" "===================
| |
| |
| |
===================" "=================
| |
| |
| |
| |
=================" "=======
| |
| |
======="]
"Step 3 - Sort on height & width, with presents stacked against a wall to help sort them";
=======
| |
| |
=======
=======
| |
| |
| |
=======
=============
| |
| |
| |
| |
| |
| |
=============
=================
| |
| |
| |
| |
=================
===================
| |
| |
| |
===================
========================
| |
========================
"Final step - stack them like a Christmas Tree";
=======
| |
| |
=======
=======
| |
| |
| |
=======
=============
| |
| |
| |
| |
| |
| |
=============
=================
| |
| |
| |
| |
=================
===================
| |
| |
| |
===================
========================
| |
========================
```
[Try it online here](http://cjam.aditsu.net/)
\* Might differ from person to person though :P
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 18 bytes
```
mx óÈíY b'=²Ãn c û
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.6&code=bXgg88jtWSBiJz2yw24gYyD7&input=WwoiICAgICAgICAgICA9PT09PT09PT09PT09PT09PT09PT09PT0iCiIgICAgICAgICAgIHwgICAgICAgICAgICAgICAgICAgICAgfCIKIiAgICAgICAgICAgPT09PT09PT09PT09PT09PT09PT09PT09IgoiICAgICA9PT09PT09PT09PT09IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICA9PT09PT09PT09PT09IgoiICAgICAgICA9PT09PT09IgoiICAgICAgICB8ICAgICB8IgoiICAgICAgICB8ICAgICB8IgoiICAgICAgICB8ICAgICB8IgoiICAgICAgICA9PT09PT09IgoiICA9PT09PT09PT09PT09PT09PT09IgoiICB8ICAgICAgICAgICAgICAgICB8IgoiICB8ICAgICAgICAgICAgICAgICB8IgoiICB8ICAgICAgICAgICAgICAgICB8IgoiICA9PT09PT09PT09PT09PT09PT09IgoiPT09PT09PT09PT09PT09PT0iCiJ8ICAgICAgICAgICAgICAgfCIKInwgICAgICAgICAgICAgICB8IgoifCAgICAgICAgICAgICAgIHwiCiJ8ICAgICAgICAgICAgICAgfCIKIj09PT09PT09PT09PT09PT09IgoiICAgPT09PT09PSIKIiAgIHwgICAgIHwiCiIgICB8ICAgICB8IgoiICAgPT09PT09PSIKXQotUg==)
I use a sufficiently different strategy from the other Japt answer that I thought it was worth its own answer. Takes input and output as an array of lines
Explanation:
```
mx #Trim leading whitespace from each line
ó Ã #Split the array between lines where:
ÈíY # The lines interleaved (e.g. "abc","def" => "adbecf")
b'=² # starts with "=="
n #Default sorting for "array of arrays of strings"
c #Flatten to a single array of lines
û #Pad each line so they are centered
```
I don't know precisely why "default sort" works like that, but I've [tested](https://ethproductions.github.io/japt/?v=1.4.6&code=bXgg88jtWSBiJz2yw24gYyD7&input=WwoiICAgICAgICAgICA9PT09PT09PT09PT09PT09PT09PT09PT0iCiIgICAgICAgICAgIHwgICAgICAgICAgICAgICAgICAgICAgfCIKIiAgICAgICAgICAgPT09PT09PT09PT09PT09PT09PT09PT09IgoiICAgICA9PT09PT09PT09PT09IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICB8ICAgICAgICAgICB8IgoiICAgICA9PT09PT09PT09PT09IgoiICAgICAgICA9PT09PT09IgoiICAgICAgICB8ICAgICB8IgoiICAgICAgICB8ICAgICB8IgoiICAgICAgICA9PT09PT09IgoiICA9PT09PT09PT09PT09PT09PT09IgoiICB8ICAgICAgICAgICAgICAgICB8IgoiICB8ICAgICAgICAgICAgICAgICB8IgoiICB8ICAgICAgICAgICAgICAgICB8IgoiICA9PT09PT09PT09PT09PT09PT09IgoiPT09PT09PT09PT09PT09PT0iCiJ8ICAgICAgICAgICAgICAgfCIKInwgICAgICAgICAgICAgICB8IgoifCAgICAgICAgICAgICAgIHwiCiJ8ICAgICAgICAgICAgICAgfCIKIj09PT09PT09PT09PT09PT09IgoiICAgPT09PT09PSIKIiAgIHwgICAgIHwiCiIgICB8ICAgICB8IgoiICAgfCAgICAgfCIKIiAgID09PT09PT0iCl0KLVI=) that the taller box of the two with the same width is on the bottom regardless of which comes first in the input.
[Answer]
# Ruby, 164
Neat challenge! Couldn't get it down much further.
```
f=->x{y=x.scan(/\s+=+[\s|]+\s+=+/).sort_by{|p|-p.count(?|)}.sort_by{|p|p.count ?=}
y.map{|p|p.gsub(/^\s+/,'').each_line{|l|puts l.strip.center(y[-1].count(?=)/2)}}}
```
### Explanation
The input `String` is chopped up into an `Array` where each present is an element. Then the array is sorted by the number of pipe characters and sorted *again* by the number of equal signs.
It then removes all leading whitespace and prints each line individually, centered by the width of the largest present.
It behaves the same with or without a trailing newline on the input.
### Readable version
```
f = lambda do |x|
y = x.scan(/\s+=+[\s|]+\s+=+/)
.sort_by { |p| -p.count("|") }
.sort_by { |p| p.count("=") }
y.map do |p|
p.gsub(/^\s+/,'').each_line do |l|
puts l.strip.center(y.last.count("=") / 2 )
end
end
end
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~23~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
|ðδÛ»…=
=…=0=:0¡{».c
```
-3 bytes thanks to *@ErikTheOutgolfer*.
[Try it online.](https://tio.run/##yy9OTMpM/f@/5vCGc1sOzz60@1HDMlsuWxBpYGtlcGhh9aHdesn//ysggC0OwIWkpkYBK6jhItocLEI1mCbRWAi7/9D5NWh@I8RH6Mfu@xqs4UaKKDZzMUVqMHSSJ4I1BpGYSP5HYkIVAAA)
**Explanation:**
```
| # Take the input split by newlines
ðδÛ # Remove leading spaces from each line
» # And join everything back together again with a newline delimiter
…=
= # Push string "=\n="
…=0= # Push string "=0="
: # Replace all "=\n=" with "=0="
0¡ # Now split on "0"
# (We now have our list of presents without any leading spaces)
{ # Sort this list (with default string-wise sorting)
» # Join the list of presents by newlines
.c # Left-focused centralize the string (and output implicitly)
```
**Notes:**
* Odd-width presents are left-focused centralized. This can be changed to right-focused by changing the trailing lowercase `c` to an uppercase `C`.
* The leading `|` can be dropped if we are allowed to take the input as a list of string-lines.
* Assumes the input contains no trailing spaces for any of the presents (similar as the input in the challenge description); trailing newlines are fine, since the `|` removes those anyway.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 91 bytes
```
Join&lf@{Center&#(_@-1@0)@>_}@{SortBy[&{#_'#__},Strip@>Lines=>Split[_,/"(?<==)\\s+(?==)"]]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@98rPzNPLSfNodo5Na8ktUhNWSPeQdfQwUDTwS6@1qE6OL@oxKkyWq1aOV5dOT6@Vie4pCizwMHOJzMvtdjWLrggJ7MkOl5HX0nD3sbWVjMmplhbwx7IUIqNrf0fUJSZVxKdFu2Yk@OZV1BaEh0bG/tfAQFscQAuJDU1ClhBDRfR5mARqsE0icZC2P2Hzq9B8xshPkI/dt/XYA03UkSxmYspUoOhkzwRrDGIxETyPxITqgAA "Attache – Try It Online")
## Ungolfed
```
?? returns [length of first entry, number of entries]
revDim := &{#_'#__}
?? regex
SPLIT_ON_BARRIERS := /"(?<==)\\s+(?==)"
splitPresents[str] := (
chopped .= Split[str, SPLIT_ON_BARRIERS];;
normalized .= Strip @> Lines => chopped
)
orderPresents[presents] :=
SortBy[revDim, presents]
fixPresents[ordered] := (
?? number of columns of bottom-most present
pad_size .= Size[Last[ordered][0]];;
?? center each line of each present
Center&pad_size @> _
)
joinNewlines := Join&lf
stackPresents := joinNewlines@fixPresents@orderPresents@splitPresents
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n0`, 123 bytes
```
sub k{pop=~y/=//}say s+^\s*+$"x((k($p[-1])- k$_)/4)+rmge for@p=sort{k($a)- k$b||$a=~y/|//-$b=~y/|//}/\s*(=+[|
]+\s*\=+)/gs
```
[Try it online!](https://tio.run/##tVHdCoIwGL33KUbsQhtrCnU56AV6ArVQMAnLDWeQ@NmjtywERRf9QOfqfGfnO3C@yaQ4rrRW5xhltRSSXyvGGWtUVCFFtoGaEzy72HZmY@lTL3QoyvDOYUuHFKc0QXtRrCVXoijr1hI9n2MAHD2CgDGK4441rA2zOfEBWSFpecCJw1KlNerBX8AaeAAZAdbHOQYJpkl/lsz9xjOMur2b@31zezDe7RvVlDtVYLL5m2L8wQEd9B/QznATsjyIXGm6WS1cz9U0d@8 "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~221~~ 196 bytes
```
s,a,b,i=[c.strip()for c in input().split("\n")]+["="],[],[],0
exec"a+=[s[i].center(max(map(len,s)))]\nif s[i][0]==s[i+1][0]=='=':b+=[a];a=[]\ni+=1;"*(len(s)-1)
for c in sorted(b):print"\n".join(c)
```
[Try it online!](https://tio.run/##vVHBTsQgEL3vVxAuy1hsth53M19COVBkI2alBDBZE/69tmoUXZqNHpwMycvLm5eZh39JD6O7m6bIFR@4RaHbmIL1DI5jIJpYN7d/Tgza6E82Mdo7CrIRFKnk4q13G3M2mqoGRRRWttq4ZAJ7Uuf5eXYyjkcAkL2zR7IoxE4izqDp3uEWt/thnlbyoFAsuga7A71ZRlmE2w42n9vEMSRzzwbY@2BdWtZpH0frmIZpouSrcKV6V4gyqVb@JrriVONyxew/uJVLL4j888zrROGxkkWu5/g7uupdofLl8J@p@s@WuEyjxB8a@go "Python 2 – Try It Online")
Expects a quoted string without trailing newlines as input.
Not great, but it's the best I can do.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~23~~ ~~20~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Similar approach to [Kevin's solution](https://codegolf.stackexchange.com/a/177734/58974). First byte can be removed if we can take input as an array of lines.
```
·mx ·r¥¬·È·Ãq, n ·û
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=t214ILdypay3yLfDcSwgbiC3%2bw&input=IiAgICAgICAgICAgPT09PT09PT09PT09PT09PT09PT09PT09CiAgICAgICAgICAgfCAgICAgICAgICAgICAgICAgICAgICB8CiAgICAgICAgICAgPT09PT09PT09PT09PT09PT09PT09PT09CiAgICAgPT09PT09PT09PT09PQogICAgIHwgICAgICAgICAgIHwKICAgICB8ICAgICAgICAgICB8CiAgICAgfCAgICAgICAgICAgfAogICAgIHwgICAgICAgICAgIHwKICAgICB8ICAgICAgICAgICB8CiAgICAgfCAgICAgICAgICAgfAogICAgID09PT09PT09PT09PT0KICAgICAgICA9PT09PT09CiAgICAgICAgfCAgICAgfAogICAgICAgIHwgICAgIHwKICAgICAgICB8ICAgICB8CiAgICAgICAgPT09PT09PQogID09PT09PT09PT09PT09PT09PT0KICB8ICAgICAgICAgICAgICAgICB8CiAgfCAgICAgICAgICAgICAgICAgfAogIHwgICAgICAgICAgICAgICAgIHwKICA9PT09PT09PT09PT09PT09PT09Cj09PT09PT09PT09PT09PT09CnwgICAgICAgICAgICAgICB8CnwgICAgICAgICAgICAgICB8CnwgICAgICAgICAgICAgICB8CnwgICAgICAgICAgICAgICB8Cj09PT09PT09PT09PT09PT09CiAgID09PT09PT0KICAgfCAgICAgfAogICB8ICAgICB8CiAgID09PT09PT0i)
```
·mx ·r¥¬·È·Ãq, n ·û :Implicit input of string
· :Split on newlines
m :Map
x : Trim
· :Join with newlines
r :Global replace
¥ : Shortcut for the == operator. Passing an operator as the first argument of a method in Japt implicitly converts it to a string
¬ : Split
· : Join with newlines, giving the string "=\n=" to be replaced
È : Pass each match through a function
· : Split on newlines. As we're working within a string, the resulting array gets cast to a string (i.e., "=\n=" -> ["=","="] -> "=,="
à :End replace
q, :Split on ","
n :Sort
· :Join with newlines
û :Centre pad each line with spaces to the length of the longest
```
[Answer]
>
> **Javascript** ~~279 bytes~~ 275 bytes
>
>
>
I am something of a novice to code-golf, and not anything like an expert in javascript but the challenge is interesting and fun. I would like to see what tricks a real expert in js would use.
**Assumptions**
* Input and output are arrays of strings
* No blank lines anywhere
* Height of a box is <= 99 lines (does this disqualify me)?
* Input and output variables are predefined, output being initially an empty array
**Code**
Input is in `g[]`. Output in `m[]`.
```
a=[];s='';b=0;c=0;o=[];g.forEach((t,x)=>{t=t.trim(),c=Math.max(c,t.length);o.push(t);if(s==''){s=t;b=x}else{if(t==s){a.push({"K":s.length*100+x-b,"O":o});s='';o=[]}}});a.sort((p,q)=>{return p.K-q.K});a.forEach((t)=>{t.O.forEach((q)=>{m.push(" ".repeat((c-q.length)/2)+q)})});
```
The code works by
1. building an array of objects, each object representing one box, with two members:
K, a sort key being the (width x 100 + height)
and O, an array of the (trimmed) strings making up the box. While building the array the code remembers the width of the widest box.
2. The array of box objects is sorted into order by the key K. Where boxes have the same width the key ensures they are sorted by height.
3. After sorting the boxes, the strings for each box are pushed into the output array with leading spaces added, which position the box centrally over the widest one.
[Try it online!](https://tio.run/##vVJBb8IgFL73VxAuwkR0O9qw205m8bCjWxZkSF3aUgGXJm1/e0fVpKm2ccsyHyHkfbz3fR8vfPIvboXZZm6S6g9Z1wowsAogaIMNBCSdshL0RnlWdpWtHy17KW@LDr6@ByovH/8zqMM1OKdyaM6/vxjQ6AXLPoo/gkM/oZt1J9XN2sq3MAiETq2OJY21Qoo6/eLMNlUIUyOzmAuJpmSqCICvKcQ4DBK2arp4c1g2GoVrNguF37pBFN1o88RFhJAjOWaPhWOOesYEYSLYM3cRTXiOBHE0lqlyEQ41zfY2Qg6H2w2yzHPiwjLnifNKxlYWHnaMWVzwY2UBF3BuT/1397PZOJ@sCVzCua7w0VRjpqp8xqnVxiGUkV3jxki3NynI6GKyo4vDfWv4YJcuW@TQkhxFIYDNRCT3ZMI3n9xPH/B4hyu/zkYJ3/8roJe6nVJHKrn@P@r6Gw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Aristotle's number puzzle is the challenge of populating each of 19 cells in a hexagonal grid with a unique integer between 1 and 19 such that the total along every axis is 38.
You can picture the game board looking like this:

And the puzzle, in essence, is the solution to the following set of fifteen equations:
```
((a + b + c) == 38 && (d + e + f + g) == 38 && (h + i + j + k + l) ==
38 && (m + n + o + p) == 38 && (q + r + s) == 38 && (a + d + h) ==
38 && (b + e + i + m) == 38 && (c + f + j + n + q) ==
38 && (g + k + o + r) == 38 && (l + p + s) == 38 && (c + g + l) ==
38 && (b + f + k + p) == 38 && (a + e + j + o + s) ==
38 && (d + i + n + r) == 38 && (h + m + q) == 38)
```
Where each variable is a unique number in the set `{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}`.
There are multiple possible solutions, and are `19!` possible combinations of integers, so naive brute force will be impractical.
Rules:
1. No hardcoding the answer or looking up the answer elsewhere; your code needs to find it on its own
2. Speed doesn't matter, but you do have to show your results, so code that takes 1000 years to run won't help you
3. Find all the answers
4. Treat answers that are identical under rotation as identical
5. Deduct 5% of your total byte count if you output the results in an attractive honeycomb
6. Fewest bytes wins
[Answer]
# Java (1517 - 75.85) = 1441.15 (1429 - 71.45) = 1357.55 (1325 - 66.25) = 1258.75
This was fun.
Prints all unique solutions w.r.t. mirroring and rotation, in a pleasant honeycomb (hence 5% reduction)
Runtime: ~0.122s (122 milliseconds) on my 4 year old laptop.
Golfed code (*edit* realized I was stupidly repeating my printfs, reduced them to a single printf for maximum golf) (*new edit* Reduced calls to Set functions into clever smaller functions, some other micro-optimizations):
```
import java.util.*;class A{boolean c(Set<Integer>u,int z){return!u.contains(z);}Set<Integer>b(Set<Integer>c,int...v){Set<Integer>q=new HashSet<Integer>(c);for(int x:v)q.add(x);return q;}void w(){Set<Integer>U,t,u,v,w,y,z;int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,X,Z;X=20;Z=38;for(a=1;a<X;a++)for(b=1;b<X;b++)if(b!=a)for(c=1;c<X;c++)if(c!=a&&c!=b&&a+b+c==Z){U=b(new HashSet<Integer>(),a,b,c);for(d=1;d<X;d++)if(c(U,d))for(h=1;h<X;h++)if(h!=d&&c(U,h)&&a+d+h==Z){t=b(U,a,b,c,d,h);for(m=1;m<X;m++)if(c(t,m))for(q=1;q<X;q++)if(q!=m&&c(t,q)&&h+m+q==Z){u=b(t,m,q);for(r=1;r<X;r++)if(c(u,r))for(s=1;s<X;s++)if(s!=r&&c(u,s)&&q+r+s==Z){v=b(u,r,s);for(p=1;p<X;p++)if(c(v,p))for(l=1;l<X;l++)if(l!=p&&c(v,l)&&s+p+l==Z){w=b(v,p,l);for(g=1;g<X;g++)if(c(w,g)&&l+g+c==Z)for(e=1;e<X;e++)if(e!=g&&c(w,e))for(f=1;f<X;f++)if(f!=e&&f!=g&&c(w,f)&&d+e+f+g==Z){y=b(w,g,e,f);for(i=1;i<X;i++)if(c(y,i))for(n=1;n<X;n++)if(n!=i&&c(y,n)&&d+i+n+r==Z&&b+e+i+m==Z){z=b(y,i,n);for(o=1;o<X;o++)if(c(z,o))for(k=1;k<X;k++)if(k!=o&&c(z,k)&&m+n+o+p==Z&&r+o+k+g==Z&&b+f+k+p==Z)for(j=1;j<X;j++)if(c(z,j)&&j!=o&&j!=k&&a+e+j+o+s==Z&&c+f+j+n+q==Z&&h+i+j+k+l==Z){System.out.printf("%6d%4d%4d\n\n%4d%4d%4d%4d\n\n%2d%4d%4d%4d%4d\n\n%4d%4d%4d%4d\n\n%6d%4d%4d\n\n",a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s);return;}}}}}}}}}public static void main(String[]a){(new A()).w();}}
```
>
> Brute force is passe, but clever use of the fact that only a very small set of solutions exists led me to an iteration based answer, where within each loop of the iteration I only consider integers that have not been "assigned" yet. I make use of Java's HashSet to gain O(1) lookups for numbers that have been used previously. Finally, there are exactly 12 solutions, but when you discount both rotation and mirroring this reduces to just one unique solution, so when the first solution is encountered, I print it out and terminate. Check out my [less-golfed code at github](https://github.com/ProgrammerDan/aristotle-number/blob/master/AristotleNumber.java) for a bit of a clearer view into how I am approaching this solution.
>
>
>
Enjoy!
[Answer]
## C, 366 bytes (C++ 541 450)
```
#define R(i)for(int i=19;i;--i)
#define X(x)if(x>0&&!V[x]++)
#define K(X)X(a)X(b)X(c)X(d)X(e)X(f)X(g)X(h)X(i)X(j)X(k)X(l)X(m)X(n)X(o)X(p)X(q)X(r)X(s)
Q(x){printf("%d ",x);}
T=38,V[99];main(){R(h)R(c)R(s)R(a)R(l)R(q)R(e){int d=T-a-h,b=T-a-c,g=T-c-l,p=T-l-s,r=T-q-s,m=T-h-q,f=T-g-e-d,i=T-b-e-m,n=T-d-i-r,o=T-p-n-m,k=T-g-o-r,j=T-h-i-k-l;R(C)V[C]=0;K(X)K(+Q),exit(0);}}
```
Compile with `gcc -std=c99 -O3`.
Prints all unique solutions modulo rotation and mirroring, in the format `a b c d ...`, one per line.
Runtime: 0.8 seconds on my computer.
>
> We enumerate the cells in the order h -> c -> s -> a -> l -> q -> e for maximum prunability. In fact the version above just tries every 20^7 assignments for those variables. Then we can compute all the other cells. There is only one unique solution modulo rotation/mirroring. An older, less golfed and ~20 times faster (due to pruning) C++ version can be found [on Github](https://gist.github.com/niklasb/9777793)
>
>
>
[Answer]
# Haskell ~~295~~ 289
```
import Data.List
t=38
y a b=[max(19-b)(a+1)..19]
w=y 0 t
x=filter((==w).sort)$[[a,b,c,d,e,f,g,h,i,t-a-e-o-s,k,l,m,t-d-i-r,o,p,q,r,s]|a<-[1..14],c<-y a a,l<-y a c,s<-y a l,q<-y a s,h<-y c q,e<-w,let{f=t-g-e-d;i=t-b-e-m;o=t-r-k-g;k=t-p-f-b;b=t-a-c;g=t-l-c;p=t-l-s;r=t-q-s;m=t-q-h;d=t-a-h}]
```
Another similar answer, using arithmetic to get the intermediate hexes. Unlike the other solutions, I don't test for those sums being > 0, testing that the sorted hexes are equal to the range [1..19] is enough. a, c and h are restricted so that only uniquely rotated/mirrored solutions are allowed. The solution appears after a few seconds, then there's a wait of a minute or so while it decides there's no more.
Usage in ghci:
```
ghci> x
[[3,19,16,17,7,2,12,18,1,5,4,10,11,6,8,13,9,14,15]]
```
Edited to shave a few chars. 'y 0 t' produces [1..19].
[Answer]
# Matlab: ~~333~~ 320 characters
This is a pretty dumb near-brute-force approach that doesn't use recursion. It builds up partial solutions in `z`, which is printed out at the end. Each column is a solution; elements are listed a-z from top to bottom. Runtime is 1-2 hours.
```
z=[];
a='abc adh hmq qrs spl lgc defg beim mnop dinr rokg pkfb hijkl aejos cfjnq';while a[k,a]=strtok(a);n=length(k);x=nchoosek(1:19,n)';s=[];for t=x(:,sum(x)==38)s=[s,perms(t)'];end
m=0.*s;m(19,:)=0;m(k(1:n)-96,:)=s(1:n,:);y=[];for p=m for w=z m=[];l=w.*p~=0;if p(l)==w(l) y(:,end+1)=w+p.*(~l);end
end
end
z=[m,y];end
z
```
Running from within Matlab:
```
>> aristotle;
>> z(:,1)
ans =
9
11
18
14
6
1
17
15
8
5
7
3
13
4
2
19
10
12
16
```
] |
[Question]
[
It seems as of recent, there have been a lot a Jimmys falling to their death, as can be seen [here](https://codegolf.stackexchange.com/questions/187586/will-jimmy-fall-off-his-platform), [and here](https://codegolf.stackexchange.com/questions/187682/how-many-jimmys-can-fit) where you were asked to determine if Jimmy would fall. It is time we put a stop to this madness and try to save Jimmy.
Jimmy has three body parts `/`, `o`, and `\` arranged like this
```
/o\
```
Platforms are represented with `-`. Jimmy will fall off their platform iff they have two or more body parts that are not directly above a platform.
Some examples:
```
/o\
- -------
```
Jimmy will balance since all their body parts are above a `-`.
```
/o\
------ ---
```
Jimmy will balanced since two body parts are above `-`s.
```
/o\
-- ---- --
```
Jimmy will balance even though they are split between two platforms
```
/o\
-
```
Jimmy will not balanced since two body parts are not above a platform.
---
Since my platform supply is running low, I only have platforms with a length of 5, and it is important we use as few as possible.
Your task is to take an input of Jimmys and output a string of platforms which will save all of the Jimmys in the input. Your output must use as few platforms as possible, but each platform must be 5 `-`'s wide.
Note that the rule of the platform being 5 `-` wide, means that each platform must have a space between them. `----------` is not valid in the output since it will be considered a platform of length 10 and not two platforms of length 5.
### Test Case's
```
/o\ /o\/o\ // input
----- ----- // output
```
```
/o\ /o\
----- -----
```
```
/o\ /o\ // same input as above
----- ----- // this is also valid output
```
```
/o\ /o\
-----
```
Standard rules apply.
This is code-golf, may the shortest answer win!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~70~~ 67 bytes
```
lambda s:S('/',' ',S("\S.{5}","----- ",s+' '*5))
import re;S=re.sub
```
[Try it online!](https://tio.run/##PYlBCsMgFET3nuLjRm1tAoVsEnIKl7WLhEYqNCr6uyilZ7cVqgMzzLwJL7x7d85m1vmx7OttgTQqznomGTCpONWqew8fKumpCKhMx99zGIQgdg8@IsRtUnPcuvRcs/EREKyDiyZAe681QMliKhtqaryOSq4jgRCtQ8BaDEfx7yR/AQ "Python 2 – Try It Online")
*-3 bytes thanks to Kevin Cruijssen & Neil*
Not the prettiest, not sure how to better handle those leftover slashes...
Unfortunately, we can't replace both ends of each platform with spaces using a single `re.sub` call, because in the case of 2 platforms being one space apart, the gap between them can't be matched more than once. A lookahead/lookbehind assertion won't help, because anything matched within those assertions doesn't get replaced.
Using a single `re.sub` reference:
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 78 bytes
```
lambda s:[s:=re.sub(".[^/ -].{5}"," ----- ",s+" ",1)for c in s][-1]
import re
```
[Try it online!](https://tio.run/##PYlBCoMwFET3OcXwV0qNIqVQBE@SpKCtoUI1IUkXpfTsqVkkA//PzBv7CU@zn6/WRT3K@Jq2@THBD8IPo1ta/54rasWtA1ft9/KjhsCTQI0/EQ7ra20c7lh3eCV4r9i6WeMC3BLTEtIiJAN1Rkog/XTUFFRUeC6ZqIHBunUPVahz0kcupWbxDw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# JavaScript (ES6), ~~56 55~~ 54 bytes
```
s=>[...s+1e4].map(c=>(s--?s:s=c>{}&&5)?'-':' ').join``
```
[Try it online!](https://tio.run/##VYvBCsIwEETv/Yo9dRNKIoJeCkk/xAgNMZWWmhQ3eBG/PTZQRQdmh3nLTPZhyd3HJYkQLz4PKpPSJyklNXt/OMubXZhTmpEQHbWknH6@6vrIOxTYIiCXUxxD3@fkKYECAqXBxUBx9nKOV0bQAJqAawyM@NZ4VZUBw100BqDc4pX/4q/@fh@w0fwG "JavaScript (Node.js) – Try It Online")
Or [47 bytes](https://tio.run/##VcvBCsIwDAbg@54ip6VltCLoZdDuQaywUjvZmO0wxYv47HWFKRrIH/h@MtmHJXcflyRCvPg8qExKn6SU1Oz94SxvdmFOaUZCdNSScvr5qusj71Bgi4A8J08JFBAoDS4GirOXc7wyggbQBFzPwIjLKY6h7zfkVVX@GO6iMQAly67@y9/56z6waX4D) if returning an array of characters is acceptable.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~17~~ 15 bytes
```
W‹ⅈLθ«×⁵№o\§θⅈ→
```
[Try it online!](https://tio.run/##S85ILErOT8z5/788IzMnVUHDJ7W4WCNCQ1NHwSc1L70kQ6NQU1NToZqLM6AoM69EIyQzN7VYw1RHwTm/FMhVyo@JUdJRcCzxzEtJrdAo1FEAagUCay5O3/yyVA2roMz0jBIgt/b/f/38GAUFIAFEXP91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
W‹ⅈLθ«
```
Repeat while the cursor position is less than the length of the input.
```
×⁵№o\§θⅈ
```
If the character at that position in the input is an `o` or a `\` then print 5 `-`s.
```
→
```
Move to the next character, thus guaranteeing at least one space between platforms.
Previous 17-byte solution is IMHO more "Charcoal-y".
```
θ⸿Fθ«×⁵¬№ /⊟KD²↑→
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRKNQ05oLwlKKKVICctLyixSAogrVXJwQ8ZDM3NRiDVMdBb/8Eg3n/FKQUgV9JR2FgPwCjYDU1GyXzKLU5JLM/DwNIx0Fq9ACTRCw5uL0zS9L1bAKykzPKAFya///18@PUVAAEkDE9V@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Output includes input, thus demonstrating correctness of solution. Explanation:
```
θ⸿
```
Print the input and move to the start of the next line.
```
Fθ«
```
Loop over every character of the input to ensure that no Jimmy gets missed.
```
×⁵¬№ /⊟KD²↑
```
Look at the character above the cursor. If there is none, or if it is space or `/`, then do nothing, otherwise print 5 `-`s.
```
→
```
Move to the next character, thus guaranteeing at least one space between platforms.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~158~~ ~~164~~ 160 bytes
```
a=input();r=""
for i,c in enumerate(a):
try:r[i]
except:
if c in"/o":
r+=(a[i+5<len(a)and i+5or len(a)-1]=="o"and" "or"")+"----- "
else:r+=" "
print(r)
```
[Try it online!](https://tio.run/##PVDLbsMgELzzFaPtBeQ8VEW9uPU/9NBbGkXEXsdUDlhA1OTr3cVNuzxnYBdmpnsegt/NeeBjGzpGAyKabeP8dM3avMaGSPUhwq1aOA/21wtHm1lbUyvkeK/j3h0U@NbylIWC61Gu0jZQgYhVo@3eVS9vI3tJs76DIKn5i9fPh6ahQMITKEQiU9G6BEjyeUxcSw05U1N0PutoZvmkUk94j6HllJw/o/x@hRyQhvAN0YPMKaO1iZNSfONWU8c9er1IMzWhEq2br@C8Hp3nAqUVrQsUsX@ubNI0ulzYpD/ilY1Z4TyGkx2TNkYt/hxLQrT@zHpXnJGHRns5dbbGw0uj5m34BGSSrpb9fxTmsZbxAw)
This is my first code golf answer, and I'm happy it's on a Jimmy question!
Explanation:
* `a=input();r=""`: Take in input and initialize a new string `r`.
* `for i,c in enumerate(a):`: Enumerate over the input.
* `try:r[i] ... except:`: See if `r[i]` exists - if not, process the `except` block.
* `if c in"/o":`: Check if the current character is in Jimmy's first two body parts.
* `r+=(a[i+5<len(a)and i+5or len(a)-1]=="o"and" "or"")+"----- "`: If so, add a new segment. Add a space before our new segment if another Jimmy head is present in five characters.
* `else:r+=" "`: Otherwise, just add a space.
* `print(r)`: Print our final result.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~23~~ 21 bytes
```
/
$
5*
\S.{5}
5*-
```
-2 bytes thanks to *@Neil*.
Contains a single trailing space on the second, fourth, and sixth lines.
Port of [*@negativeSeven*'s Python 2 answer](https://codegolf.stackexchange.com/a/187735/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##K0otycxLNPyvquGe8F@fS4FLhctUS4ErJliv2rQWyNRV@P9fPz9GQQFIABEXmA0HIBEoDcIA)
**Explanation:**
Replace all `"/"` with a `" "`:
```
/
```
Append 5 trailing spaces:
```
$
5*
```
Replace all substrings of size six that do not start with a space by `"----- "`:
```
\S.{5}
5*-
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~23~~ 22 bytes
A port of Arnauld's JS solution that I'm just too exhausted to fully test. If it's invalid can a Diamond please delete?
```
+L² £=U´?U:X>M©5)?'-:S
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=K0yyIKM9VbQ/VTpYPk2pNSk/Jy06Uw&input=Ii9vXCAgICAgICAgICAgL29cIg)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes
```
;3x5¤;0;ṛṫ6ɗ
;⁶x5¤e€⁾o\œṡ1ç/$ÐLị⁾-
```
[Try it online!](https://tio.run/##y0rNyan8/9/auML00BJrA@uHO2c/3Lna7OR0LutHjdtAgqmPmtY8atyXH3N08sOdCw0PL9dXOTzB5@HubqCgrsL////182MUEADEAwA)
A monadic link that takes the input as a string and returns a Jelly string with the platforms.
Takes inspiration from [@negativeseven’s answer](https://codegolf.stackexchange.com/a/187735/42248).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~25~~ 24 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ð5׫'/ð:DŒ6ùʒнðÊ}'-5×ð«:
```
Port of [*@negativeSeven*'s Python 2 answer](https://codegolf.stackexchange.com/a/187735/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f//8AbTw9MPrVbXP7zByuXoJLPDO09NurD38IbDXbXqukCpwxsOrbb6/18/P0ZBAUgAEQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TpuSZV1BaYqWgoGRfqcMFpPxLS8ACQP7/wxtMD08/tFpd//AGK5ejk8wO7zw16cLewxsOd9Wq6wKlDm84tNrqv86hbfb/9fNjFBSABBBxgdlwABKB0iAMAA).
**Explanation:**
```
ð5׫ # Append 5 trailing spaces to the (implicit) input-string
'/ð: '# Replace all "/" with a space
D # Duplicate the string
Œ # Get all substrings of this
6ù # Only leave those of length 6
ʒ } # Filter it further by:
нðÊ # Only keep those which do NOT start with a space
'-5×ð« '# Push a string of 5 "-" appended with a space: "----- "
: # Replace in the initially duplicated string all substrings
# remaining in the list with this "---- "
```
] |
[Question]
[
Polystrips are a subset of polyominoes conforming to the following rules:
* each piece consist of 1 or more cells
* no cell can have more than two neighbours
* the cells should not enclose a hole
Free polyominoes are distinct when none is a rigid transformation (translation, rotation, reflection or glide reflection) of another (pieces that can be picked up and flipped over). Translating, rotating, reflecting, or glide reflecting a free polyomino does not change its shape ([Wikipedia](https://en.wikipedia.org/wiki/Polyomino#Free,_one-sided,_and_fixed_polyominoes))
For example, there are 30 free heptastrips (polystrips with length 7). Here are all of them, packed into a 14x15 grid.
[](https://i.stack.imgur.com/Dtwzt.gif)
[Image credit: Miroslav Vicher](http://www.vicher.cz/puzzle/polyform/minio/polystrip.htm)
## Goal
Write a program / function that takes a positive integer `n` as input and enumerates the distinct free `n`-polystrips.
* n=1 --> 1 (A single square)
* n=2 --> 1 (There is only one possible 2-polystrip made of 2 squares)
* n=3 --> 2 (One is composed of 3 squares joined in a line and the
other one is L-shaped)
* n=4 --> 3 (One straight, one L-shaped and one Z-shaped)
* . . .
## Test cases:
```
n polystrips
1 1
2 1
3 2
4 3
5 7
6 13
7 30
8 64
9 150
10 338
11 794
12 1836
13 4313
14 10067
15 23621
```
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shorter code is better. I would highly appreciate detailed explanations of the algorithm and the code.
## Partial reference implementation in [J](http://www.jsoftware.com/)
I decided to describe each piece in "vector" format and I only need n-2 blocks to describe an n-polystrip piece (there is only 1 2-polystrip and it's returned explicitly). The blocks describe the relative direction: 0 - no change; 1 - turn left; 2 - turn right. It doesn't matter which direction one will start but only to indicate where the next cell is to be put. There can be any number of consecutive 0s, but 1s and 2s are always single.
This implementation is partial, because it doesn't account for the holes - solutions for n>6 count the pieces with holes too.
[Try it online!](https://tio.run/##nZTdjtowEIXv8xQjLRIgQRTS7k1Y9qIP0EdoZcJAXAU7Gju7G7Xqq9OxnUACBK3qi/zI48/nzIz963SCPWwy@AoZJBG4Qe7/A0bG928xEJq6tCFa7mOYPTVzeIHf2eQDdjq@ipZ7sAVCiepgC9DhL6@JUFkopbEgDc8awxNCgQKIzuuJ1TWLZERHLsqSA94lcxMQVYVqh7vh6h8ZzFbwN2N1LLKBBazurF6dV5/lCifM4tGpU9rC6pabDrjp/3HTwMXSYDxwzlUgxjb3nAdqALoMWu2/Q2FaCgfEXUUfjVBRW5PqMSKYR1Gwo5WxVOfWgAibeWfOZKWNkdsSQRAJdcAjV5SjWBjhUb@h8UDTHNGS5LR43yaCA2xi@OI6Di5NlMJrxmZd/yStnth7OHeRgpcNhy1fQauy4QezdVlbqVXACMedJS5py3Q@Se4YNVZQ6wCPlW06TynkyI5MockiBdzW4QSXMpmMdeABFZKw6NMxyELXxbmDUCCNQIIQJ8PAXlO/ki6XteHu4ST6LKJpW4QDf8qYNQ4PXA/rUCjyoq/r0l8@58tYAnddPoS06ZZ2GjpUqq6OrYSQsmi4JQWjC5AjzSqv29SZu4L4bOWfgvTkjEH@xHIEYljDG5LBW9q4IqrKnC@TdQprSNer@WekdbcAz6dg3l3obmyHGeud3@zid2jPeie6vUTFlg9ZH9UjX05///PxTfDgKvBH6wDP4@t20lSlaPxCzofle45kxcWJMC80iPCaTsP7SZxO/wA "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 480 433 406 364 309 299 295 bytes
Looked like a good point to start my PPCG career (or not?).
```
def C(s):
S,*a={''},0,1;n=d=r=1
for c in s:d=c*d*1jor d;n+=d;a+=n,;r*=not{n}&S;x,*a=a;S|={x+t+u*1jfor t in A for u in A}
return r
from itertools import*;A=-1,0,1;n,y=int(input())-2,0;x={*filter(C,product(*[A]*n))}
while x:s=x.pop();S=*(-u for u in s),;x-={s[::-1],S,S[::-1]}-{s};y+=1
print(y)
```
[Try it online!](https://tio.run/##RVHBbqswEDyXr7Ai5WGbpcI4ISnW6imqeuiZY5RDFIxKlRpkjB4Rj29PTajUk0fendHMbHtzH42R91JXpDZt72jw9I5HASlI2MAWMtjBHl5AJCAEiBSEBLEBsT1B8PQ2by67u3kgE8jmWQJS7mH34vFeZrCRMylJsh2kMkvFKWB5DRo7Z@n7c9u0NGEM3n6Qam1tHF1VdJ12LCfrbUn@IlnzbrWmngbb@KoNncna01YrBtqU6F9lteutIXWgB32hYRg@cr1SLxOQAvgZxzCcwEdRBku0KAJSNZZcfHbS5SVeeMnFp/8plYmwVOcIDSjL0TRuNNOfQg2zylkV/3EcIhf1fn1WcLPC4SHWP@AUkB83Nqhs80Vqp61rmmtH6q@2sY6rA8Zi8QI3nCMvB2AsTiFRA468qq@eRV@htU3ZXxzlx8OJG8am4N9HfdVkyDscHr0xVSCncf9roWOghhjH7pjnsThBAcWCpnjsJnWLfPql6hu7@6642LD7Nw "Python 3 – Try It Online")
**Edits:**
* Inlined `D` and `X`, and tweaked a little bit on some golfable spots.
* Applied more tricks, mainly set-related ones.
* Changed into program form, and changed to using complex numbers instead of arbitrary number `m`. (Complex numbers are really a strong but often ignored golfy feature; adapted from [xnor's solution for another challenge](https://codegolf.stackexchange.com/a/156598/78410))
* Changed the `LFR` string representation to `-1,0,1` tuples and sacrificed execution time for crazy amount of byte reduction(!). Now the solution is theoretically correct but timeouts before outputting the result for 15.
* One-lined the loop thanks to Jonathan Frech, then I found the much better alternative for calculating `r`. FINALLY UNDER 300 BYTES!!!
* Surprisingly `1j` can stick to anything else without confusing the parser (-2B), and `not` has insanely low precedence (-2B).
Obsolete version (480 bytes):
```
def C(s):
m=999;a=[0,1];n=d=1
D={'F':{},'L':{1:m,m:-1,-1:-m,-m:1},'R':{1:-m,-m:-1,-1:m,m:1}}
X=lambda x:{x+~m,x-m,x-m+1,x-1,x,x+1,x+m-1,x+m,x-~m}
for c in s:
d=D[c].get(d,d);n+=d;a+=n,
if n in set().union(*map(X,a[:-3])):return 0
return 1
def f(n):
if n<3:return 1
x={*'LF'}
for _ in range(3,n):x={s+c for s in x for c in({*'LRF'}-{s[-1]})|{'F'}}
y={*x}
for s in x:
if s in y:S=s.translate(str.maketrans('LR','RL'));y-={s[::-1],S,S[::-1]}-{s}
return sum(map(C,y))
```
[Try it online!](https://tio.run/##RVDBioMwEL37FbmZrBNpEBYaN6eWnnpqLwWRJVu1K9ukxVhQXPvr3YmWbiDJJG/mzbx37dvvi00ej6KsyIo6JgNi1HK5TLXKFiDy1KpCiYCs1RBuQjmMEG7xEtKAkVwAF5Ib4EYKRHYTMr9nzGeJcQzIQZ21@So06eTQRXcDHZ92JPDEDZ2PIsOnE//uBquqS0OOpLbE4VykUOvsmMensqUFFCy1kSpSHSkLCNYVsVMmoiy@2fpi6ZvRV3oAnUme5IzJpmxvjSWLgDwjEXjdFbVet2f4SOQLIp0a3sLtJnwO8unpG21PJU0AKxB20XGCnIe617jU1@2wkA8u4yIf2a93z/vQI2f3JJyr5Dz89OjlXrm4xSburNuSuraJjf4ppx@KnCGavA0ZS3uO3TOJNuewh/0c@X7jS5y7GeoNWEHP2MM3rP8VCBDvXjSua1PbltaAPtSY@Ac "Python 3 – Try It Online")
Ungolfed solution with comments:
```
t = str.maketrans('LR','RL')
# hole checking function
def check(s):
m = 999 # (imaginary) board size enough to fit all generated polyominoes
a = [0,1] # previous path
n = 1 # current cell
d = 1 # current direction
# dict for direction change
D = {'F':{}, 'L':{1:m, m:-1, -1:-m, -m:1}, 'R':{1:-m, -m:-1, -1:m, m:1}}
# used to 'blur' all cells in path into 3x3
X = lambda x: {x-m-1,x-m,x-m+1,x-1,x,x+1,x+m-1,x+m,x+m+1}
for c in s:
d = D[c].get(d,d) # change direction
n += d # move current cell
# the polyomino has a hole if the current cell touches previous cells (including diagonally; thus the blurring function)
if n in set().union(*map(X,a[:-2])): return False
a.append(n) # add current cell to the path
return True
# main function
def f(n):
if n < 3: return 1
x = {*'LF'}
# generate all polystrips using the notation similar to the reference
for _ in range(3, n): x = {s+c for s in x for c in ({*'LRF'}-{s[-1]})|{'F'}}
y = {*x}
# remove duplicates (mirror, head-to-tail, mirror of head-to-tail) but retain self
for s in x:
if s in y:
S = s.translate(t)
y -= {s[::-1], S, S[::-1]} - {s}
# finally filter out holey ones
return sum(map(check,y))
```
[Try it online!](https://tio.run/##bVRNb9swDL3nVxDowXZjB/MCDKi33oqeckp3KBAEg2rJsVB9GJJcxMvy2ztSdj7azYgthU8iH8kndUNorVm@vwe4Bx/cQrNXERwzPk1W6yRP1qskm81uoLVKQN2K@lWaHTS9qYO0ZsZFM1pTn1UzwEejo7vb2zuAG0ilZjtpmBsyeLHMcfDytwBhbL9rIVhoZACmFOyEEY4FwaGzarBaGit8dMfQ3eZLXm7RXefEm7S9h46FNqIG0ZImiNa9c8IEqIVSEeT/Abl0YmQ@2rmsAzTWXQBMh5mdiPgDejgkj0l1OOaQrHAsK52Drooyh6KsCvxT6KokdB3RyTLhcW15PE7Beo8JYtbJi@pdEhMnsh6kiSnhiOhyv4zrnzG4YvqFM9hXcNgXGr3il945zfDN9zSbR2Su6Z2XYzTKqSbHfmzLqSAPm3q72ImQ8pxnVJiY7ae6jKWd3@OOq@cGtH0T/9Z5xEIrLs2DlnlsXRSNbCJ2vQ2L0KNq/KWjYx1SaWrVc1IYl2xnDZZo@I7bcQX5oLq5a/1lZwIYxcR0MbVs0RsE01vNuvQ5Z5uq@LrNsgqcCL0z8MiUF@edbMG6ThiemuycDOP8M@ExwZPwJk8/XS/odGiGoT8cigbdjZWPzH7A8hy@jOY9aes2WT0mJ3mcDkEUBpUSz6PsPMqGUqbwxgYWNeqlloq5Ey0nGoFca3Fu/S@qhaPWpssckMoYz8/rCEfJ7S8iSYnJGqkUB78pyu0x@0O6n5Q7RKr7E08nog543ylZI1/sm5bOWZdDKxgvgi0Ckwq1H61gmw92vAr6QLVgsV2qOZMeWVXXPY2m4WKi54muqkW8pBSGT0P2AR6goEw3FZ7CbQ5P@BvnRyjQfsqikVFdOKogkCRyIrkOYM109Uzt8r1OSUjxmsuHLHsnrvJS4DIvv0297lCdIZU5tl/iwr8 "Python 3 – Try It Online")
`m = 999` is chosen because it takes exponential time to count everything, and it's already taking ~8s to calculate `n = 1..15`. Maybe it's fine to save 1 byte by using 99 instead. We don't need this anymore, and now it's guaranteed to be correct for arbitrary input size, thanks to complex number built-in.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~70~~ 65 bytes
```
+/{∧/∊2≤|(⊢-¯3↓¨,\)+\0 1,×\0j1*⍵}¨∪{(⊃∘⍋⊃⊢)(⊢,⌽¨)⍵(-⍵)}¨2-,⍳2↓⎕⍴3
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@2fvWjjuX6jzq6jB51LqnReNS1SPfQeuNHbZMPrdCJ0dSOMVAw1Dk8PcYgy1DrUe/W2kMrHnWsqgYqa37UMeNRbzeI0bVIE6RP51HP3kMrNIGqNHSBhCZQrZGuzqPezUZA0x71TX3Uu8UYZOl/BTAo4DLkgrGM4CxjOMsEzjKFs8zgLHM4ywLOsoSzDA0QTEMA "APL (Dyalog Unicode) – Try It Online")
Full program version of the code below, thanks to Adám.
---
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 70 bytes
```
{+/{∧/∊2≤|(⊢-¯3↓¨,\)+\0 1,×\0j1*⍵}¨∪{(⊃∘⍋⊃⊢)(⊢,⌽¨)⍵(-⍵)}¨2-,⍳3⍴⍨0⌈⍵-2}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@fnpr3qG1CtZGuzqPezY96tz7q3WJcy5WcmJefl5mcmJNZlQqS1njU1fyoY8aj3m4Qo2uRJlBgkc6jnr2HVmgCNWnoAgnNWq6S1OISiPKO5fpAFdUg2uhR55KaR727dA@tN37UNhmosvbQCp0YTe0YAwVDncPTYwyyDLVAov@rtfXBOh51dIE1gSyB6sKu49CKRx2riHTcoRUQPxoDffiod4XBo54OoLiuUe3/NKCTH/X2Peqb6ukPNAFs4UQgLzjIGUiGeHgG/68AKkkD2ta72dCQq4Kr4lHnQkMFQwUjBWMFcwVDYwVjAwUzEwVDUwMFY2MLBXNLEwA "APL (Dyalog Unicode) – Try It Online")
### How it works
The code above is equivalent to the following definition:
```
gen←{2-,⍳3⍴⍨0⌈⍵-2}
canonicalize←{(⊃∘⍋⊃⊢)(⊢,⌽¨)⍵(-⍵)}
test←{(∧/⊢{∧/2≤|⍺-¯3↓⍵}¨,\)+\0 1,×\0j1*⍵}
{+/test¨∪canonicalize¨gen⍵}
```
This works like the Python solution, but in a different order. It `gen`erates `LFR`-strips of length `n-2`, `canonicalize`s each strip, takes `∪`nique strips, `test`s each strip if it touches itself (1 if not touching, 0 otherwise), and sums `+/` the boolean result.
### `gen`
```
{2-,⍳3⍴⍨0⌈⍵-2}
{ } ⍝ ⍵←input number n
0⌈⍵-2 ⍝ x←max(0, n-2)
3⍴⍨ ⍝ x copies of 3
,⍳ ⍝ multi-dimensional indexes; x-th cartesian power of [1,2,3]
⍝ (`⍳` gives x-dimensional hypercube; `,` flattens it)
2- ⍝ compute 2-k for each k in the array
⍝ in each strip, ¯1, 0, 1 corresponds to R, F, L respectively
```
### `canonicalize`
```
{(⊃∘⍋⊃⊢)(⊢,⌽¨)⍵(-⍵)}
{ } ⍝ ⍵←single strip
⍵(-⍵) ⍝ nested array of ⍵ and its LR-flip
(⊢,⌽¨) ⍝ concatenate their head-to-tail flips to the above
(⊃∘⍋ ) ⍝ find the index of the lexicographically smallest item
⊃⊢ ⍝ take that item
```
### `test`
```
{(∧/⊢{∧/2≤|⍺-¯3↓⍵}¨,\)+\0 1,×\0j1*⍵}
{ } ⍝ ⍵←single strip
0j1*⍵ ⍝ power of i; direction changes
×\ ⍝ cumulative product; directions
0 1, ⍝ initial position(0) and direction(1)
+\ ⍝ cumulative sum; tile locations
( ⊢{ }¨,\) ⍝ test with current tile(⍺) and all tiles up to ⍺(⍵):
¯3↓⍵ ⍝ x←⍵ with last 3 tiles removed
⍺- ⍝ relative position of each tile of x from ⍺
2≤| ⍝ test if each tile of x is at least 2 units away
∧/ ⍝ all(...for each tile in x)
∧/ ⍝ all(...for each position in the strip)
```
[Answer]
# [Scala](https://www.scala-lang.org/), ~~2277~~ 1710 bytes\*:
Modified from [@Bubbler's answer](https://codegolf.stackexchange.com/a/156335/110802).
### Golfed version
[Try it online!](https://tio.run/##fVRba9swFH73rzikhUr4srjdHhbWwgotDDoGTfdUSlFtOVFny6mkdAnBvz07kuVLIF0eYvuc7/vOVdIZK9l@L6pVrQxo@5VkdVnyzIhaJtXasJeSJ3NugqB@eUUz/GRCwi4AyHkB2ZJnf@b8jegZzI0SckFncF3XJWcSLh0M4J2VULENfl@LxQ9pyFearOq/@PBuBQydVsYDpjTqsCkdUHKQSAdrfsRaQi6URsdPtiLOBnB2ewbxlbU8tvAuxhOhUYe56zCkl7QGTD9yNeC7d8TpkGTcomIHiw9xWECvfn9c/SjviP6RLLr2DIWz/BXrJpuZh1C4vMLeGoK0lgxpBP6jf4Gws9qHffOGcMwJO07YcWjgAuukqBVn2RJ2kGFAX7AdjR0EyWiy4OaXuik1J3kEOfUICSFC/IdN/z1FjiiAsKTkcmGWcAXnFFiiS5FxMo2gd8ToSCpsJpZMgaO02yE6UtOd2nuaCH1TrcyW2mY89pNveehWPF9jgGcIQ3juNCxVp3gkpMG110RSCoqbtZJQMCR6mF1fBrMQpDM07t@otfU3gT8rBZEzsANx//3psCEkfIOLXjkN@t3euHNhyORuEsHkdtLmRS5gLY0oQdJR35@HvlvaJilKZnDX0KX52@BsO5MtmTsgVh23PrLLGdkzgptm8UnJtMEJo6XnOY7ruJ2xUw0h63rV@Nr75Lcui6ysJfdD2YzSPcjJNmE7tBl92OjdQcJGzS3D5ab4qmQ4rLYtJxM6WO6t5W5sObGW@wk9UHOLYWtv5d650jxqY/hHZx14W4hjjJ8muSgK4sn0aPm2FhwR6e5HOl6ECmskTC3wzvyuFNs@tjfnEy7GbynMwb1pXJ5bbXiVSCbrB1F1zSQpmBrSL@MdEENLHfv8Q3YLUNzuQEHE2Ggu/sNaYaqmlERPTgWcWv7pDgkxxmqk9l1uhvw/f6g1KD3UxkLRNUM1ghyUwyvvE6RT90umTdVqN0ET7Pf/AA)
```
import scala.collection.mutable.Set
object Main {
def checkSeq(s: String): Boolean = {
val max = BigInt(9).pow(9)
var a = Seq(BigInt(0), BigInt(1))
var n = BigInt(1)
var d = BigInt(1)
val dirs = Map(
'F' -> Map[BigInt, BigInt](),
'L' -> Map(BigInt(1) -> max, max -> BigInt(-1), BigInt(-1) -> -max, -max -> BigInt(1)),
'R' -> Map(BigInt(1) -> -max, -max -> BigInt(-1), BigInt(-1) -> max, max -> BigInt(1))
)
val adj = (x: BigInt) => Set(x - max - 1, x - max, x - max + 1, x - 1, x, x + 1, x + max - 1, x + max, x + max + 1)
s.foreach { c =>
d = dirs(c).getOrElse(d, d)
n += d
val v1 = if (a.length > 2) a.slice(0, a.length - 2).map(adj) else Seq()
val s1 = if (v1.isEmpty) Set[BigInt]() else v1.reduce(_ ++ _)
if (s1.contains(n)) return false
a = a :+ n
}
true
}
def f(n: Int): Int = {
if (n < 3) return 1
var x = Set("L", "F")
(3 until n).foreach { _ =>
x = x.flatMap { seq =>
val chars = Set('L', 'R', 'F') - seq.last + 'F'
chars.map(c => seq + c)
}
}
var y = x.clone()
x.foreach { seq =>
if (y.contains(seq)) {
val trSeq = seq.replace("L", "#").replace("R", "L").replace("#", "R")
val s1 = Set(seq.reverse, trSeq, trSeq.reverse)
y --= s1.diff(Set(seq))
}
}
y.count(checkSeq)
}
def main(args: Array[String]): Unit = {
val t1 = System.nanoTime()
(1 to 15).foreach { i =>
val t2 = System.nanoTime()
val res = f(i)
val t3 = System.nanoTime()
println(s"$i $res ${t3 - t2}ns")
}
val t4 = System.nanoTime()
println(s"Total time: ${(t4 - t1) / 1000000.0}ms")
}
}
```
### Ungolfed version
[Try it online!](https://tio.run/##jVXbbtw2EH3frxhsHkJCF1t2@9BFbCBBEqCAjQJ22hcjCBiJu1ZCUVuSSnZR7Le7MxIpSvY6iQ1Y1vDMmeuhbCmUeHiom21rHFh6y8tWKVm6utV50znxWcn8VrrFov38Bc1wLWoN/y0AKrmG8l6WX2/lv53UpWR2BbfO1HrDV/CmbZUUGi56LMA3oaARu3@E6iQa39SbP7Vjf/B8237Hh8cYEHiIhMwDTnkasAWPKB0pimitjlgVVLUZyrF4fC22rD8BePn@JWSXZLkbnEKkj4ynAXP1LGYMRIBQWRprRKuHZEUsIhvwWXTIjnhgqWMGN7@WwU8Yj@Tww5xDs2MbcTfKTgknX1dfRCm1w26y3co7cLi4xLk5toNswgdFClPL/A2ScE4P@s8bkicUyYwimVFwzPDkBIx0ndG4QJa2ldJetwZYCa8ysNyvIfRLEleClTzfSPeXeaesZFUKFfc4DQkC/Qs1ADesQN96DUzkSuqNu4dLOOMgcqtqXP/TFMaDDA/yBpftSds4SAzV7zifsGPSgZ0C5bV912zdnlNT78a9HHx7gJFVh0E/QZLAp8BE7sSEItYOhWqZ5rF0CD1aC6TxxoN/kvAErBLQi2h2piPcYeH1vmZ6BTTu/u8obgqr4RWcx1g@UuHJRo3uen07trxaprB8v@RxUjVN6hw67WoFOlJRe7T8jl6D791wyXwc@9d7W38LEcluWjNFLe@FEaWTxvrwKOyUtJXSNYBygOCeK2Hd6Dvxw21A6Hgy7FY4pqARO40OIXX0H1NMIngEHh7Ngxo1uD5u4R5PdnmpWi3ZpH3PNIBms4/7EFB83iKFoxba0qJW4T6HmDFu21bh@vqxvVjyaLkhy9XU8oIsN0uOqpQ7rFRvZH@TCl319xl@QALxLAWvAZrPJPA37Ciq/ml@x2wBzx8Tnz0ifgJ4W6/X0ox1o4YqtJCaziJ2D1l2MUfPxuanRP3GNWazzyOfCqnBYTBhNvjJfG2M2IedRmH9rWs3@2wOTdlbJ5tcC91@qJvZ4HvdFOBaKH6fq2ao@qjnADDSdoqirVk9tbvzHzhuMVOnNMZNYIm/SaAJrwzdMwzOyaKt1/ghFvTbs@x0LJXYWlldk1YZYpEK7/gTKE77n/x0Mc1i@aF1xIkcqz56dMfozRD9sDgsHh7@Bw)
```
import scala.collection.mutable.Set
object Main {
def checkSequence(s: String): Boolean = {
val maxValue = BigInt(9).pow(9)
var a = Seq(BigInt(0), BigInt(1))
var n = BigInt(1)
var d = BigInt(1)
val directions = Map(
'F' -> Map[BigInt, BigInt](),
'L' -> Map[BigInt, BigInt](BigInt(1) -> maxValue, maxValue -> BigInt(-1), BigInt(-1) -> -maxValue, -maxValue -> BigInt(1)),
'R' -> Map[BigInt, BigInt](BigInt(1) -> -maxValue, -maxValue -> BigInt(-1), BigInt(-1) -> maxValue, maxValue -> BigInt(1))
)
val calculateAdjacent = (x: BigInt) => Set(x - maxValue - 1, x - maxValue, x - maxValue + 1, x - 1, x, x + 1, x + maxValue - 1, x + maxValue, x + maxValue + 1) // return a set
for (c <- s) {
d = directions(c).getOrElse(d, d)
n += d
val var1 = if (a.length > 2) a.slice(0, a.length - 2).map(calculateAdjacent) else Seq()
val set1 = if (var1.isEmpty) Set[BigInt]() else var1.reduce(_ ++ _)
if (set1.contains(n)) {
return false
}
a = a :+ n
}
true
}
def f(n: Int): Int = {
if (n < 3) {
return 1
}
var x = Set("L", "F")
for (i <- 3 until n) {
val newSet = Set[String]()
for (sequence <- x) {
var characters = Set('L', 'R', 'F') - sequence.last
characters += 'F'
for (character <- characters) {
newSet += sequence + character
}
}
x = newSet
}
var y = x.clone()
for (sequence <- x) {
if (y.contains(sequence)) {
val translatedSequence = sequence.replace("L", "#").replace("R", "L").replace("#", "R") //exchange 'L' and 'R' in sequence
val set1 = Set(sequence.reverse, translatedSequence, translatedSequence.reverse)
val set2 = Set(sequence)
val setDifference = set1.diff(set2)
y --= setDifference
}
}
y.count(checkSequence)
}
def main(args: Array[String]): Unit = {
val t1 = System.nanoTime()
for (i <- 1 to 15) {
val t2 = System.nanoTime()
val result = f(i)
val t3 = System.nanoTime()
println(i + " " + result + " " + (t3 - t2) + "ns")
}
val t4 = System.nanoTime()
val elapsedMs = (t4 - t1) / 1000000.0
println("Total time: " + elapsedMs + "ms")
}
}
```
\* Rather long in bytes, but computes solutions up to and including \$n=15\$
around 15 seconds on TIO.
] |
[Question]
[
*Inspired by [Bake a slice of Pi](https://codegolf.stackexchange.com/q/93615/42963)*
### Challenge
Given input `3 <= n <= 100` and `3 <= y <= n`, construct an `n x n` matrix of the decimal portion of `pi` (`14159...`), starting in the top left. Then, take the upper-right triangle of size `y x y` and concatenate it together. Output the resulting number.
For example, for input `n = 5`, `y = 3`, the following matrix is constructed
```
14159
26535
89793
23846
26433
```
Then, the upper-right `3 x 3` triangle would be
```
159
35
3
```
so `159353` is the output.
### Input
Two integers -- `n` representing the size of the square matrix of the digits of pi, and `y` representing the upper-right triangle -- in [any convenient format](https://codegolf.meta.stackexchange.com/q/2447/42963).
### Output
* The resulting sliced and concatenated number, either printed/displayed to the screen, returned as a string, etc.
* Trailing/leading whitespace is optional, so long as there's no whitespace *in* the output (i.e., `159 35 3` or the like would be invalid).
* Note that since we're explicitly looking for the digits of `pi`, and not an approximation or mathematical calculation, answers should not round the final digit of the matrix.
### Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all the usual rules for golfing apply, and the shortest code (in bytes) wins.
* Either a full program or function are acceptable.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061/42963) are forbidden.
### Examples
```
n y output
-------------
3 3 141923
5 3 159353
6 4 1592589383
6 6 141592535893238643794
20 12 358979323846950288419715820974944628620899211706792306647223172745025559196615
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 19 bytes
Uses [CP-1252](http://www.cp1252.com) encoding.
```
nžs¦¦¹ôI£íRvyN>£J}R
```
[Try it online!](http://05ab1e.tryitonline.net/#code=bsW-c8KmwqbCucO0ScKjw61SdnlOPsKjSn1S&input=MjAKMTI)
**Explanation**
`n=5, y=3` used for example
```
nžs # push pi to n^2 digits
# STACK: 3.1415926535897932384626433
¦¦ # remove the first 2 chars
# STACK: 1415926535897932384626433
¹ô # split into n*n matrix
# STACK: ['14159', '26535', '89793', '23846', '26433']
I£ # keep the first y rows
# STACK: ['14159', '26535', '89793']
íR # reverse the list of rows and each individual row
# STACK: ['39798', '53562', '95141']
v } # for each y,N (row, index) in the list
yN>£J # keep the first index+1 digits of the row and join to string
# STACK: 353951
R # reverse the string
# STACK: 159353
# implicit print
```
[Answer]
# Python 2 (with sympy), 100 bytes
```
from sympy import*
lambda n,y:''.join(c for i,c in enumerate(`pi.round(n*n+1)`[2:])if i%n-i/n>n-y-1)
```
---
### No sympy, ~~260 246 244 233 231~~ 218 bytes
```
p=lambda n,y,a=-30,b=10,c=3,d=2,e=0,f=5,s='',i=0:i<n*n and p(n,y,*[((2*b+a)*f,b*d,c*f,d+1,(b*(7*d)+2+(a*f))/(c*f),f+2,s,i),(10*(a-e*c),10*b,c,d,((10*(3*b+a))/c)-10*e,f,s+(str(e)[:i%n-i/n>n-y-1]),i+1)][4*b+a-c<e*c])or s
```
This employs ["The Spigot Algorithm For Pi"](http://www.mathpropress.com/stan/bibliography/spigot.pdf) of Stanley Rabinowitz and Stan Wagon.
The standard arguments would be `a,b,c,d,e,f=0,1,1,1,3,3` to yield the first digit of pi, `3`, since that is not required the algorithm is initialised to the point before `1` is yielded, which saves two bytes even though `a` and `b` are longer as the result does not require slicing and `i` can start at `0` rather than `-1`.
Hits default recursion limit for last test case
Uses `//` for the first of the divisions so that `str(v)` may be replaced by ``v`` (otherwise it would end in `L` for a long).
**[repl.it](https://repl.it/Dv2R/8)**
---
A non-recursive version for 232 bytes which evaluates the last test case too:
```
def p(n,y):
a,b,c,d,e,f,i,s=-30,10,3,2,0,5,0,''
while i<n*n:
if 4*b+a-c<e*c:s+=`e`[:i%n-i/n>n-y-1];g=10*(a-e*c);e=((10*(3*b+a))//c)-10*e;b*=10;i+=1
else:g=(2*b+a)*f;h=(b*(7*d)+2+(a*f))/(c*f);b*=d;c*=f;f+=2;d+=1;e=h
a=g
print s
```
**[repl.it](https://repl.it/Dv5k/5)** (first indent is one space, second indent is one tab)
[Answer]
# Mathematica, 82 bytes
```
Print@@Join@@Partition[RealDigits[Pi-3,10,#^2][[1]],#][[i,i-#2-1;;]]~Table~{i,#2}&
```
[Answer]
# MATL, ~~23~~ ~~22~~ 27 bytes
*1 Byte saved thanks to @Luis*
```
UtEYPwY$IbH+&:)GetGi-&R!g)!
```
[**Try it Online**](http://matl.tryitonline.net/#code=VXRFWVB3WSRJYkgrJjopR2V0R2ktJlIhZykh&input=MjAKMTI)
**Explanation**
```
% Implicitly grab input (n)
Ut % Square n and duplicate
E % Multiply n^2 by 2
YP % Pi literal
w % Flip the stack
Y$ % Compute the first 2 * (n^2) digits of pi (accounts for rounding)
IbH+&:) % Grab the first n^2 digits after the decimal
Ge % Reshape it into an n x n matrix in row-major ordering
t % Duplicate this matrix
Gi- % Grab the second input (y) and compute the difference between n and y
&R! % Get the upper diagonal part and transpose to convert to lower diagonal
g) % Convert it to a logical array and use it to select the digits of interest
! % Transpose the result and implicitly display
```
[Answer]
# Perl, 67 bytes
```
s/ /bpi++$_**2/e;$%=$';$%-=print/(.{$%})$/ for/\d{$`}/g
```
Requires the command line option `-nMbignum=bpi`, counted as 12. Input is taken from stdin.
**Sample Usage**
```
$ echo 3 3 | perl -nMbignum=bpi primo-square-pi.pl
141923
$ echo 5 3 | perl -nMbignum=bpi primo-square-pi.pl
159353
$ echo 6 4 | perl -nMbignum=bpi primo-square-pi.pl
1592589383
$ echo 6 6 | perl -nMbignum=bpi primo-square-pi.pl
141592535893238643794
$ echo 20 12 | perl -nMbignum=bpi primo-square-pi.pl
358979323846950288419715820974944628620899211706792306647223172745025559196615
```
[Answer]
# C#, 232 bytes 268 bytes
Edit:
I originally used a constant string for Pi outside of the method, but it seems this was cheating. I've had to use the C# Math.PI value, which only has 14 decimal places, so the highest `m` value I can use is 3. Back to the drawing board...
Golfed:
```
IEnumerable<string>f(int m,int t){var a=new string[m, m];var b=Math.PI.ToString().Replace("3.","").Substring(0,m*m).ToArray();var c=0;for(int i=0;i<m;i++){for(int j=0;j<m;j++){a[i, j]=b[c]+"";c++;}}c=0;while(t>0){for(int i=t;i>0;i--){yield return a[c,m-i];}t--;c++;}}}
```
Ungolfed:
```
class ATriangularSliceOfSquaredPi
{
//http://www.piday.org/million/
//const string p = "1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831";
public IEnumerable<string> f(int m, int t)
{
var a = new string[m, m];
//var b = p.Substring(0, m * m).ToArray();
var b = Math.PI.ToString().Replace("3.", "").Substring(0, m * m).ToArray();
var c = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
a[i, j] = b[c] + "";
c++;
}
}
c = 0;
while (t > 0)
{
for (int i = t; i > 0; i--)
{
yield return a[c, m - i];
}
t--;
c++;
}
}
}
```
Not the shortest answer, but I was just happy I solved this one...
Test Output:
```
m t output
3 3 141923
```
5 3 159353
6 4 1592589383
6 6 141592535893238643794
20 12 358979323846950288419715820974944628620899211706792306647223172745025559196615
] |
[Question]
[
I got the following question at a test:
>
> Write a function `f` with the following type `a -> b -> (a -> b)`. `a` and `b` should not be bound in any sense, the shorter the code, the better.
>
>
>
I came up with `f a b = \x -> snd ([a,x],b)`. Can you find something tinier?
**Currently the winner is: `f _=(.f).const`**
[Answer]
Your example can be shrunk by getting rid of the anonymous function on the right-hand side:
```
f a b x = snd ([a,x],b)
```
This works because the type `a -> b -> a -> b` is equivalent to `a -> b -> (a -> b)` in Haskell.
[Answer]
The function `f _=(.f).const` is actually of a more general type than `f :: a -> b -> (a -> b)`, namely `f :: a -> b -> (c -> b)`. If no type signature is given, the type inference system infers a type of `f :: a -> b -> (a -> b)`, but if you include the type signature `f :: a -> b -> (c -> b)` with the exact same definition, Haskell will compile it without issue and will report consistent types for the partial applications of f. There is probably some deep reason why the type inference system is stricter than the type checking system in this case, but I don't understand enough category theory to come up with a reason as to why this should be the case. If you are unconvinced, you are welcome to try it yourself.
[Answer]
Given `ScopedTypeVariables`, I came up with this:
```
f (_::a) b (_::a) = b
```
If you shrink down both my function and yours, mine is a hair shorter:
```
f(_::a)b(_::a)=b
f a b x=snd([a,x],b)
```
Of course, you're probably not allowed to rely on `ScopedTypeVariables` :P.
] |
[Question]
[
Jelly has [compressed string literals](https://github.com/DennisMitchell/jellylanguage/wiki/Syntax#string-literals), using the `“...»` delimiters. The way these work is by interpreting the `...` as a base-250 integer, \$n\$, then repeatedly divmod-ing this integer until it reaches \$0 \newcommand{\d}[2]{ \left( \left\lfloor \frac {#1} {#2} \right\rfloor, #1 \text{ mod } #2 \right) }\$, building up the decompressed version as it goes by indexing into dictionaries and printable ASCII.
Jelly has 2 dictionaries, "short" and "long". "Short" contains \$20453\$ words of 5 letters or shorter. "Long" contains \$227845\$ words with 6 or more letters.
As the exact method is rather [complicated](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/interpreter.py#L1055), I'll work through how \$n\$ is decompressed:
* First, we divmod \$n\$ by \$3\$: \$n, m = \d n 3\$. We then call \$m\$ the *mode*.
* If the mode is \$0\$:
+ Divmod \$n\$ by \$96\$, yielding \$n, c = \d n {96}\$
+ Add the \$c\$th character in the printable ASCII range ( to `~`) to the decompressed string. If \$c\$ is \$95\$ yield a newline instead of **0x7F**
* If the mode is \$1\$:
+ If \$n\$ is even, use the "long" dictionary and replace \$n\$ with \$\frac n 2\$
+ If \$n\$ is odd, use the "short" dictionary and replace \$n\$ with \$\frac {n-1} 2\$
+ Then, take the length \$l\$ of the dictionary (\$20453\$ for "short", \$227845\$ for "long"), calculate \$n, i = \d n l\$ and retrieve the \$i\$th element of the dictionary, the *word*
+ If the decompressed string is not empty, prepend a space to the word. Finally, append the word to the decompressed string
* If the mode is \$2\$:
+ Calculate a *flag* \$f\$ as \$n, f = \d n 3\$ and update \$n\$
+ If \$n\$ is even, use the "long" dictionary and replace \$n\$ with \$\frac n 2\$
+ If \$n\$ is odd, use the "short" dictionary and replace \$n\$ with \$\frac {n-1} 2\$
+ Then, take the length \$l\$ of the dictionary (\$20453\$ for "short", \$227845\$ for "long"), calculate \$n, i = \d n l\$ and retrieve the \$i\$th element of the dictionary, the *word*
+ If the flag doesn't equal \$1\$, swap the case of the first character of the word
+ If the flag doesn't equal \$0\$ and the decompressed string is not empty *or* the flag equals \$0\$ and the decompressed string is empty, prepend a space to the word
+ Finally, append the word to the decompressed string
* If \$n\$ is non-zero, go to the first step with the new value of \$n\$
---
We can work through an example, using \$n = 46886323035539\$:
* First, we divmod by \$3\$: \$n = 15628774345179, m = 2\$.
As the mode is \$2\$, we calculate \$n\$ and \$f\$ as \$n = 5209591448393, f = 0\$. \$n\$ is odd, so we're using the "short" dictionary and \$n\$ becomes \$2604795724196\$.
Calculate the index and the updated value of \$n = \left\lfloor \frac {2604795724196} {20453} \right\rfloor = 127355191\$ and \$i = 2673\$. The \$2673\$th word in the "short" dictionary is `Caird`, so we call that our word.
As \$f \ne 1\$, we swap the case of the first character of the word: `caird`. However, \$f = 0\$ and the decompressed string is empty, so we don't prepend a space. Finally, we append `caird` to the (empty) decompressed string, yielding `d = 'caird'`
As \$n = 127355191\$, which is non-zero, we go to the first step again
* Now, `d = 'caird'` and \$n = 127355191\$. Divmod by \$3\$ to get \$n = 42451730, m = 1\$.
As the mode is \$1\$ and \$n\$ is even, we're going to use the "long" dictionary this time around and \$n\$ becomes \$21225865\$
We calculate the index into the dictionary as \$n = \left\lfloor \frac {21225865} {227845} \right\rfloor = 93\$ and \$i = 36280\$. The \$36280\$th element of the "long" dictionary is `coinhering`, so we set that as our word.
As `d` is non-empty, we prepend a space to our word, then append it to `d`: `d = 'caird coinhering'`
As \$n = 93\$, which is non-zero, we go to the first step again
* Now, `d = 'caird coinhering'` and \$n = 93\$. Divmod by \$3\$ to get \$n = 31, m = 0\$
As the mode is \$0\$, we calculate \$n\$ and \$c\$ as \$n = 0, c = 31\$. The \$31\$st ASCII character (alternatively, the character with ordinal \$63\$) is `?`
We add `?` to the end of `d`, resulting in `d = 'caird coinhering?'` and \$n = 0\$
As \$n = 0\$, we are done, and we return `caird coinhering?` as our decompressed string
---
Alternatively, [here](https://tio.run/##3VPLboMwEDzDV2zVA1iJoiQ0URIph6qnnNsbQpUFC7gCG9luab6e2i55uE1/oOJgez0zuzuLu6OuBU@GoZSihTdsmiOwthNSQ8FyzQSn8jiFXBT42tEKw7DAEpRSMeMaK5RkFwYF5qLtJCqFBewhisIw6GvWIIwggwnG7RRao2VQBfswu/gcTogFleP1HuaWdGHlt1nbtaUFvZA287nM1MEnkCwzuIeXmimQqN8lV6BrBB7pGh6fnw4HyGsqaa6tlpBAgWPfMG4qL4Ebxe0q9Mta@GWp2lr1u66lK8vker3YaGDx5TRrBK@mVy7PnBZJ3ZJ5WRgv8PNGlgZ57OcgJLzyw79LnUzmAKaj66ntYGRE5pu4w4@@l37fZUOr20P8L/a4Du/swOFkjl3SeTZTPe1yqjAmo1fpYpeNtJgL7VlLrIiLWkXyh9PeE5rsT/Hvn9bTGzppGoztE3xYbzbrZJnMk9Uq2RIyfAE) is a version of the `sss` function adjusted slightly.
## Task
You are to take a positive integer \$n\$ as input and output the decompressed string that \$n\$ maps to. You may also take the two dictionaries ("short" and "long") as input if you wish. The dictionaries can be [found on TIO](https://tio.run/##S0oszvj/v6CyJCM/z1hBN1lBPa0oP1chKzUnp1IhM7cgv6hEISUzuSQzPy@xqNK6oCgzr0QDIaBXnAFUoamuYAdWFQ/m6pVUlHCRb2ROfl460ESYkSAu2MTkxBI0S/7/BwA) or in the [Jelly repo](https://raw.githubusercontent.com/DennisMitchell/jellylanguage/master/jelly/dictionary.py)
You will never be given an input \$n\$ outside the native bounds of integers in your language, but your program [must *theoretically* work for arbitrarily large integers](https://codegolf.meta.stackexchange.com/questions/18196/how-can-we-clearly-define-must-work-for-theoretically-large-values)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
## Test cases
```
n out
1 Aachen
2 aachen
3 !
47 Aah
218 aaronical
250 Abdul
745 abdominoplasties
7180 auto
8106 . aahs
364038195 Q unconfine
396478210 SoddyAberration
592528345 insulting abature
4060289999 Shool< aalborg
6079656777 CcircuityAachen
2402785962 njX abac
1192732966 flongAllel
69526673848 Kansu4Abderian
7240502929952 Eyehook% arval
7300618740196341 g noninterchangeableu mahwa
98944394632073037 /;streetwards Harz aachen
8092569718755799474 epos sporran@ Apriorism
11508828911594644653 /,e Waterbirdanelasticities
11209288138354511564 eale Thuya&decokes (note the leading space)
11683582443091721078 Saveable! duly babbliest (note the leading space)
13365392696538596641 tambourinists}Battu0abaca
```
Additionally, make sure your program works for \$n = 8609941742042387534416\$:
```
this
has
newlines
```
and also for \$n = 16505187\$:
```
a
b
```
And the outputs for \$1 \le n \le 100\$ (one per line): [Try it online!](https://tio.run/##NVFJcoRADLv7FWTf932bxLnnEQ10aCpdUIUHUnk9sWzmRFuSJdtIDpKizDOHKsWOgn@2iJmKBdtWNLVdQ8XC7ijLFJh2iUMu@0EpBfagUxHTPvAoY1frw1oPwMUaFlYfap3bVhBiwBEEoqZMx@hu/@CFnBNIYct0qs@hnsLwA8yCz9wIPg6cm@a3z98Ic@wCIsEsdLmhpyg2DV0hTtY2CV1rMTRhRIMvcAN63VuAI7fQpNHaF@hOL/IFf13xHnTftZXZK/AAQC0L5x83vG7FfoQnDNUkM0T97BIpRzutgy8OIkXoFR1Li5ZvxJ/mL7RamGSHwRXflWS3QfmhhEx9E7PnAdO/WYZqnv8B)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~173 170~~ 163 bytes
Expects `([ long_dic, short_dic ])(n)`, where the dictionaries are arrays of words and **n** is a BigInt.
```
d=>F=(n,C)=>n?(B=Buffer,(g=k=>x=+[n%(n/=k=BigInt(k),k)])(3)?(q=x^2||g(3),b=B(d[g(2)][g(d[x].length)]),b[-q%2]^=32,q%3>0^C?' '+b:b):B([g(96)^95?x+32:10]))+F(n,1):''
```
[Try it online!](https://tio.run/##jZbfcqM2FMbv/RRapikwIV4hhICkJI0zu9NOrzrpTDvjdboCZMMGS44Qid1s3qAzvell@x59nn2BPkJ6SNabfzgpFxpj8dP5dDjfER/4OW9yXS3MjlSFuM6VbAy6RGIp8uOVzNEVSpEWZ22lhWPlZVUXvy60ykXTWK43KKoc5sfIrpWc2R6ym1JpY6PJcM4XToPSfSTOee2sl3PeL1amVDJAOzmyp1rN0QdR1ytUzRcAIljPVEpyvdpb6Eoa5@6P4VeXzZVrv3eHRh0bmJw5ruvuDQbT9LpI99@mjvSO3HRfHjijdNROp0J7ziw9TfeX6fZYbjnyNdyMqtn3sOyp6526E9cJ3APnLF2ekI8fZ3DjZenIKcYzh7gTGIvxcjKshZyZEh72svHO2RaZnKQB8c62gn18cnRgI3s7283c3ZEDQMLckyQ8WG4HZNfHE9fdfguqfHfXtq/3xgMEmfIl6rs8ZB3yvBTS6p1GE@@GJhtp/j/oYCP9agN4n6aR3Ki8tF6iiR/LTcq1klXOa@sZOsQb6MOsaGvr@dgRDTfFzgo1r6Ra1LwxlWisPtqP@4J3dGuU9cK@Yx@zfnqIOC@bF94YoziI/eSRfqB/RK0Es04rKayNdMJoFBMfP6GPVVGsDjOhNe/sZfXRYUJCEgf0aexKNm1twIGIZ9y0@oGCdbVghkmcwCUfxy6Vqr@BzdeZ0jOrVznDUcJCFkXRY/oor3TeVmbVZ5d1tVBMojhMGHlMyw@/dJpz65mc@35CooAkjD2mp12XO6xr0Vdwa@VJSBiLgpg@qHegf@CQNgr1KnTFZf@@I5AeYpKQBJaR9@k3KwF5O91CXJ8/scqaDjBmfhxR7CcsoOtWA/QMSfCYNELnJZczwbNatGjOywturekkTigNEsoCgmGl4HPqgX691xgthLngumjQd1z/hu7azbrOMZQLS8AsURhGSUIjKm9psVANaqC9ay6/RYfQ15Wumrn1MOchjmOoF/gBCihlYdesutieQD9zEJ5VuuBS3Bg1r27N@oUmED2O/SAOQhrCGoze0kjwWqCfynbFvy5Erk7vW/wLzQCLCWweJ34Edoniz/QxP79J1SsETWaFMp5lNQQ29/btBwFoTQiDeg26mmM3eQfa8HmmWjioqsY0VyNuTIu72uP3s8YwpMqPKMGUBJC6gFKfyY4uq@adLDkMUlzUYPMe5SzEISRcPu1M72S2uTMNJoPhVOk38A4dZ4wgnFguRG5EgSZud2ZfwpEPhzeaduev60h3D3UfBqoWw1rNHJj0bp9I78gDZP/7zx@f/voTRhvtIvvT37/bAF651/8B "JavaScript (Node.js) – Try It Online")
### Commented
```
d => // outer function taking d[] = dictionaries
F = (n, C) => // inner function taking n and a flag C
n ? // if n is not equal to 0:
( B = Buffer, // B = alias for Buffer
( g = k => // g is a helper function taking a divisor k
x = +[ // it computes and returns x = n modulo k
n % ( // and updates n to floor(n / k) afterwards
n /= //
k = BigInt(k), // k is first converted to a BigInt
k // but x is converted back to a Number
) //
] //
)(3) ? // extract the mode; if it's not 0:
( q = // q = flag; we force q = 3 in mode 1
x ^ 2 || g(3), // otherwise, it's extracted from n
b = B( // b is a Buffer:
d[g(2)] // select the relevant dictionary
[g(d[x].length)] // and extract the relevant word from it
), // end of Buffer
b[-q % 2] ^= 32, // if q is even, toggle the case of the 1st char.
q % 3 > 0 ^ C ? // if (q mod 3 != 0) XOR C is true:
' ' + b // append a space and the word
: // else:
b // just append the word
) //
: // else (mode 0):
B([ // use a Buffer to generate a character:
g(96) ^ 95 ? x + 32 // extract the character ID and add 32
: 10 // or force a line-feed if it's 95
]) // end of Buffer
) //
+ F(n, 1) // append the result of a recursive call
: // else (n = 0):
'' // stop the recursion
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/iki/Code-page)
Obligatory Jelly answer.
```
ḃØ⁵ịØJ⁾“»jV
```
**[Try it online!](https://tio.run/##ATgAx/9qZWxsef//4biDw5jigbXhu4vDmErigb7igJzCu2pW////ODYwOTk0MTc0MjA0MjM4NzUzNDQxNg "Jelly – Try It Online")**
### How?
```
ḃØ⁵ịØJ⁾“»jV - Link: integer, n
ḃ - convert (n) to bijective base:
Ø⁵ - 250
ị - index into:
ØJ - Jelly's code-page
⁾“» - list of characters = "“»"
j - join -> "“...»"
V - evaluate as Jelly code
```
[Answer]
# [Python 3](https://docs.python.org/3/), 245 bytes
```
def f(n,s,l,i=0):
t=""
while n:
if n%3:
if n%3>1:f=n//3%3;n//=9
else:f=-1;n//=3
d=[l,s][n%2];w=d[n//2%len(d)];t+=((t!="")^(f>0))*" "+[w[0].swapcase(),w[0]][f%2]+w[1:];n//=2*len(d)
else:t+=chr((n//3%96+22)%117+10);n//=288
return t
```
[Try it online!](https://tio.run/##VVLdruM0EL6un8InUlGyLT3@SRz7HLrigFZC4gotEkhNkZzEabxNnchxthRpb3kAHpEXOUzSgxC5yXh@vm/mmxluoe0df32tTYOb2G3Hbbe1e5I8oVXYRxFaXVvbGezgvbINdms@W2/me/rU7N3jI1/zZ/jt1Rwy3WjA/TVdXHx21ftDtx2PB7dmx@frvj5AhK074@I6OT6HzT6OwwOwJb/FzXuSJO8iHG0O1wM57sarHio9mjjZzu/joQGMzfVAn44LPnt3h0FvxABWtT6Ol66U2DCWrCnNN5Qk93wp0cqbMHmHw2vj@wv@ZLruhu1l6H3Ata2C7Z32N4Tuo//sJwMz6y0u8R5bN0whTnbj0NkQR0URAbVeAiHWuzF4O8QJ@M7ga2Ko@g9xN7ZA8T9P17sTJA9@Lo/M74Opgqkj4Nri6NQHsM5g4b///AtHSwd7fE5eKYhavOiqNQ6x2dZ3m8/2A0rze7xFjMp72PfOVrpDLCNLrKynDuVptkTLur9Y1w@dHoM1I8qpXLL0FHokKRHzY4e1bkfERUq4pAoqi5/w5KreNdYZxJVIc8koFBYf@7q@vZTGez0PijLFMib5zFZYN05dsO6EdalhDQalRBAmFXxzadv33TdA1ZW9PyFBciUykecwUfF9ZX012XD7d/KUsFxmSoAEhfv064xYIUoVyzlTAroumlngl64zHRIqY0LkXKYgSfGjhj5SkMF4qx3KASsjTDEFWRD@cDPQyHmNtf8MquWcEEFlnhKqBE/pqjhhB4q6YHzVancyuuzMhC@6vWqkpEpTrlLBGYFKnq@Kx2e4DGPCVft6xD9o/wd@W5kkII5QIHmeZblSaZ6uCjP0Ix7hIL123@IXOI/e2/ECs2VEShALDMBPU5FxAN8a/IuGVkrra@3MssbKLquklAGBlJRLnqUZ1AnAx0bPl91ON/1Vbar@vGQKSJEMWieK5rDJXELmR/15Ge4Bw8XccKnLsgPggCjnwK6YgAXxeQti1iXoS9lPcM52DOOX73QIE5nXov8B "Python 3 – Try It Online")
Pretty poorly optimized; working on a better approach.
] |
[Question]
[
Your task is simple: Write a program (or function) that takes no input and outputs something like this:
```
## *name*, *length* bytes
*code*
```
Where `*name*` is the name of the language you are using, `*length*` is the number of bytes in your code, and `*code*` is your program's source code. If `*code*` contains multiple lines, it have four spaces before each line.
Here's a 124-byte example implementation in Python 3:
```
s = "## Python 3, 124 bytes{2} s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))
```
The output is:
```
## Python 3, 124 bytes
s = "## Python 3, 124 bytes{2} s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
print(s.format(s,chr(34),chr(10)))
```
Which in Markdown is:
>
> ## Python 3, 124 bytes
>
>
>
> ```
> s = "## Python 3, 124 bytes{2} s = {1}{0}{1}{2}print(s.format(s,chr(34),chr(10)))"
> print(s.format(s,chr(34),chr(10)))
>
> ```
>
>
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer (in bytes) wins.
[Answer]
# RProgN 2, 28 Bytes
```
«" %s"F"#RProgN 2, 28 Bytes"
```
[Answer]
# Underload, 48 bytes
```
(#Underload, 48 bytes
)(~:S( ):S*aSaS(:^)S):^
```
[Answer]
## Python 2, 58 bytes
```
_='## Python 2, 58 bytes\n _=%r;print _%%_';print _%_
```
[Answer]
## reticular, 58 bytes
```
"'34'c: 4*91+c:s:e:t:y:b: 85: :,:r:a:l:u:c:i:t:e:r: :#dqO;
```
[Try it online!](http://reticular.tryitonline.net/#code=IiczNCdjOiA0KjkxK2M6czplOnQ6eTpiOiA4NTogOiw6cjphOmw6dTpjOmk6dDplOnI6IDojZHFPOw&input=)
Explanation: `:c` pushes the single-char string `c`. This builds the string "## reticular, 58 bytes", backwards character by character, reverses the stack, and `O`utputs everything, including the string captured by the initial quote.
[Answer]
## CJam, 33 bytes
```
{"## CJam, 33 bytes"N@S4*\"_~"}_~
```
Works a lot like the Underload answer.
Stack trace (`N` represents `\n`)
```
{"## CJam, 33 bytes"N@S4*\"_~"}
{"## CJam, 33 bytes"N@S4*\"_~"} {"## CJam, 33 bytes"N@S4*\"_~"}
{"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes"
{"## CJam, 33 bytes"N@S4*\"_~"} "## CJam, 33 bytes" N
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"}
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " "
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " " 4
"## CJam, 33 bytes" N {"## CJam, 33 bytes"N@S4*\"_~"} " "
"## CJam, 33 bytes" N " " {"## CJam, 33 bytes"N@S4*\"_~"}
"## CJam, 33 bytes" N " " {"## CJam, 33 bytes"N@S4*\"_~"} "_~"
<implicit output>
```
[Answer]
# V, 25 bytes
```
ñi#V, 25 bytes<esc>o´ Ñ<esc>~"qpx
```
---
(This is not counted in the generated markdown, because I like providing explanations for my code :P)
Here is a hexdump, since the source code contains unprintable/non-ASCII characters:
```
00000000: f169 2356 2c20 3235 2062 7974 6573 1b6f .i#V, 25 bytes.o
00000010: b420 d11b 7e22 7170 78 . ..~"qpx
```
This answer is just a trivial modification of the standard [extensible V quine](https://codegolf.stackexchange.com/a/100426/31716).
Explanation:
```
ñ " Run the following code one time, storing it in
" register 'q'
i " Enter insert mode
#V, 25 bytes<esc> " And insert the header
o " Open up a newline, and enter insert mode again
´ Ñ " Enter four spaces, then a 'Ñ' character.
" (The reason we insert it uppercase, is because
" lowercase would end the loop now)
<esc> " Return to normal mode
~ " Toggle the case of the char under the cursor ('Ñ')
"qp " Paste the contents of register 'q' (this is the
" same as the entire program minus the initial 'ñ',
" followed by a 'ÿ' character because V is weird)
x " Delete the last character (the ÿ)
```
[Answer]
# JS, ~~50~~ ~~49~~ ~~27~~ 30 bytes
```
f=_=>`#JS, 30 bytes\n f=`+f
```
---
## Try It
```
f=_=>`#JS, 30 bytes\n f=`+f
console.log(f())
```
[Answer]
# [Go](https://go.dev), 102 bytes
```
import.`fmt`;func f(){s:="## Go, 102 bytes\n import.`fmt`;func f(){s:=%q;Printf(s,s)}";Printf(s,s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BmoLE5OzE9FSF3MTMvKWlJWm6FjfTMnML8otK9BLScksSrNNK85IV0jQ0q4utbJWUlRXc83UUDA2MFJIqS1KLY_IUgACnetVC64CizLySNI1inWLNWiUUHsS2TWD1INuBWriA-rigEgsWQGgA)
From my variant in a [comment](https://codegolf.stackexchange.com/questions/69/golf-you-a-quine-for-great-good/123763#comment564137_123763) under the post below. A callable function. Prints:
```
## Go, 102 bytes
import.`fmt`;func f(){s:="## Go, 102 bytes\n import.`fmt`;func f(){s:=%q;Printf(s,s)}";Printf(s,s)}
```
## [Go](https://go.dev), 134 bytes
```
package main;import.`fmt`;func main(){s:="## Go, 134 bytes\n package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BgqWlJWm6FjfbChKTsxPTUxVyEzPzrDNzC_KLSvQS0nJLEqzTSvOSwcIamtXFVrZKysoK7vk6CobGJgpJlSWpxTF5CkBAtH7VQuuAosy8kjSNYp1izVolFB7ENVBHwRwHAA)
Using the quine found [here](https://codegolf.stackexchange.com/a/123763/77309). A full program. Prints:
```
## Go, 134 bytes
package main;import.`fmt`;func main(){s:="## Go, 134 bytes\n package main;import.`fmt`;func main(){s:=%q;Printf(s,s)}";Printf(s,s)}
```
[Answer]
# [Factor](https://factorcode.org/), 80 bytes
```
"# Factor, 80 bytes\n %uUSE: formatting dup printf"USE: formatting dup printf
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjYP1fSVnBDSyjo2BhoJBUWZJaHJOnAASqpaHBrlYKaflFuYklJZl56QoppQUKBUWZeSVpSril/v8HAA "Factor – Try It Online")
] |
[Question]
[
**TLDR: This is the hexagonal version of [Is this square symmetrical?](https://codegolf.stackexchange.com/q/90214/9288)**
Given a hexagonal grid, decide if it is symmetric.
The shape of the grid is a regular hexagon. Each cell in the grid has two possible states.
Let's only consider reflections and rotations. Here are all the possible symmetries:
* Reflection symmetry, where the axis is the perpendicular bisector of an edge (there are 3 possible such axes):
[](https://i.stack.imgur.com/tKIzX.png)
[](https://i.stack.imgur.com/CPn3T.png)
[](https://i.stack.imgur.com/cWZGR.png)
Smaller examples in ASCII art:
```
. . . . . . * . * . * .
. * . * . * . * * . . . . . *
* . . . . * * * . . . . . * . . . .
* * . . . * * * * * * . * . * . . . . . *
. . * * . . . * * . * * . . . . * .
. . * . . . * * . . * . . . .
* . . * * * * . . * . *
```
* Reflection symmetry, where the axis is a diagonal (there are 3 possible such axes):
[](https://i.stack.imgur.com/5h5sP.png)
[](https://i.stack.imgur.com/bYBLh.png)
[](https://i.stack.imgur.com/wJv2t.png)
Smaller examples in ASCII art:
```
* . * * . . * * * * . *
* * . * . . * . * . . * . . .
. . . . . . * . . . . . * . . . . *
* . . . . . . * * . . . * . * * . * . * *
. . . . . . . . . . * * . . . . . .
* * . * . . * * . . . . . * *
* . * * . * . . * . . *
```
* 60° rotational symmetry:
[](https://i.stack.imgur.com/AnCez.png)
A smaller example in ASCII art:
```
* * . *
. * . * *
* . . . . .
* * . * . * *
. . . . . *
* * . * .
* . * *
```
* 120° rotational symmetry:
[](https://i.stack.imgur.com/Vbw1f.png)
A smaller example in ASCII art:
```
* . . .
. . * . *
* . . . . .
. . . . . . *
. * . . * .
. . . . .
* . * .
```
* 180° rotational symmetry:
[](https://i.stack.imgur.com/Ei9UE.png)
A smaller example in ASCII art:
```
. . . .
* . * . .
. . * * . .
* . . . . . *
. . * * . .
. . * . *
. . . .
```
### Input
A hexagonal grid, in any reasonable format. You may choose the two distinct values for the two states in the input. When taking input as an 2d array, you may use one of the two states or a third value for padding.
Some example inputs (Taken from [Bubbler's HexaGoL challenge](https://codegolf.stackexchange.com/q/240238/9288)):
* ASCII art:
```
. . .
* . . *
* . * * *
* * * .
* . .
```
* List of rows:
```
[[0, 0, 0],
[1, 0, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 0],
[1, 0, 0]]
```
* 2d array, skewed to the right (with zero padding):
```
[[0, 0, 0, 0, 0],
[0, 1, 0, 0, 1],
[1, 0, 1, 1, 1],
[1, 1, 1, 0, 0],
[1, 0, 0, 0, 0]]
```
* 2d array, skewed to the left (with `2`'s as padding):
```
[[0, 0, 0, 2, 2],
[1, 0, 0, 1, 2],
[1, 0, 1, 1, 1],
[2, 1, 1, 1, 0],
[2, 2, 1, 0, 0]]
```
* Flatten array, with an integer that indicates the size:
```
3, [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0]
```
### Output
A value representing whether the hexagonal grid is symmetric. You can choose to
* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
### Testcases
Here I use 2d arrays skewed to the left with zero padding.
**Truthy:**
```
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 1, 0], [0, 1, 1]]
[[1, 1, 1, 0, 0], [1, 0, 0, 1, 0], [1, 0, 1, 0, 1], [0, 1, 0, 0, 1], [0, 0, 1, 1, 1]]
[[1, 0, 1, 0, 0], [0, 1, 1, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1]]
[[1, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 1, 1, 1, 1], [0, 1, 1, 0, 1], [0, 0, 1, 1, 1]]
[[1, 1, 1, 1, 0, 0, 0], [1, 0, 1, 0, 1, 0, 0], [1, 0, 0, 1, 0, 1, 0], [1, 0, 0, 1, 0, 0, 1], [0, 1, 0, 1, 0, 0, 1], [0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 1, 1, 1, 1]]
```
**Falsy:**
```
[[1, 0, 0], [0, 0, 0], [0, 1, 1]]
[[0, 1, 0], [1, 0, 1], [0, 0, 0]]
[[0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [1, 0, 1, 1, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 1]]
[[0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 1, 1], [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0], [1, 1, 0, 0, 0], [1, 0, 1, 1, 1], [0, 1, 0, 1, 0], [0, 0, 0, 1, 0]]
[[1, 0, 1, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]]
```
[Answer]
# [Python](https://www.python.org) NumPy, 92 bytes (@Neil)
```
def f(l,*o):
for a in[l>0]*6:l.T[::-1][a[::-1]]=l[a];o+=str(l),str(l.T)
return 7>len({*o})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVTBbqMwEFXVG_-w0jS92ClJ8R7aioretl-QG-VgNSZYdQyyTaOo2i_pJZfuP20_YL9jAZcQA2mlIiSPx-M3894MvP4ptibL5W73Vpp0dvP3YclSSJHwpzkOPUhzBRS4jMVdkEyvQjFfxGE4I0lM7ZpEIqbJbX4RaaOQwH6zzBfYA8VMqSRc3wkm0cs0_41tjveTH3xd5MqALNfFFqgGWXibjAsGSIcRl0VpEMZn0eSXXE6qKoCnoOfaUGX0hpsMTeJJXV31aIiq23OqFN0i9kwF0hg3J-fwqBg1DNbUPGZcripDPzVH1F4yigtk1xLpKNL-DNW1anx5-RNj_3DTQmZUrhikKl-DYKkB_cQ2bAkmB8VXWbtvolmVRVfifNQ5jSCw5l67KoBdkMZZKC4NSuvqrUq799N_C1WabBt6XhwHPtRv4sOYmQwiiGOSJoJYu4v7MLtost_VdzokxxG0MHvUwEHtzvuopI9KHB5t3g51QJUMmPVRyRe1OiKM0T4iT5_OmDJk3N07OXC7HBLPu6dC24aTPvVBO4d9OzISn4j4ndY45B0uB8KRkbyBk-bgymitx7v0Ra2twxnOAVR_FAYT1J-04w0f0zj4TIKOt1f94ez3_h8)
## Pure (no NumPy) [Python](https://www.python.org) version, 111 bytes
```
lambda l:7>len({l:=((x:=~len(l)//2)and(*(k[(x:=x+1):]+k[:x]for k in i*l[::-1]),)or(*zip(*l),))for i in[0,1]*6})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVTBjtMwEBXilq8YysVO092YA6BI4QZfwC3kYLZOY8VxItuhLQh-hMtKCP6J_YD9Dpyk2dRJuishRc3MeOaN35tJf_6pjyav5O2vLP70uzHZ5u3fStDy85aCiN68E0yibyKKETpE8Y_WE_j6-hWmcot8VCRt-LAmOErXRRId0qxSUACXwH2RRNGGpDjAlUL-V14jX1gHtyncpiRhQFL_9Xfct717tuFlXSkDsinrI1ANsvb2ORcMkI5iLuvGIIxfxKv3cruKPACegb7Shiqj99zkaJWscBsH0BDb6iuqFD0i9oUKpDHuTl7CjWLUMCipucm53FlDF90R7YuM4gL17wbpONbBBrXEdUccB-fOAJlTuWOQqaoEwTIDumB7tgVTgeK7fPC7bGa76ISmp3v6MYS9mdBesNQmsDXpgrXi0qAMnfTrfiwTq-JJtdu75_cfVWPyY-R5iZUU2icNYMlMZxnEMUmXQXp7zDuZYzZ58NqaEckJhAPMA2rooI7nU1QyRSUOj6HviDqjSmbMpqjkibs6IizRviDPlM6SMmQ5PDk5C7scUs_7QIXuB06m1GfjnM_twko8IuL_jMYh73A5E44s9A2dNmcli3e9PKUn7joEnOWcQU1XYbZB0027PPAljcPHJBh5e_Yfr__e_wE)
#### Old [Python](https://www.python.org), 128 bytes
```
def f(*l):
for n in[len(*l)//2]*6:l+=(k:=(*(j[i:]+j[:i]for i,j in enumerate(l[-1][::-1],-n)),)),(*zip(*k),)
return 7>len({*l})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVTBjpswEFW1N75iNr0YAru4h-4Kid7aL-jN4mBtTHDiGGSbjdKqUv-jl1zaf-p-QL-jBsISA9mVFiEYj8dv5r0Z-PWnOpiilMfj79rk0f3fnyuWQ44C4Sce5KUCCVwSwWTjur39kAUfE7FM0TZJUYA2hCfZckMSnjWxPNzYaGCy3jFFDUOCRDgjSWKfYSR9P7Q3Cr7xCgVbu_BAMVMrCXefmgzfA_HD7-p4ehfxXVUqAxarOgDVICtvX3DBAOkk5bKqDfL963TxWa4WtlbgOegbbagyes9NgRZk0XCwl4bUnr6hStEDYo9UIO377c57eFDMFgo7ah4KLtfW0Nt2i3aHjOICde8a6TTVYYSaWnUjRsPmbNFDFlSuGeSq3IFguQG9ZXu2AlOC4uuiX7fRzGbRhGanOoMU4s4ktJMtswFsiVtnpbg0KEcnBduHbkU9qXZ8uvr3VdWmOCSeR0gcQnNnIcyZ2SQCOyZuI3BnD3Enc4jGz6vmzIDkOOIe5hk1dlCH_TEqHqNih0efd0CdUMUTZmNU_EqtjghztC_IM6Yzpwyed492ztwuh8zzvlChu4bjMfVJO6d9uzASL4j4ltY45B0uZ8Lhmbyxk-bsyGytl7v0Sq29wxnOCdR4FCYTNJ60yw2f0zh-SYKBt2f_eN33_h8)
#### Old [Python](https://www.python.org) NumPy, 93 bytes
```
def f(l,*o):
for a in[l>0]*6:l.T[::-1][a[::-1]]=l[a];o+=str(l),str(l.T)
return 12>len({*o})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVTBbqMwEFXVG_9QaZpe7JSkOIeqoqK37RfkhjhYjQlWHINs0yha7ZfsJZfdf9p-wH5HAZcQA2mlIiSPx-M3894M_P5b7E2Wy8PhT2nS2cO_ZMVSSJHwpzkOPUhzBRS4jMVTkEzvQzFfxmE4I0lM7ZpEIqbJY34baaOQwH6zzJfYA8VMqSSQxZNgEv2c5r-wTfJ2ccW3Ra4MyHJb7IFqkIW3y7hggHQYcVmUBmF8HU1-yNWkKgN4CnquDVVG77jJ0CSe1OVVj4aouj2nStE9Yq9UII1xc3IDL4pRw2BLzUvG5boy9KY5ovaSUVwgu5ZIR5H2Z6iuVeO7uwXG_ummhcyoXDNIVb4FwVIDesN2bAUmB8XXWbtvolmVRVfqfNQ5jSCw5lG8KoDdksZZKC4NSuvqrUqHt8v_S1WabB96XhwHPtRv4sOYmQwiiGOSJoJYu4v7MLtoctzVdzokxxG0MEfUwEHtzvuopI9KHB5t3g51QJUMmPVRyRe1OiKM0T4jT5_OmDJk3N07OXG7HBLPe6ZC24aTPvVBO4d9OzMSn4j4ndY45B0uJ8KRkbyBk-bkymit57v0Ra2twxnOAVR_FAYT1J-08w0f0zj4TIKOt1f94ez3_g4)
#### Old [Python](https://www.python.org) NumPy, 97 bytes
```
def f(l):
o={0}
for a in[l>0]*6:l[::-1][a[::-1]]=l[a];o|={str(l),str(l:=l.T)}
return 13>len(o)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVRBbtswEETRm_5QYOtcyFR2xAYoChXMrX1BboIORExZRGhKIKkaRtqX9OJL-6fmAX1HKTGyTElOgBgGuFzuzu7Mrv3rT723ZaUOh9-NLZaf_7I1L6BAEqcRVPQh-RlBUWlgIFQmb5L88lMqszRdkjxj_sypzFj-pfpBH4zVLjPujpTK1S126ZrbRisg1zeSK1RhX-jxzTuxrSttQTXbeg_MgKqjXSkkB2RSKlTdWITxe7r4qtYL1w2IAszKWKat2QlbokW2aLt0HwPUZa-Y1myP-HcmkcG4e7mAO82Z5bBl9q4UauMMc989MZ9ktZDInw0ylJp4idpGDb66-ohxfHrpIUumNhwKXW1B8sKCuec7vgZbgRabsr930dxVMU6fpz4vKSTePMrnAvgH0jlrLZRFRdu9V-nw-PbfrW5suU-jKMuSGNpvHsOcmU8iSGCSLoJ4e4h7Modocry1OQNS4Eh6mCNqEqAO72NUMkYlAY--7oA6oUomzMao5IVeAxHmaJ-RZ0xnThky7x69nLhDDnkUfWPS-IGTMfXJOKdzO7MSz4j4mtEE5AMuJ8KRmbpJUOYkZbbX81N6odfeESznBGq8CpMNGm_a-YHPaZw8J8HAO3L_cP73_h8)
#### Old [Python](https://www.python.org) NumPy, 111 bytes
```
def f(l):a=l>0;b=l*0;l=l[a];b[a]=range(len(l));return 12>len({str(l:=l[s])for s in[b.T[a],b[::-1][a[::-1]]]*6})
```
[Attempt This Online!](https://ato.pxeger.com/run?1=nVRBbtswEETRm_5QYOteSEd2xByKQgZza1-Qm6ADHVMWEZoSSCqGUeQlufjS_ql5QN9RSoosU5IToIAgLZe7szuzaz__Lg82L9Tx-Kuy2eLbn2LDM8iQxDGj8jZaramcRytJZcLS1dq9qGZqy5HkygXhlea20grIzW3t-WmsRjJ20SbFWaHBgFDJennnEsN1EscLkias_abp_OsTbsu-fPgkdmWhLahqVx6AGVBlsM-F5IBMTIUqK4sw_kxn39VmFgcAIgOzNJZpa_bC5miWzHDtB1eTuuwl05odEH9kEhmMm5svcK85sxx2zN7nQm2dYR6aK9YmWS0kar8VMpSacNFQNfj6-gbj8PzQQea1IJDpYgeSZxbMA9_zDdgCtNjm3bmJ5q6KcVq89jmnELXmSRQXwK9I4yy1UBZldfetSseXj3_vdGXzQxwESRKFUD9pCFNmOoognkmaCNLafdyr2UeT06nO6ZE8R9TBnFAjD7W_H6KSISrxeHR1e9QRVTJiNkQl7_TqiTBF-4I8QzpTypBp9-DmzO1zSIPgB5OmHTgZUh-Nczy3Cyvxhoj_MxqPvMflTDgyUTfyypylTPZ6eUrv9No5vOUcQQ1XYbRBw027PPApjaO3JOh5B-4frv29_wM)
Takes right-skewed zero-padded input with values 1 and 2.
Generates the 12 possible symmetries from two relatively easy to implement reflections, viz. updown and matrix transpose. As their axes subtend an angle of 30° their composition is a 60° rotation. We can therefore apply them alternately and then count the number of distinct patterns.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~61~~ 58 bytes
```
WS⊞υ⪪ι¹≔⟦⟧θF⁶F²«⊞θ⭆υ⪫λωUMυ⎇κ⮌λE✂υ⁺⊘Lυμ±⁻⊘⊕׳Lυμ±¹⊟ν»⊙θ⊖№θι
```
[Try it online!](https://tio.run/##RU/NasMwDD43T6GjXLxAN9hlp9Id1rGOsPQ2djCpmpg5cuo4LWXs2TM5hcXGlvz9IVeNCZU3bhwvjXUEuOVuiGUMlmtUCoqhb3DQUHbORrQaVko9Zeu@tzXj55eGkzyPPgA@KpjqvYKfbDH5TuKbknamSyGv3jI6DReVQhaCbnzbGj4kck@BTbjit4YPOlPoCZ3SkKylsxUlTeGGHl@MO9MB34jrKLMpEbVy3qk2kXBnedZsuQrUEkfp97alHh80zMabdfauUl/4DllNE/5mhUwfcc3X9JdnmtM2fhBCQDtJx3EpK1vmsuWeS34D838uyca7s/sD "Charcoal – Try It Online") Link is to verbose version of code. Takes input as newline-terminated ASCII art but without any spaces and outputs a Charcoal boolean, i.e. `-` for symmetric, nothing if not. Explanation:
```
WS⊞υ⪪ι¹
```
Input the list of rows.
```
≔⟦⟧θ
```
Start building up the list of rows and reflection.
```
F⁶F²«
```
Loop through six rotations and two reflections. (Probably overkill, but I can't make it any shorter by performing less work.)
```
⊞θ⭆υ⪫λω
```
Save the current hexagon to the list.
```
UMυ⎇κ
```
Modify the hexagon in-place, alternating between either...
```
⮌λ
```
... reflecting it along the T-B bisector, or...
```
E✂υ⁺⊘Lυμ±⁻⊘⊕׳Lυμ±¹⊟ν
```
... reflecting it along the BL-TR diagonal. Since the combination of these two reflections is a 60° rotation, this eventually covers all possible symmetries.
```
»⊙θ⊖№θι
```
Check the list for duplicates.
The BL-TR diagonal reflection is obtained by taking slices of the hexagon, starting from just the top half, extending each row until the whole hexagon is covered, then shrinking until the last row takes the bottom half of the hexagon. The last character of each row is removed and these characters form the new row of the hexagon.
Previous 61-byte canvas based version:
```
WS⊞υι≔⟦⟧θF³«FLυ«M✳⁻ι⊗⊕‹⊗κLυP✳⊖ι§υκ»F²«⊞θ⪫KAω‖»⎚»F✂θ⊞θ⮌ι⊙θ⊖№θι
```
[Try it online!](https://tio.run/##TVBNb8IwDD3TX5Gjg7oetmNPFb2AQKrgOO3QFUOjZgnNR9k08ds7J4WVREpsP/v52U1bm0bXchyvrZDIYK0u3h2cEeoMnLPK2xZ8ygTPk8JacVbw/pGyntyTNgzeOPtNFtHcojo7SuYxtNjpAaEUBhsntIKdUN6CSFmp/afEIzVqDH6hcmRv0Vp4AB1P2cwVTx74vHTiQrrcE2uJM4ngVFi4tTrid5DcxbrbXd3rpCrO06dso4WCCrErpASqu05N9niSRA33ypXE2gTnNk17kKJB6B97IZ49DmgshuZ5UkV1hfoJyLO0lfYE9GGNYZpxXNJJlhldeucvm4LZPxbSxpdB/gE "Charcoal – Try It Online") Link is to verbose version of code. Takes input as newline-terminated ASCII art but without any spaces and outputs a Charcoal boolean, i.e. `-` for symmetric, nothing if not. Explanation:
```
WS⊞υι
```
Input the ASCII art.
```
≔⟦⟧θ
```
Start building up the list of rotations and reflections.
```
F³«
```
Loop through the rotations of -60°, 0° and 60°.
```
FLυ«
```
Loop though each line of the ASCII art.
```
M✳⁻ι⊗⊕‹⊗κLυ
```
Move along the edge of the hexagon.
```
P✳⊖ι§υκ
```
Output the line of ASCII art.
```
»F²«
```
Loop through each reflection.
```
⊞θ⪫KAω
```
Serialise the ASCII art back to text and join all of the lines together.
```
‖
```
Reflect the ASCII art horizontally.
```
»⎚
```
Clear the canvas ready for the next rotation.
```
»F✂θ⊞θ⮌ι
```
Append the 180° rotations of the above rotations and reflections to the list.
```
⊙θ⊖№θι
```
Check the list for duplicates.
Here's a 73 byte modification that takes (spaced) ASCII art as input and outputs all 12 rotations and reflections as ASCII art:
```
WS⊞υ⁻ι ≔⟦⟧θF³«FLυ«P✳⊖ι⪫§υκ… ¬⊖ι¿‹⊗⊕κLυM⊕¬ι✳⁺⁴÷׳ι²M⊕‹¹ι✳⁻⁻ι¬ι²»F²«D‖D‖↓»⎚
```
[Try it online!](https://tio.run/##ZZBNT8JAEIbP7a@YcJo11UTwpCdCLzViiHozHrAMdMKyW7u7oDH89rrbQguSpul8Pu/byYt5leu5rOtdwZIAM1U6@2orVisUAmbOFOgSmLJyBjmBAQyEeIjHxvBK4ftHAl8@XeoKcCTgN46a8InUyvpF0ZSiqZOWS8@0mHJFuWWtMKW8og0pSwtkIRJ41KxwbDO1oO@gufa1yU8uaVLoEr1wAs/a/t8TwU4U8TKoGoOpdp/StzLVj60D/sTTVG/pbCBwGw@9vZn0P3yXQKZsylteEL7xhgyOEmA/ODwKkzR0CWys3IbRM2h7xu6Yneywhe0P5xu2Z0vdpsRG5IWW0iPa5LJ8n@qdOgAmkuZVaO/rGgCu2icO0U37xs3nmPRx1@qS050eVV9v5R8 "Charcoal – Try It Online") Link is to verbose version of code. Output is in the following order:
* Rotate 60° clockwise
* Reflect along TL-BR diagonal
* Rotate 120° anticlockwise
* Reflect along BR-TL bisector
* Rotate 0°
* Reflect along T-B bisector
* Rotate 180°
* Reflect along L-R diagonal
* Rotate 60° anticlockwise
* Reflect along BR-TL diagonal
* Rotate 120° clockwise
* Reflect along TL-BR bisector
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 137 bytes
```
g=lambda h:(*[".".join(r.split(".")[::-1])for r in h],)
f=lambda h,*S:len(S)<8>0<f(g(map("".join,zip(*(t:=h[::-1])))),h,g(t),*S)or h in S
```
[Try it online!](https://tio.run/##nVPbjpswFHz3VxylD2tnCYvblxVa@g2V8ohQ5TYGuyLGMk7T7c@ntgkh3JqqKFLsc5kzMxz0uxWN@vSqzeVSZTU7fjswECne5pt4E/9opMImbnUtLXYBkqfpjhakbAwYkApEERFU3vqi7T6tucJ78vb6OXkrcYWPTONNhxT9lhpvsU0zccVxTySiClviOokDFR50f5FH3RgL7XuL/KhaKu4T7h639iBVikCWIezuzNj2LK3AT9kTcRnQRiqLfZa42/dGWalOHAECw85fBWTAf7K6L2jlgbsQ9rxDnsAzUPLy8hEh@ABfDNfM@PH6ZBH47rxA4GlJz8kwVXHsQcJs05xdxVVwEN9aEwXcXBZ56gufpVPuhjhDt6FzJ3fUUxUx05qrA3YoZHFGBAPN@3keSe4COA3QawT6otRRmE/06uxJ1xwL4v3y8p2XnXgQ/BerGtUR84P9AqSd211/dyZo6DS8PdXOt@7fwZcB@toUgkPfJc@TCPyviGDpWKBpBR0daaig3Xmoux6Hanq7@Z4BaRRIepgbajJCHfJTVDpFpSMd/dwBdSaVzpRNUekDriMTlmSv2DOVs@QMXQ5PMnfhsYYCZf/wDObMl@EmdP5OV9blLwb/z2tLFpYhmXpNF@YmozF3LYtc19/gA659YLS4dAF79q2Mtmu6hevLkKxqfRAu/gA "Python 3.8 (pre-release) – Try It Online")
The function `f` takes in a tuple of strings representing a left-skewed hexagon. Returns `True` if the hexagon is symmetric, or `False` otherwise.
# Explanation
At each iteration, adds the current hexagon and its vertical flip to the list `S`. Then rotates the hexagon by 60 degrees clockwise, and repeats. Stops when we finds a duplicate hexagon (symmetric), or if `S` gets too big (not symmetric).
#### Skew helper
`g` is a helper function that converts a right-skewed hexagon to a left-skewed one:
```
..ABC ABC..
.DEFG DEFG.
HIJKL -> HIJKL
MNOP. .MNOP
QRS.. ..QRS
```
This is done by taking each row `r`, and swapping the empty (`.`) with non-empty positions: `".".join(r.split(".")[::-1])`
#### Rotate a hexagon
To rotate a hexagon: simply rotates the 2D array 90 degrees, then applies `g` to fix the skewness.
```
ABC.. ..HDA HDA..
DEFG. rot90 .MIEB g MIEB.
HIJKL ------> QNJFC -----> QNJFC
.MNOP ROKG. .ROKG
..QRS SPL.. ..SPL
```
Rotating a 2D array can be done with `map("".join,zip(*h[::-1]))`
#### Flip a hexagon vertically
Simply flips the 2D array vertically, then applies `g` to fix the skew: `g(h[::-1])`
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 72 bytes
Based on @loopy walt's Python answer.
```
a->7>#Set([a=if(i%2,matrix(#a,,i,j,a[i,(#a\2+i-j)%#a+1]),a~)|i<-[1..8]])
```
[Try it online!](https://tio.run/##lVPBasMwDP0V01CwqVysXjbomp/Y0ctBh2W4bMWEHDYY@/UsYXFj2XFgYMKT5Ly8JymeOqff/NCKy0C6fqir59deWrq4Vrr9CT6o79ynrAjAwRXIOhiDl9PB6avaV3TARgH9qG/3pC0ej49Nowby/v1LktC18J279SPcTcFOtJKUAmGtATGds0hBM1bjHEYApyL@wXBlBuEi3vH4PC/4HprweiAzEdlS5GTIyTASPGcWssQQJhY4GW4pY05zd6sd4NJz@wjFnphMDpMcOeRTC8V0BmsjLfTmn4022dQMbxJmnzIR93JWlJU6vqFsDtk@YUaZ7C2bP9@R0tRMwdVWcvodfwE "Pari/GP – Try It Online")
Takes a matrix skewed to the left with zero padding.
] |
[Question]
[
You are provided with a non-empty array \$A\$ of integers, all greater than 0. But what good is an array if the elements do not sum up to the number \$N\$ (also provided as input)...
So to change that, you can pick any integer of your choice present in the array and replace any of its digits with a different digit between 0-9 of your choice. What is the **minimum** number of digits that you should replace so that the sum of the elements becomes \$N\$?
Note that after replacing the digits, some of the numbers may contain leading zeroes, which is fine. For example: you can change \$123\$ to \$023\$, or even \$000\$ if you want to. However, the input will not contain any leading zeroes and you cannot assume any before the input number.
# Example
Consider the array \$A=[195, 95]\$ and \$N = 380\$. You can do the following replacements:
1. 1**9**5 -> 1**8**5
2. 18**5** -> 18**1**
3. **1**81 -> **2**81
4. 9**5** -> 9**9**
So the new array is \$A=[281,99]\$ with a sum of \$380\$ in 4 steps. However, this is not minimal and you can do it in even fewer steps:
1. **1**95 -> **2**95
2. **9**5 -> 85
So we got our desired sum in 2 steps. There is no way to get a sum of \$380\$ in less than 2 steps so the answer for \$A=[195, 95]\$ and \$N = 380\$ will be \$2\$.
# More examples
```
A, N -> Answer
[195, 95], 380 -> 2
[100, 201], 0 -> 3
[32, 64], 96 -> 0
[7, 1, 1], 19 -> 2
[100, 37], 207 -> 1
[215], 25 -> 2
[123, 456], 1998 -> 6
```
# Rules
* Standard loopholes are forbidden.
* You do not need to handle inputs for which answer does not exist.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code, in bytes, wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~95~~… 93 bytes
```
a#n|s<-show=minimum[sum[1|(x,y)<-s a`zip`s b,x/=y]|b<-mapM(mapM(:s(56^7)))a,n==sum(read<$>b)]
```
[Try it online!](https://tio.run/##NY/hToMwFIX/8xTNZkKblYx2AsLo/ptofIAGt@Jwa4RCVoxg9uziLc6kbW6@e869p2dlP6q6nia1NFebB/bcfolGG918NtLCZVc80JFAB6nDt@4OFpV0WIuxuJZ50KjuGc9PZnEUvyaEEEWNEGDFl0od87tdSYqpUdqIY@shhDXdZ/usdRM7ZfBa@IFPQHaq@idtKpDUVY@wmmUlEf@qwif61hyEiwmeeQVWq9WiWJAsk4@mL8jWCIdRuR3/Cre2u2jT42EJ0UY6UANfAupiTZKlEUVpVFC0eQhRsEPckxtOUXwPKI0dCT2ZUMTgAGLpTcTCEDwJIB4mjjFPcuYG8WiW/Ly91@pkp@CF/wI "Haskell – Try It Online")
The relevant function is `(#)`, which takes as input the array `a` and the integer `n` and returns the minimum number of moves. Elements of `a` are represented as strings of digits.
## How?
Standard bruteforce, we try all the possible substitutions and return the minimum number of changes. The only things I'm vaguely proud of are the `show` tricks I've found while working on this answer.
* First of all, `mapM(:show(56^7))` is shorter than `mapM(\_->['0'..'9'])` for enumerating all the possible digits substitutions of a single number. We save 3 bytes and we gain an exponentially slower solution.
* Moreover, using `show a`zip`show b` instead of `zip(a>>=id)$b>>=id` saves another byte.
* With the two previous tricks, we use the `show` function often enough that defining an alias for it saves an additional byte.
[Answer]
# JavaScript (ES6), ~~132 123~~ 120 bytes
*Saved 3 bytes by wrapping in `eval()`, as suggested by @l4m2*
Expects `(list)(n)`, where `list` is an array of strings.
```
a=>n=>eval('for(m=k=1+a.join``;k--;)m=a.map(x=>s-=x.replace(/./g,j=>(d=~~i%10,t+=d!=j,i/=10,d)),s=n,i=k,t=0)|s|t>m?m:t')
```
[Try it online!](https://tio.run/##fc9LboMwEAbgfU9BF5VtxYBtAoRGQw5SVYrFIzIPG4EVZRHl6gSXZkXVzUgjfTP/TCOvcipGNVhfm7Kaa5gl5Bry6io7jGoz4h5a4DsZNEbp8/nY@v6R9CCDXg74Bvnkwy0Yq6GTRYXDILzQBnJcwuOhPjijdgflOzRUhbB0JSF0Ak0VtNQCI/fpbvP@1H9aRObC6Ml0VdCZC67xF@JZjKiHlvpNcHRghHieF4aeeNtIxpwUjDu6QiejjYyEg8neuSxZoZNsI1MH@VoWzDOH/0uPUucES1938o0U/OcXEf8Gv9L/2Ckit3MfJ2t4dlhGFpnMTw "JavaScript (Node.js) – Try It Online")
### Commented
This is a version without `eval()` for readability.
```
a => // a[] = list of positive integers, as strings
n => { // n = target sum
for( // loop:
m = k = // start with m = k = a number higher than 10 ** p
1 + a.join``; // where p is the total number of digits in a[]
k--; // stop when k = 0 (decrement it afterwards)
) //
m = // update the minimum m:
a.map(x => // for each integer x in a[]:
s -= // subtract from s:
x.replace( // replace in x
/./g, j => ( // each digit j:
d = ~~i % 10, // extract the next digit d from i
t += d != j, // increment t if d is not equal to j
i /= 10, // divide i by 10
d // replace j with d
) //
), // end of replace
s = n, // start with s = copy of n,
i = k, // i = copy of k
t = 0 // and t = 0 (counter of modified digits)
) // end of map()
| s // if s is not equal to 0
| t > m ? m // or t is greater than m, leave m unchanged
: t; // otherwise, update it to t
return m // end of loop: return m
} //
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 140 bytes
```
n=>g=x=>x.every(t=>t.split`+`.reduce((a,b)=>a-b,n))&&1+g(x,x.map(t=>{for(i in t)for(j=10;1/t[i]&&j--;)x.push(t.slice(0,i)+j+t.slice(-~i))}))
```
[Try it online!](https://tio.run/##bc5BboMwEAXQfU@RFZmRsWNDCUGRWXKJKFIIcakRtRE4kauqvTqNFWVRld2M3vyv6epbPTWjHhw19qLmSs5Glq30svRM3dT4CU6Wjk1Dr92JnNioLtdGAdTxGWVZ03NsEKNIkBZ87NlHPYTA15sdQa@0WTkMYycF34uNO@hjFHWU7tGz4Tq9w7251/c@HmskHXmu9EcjfiPOjTWT7RXrbQsVpDuOcFiLIiNFtj4ivvz1h3JOEi7@Mamg2IaDNCHb14W0KILmRBCxoAnPn@1pvuRZ4EQ8/pp/AQ "JavaScript (Node.js) – Try It Online")
If no expression equals, replace every digit to any another and try again
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Maybe there's a smarter way to approach this for golf?
```
D©⁵ṁḶŒp€ŒpḌS⁼ɗƇn®§§Ṃ
```
A dyadic Link accepting a list of positive integers, \$A\$, on the left and an integer, \$N\$, on the right that yields the minimal number of digit changes to make to \$A\$ that are needed to make it sum to \$N\$.
**[Try it online!](https://tio.run/##AUAAv/9qZWxsef//RMKp4oG14bmB4bi2xZJw4oKsxZJw4biMU@KBvMmXxoduwq7Cp8Kn4bmC////MTksIDcsIDIz/zIz "Jelly – Try It Online")** Or see [all but one of the tests](https://tio.run/##y0rNyan8/9/l0MpHjVsf7mx8uGPb0UkFj5rWAMmHO3qCHzXuOTn9WHveoXWHlh9a/nBn0//Dy/WB0v//R0dHG1qa6ihYmsbqKBhbGMRy6QBFDAx0FIwMDIFCEAFjIx0FMxMg19IMzDfXUTAEIqCAoSVCh7F5LEibOVjEyBBkopFpLFcsAA "Jelly – Try It Online") or [the other one](https://tio.run/##AUMAvP9qZWxsef//RMKp4oG14bmB4bi2xZJw4oKsxZJw4biMU@KBvMmXxoduwq7Cp8Kn4bmC////WzEyMywgNDU2Xf8xOTk4 "Jelly – Try It Online").
### How?
```
D©⁵ṁḶp/€ŒpḌS⁼ɗƇn®§§Ṃ - Link: positive integer array A; integer N
D - decimal digit lists (for each of A)
© - copy that to the register for later (and yield it for now)
⁵ - literal ten
ṁ - mould-like (the digit lists)
Ḷ - lowered range (giving us [0,1,...,9] for each digit of each number in A)
€ - for each (digit-option-list-of-lists):
Œp - Cartesian product (giving us all digit lists we could make for each of A)
Œp - Cartesian product (giving us all lists of such possibilities)
Ƈ - filter by:
ɗ - last three links as a dyad - f(x=that, N)
Ḍ - convert (each) from base ten
S - sum
⁼ - equals (N)?
® - recall the original digits lists of A from the register
n - not equal? (vectorises)
§ - sum of each
§ - sum of each
Ṃ - minimum
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 154 bytes
```
->a,n{[0].product(*a.map{|c|[*0...10**c.to_s.size]}).select{|x|x.sum==n}.map{|c|(0...a.size).sum{|i|a[i].digits.zip(c[i+1].digits).count{|x,y|x!=y}}}.min}
```
[Try it online!](https://tio.run/##NYzfDoIgHEbve4q6U6LfNLPJBb0IY43QGlv@mcCmAs9OWfP2fN85o33M8Unj6SZw51jGYRj72kqTIAGtGJyXnqEMAPIMIQmmv2vQaml4SEE370Ya5yc/gbYtpV3YnGRVxO@ZrpvzygumONTqpYyGRQ2JZOqYbyQF2dtujeHZTwc6h/CNqS7EYf9kLCclJiXHRZXx3Z@cC3wprxznhFQ8fgA "Ruby – Try It Online")
Not particularly clever: for each element of a, checks all numbers between 0 and 10^(number of digits), then filters the substitutions which yields the desired sum, and counts the digits that have changed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
NθI⌊EΦEXχLη⭆η⎇⁼λ,λ﹪÷ιXχμχ⁼θΣιΣEη¬⁼λ§ιμ
```
[Try it online!](https://tio.run/##TY7NCsIwEITvfYrgaQMRmpOIJ/EHClYEfYFoQxvIT5tuqj59TETRvezAznw7t074mxM6xsr2AY/BXKWHga6Kk1cWYSNGhFpZZYKBWvSwVxqTI8uTuyfFS0YO0rbYQUcpI2dMwTbfO0Yu0lvhn7AbgtAjaEZmbJZMSdSuCdpBZXGrJtVIUIz8iCajeElp3p/0kOCphXp/@dRJP44O//hrrGwjH5lm6HdWMfJlsWCc8Tif9As "Charcoal – Try It Online") Very slow, so TIO can't handle arrays where the total length of digits and commas is greater than 5. Explanation:
```
Nθ First input as a number
χ Predefined variable `10`
X Raised to power
η Second input as a string
L Length
E Map over implicit range
η Second input as a string
⭆ Map over characters and join
λ Current character
⁼ Equal to
, Literal string `,`
⎇ If true then
λ Current character else
ι Outer value
÷ Integer divide
χ Predefined variable `10`
X Raised to power
μ Inner index
﹪ Modulo
χ Predefined variable `10`
Φ Filter strings where
ι Current string
Σ Sum as array of integers
⁼ Equal to
θ First input as a number
E Map over strings
η Second input as a string
E Map over characters
λ Current character
¬ Is not
⁼ Equal to
§ιμ Character from string
Σ Take the sum
⌊ Take the minimum
I Cast to string
Implicitly print
```
] |
[Question]
[
A [half-exponential function](https://en.wikipedia.org/wiki/Half-exponential_function) is one which when composed with itself gives an exponential function. For instance, if `f(f(x)) = 2^x`, then `f` would be a half-exponential function. In this challenge, you will compute a specific half-exponential function.
Specifically, you will compute the function from the non-negative integers to the non-negative integers with the following properties:
* Monotonically increasing: if `x < y`, then `f(x) < f(y)`
* At least half-exponential: For all `x`, `f(f(x)) >= 2^x`
* Lexicographically smallest: Among all functions with the above properties, output the one which minimizes `f(0)`, which given that choice minimizes `f(1)`, then `f(2)`, and so on.
The initial values of this function, for inputs `0, 1, 2, ...` are:
`[1, 2, 3, 4, 8, 9, 10, 11, 16, 32, 64, 128, 129, 130, 131, 132, 256, 257, ...]`
You may output this function via any of the following methods, either as a function or as a full program:
* Take `x` as input, output `f(x)`.
* Take `x` as input, output the first `x` values of `f`.
* Infinitely output all of `f`.
If you want to take `x` and output `f(x)`, `x` must be zero indexed.
[Reference implementation](https://tio.run/##bZFNboMwEIX3nGKSla02iJ@qCxPSW3SDUGSldmOJTJBtkqiIs1MbKA1tvBnPm8/PM7ZujO17iXDkldyLW02QQWPUl6Cw2cG7OGyHbAdtAG5VwsKpsSDZfS2HizisiigDLLOBUxIQ8hwiaEEL22gECd1QkkVUuhPxEowfgbEHkyWYPAITD6YjKM8aFCiENAxxansykIUqp65meTTwug8bd@XTT29@dfPOjy73auTKbOHr5C3gP1ene1@SADfQvL7QsD5fiRqyNKFD9C/457ZpqqALAvczJ66Q0Pv35zdnauwHYwIvjHH9aQgN0R5JTMMGr5rXLq@5NoL8CtlsIN3x@b@d21SqtUJb4YqsW/bWrZ9BukIX9H2fRN8)
This is code golf - shortest code in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are banned, as always.
[Answer]
## JavaScript (ES7), ~~51~~ 48 bytes
*Saved 3 bytes thanks to @Arnauld*
```
f=i=>i?f[f[q=f(i-1),r=f[i]||q+1]=(i>1)<<i,i]=r:1
```
Takes in **n** and outputs the **n**'th item in the sequence.
---
## JavaScript (ES7), ~~70~~ ~~68~~ 64 bytes
```
f=(n,a=[],q=1)=>n?f(n-1,a,(n=2**a.indexOf(a.push(q)))<++q?q:n):a
```
A recursive function that takes in `x` and returns the first `x` items of the sequence as an array.
### How it works
The array **a** is procedurally generated, one item at a time, until it reaches the desired length. (A port of the infinite technique used in [xnor's excellent Python answer](https://codegolf.stackexchange.com/a/150067/42545) would likely be shorter.)
We can make the following observation for each index **i** (0-indexed):
* If **i** exists as an item in **a** at index **j** (**a[j] = i**), then **a[i]** needs to be at least **2j**.
This is true because **f(f(j))** needs to be at least **2j**, and **f(f(j))** is equivalent to **a[a[j]]**, which is in turn equivalent to **a[i]**.
Normally the correct option is exactly **2j**. However, for the singular case **i = 2**, **2** exists in the array at index **j = 1**, which means that **2j** would be **2**—but this means that we would have **2** at both **a[1]** and **a[2]**. To get around this, we take the maximum of **2j** and **a[i-1] + 1** (one more than the previous item), which gives **3** for **i = 2**.
This technique also happens to take care of deciding whether or not **j** exists—if it doesn't, JS's `.indexOf()` method returns **-1**, which leads to taking the max of **a[i-1] + 1** and **2-1 = 0.5**. Since
all items in the sequence are at least **1**, this will always return the previous item plus one.
(I'm writing this explanation late at night, so please let me know if something is confusing or I missed anything)
[Answer]
# [Python 2](https://docs.python.org/2/), 60 bytes
```
d={};a=n=1
while 1:print a;a=d.get(n,a+1);d[1%n*a]=2**n;n+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8W2utY60TbP1pCrPCMzJ1XB0KqgKDOvRCERKJqil55aopGnk6htqGmdEm2omqeVGGtrpKWVZ52nbWv4/z8A "Python 2 – Try It Online")
Prints forever.
---
# [Python](https://docs.python.org/2/), 61 bytes
```
f=lambda n,i=2:n<1or(i>=n)*-~f(n-1)or(f(i)==n)<<i or f(n,i+1)
```
[Try it online!](https://tio.run/##Dcw7DoAgEIThq2zJ@iiW0oB3wSi6iQ6G2Nh4ddxyvkz@@32OAt9ajme6ljURBo1@QpBSnc4R3I1fdhiFDbJTjmYhKJVK5oP2wi3bACmoJuybE@HprorHavbh9gM "Python 2 – Try It Online")
A function. Outputs `True` in place of `1`.
[Answer]
# Perl 5, 53 + 1 (`-p`) = 54 bytes
```
$\=$_>0;map$a[$\=$a[$_]?2**$a[$_]:$\+1]=$_,++$\..$_}{
```
[Try it online](https://tio.run/##K0gtyjH9/18lxlYl3s7AOjexQCUxGsQDkvGx9kZaWhCWlUqMtmEsUJGOtrZKjJ6eSnxt9f//hub/8gtKMvPziv/rFgAA)
[Answer]
# Bash, 66 bytes
```
for((r=$1?2:1,i=2;i<=$1;i++));{ a[r=a[i]?2**a[i]:r+1]=$i;};echo $r
```
[Try it online](https://tio.run/##S0oszvj/Py2/SEOjyFbF0N7IylAn09bIOtMGyLPO1NbW1LSuVkiMLrJNjM6MtTfS0gLRVkXahrG2KpnWtdapyRn5CipF////NzQHAA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
iL’2*»Ṁ‘$ṭ
⁸Ç¡
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//aUzigJkyKsK74bmA4oCYJOG5rQrigbjDh8Kh//8xOA "Jelly – Try It Online")
### How it works
```
⁸Ç¡ Main link. No arguments.
⁸ Set the left argument and the return value to [].
Ç¡ Read an integer n from STDIN and call the helper link n times, first on
[], then on the previous result. Return the last result.
iL’2*»Ṁ‘$ṭ Helper link. Argument: A (array)
L Take the length of A. This is the 0-based index of the next element.
i Find its 1-based index in A (0 if not present).
’ Decrement to a 0-based index (-1 if not present).
2* Elevate 2 to the 0-based index.
Ṁ‘$ Take the maximum of A and increment it by 1.
Note that Ṁ returns 0 for an empty list.
» Take the maximum of the results to both sides.
ṭ Tack (append) the result to A.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 111 bytes
```
def f(x):
a=range(1,2**x)
for i in range(1,x):a[i]=max(a[i],a[i-1]+1);a[a[i]]=max(a[a[i]],2**i)
return a[:x]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNo0LTiksh0bYoMS89VcNQx0hLq0KTSyEtv0ghUyEzTwEmDlSWGJ0Za5ubWKEBYugACV3DWG1DTevEaJAATArMBhmTCTSmKLWktChPITHaqiL2f0FRZl4J0EYjA83/AA "Python 2 – Try It Online")
This is a significant modification of [user202729](https://codegolf.stackexchange.com/users/69850/user202729)'s answer. I would have posted this improvement as a comment, but the answer is deleted and so comments are disabled.
[Answer]
# [Swift](https://swift.org), 137 bytes
```
func f(n:Int){var l=Array(1...n).map{$0>3 ?0:$0},p=8;if n>3{for i in 3..<n{if l[i]<1{l[i]=l[i-1]+1};if l[i]<n{l[l[i]]=p};p*=2}};print(l)}
```
Takes input as `Int` (integer) and prints as `[Int]` (integer array).
## Ungolfed version
```
func f(n:Int){
var l = Array(1...n).map{$0 > 3 ? 0 : $0} // Create the range from 1 to n and set all
var p = 8 // values greater than 3 to 0
if n > 3 {
for i in 3 ..< n {
if l[i] < 1 {
l[i] = l[i - 1] + 1
}
if l[i] < n {
l[l[i]] = p
}
p *= 2
}
}
print(l)
}
```
] |
[Question]
[
>
> This competition is over. Thanks for the interesting non-esolang entries, and congrats to [Jakuje](https://codegolf.stackexchange.com/a/57460/42963) for his winning JavaScript submission.
>
>
>
In the great tradition of ASCII Art Challenges on this site, here's another one. Given an input, draw a spiral.
```
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<
```
Simple, yeah? Heh, heh, heh ... Yeah...
(Inspired by the [ASCII Dragons Curve](https://codegolf.stackexchange.com/questions/52996/ascii-dragons-curve) post, and Optimizer's [ASCII Art of the Day](https://codegolf.stackexchange.com/questions/50484/ascii-art-of-the-day-1-double-knot) posts)
### Input
Input will be in the form of a series of parameters, taken from the usual STDIN/function argument/etc., whatever your language equivalent, comprised of four parts. These parts can be four separate arguments, a quadruple, an array of size 4, etc. For simplicity and consistency throughout the challenge, I will represent the input as a single word.
* An integer `2 ≤ x ≤ 20` that specifies the size of the spiral in terms of "squares" with each printed character representing one "square" in size. Theoretically this could be enormous in scope, but given that we're drawing ASCII art, a safe upper limit on this will be 20 so that it fits somewhat decently on screen.
* A single letter of `d u r` or `l`, indicating the initial movement from the starting "square" (down, up, right, left).
* An optional `c`, indicating "counter-clockwise." If the `c` is omitted, assume clockwise rotation for the spiral.
* A final integer `1 ≤ y ≤ 10` that specifies how many times to recurse the spiral drawing, using the finish "square" of the previous spiral as the starting "square" of the new one. I'm picking an upper limit of 10 because I want the drawing to finish at some point.
* A few example inputs: `20lc5` `13d2` `2rc1`
Of interest, do note that odd values for the size input will result in the `@` always being the exact center of a spiral, but even values may have the starting "square" offset in any of the four diagonal directions, dependent upon the direction of initial travel. This can result in some ... interesting ... patterns. See the two even examples below.
Input that doesn't follow the input specification (e.g., `11q#s`) is undefined and I fully expect the program to barf appropriately. :)
### Output
Output is an ASCII printable output via language-equivalent STDOUT, with the following specifications:
* The starting "square" (of each recursion) must be marked with an at-sign `@`.
* The final "square" must be marked with an ampersand `&`. In the case of multiple recursions, only the very final "square" should be marked `&`.
* Corners of the spiral path need to "point" in the direction of travel, using `< > v ^`.
* Vertical travel need to be drawn by pipes `|`.
* Horizontal travel needs to be drawn with dashes `-`.
* "Squares" that are overwritten by later recursions should display the most-recent direction of travel. This will result in "newer" recursions seeming to be layered on top of the "older" recursions. See the `4rc3` example below.
* A final trailing newline is OK, leading spaces could be a must and so are allowed, but trailing spaces are not allowed.
* I won't dock you if you use escape sequences to draw the ASCII art going to STDOUT, but I will be silently disappointed in you. (You'll still be eligible for the bounty if you use them)
### Examples
`2d4` = diameter of 2, starts by going down, clockwise, 4 recursions
```
&@@@@
^<<<<
```
In this example, the drawing starts in the upper-right `@`, goes down one, left one, up one. At this point, we've finished the `2d` portion, and so start the 2nd recursion, so we have another `@`, down one, left one, up one; then the 3rd recursion; then the 4th and finally our `&`.
`4rc3` = diameter of 4, starts by going right, counter-clockwise, 3 recursions
```
&--<
v-<|
|@^|<
>--^|
|@^|<
>--^|
|@^|
>--^
```
In this example, the drawing starts in the bottom `@`, goes right one, up one, spirals around, until it reaches the middle `@` and finishes the `4rc` portion. This then repeats two more times to get the full 3 recursions requested. Note that `4rc1` would be just the upper-left 4x4 block of this example.
`7u1` = diameter of 7, starts by going up, clockwise, 1 recursion (note the is the same as the intro)
```
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<
```
### Winning & Restrictions
This is Code Golf, so smallest answer in bytes wins. Submissions should be in the usual form of program/function/CJam Code Block/etc. Standard Loophole Restrictions Apply. Professional driver on closed course. If irritation persists, discontinue use and consult your doctor.
[Answer]
# Common Lisp, ~~649~~ ~~617~~ ~~605~~ ~~586~~ ~~576~~ ~~565~~ ~~554~~ ~~527~~ 518
```
(lambda(r v z c &aux(m 0)s(c(if c 1 -1))o p(x 0)i(y 0)j u)(#8=dotimes(_ z)(#7=setf p(aref"ruld"v)i(1-(abs(- p 2)))j(- 1(abs(1- p)))s'@)(#8#($(1- r))#5=(#7#m(min m x)o(cons`(,x,y,s)o)s(aref"-|-|"p)x(+ x i)y(+ y j))#2=(#7#s(*(- c)j)j(* i c)i s p(mod(+ p c)4)s(aref">^<v"p)u(#8#(_(1+ $))#5#))#2#))(#7#s'& u #5#o(#4=stable-sort(#4#o'< :key'car)'> :key'cadr)y(cadar o)x m)(dolist(k o)(do()((>=(cadr k)y))(#7#y(1- y)x m)(terpri))(do()((<=(car k)x))#9=(incf x)(princ" "))(and(=(cadr k)y)(=(car k)x)#9#(princ(caddr k)))))
```
*All tests still pass. The ungolfed function was also updated to reflect the changes, as were comments.
I finally got rid of `remove-duplicates` in order to shorten the code, but now I don't know where to find more bytes. Well done Jakuje.*
## Examples
```
(funcall *fun* 8 #\r 3 nil)
>------v
|>----v|
||>--v||
|||@v|||
>------v|||
|>----v|<||
||>--v||-<|
|||@v|||--<
>------v|||
|>----v|<||
||>--v||-<|
|||@v|||--<
||^-<|||
|^---<||
^-----<|
&------<
(funcall *fun* 8 #\r 3 t) ;; counter-clockwise
&------<
v-----<|
|v---<||
||v-<|||
|||@^|||--<
||>--^||-<|
|>----^|<||
>------^|||
|||@^|||--<
||>--^||-<|
|>----^|<||
>------^|||
|||@^|||
||>--^||
|>----^|
>------^
(funcall *fun* 7 #\u 1 nil)
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<
(funcall *fun* 2 #\d 4 nil)
&@@@@
^<<<<
```
See also [`20lc10`](http://pastebin.com/raw.php?i=vai7msRw) (pastebin).
## Ungolfed
There is no recursion involved here, just a basic *Turtle graphics* approach with loops:
1. Draw the spirals in memory by storing `(x y char)` triples in a stack.
2. Stable-sort elements according to `y` and `x`
3. Iterate over that list while avoiding duplicates (previous traces) and print from top-left to bottom-right.
```
(lambda
(r v z c
&aux
(m 0) ; minimal x
s ; symbol to print (a character)
(c ; 1 if clockwise, -1 otherwise
(if c
1
-1))
o ; stack of (x y char) traces
p ; position of s in ">^<v"
i ; move direction of x
j ; move direction of y
(x 0) ; position in x
(y 0) ; position in y
u ; auxiliary variable
)
;; repeat for each recursive step
(dotimes (_ z)
;; initialize spiral parameters
(setf s '@ ; start spiral with @
p (position v"ruld") ; initialize p according to input V
;; Set initial direction in I and J.
i (1-(abs(- p 2))) ; i(0..3) = ( 1, 0, -1, 0 )
j (- 1(abs(1- p))) ; j(0..3) = ( 0, 1, 0, -1 )
;; Iterate with increasing diameter $. For each iteration, draw a
;; "L"-shape that extends previous shape. Here is roughly what
;; happens at each step:
;;
;; 3334
;; 3124
;; 3224
;; 4444
;;
(dotimes($(1- r))
;;
;; Assign the form to the reader variable #1# in order to
;; copy-paste later. This is like declaring a local function,
;; but shorter: push trace into list O and move forward.
;;
#1=(setf m (min m x)
o (cons `(,x ,y ,s) o)
s (aref "-|-|" p)
x (+ x i)
y (+ y j))
;;
;; Helper function #2#: rotate and draw a line of length $.
;;
#2=(setf u (* (- c) j) ; rotation as a vectorial
j (* i c) ; product of (i j 0) with (0 0 c).
u i ; At first I used PSETF, but now I reuse
; the existing SETF with an auxiliary
; variable U to shorten the code and get
; rid of PROGN. That's also why I affect
; the result of DOTIMES to U (no need
; for two forms and a PROGN, just SETF).
p (mod(+ p c)4) ; ">^<v" is sorted counter-clockwise, which
s (aref ">^<v" p) ; means that adding P and C (modulo 4) gives
; the next symbol after rotation.
;; trace a line by repeatedly invoking code snippet #1#
u (dotimes(_(1+ $)) #1#))
;;
;; Rotate and draw a second line, hence drawing a "L"-shape.
;;
#2#))
;; Finally, draw the final symbol &
(setf s '&)
#1#
(setf o
;; From inside-out:
;;
;; - stable sort O according to X
;; (from lowest (left) to highest (right))
;;
;; - stable sort the result according to Y
;; (from highest (top) to lowest (bottom))
;;
(stable-sort (stable-sort o '< :key 'car) '> :key 'cadr)
;; initialize Y with the first Y in O, which is also the
;; minimum of all Y.
y (cadar o)
;; initialize X with the minimum of all X
x m)
;; For each trace in O
(dolist (k o)
;; Add as many lines as needed to advance Y to current trace's Y.
(do ()
((<= y (cadr k)))
(setf y (1- y)
x m)
(terpri))
;; Add as many spaces as needed to advance X to current trace's X.
(do () ((>= x (car k))) (incf x) (princ " "))
;; Then, print current trace's character and increment X.
;; This happens only when we have a "new" trace, not another
;; trace at the same point (which was being overwritten).
(and(=(car k)x)(=(cadr k)y)(incf x)(princ(caddr k)))
```
[Answer]
# Javascript, ~~578~~, ~~575~~, ~~553~~, ~~478~~, 377 Bytes
After the beaten Lua I switched to some more compact language and moved competition to Javascript:
```
s=function(w,d,c,r){d="dlur".indexOf(d)
j=i=G=H=I=J=w*r;o=[];for(x=0;x<J*2;x++){o[x]=[]
for(y=0;y<J*2;)o[x][y++]=' '}for(;r--;){a=d;m=l=z=1;o[i][j]="@"
for(k=w*w-1;k--;){G=G<i?G:i;H=H>i?H:i;I=I<j?I:j;J=J>j?J:j
o[i+=(1-a)%2][j+=a?a-2:0]=l++==m?(a+=c=="c"?3:1,m+=z=!z,l=1,"v<^>"[a%=4]):k?"|-"[a%2]:"&"}}for(i=G;i<=H;)console.log(o[i++].slice(I,J+1).join("").replace(/\s+$/g,''))}
```
Algorithm is the same, but written in more more compact language so I managed to beat the evil Lisp :)
*Edit: Some structural changes were needed to reach under Lisp again and to eliminate trailing whitespaces. But we are here again.*
*Edit2: Some abstractions taken into account to get under 500. Hope it will be enough :)*
*Edit3: Thanks @Timwi, the code is another 100 chars slimmer. I didn't update the explanation yet.*
Tests ([online version](http://jakuje.dta3.com/misc/ss.html), tested in Chrome):
```
----| 2d4 |---
s.js:9 &@@@@
s.js:9 ^<<<<
ss.html:7 ----| 4rc3 |---
s.js:9 &--<
s.js:9 v-<|
s.js:9 |@^|<
s.js:9 >--^|
s.js:9 |@^|<
s.js:9 >--^|
s.js:9 |@^|
s.js:9 >--^
ss.html:9 ----| 7u1 |---
s.js:9 &>----v
s.js:9 ||>--v|
s.js:9 |||>v||
s.js:9 |||@|||
s.js:9 ||^-<||
s.js:9 |^---<|
s.js:9 ^-----<
ss.html:11 ----| 8r3 |---
s.js:9 >------v
s.js:9 |>----v|
s.js:9 ||>--v||
s.js:9 |||@v|||
s.js:9 >------v|||
s.js:9 |>----v|<||
s.js:9 ||>--v||-<|
s.js:9 |||@v|||--<
s.js:9 >------v|||
s.js:9 |>----v|<||
s.js:9 ||>--v||-<|
s.js:9 |||@v|||--<
s.js:9 ||^-<|||
s.js:9 |^---<||
s.js:9 ^-----<|
s.js:9 &------<
ss.html:13 ----| 8rc3 |---
s.js:9 &------<
s.js:9 v-----<|
s.js:9 |v---<||
s.js:9 ||v-<|||
s.js:9 |||@^|||--<
s.js:9 ||>--^||-<|
s.js:9 |>----^|<||
s.js:9 >------^|||
s.js:9 |||@^|||--<
s.js:9 ||>--^||-<|
s.js:9 |>----^|<||
s.js:9 >------^|||
s.js:9 |||@^|||
s.js:9 ||>--^||
s.js:9 |>----^|
s.js:9 >------^
```
And to be fair, there is fair explanation:
```
s = function(w, d, c, r) {
// width, direction, "c" as counter-clockwise and number of repetition
// transfer direction to internal numerical representation
d=d=="d"?0:d=="u"?2:d=="l"?1:3;
// output strings
x="v<^>"
y="|-"
// this is size of our canvas. Could be smaller, but this is shorter
M = w * r * 2;
// fill canvas with spaces to have something to build upon
o = [];
for (i = 0; i < M; i++) {
o[i] = [];
for (j = 0; j < M; j++)
o[i][j] = ' '
}
// i,j is starting position
// G,H,I,J are current boundaries (maximum and minimum values of i and j during the time)
j = i = G = H = I = J = M / 2
for (q = 0; q < r; q++) { // number of repeats
a = d; // reset original direction
// m is the expected length of side
// l counts the of current side length
m = l = 1;
z = 0; // counts occurrences of the length
o[i][j] = "@" // write initial character
for (k = w * w; k > 1; k--) { // cycle over the whole spiral
// update boundaries
G = G < i ? G : i;
H = H > i ? H : i;
I = I < j ? I : j;
J = J > j ? J : j;
// move to the next position according to direction
i+=a<3?1-a:0;
j+=a>0?a-2:0
if (k == 2) // we reached the end
o[i][j] = "&"
else if (l == m) {
// we reached the corner so we need to count next direction
a=(c=="c"?a+3:a+1)%4;
// and write according sign
o[i][j]=x[a]
// first occurrence of this length
if (z == 0)
z = 1; // wait for finish of the other
else {
m++; // increase length of side
z = 0 // wait again for the first one
}
l = 1 // start the side counter over
} else {
l++ // another part of this side
// according side character
o[i][j] = y[a%2]
}
}
}
// blow it all out
for (i = G; i <= H; i++)
console.log(o[i].slice(I, J + 1).join("").replace(/\s+$/g, ''))
}
```
[Answer]
# Lua 5.2, 740 Bytes
```
s=io.read W=io.write Z=math.max A=math.min
D="d"U="u"L="l"R="r"function n()G=A(G,i)H=Z(H,i)I=A(I,j)J=Z(J,j)i=(a==D and i+1 or a==U and i-1 or i)j=(a==R and j+1 or a==L and j-1 or j)end
w=s"*n"d=s(1)c=s(1)r=(c=="c")and s"*n"or c
c=c=="c"M=w*(r+1)o={}for i=1,M do o[i]={}for j=1,M do o[i][j]=" "end end
i=M/2 j=i G=i H=i I=i J=i
for q=1,r do a=d m=1 l=1 z=0
o[i][j]="@"for k=3,w^2 do
n()if l==m then
a=c and(a==D and R or a==U and L or a==L and D or a==R and U)or(a==D and L or a==U and R or a==L and U or a==R and D)o[i][j]=(a==D and"v"or a==U and"^"or a==L and"<"or a==R and">")
if z==0 then z=1 else m=m+1;z=0 end
l=1
else
l=l+1
o[i][j]=(a==D or a==U)and"|"or"-"end end
n()o[i][j]="&"end
for i=G,H do for j=I,J do
W(o[i][j])end W("\n")end
```
I though that it would be fun to try to implement some algorithm to beat Lisp, but Lua is probably not the best option. I spend too much time on it, over-engineered some parts to end with this uggly one, but working solution. Probably I will try different language later to beat Lisp since there is some 90 characters that I can't take away from this algorithm.
Testing outputs:
```
jakuje@E6430:/tmp$ echo "2d4" | lua s.lua
&@@@@
^<<<<
jakuje@E6430:/tmp$ echo "4rc3" | lua s.lua
&--<
v-<|
|@^|<
>--^|
|@^|<
>--^|
|@^|
>--^
jakuje@E6430:/tmp$ echo "7u1" | lua s.lua
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<
```
[Answer]
# PHP, 524 bytes
I arrived late at this party. My PHP solution is neither the smallest, nor the smartest. It just works.
```
$a=$argv;
$b=[['|','^',0,-1],['-','>',1,0],['|',v,0,1],['-','<',-1,$x=$y=$o=$p=$q=$r=0]];
for($t=$a[4];$t;$t--){$d=strpos(urdl,$a[2]);$c=$b[$d];$m[$y][$x]='@';
for($s=0;++$s<$a[1];){for($k=3;--$k;){for($i=$s;--$i;)
$m[$y+=$c[3]][$x+=$c[2]]=$c[0];$x+=$c[2];$y+=$c[3];$c=$b[$d=($d+($a[3]==c?3:1))%4];
$m[$y][$x]=$c[1];}$o=min($x,$o);$p=max($p,$x);$q=min($y,$q);$r=max($r,$y);}
for($i=$s;--$i;)$m[$y+=$c[3]][$x+=$c[2]]=$c[0];$m[$y][$x]='&';}
for($y=$q;$y<=$r;$y++){$l='';for($x=$o;$x<=$p;$x++)$l.=$m[$y][$x]?:' ';
echo rtrim($l)."\n";}
```
How to run it:
```
$ php -d error_reporting=0 recursive-ascii-spirals.php 4 r c 3
&--<
v-<|
|@^|<
>--^|
|@^|<
>--^|
|@^|
>--^
$ php -d error_reporting=0 recursive-ascii-spirals.php 7 u '' 1
&>----v
||>--v|
|||>v||
|||@|||
||^-<||
|^---<|
^-----<
```
The detailed version with tests, explanation and other goodies can be found on [github](https://github.com/axiac/code-golf/blob/master/recursive-ascii-spirals.php).
] |
[Question]
[
Write a function/subroutine to sort a list of integers, [Tower of Hanoi](http://en.wikipedia.org/wiki/Tower_of_Hanoi) style.
You will be given a [stack](http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29) of integers. This is the main stack.
You are also given two more helper stacks. These helper stacks have a unique property though: every element must be smaller than or the same size as the element underneath it. The main stack has no such restriction.
You are tasked with sorting the main stack in place, putting the largest integers underneath. Your function/subroutine will return (or equivalent) the number of moves it made in sorting the stack.
Note: you must sort the main stack **in place**, no sorting onto another stack and calling that the answer. However, if you for some reason cannot do so, you may simulate the mutable stacks, but remember that this is Tower of Hanoi sort; there are only 3 pegs and only 1 peg may be unordered.
Your function/subroutine can inspect any stack at any time, but it can only make a move by popping and pushing. A single move is a pop from one stack which is pushed to another.
Test your function/subroutine for each permutation of the first 6 natural numbers. In other words, test your function/subroutine for `{1},{2},...,{6},{1,1},{1,2},...,{1,6},{2,1},...` (this should be a total of `61+62+...+66` or `55986` possibilities (thanks to Howard for correcting my math)). The function/subroutine that moves elements the least number of times wins.
[Answer]
# Java - optimal solution (1080544 moves)
This solution builds a shortest path tree from the target and backwards, then traverses the path from the initial state to the target. Lots of room for speed improvement, but it still completes all 55986 problems in about a minute.
Assuming the algorithm is correctly implemented, this should be the theoretically best solution.
```
import java.util.*;
public class HanoiSort {
public static void main(String[] args) {
int sumNumMoves = 0;
for (int size = 1; size <= 6; ++size) {
Collection<List<Integer>> initMainStacks = generateInitMainStacks(Collections.<Integer>emptyList(), size);
for (List<Integer> initMainStack : initMainStacks) {
sumNumMoves += solve(initMainStack);
}
}
System.out.println(sumNumMoves);
}
/*
* Recursively create initial main stacks
*/
private static Collection<List<Integer>> generateInitMainStacks(List<Integer> mainStack, int remainingSize) {
Collection<List<Integer>> initMainStacks;
if (remainingSize > 0) {
initMainStacks = new ArrayList<>();
for (int number = 1; number <= 6; ++number) {
List<Integer> nextMainStack = new ArrayList<>(mainStack);
nextMainStack.add(number);
initMainStacks.addAll(generateInitMainStacks(nextMainStack, remainingSize - 1));
}
} else {
List<Integer> initMainStack = new ArrayList<>(mainStack);
initMainStacks = Collections.singleton(initMainStack);
}
return initMainStacks;
}
private static final List<Integer> EMPTY_STACK = Collections.emptyList();
/*
* Create a shortest path tree, starting from the target state (sorted main stack). Break when the initial state
* is found, since there can be no shorter path. This is akin to building a chess endgame tablebase.
*
* Traverse the path from initial state to the target state to count the number of moves.
*/
private static int solve(List<Integer> initMainStack) {
List<List<Integer>> initState = Arrays.asList(new ArrayList<>(initMainStack), EMPTY_STACK, EMPTY_STACK);
List<Integer> targetMainStack = new ArrayList<>(initMainStack);
Collections.sort(targetMainStack);
List<List<Integer>> targetState = Arrays.asList(new ArrayList<>(targetMainStack), EMPTY_STACK, EMPTY_STACK);
Map<List<List<Integer>>,List<List<Integer>>> tablebase = new HashMap<>();
Deque<List<List<Integer>>> workQueue = new ArrayDeque<>();
tablebase.put(targetState, null);
workQueue.add(targetState);
while (!tablebase.containsKey(initState)) {
assert !workQueue.isEmpty() : initState.toString();
List<List<Integer>> state = workQueue.removeFirst();
Collection<List<List<Integer>>> prevStates = calcPrevStates(state);
for (List<List<Integer>> prevState : prevStates) {
if (!tablebase.containsKey(prevState)) {
tablebase.put(prevState, state);
workQueue.add(prevState);
}
}
}
int numMoves = 0;
List<List<Integer>> state = tablebase.get(initState);
while (state != null) {
++numMoves;
state = tablebase.get(state);
}
return numMoves;
}
/*
* Given a state, calculate all possible previous states
*/
private static Collection<List<List<Integer>>> calcPrevStates(List<List<Integer>> state) {
Collection<List<List<Integer>>> prevStates = new ArrayList<>();
for (int fromStackNo = 0; fromStackNo < 3; ++fromStackNo) {
List<Integer> fromStack = state.get(fromStackNo);
if (!fromStack.isEmpty()) {
int number = fromStack.get(0);
for (int toStackNo = 0; toStackNo < 3; ++toStackNo) {
if (toStackNo != fromStackNo) {
List<Integer> toStack = state.get(toStackNo);
if ((toStackNo == 0) || toStack.isEmpty() || (toStack.get(0) >= number)) {
List<List<Integer>> prevState = new ArrayList<>(state);
List<Integer> prevFromStack = new ArrayList<>(fromStack);
prevFromStack.remove(0);
prevState.set(fromStackNo, prevFromStack);
List<Integer> prevToStack = new ArrayList<>(toStack);
prevToStack.add(0, number);
prevState.set(toStackNo, prevToStack);
prevStates.add(prevState);
}
}
}
}
}
return prevStates;
}
}
```
[Answer]
## Python, 3983838 3912258 moves over 55986 inputs
This is ***very*** inefficient.
I'll add the total number of moves after the OP clarifies whether they are for all of those cases or for specific other cases.
---
```
from itertools import product # Required for testing
import time # Required if you want to see it in action.
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
def main( l ):
################### Data ###################
global a , b , c , d , copy , total_moves
total_moves = 0
a = [ x for x in l ] # Input stack, order doesn't matter, we'll try to empty this one
b = [] # Usable stack, restricted by order, we'll try to get the final sorted order here
c = [] # Usable stack, restricted by order, but we'll try to keep it as empty as possible
d = { 'a':a , 'b':b , 'c':c } # Passing the stacks to the nested functions by their names as a string
copy = [ x for x in a ] # reference copy, read-only
################### Functions ###################
def is_correct( stack ):
if d[ stack ] == sorted( copy , reverse = True ):
return True
else:
return False
def reverse_exchange( source , destination , keep = 0 ):
#
# keep is the number of elements to keep at the bottom of the source stack
# The remaining top elements are moved to the destination stack
# We first move the top elements to stack a
# and from a to c so that the order is preserved
# effectively splitting the source stack into two
#
i = 0
while len( d[ source ] ) > keep :
move( source , 'a' )
i += 1
else:
while i > 0:
move( 'a' , destination )
i -= 1
# def validate( source , destination ):
# #
# # Validates the give move
# #
# if len( d[ source ] ) == 0:
# return False
# if destination == 'a' or len( d[ destination ] ) == 0:
# return True
# else:
# if d[ destination ][ len( d[ destination ] ) - 1 ] >= d[ source ][ len( d[ source ] ) - 1 ]:
# return True
# else:
# return False
def move( source , destination ):
global total_moves
# if validate( source , destination ):
d[ destination ].append( d[ source ].pop() )
total_moves += 1
# Uncomment the following to view the workings step-by-step
# print '\n'
# print a
# print b
# print c
# print '\n'
# time.sleep(0.1)
return True
# else:
# return False
################### Actual logic ###################
while ( not is_correct( 'a' ) ):
copy_b = [x for x in b ] # Checking where the topmost element of a
top_of_a = a[ len(a) - 1 ] # should be inserted
copy_b.append( top_of_a ) #
sorted_copy_b = sorted( copy_b , reverse = True ) #
reverse_exchange( 'b' , 'c' , sorted_copy_b.index( top_of_a ) ) # Sandwiching the top-most element
move( 'a' , 'b' ) # to proper position in b
while (len(b) > 0 and len(c) > 0 and len(a) > 0) and (sorted (b , reverse = True)[0] <= a[len(a) - 1] <= c[0]): # # Optimization
move( 'a' , 'b' ) # #
reverse_exchange( 'c' , 'b' ) # b is always sorted, c is always empty
if is_correct( 'b' ): # Just moving b to a
while ( not is_correct( 'a' ) ): # The entire program focuses on "insertion sorting"
reverse_exchange( 'b' , 'c' , 1 ) # elements of a onto b while keeping c empty
move( 'b' , 'a' ) #
if len(c) > 0 : #
reverse_exchange( 'c' , 'b' , 1 ) # Slightly more efficient
move('c' , 'a' ) #
return total_moves
# with PyCallGraph( output= GraphvizOutput() ):
################### Test cases #############
i = 0
for elements in xrange( 1 , 7 ):
for cartesian_product in product( [ 1 , 2 , 3 , 4 , 5 , 6 ] , repeat = elements ):
input_list = [ int( y ) for y in cartesian_product ]
i += main(input_list)
print i
print i
```
---
### Explanation
What, comments not good enough for you?
---
Note to OP: Thanks for not making this code-golf.
[Answer]
# C - 2547172 for 55986 inputs
There is a lot of room for improvement here. For my own sanity, I simplified this so that it was only possible to inspect the top element of each stack. Lifting this self-imposed restriction would allow optimizations like determining the final order in advance and trying to minimize the number of moves required to achieve it. A compelling example is that my implementation has worst case behavior if the main stack is already sorted.
## Algorithm:
1. Fill both auxiliary stacks (room for optimization here, possibly assigning to which stack based on some kind of pivot).
2. Merge sort the auxiliary stacks back onto the main stack.
3. Repeat 1-2 until the main stack is sorted (but in reverse).
4. Reverse the main stack (more room for optimization, shuffling a lot of the same elements repeatedly).
## Analysis:
* Additional space complexity is O(n) (for the two auxiliary stacks), which is good, since that was a requirement of the problem.
* Time complexity is O(n^2) by my count. Corrections are welcome.
---
```
#include <assert.h>
#include <stdio.h>
#define SIZE 6
int s0[SIZE + 1];
int s1[SIZE + 1];
int s2[SIZE + 1];
int
count(int *stack)
{
return stack[0];
}
int
top(int *stack)
{
return stack[stack[0]];
}
void
push(int *stack, int value)
{
assert(count(stack) < SIZE && "stack overflow");
assert((stack == s0 || count(stack) == 0 || value <= top(stack)) && "stack order violated");
stack[++stack[0]] = value;
}
int
pop(int *stack)
{
int result = stack[stack[0]];
assert(count(stack) > 0 && "stack underflow");
stack[stack[0]] = 0;
stack[0]--;
return result;
}
int permutations;
void
permute(int len, int range, void (*cb)(void))
{
int i;
if(len == 0)
{
permutations++;
cb();
return;
}
for(i = 1; i <= range; i++)
{
push(s0, i);
permute(len - 1, range, cb);
pop(s0);
}
}
void
print(void)
{
int i;
for(i = 1; i <= count(s0); i++)
{
printf("%d ", s0[i]);
}
printf("\n");
}
int save[SIZE + 1];
void
copy(int *src, int *dst)
{
int i;
for(i = 0; i <= SIZE; i++)
{
dst[i] = src[i];
}
}
int total;
void
move(int *src, int *dst)
{
total++;
push(dst, pop(src));
}
void
merge(void)
{
while(1)
{
if(count(s1) == 0 && count(s2) == 0)
{
break;
}
else if(count(s1) == 0 || (count(s2) > 0 && top(s2) < top(s1)))
{
move(s2, s0);
}
else
{
move(s1, s0);
}
}
}
void
reverse(void)
{
while(1)
{
while(count(s2) == 0 || top(s0) == top(s2))
{
move(s0, s2);
}
if(count(s0) == 0 || top(s2) < top(s0))
{
while(count(s2) > 0)
{
move(s2, s0);
}
break;
}
while(count(s0) > 0 && (count(s1) == 0 || top(s0) <= top(s1)))
{
move(s0, s1);
}
while(count(s2) > 0)
{
move(s2, s0);
}
merge();
}
}
void
sort(void)
{
while(1)
{
if(count(s0) == 0)
{
merge();
reverse();
break;
}
else if(count(s1) == 0 || top(s1) >= top(s0))
{
move(s0, s1);
}
else if(count(s2) == 0 || top(s2) >= top(s0))
{
move(s0, s2);
}
else
{
merge();
}
}
}
void
helper(void)
{
copy(s0, save);
sort();
copy(save, s0);
}
int
main(void)
{
permute(1, 6, helper);
permute(2, 6, helper);
permute(3, 6, helper);
permute(4, 6, helper);
permute(5, 6, helper);
permute(6, 6, helper);
printf("%d\n", permutations);
printf("%d\n", total);
return 0;
}
```
[Answer]
## Python: ~~1,688,293~~ ~~1,579,182~~ ~~1,524,054~~ ~~1,450,842~~ 1,093,195 moves
The main method is `main_to_help_best`, which is to move some selected elements from main stack to helper stack. It has a flag `everything` which defines whether we want it to move everything into the specified `destination`, or whether we want to keep only the largest in `destination` while the rest in the other helper.
Supposing we are moving to `dst` using helper `helper`, the function can roughly be described as follows:
1. Find the positions of largest elements
2. Move everything on top of the top-most largest element to `helper` recursively
3. Move the largest element to `dst`
4. Push back from `helper` to main
5. Repeat 2-4 until the largest elements are in `dst`
6. a. If `everything` is set, recursively move elements in main to `dst`
b. Otherwise, recursively move elements in main to `helper`
The main sort algorithm (`sort2` in my code) will then call `main_to_help_best` with `everything` set to `False`, and then move the largest element back to main, then move everything from the helper back to main, keeping it sorted.
More explanation embedded as comments in the code.
Basically the principles that I used are:
1. Keep one helper to contain the maximum element(s)
2. Keep another helper to contain any other elements
3. Don't do unnecessary moves as much as possible
Principle 3 is implemented by not counting the move if the source is the previous destination (i.e., we just moved main to help1, then we want to move from help1 to help2), and further, we reduce the number of movement by 1 if we are moving it back to the original position (i.e. main to help1 then help1 to main). Also, if the previous `n` moves are all moving the same integer, we can actually reorder those `n` moves. So we also take advantage of that to reduce the number of moves further.
This is valid since we know all the elements in the main stack, so this can be interpreted as seeing in the future that we're going to move the element back, we should not make this move.
Sample run (stacks are displayed bottom to top - so the first element is the bottom):
```
Length 1
Moves: 0
Tasks: 6
Max: 0 ([1])
Average: 0.000
Length 2
Moves: 60
Tasks: 36
Max: 4 ([1, 2])
Average: 1.667
Length 3
Moves: 1030
Tasks: 216
Max: 9 ([2, 3, 1])
Average: 4.769
Length 4
Moves: 11765
Tasks: 1296
Max: 19 ([3, 4, 2, 1])
Average: 9.078
Length 5
Moves: 112325
Tasks: 7776
Max: 33 ([4, 5, 3, 2, 1])
Average: 14.445
Length 6
Moves: 968015
Tasks: 46656
Max: 51 ([5, 6, 4, 3, 2, 1])
Average: 20.748
--------------
Overall
Moves: 1093195
Tasks: 55986
Average: 19.526
```
We can see that the worst case is when the largest element is placed on the second bottom, while the rest are sorted. From the worst case we can see that the algorithm is O(n^2).
The number of moves is obviously minimum for `n=1` and `n=2` as we can see from the result, and I believe this is also minimum for larger values of `n`, although I can't prove it.
More explanations are in the code.
```
from itertools import product
DEBUG = False
def sort_better(main, help1, help2):
# Offset denotes the bottom-most position which is incorrect
offset = len(main)
ref = list(reversed(sorted(main)))
for idx, ref_el, real_el in zip(range(len(main)), ref, main):
if ref_el != real_el:
offset = idx
break
num_moves = 0
# Move the largest to help1, the rest to help2
num_moves += main_to_help_best(main, help1, help2, offset, False)
# Move the largest back to main
num_moves += push_to_main(help1, main)
# Move everything (sorted in help2) back to main, keep it sorted
num_moves += move_to_main(help2, main, help1)
return num_moves
def main_to_help_best(main, dst, helper, offset, everything=True):
"""
Moves everything to dst if everything is true,
otherwise move only the largest to dst, and the rest to helper
"""
if offset >= len(main):
return 0
max_el = -10**10
max_idx = -1
# Find the location of the top-most largest element
for idx, el in enumerate(main[offset:]):
if el >= max_el:
max_idx = idx+offset
max_el = el
num_moves = 0
# Loop from that position downwards
for max_idx in range(max_idx, offset-1, -1):
# Processing only at positions with largest element
if main[max_idx] < max_el:
continue
# The number of elements above this largest element
top_count = len(main)-max_idx-1
# Move everything above this largest element to helper
num_moves += main_to_help_best(main, helper, dst, max_idx+1)
# Move the largest to dst
num_moves += move(main, dst)
# Move back the top elements
num_moves += push_to_main(helper, main, top_count)
# Here, the largest elements are in dst, the rest are in main, not sorted
if everything:
# Move everything to dst on top of the largest
num_moves += main_to_help_best(main, dst, helper, offset)
else:
# Move everything to helper, not with the largest
num_moves += main_to_help_best(main, helper, dst, offset)
return num_moves
def verify(lst, moves):
if len(moves) == 1:
return True
moves[1][0][:] = lst
for src, dst, el in moves[1:]:
move(src, dst)
return True
def equal(*args):
return len(set(str(arg.__init__) for arg in args))==1
def move(src, dst):
dst.append(src.pop())
el = dst[-1]
if not equal(dst, sort.lst) and list(reversed(sorted(dst))) != dst:
raise Exception('HELPER NOT SORTED: %s, %s' % (src, dst))
cur_len = len(move.history)
check_idx = -1
matched = False
prev_src, prev_dst, prev_el = move.history[check_idx]
# As long as the element is the same as previous elements,
# we can reorder the moves
while el == prev_el:
if equal(src, prev_dst) and equal(dst, prev_src):
del(move.history[check_idx])
matched = True
break
elif equal(src, prev_dst):
move.history[check_idx][1] = dst
matched = True
break
elif equal(dst, prev_src):
move.history[check_idx][0] = src
matched = True
break
check_idx -= 1
prev_src, prev_dst, prev_el = move.history[check_idx]
if not matched:
move.history.append([src, dst, el])
return len(move.history)-cur_len
def push_to_main(src, main, amount=-1):
num_moves = 0
if amount == -1:
amount = len(src)
if amount == 0:
return 0
for i in range(amount):
num_moves += move(src, main)
return num_moves
def push_to_help(main, dst, amount=-1):
num_moves = 0
if amount == -1:
amount = len(main)
if amount == 0:
return 0
for i in range(amount):
num_moves += move(main, dst)
return num_moves
def help_to_help(src, dst, main, amount=-1):
num_moves = 0
if amount == -1:
amount = len(src)
if amount == 0:
return 0
# Count the number of largest elements
src_len = len(src)
base_el = src[src_len-amount]
base_idx = src_len-amount+1
while base_idx < src_len and base_el == src[base_idx]:
base_idx += 1
# Move elements which are not the largest to main
num_moves += push_to_main(src, main, src_len-base_idx)
# Move the largest to destination
num_moves += push_to_help(src, dst, base_idx+amount-src_len)
# Move back from main
num_moves += push_to_help(main, dst, src_len-base_idx)
return num_moves
def move_to_main(src, main, helper, amount=-1):
num_moves = 0
if amount == -1:
amount = len(src)
if amount == 0:
return 0
# Count the number of largest elements
src_len = len(src)
base_el = src[src_len-amount]
base_idx = src_len-amount+1
while base_idx < src_len and base_el == src[base_idx]:
base_idx += 1
# Move elements which are not the largest to helper
num_moves += help_to_help(src, helper, main, src_len-base_idx)
# Move the largest to main
num_moves += push_to_main(src, main, base_idx+amount-src_len)
# Repeat for the rest of the elements now in the other helper
num_moves += move_to_main(helper, main, src, src_len-base_idx)
return num_moves
def main():
num_tasks = 0
num_moves = 0
for n in range(1, 7):
start_moves = num_moves
start_tasks = num_tasks
max_move = -1
max_main = []
for lst in map(list,product(*[[1,2,3,4,5,6]]*n)):
num_tasks += 1
if DEBUG: print lst, [], []
sort.lst = lst
cur_lst = lst[:]
move.history = [(None, None, None)]
help1 = []
help2 = []
moves = sort_better(lst, help1, help2)
if moves > max_move:
max_move = moves
max_main = cur_lst
num_moves += moves
if DEBUG: print '%s, %s, %s (moves: %d)' % (cur_lst, [], [], moves)
if list(reversed(sorted(lst))) != lst:
print 'NOT SORTED: %s' % lst
return
if DEBUG: print
# Verify that the modified list of moves is still valid
verify(cur_lst, move.history)
end_moves = num_moves - start_moves
end_tasks = num_tasks - start_tasks
print 'Length %d\nMoves: %d\nTasks: %d\nMax: %d (%s)\nAverage: %.3f\n' % (n, end_moves, end_tasks, max_move, max_main, 1.0*end_moves/end_tasks)
print '--------------'
print 'Overall\nMoves: %d\nTasks: %d\nAverage: %.3f' % (num_moves, num_tasks, 1.0*num_moves/num_tasks)
# Old sort method, which assumes we can only see the top of the stack
def sort(main, max_stack, a_stack):
height = len(main)
largest = -1
num_moves = 0
a_stack_second_el = 10**10
for i in range(height):
if len(main)==0:
break
el = main[-1]
if el > largest: # We found a new maximum element
if i < height-1: # Process only if it is not at the bottom of main stack
largest = el
if len(a_stack)>0 and a_stack[-1] < max_stack[-1] < a_stack_second_el:
a_stack_second_el = max_stack[-1]
# Move aux stack to max stack then reverse the role
num_moves += help_to_help(a_stack, max_stack, main)
max_stack, a_stack = a_stack, max_stack
if DEBUG: print 'Moved max_stack to a_stack: %s, %s, %s (moves: %d)' % (main, max_stack, a_stack, num_moves)
num_moves += move(main, max_stack)
if DEBUG: print 'Moved el to max_stack: %s, %s, %s (moves: %d)' % (main, max_stack, a_stack, num_moves)
elif el == largest:
# The maximum element is the same as in max stack, append
if i < height-1: # Only if the maximum element is not at the bottom
num_moves += move(main, max_stack)
elif len(a_stack)==0 or el <= a_stack[-1]:
# Current element is the same as in aux stack, append
if len(a_stack)>0 and el < a_stack[-1]:
a_stack_second_el = a_stack[-1]
num_moves += move(main, a_stack)
elif a_stack[-1] < el <= a_stack_second_el:
# Current element is larger, but smaller than the next largest element
# Step 1
# Move the smallest element(s) in aux stack into max stack
amount = 0
while len(a_stack)>0 and a_stack[-1] != a_stack_second_el:
num_moves += move(a_stack, max_stack)
amount += 1
# Step 2
# Move all elements in main stack that is between the smallest
# element in aux stack and current element
while len(main)>0 and max_stack[-1] <= main[-1] <= el:
if max_stack[-1] < main[-1] < a_stack_second_el:
a_stack_second_el = main[-1]
num_moves += move(main, a_stack)
el = a_stack[-1]
# Step 3
# Put the smallest element(s) back
for i in range(amount):
num_moves += move(max_stack, a_stack)
else: # Find a location in aux stack to put current element
# Step 1
# Move all elements into max stack as long as it will still
# fulfill the Hanoi condition on max stack, AND
# it should be greater than the smallest element in aux stack
# So that we won't duplicate work, because in Step 2 we want
# the main stack to contain the minimum element
while len(main)>0 and a_stack[-1] < main[-1] <= max_stack[-1]:
num_moves += move(main, max_stack)
# Step 2
# Pick the minimum between max stack and aux stack, move to main
# This will essentially sort (in reverse) the elements into main
# Don't move to main the element(s) found before Step 1, because
# we want to move them to aux stack
while True:
if len(a_stack)>0 and a_stack[-1] < max_stack[-1]:
num_moves += move(a_stack, main)
elif max_stack[-1] < el:
num_moves += move(max_stack, main)
else:
break
# Step 3
# Move all elements in main into aux stack, as long as it
# satisfies the Hanoi condition on aux stack
while max_stack[-1] == el:
num_moves += move(max_stack, a_stack)
while len(main)>0 and main[-1] <= a_stack[-1]:
if main[-1] < a_stack[-1] < a_stack_second_el:
a_stack_second_el = a_stack[-1]
num_moves += move(main, a_stack)
if DEBUG: print main, max_stack, a_stack
# Now max stack contains largest element(s), aux stack the rest
num_moves += push_to_main(max_stack, main)
num_moves += move_to_main(a_stack, main, max_stack)
return num_moves
if __name__ == '__main__':
main()
```
[Answer]
# Java -- 2129090 2083142 moves on 55986 arrays
The [ideone link](http://ideone.com/EA0zNg).
The framework to ensure the algorithm is correct:
```
private final Deque<Integer> main = new ArrayDeque<Integer>();
private final Deque<Integer> help1 = new ArrayDeque<Integer>();
private final Deque<Integer> help2 = new ArrayDeque<Integer>();
private int taskCount = 0;
private int opCount = 0;
private void sort(List<Integer> input) {
taskCount++;
main.addAll(input);
sortMain();
verify();
main.clear();
}
private void verify() {
if (!help1.isEmpty()) {
throw new IllegalStateException("non-empty help1\n" + state());
}
if (!help2.isEmpty()) {
throw new IllegalStateException("non-empty help2\n" + state());
}
int last = 0;
for (int i: main) {
if (last > i) {
throw new IllegalStateException("unsorted main: " + main);
}
last = i;
}
}
private void done() {
System.out.println();
System.out.print(opCount + "/" + taskCount);
}
private void move(Deque<Integer> from, Deque<Integer> to) {
if (from == to) throw new IllegalArgumentException("moving from/to " + from);
Integer i = from.pop();
if (to != main && !to.isEmpty() && i > to.peek()) {
throw new IllegalStateException(
from + " " + i + " -> " + to);
}
to.push(i);
opCount++;
}
private String name(Deque<Integer> stack) {
return stack == help1 ? "help1" :
stack == help2 ? "help2" :
"main";
}
private String state() {
return "main: " + main +
"\nhelp1: " + help1 +
"\nhelp2: " + help2;
}
```
The actual algorithm:
```
private void ensureMain(Deque<Integer> stack) {
if (stack != main) {
throw new IllegalArgumentException("Expected main, got " + name(stack) + "\n" + state());
}
}
private void ensureHelp(Deque<Integer> stack) {
if (stack == main) {
throw new IllegalArgumentException("Expected help, got main\n" + state());
}
}
private void ensureHelpers(Deque<Integer> stack1, Deque<Integer> stack2) {
ensureHelp(stack1);
ensureHelp(stack2);
}
private void sortMain() {
int height = main.size();
int topIndex = height;
while (topIndex == height && height > 1) {
topIndex = lastIndexOfLargest(height, main);
height--;
}
if (topIndex == height) {
// is already sorted
return;
}
// split stack at largest element
int part1Count = topIndex;
int part2Count = height - topIndex;
// move largest and first part to help 1
moveFromMain(part1Count+1, help1, help2);
// merge both parts to help 2, leaving largest on 1
mergeToHelp(part2Count, main, part1Count, help1, help2);
// move largest to main
move(help1, main);
// move remaining to main
moveToMain(height, help2, help1);
}
/** Moves elements from main to helper, sorting them */
private void moveFromMain(int amount, Deque<Integer> target, Deque<Integer> help) {
if (amount < 1) return;
ensureHelpers(target, help);
int topIndex = lastIndexOfLargest(amount, main);
int part1Count = topIndex;
int part2Count = amount - topIndex - 1;
// move first part to help
moveFromMain(part1Count, help, target);
// move largest to target
move(main, target);
// merge both parts to target
mergeToHelp(part2Count, main, part1Count, help, target);
}
/** Moves elements from helper to main, keeping them sorted */
private void moveToMain(int amount, Deque<Integer> source, Deque<Integer> help) {
if (amount < 1) return;
ensureHelpers(source, help);
moveHelper(amount-1, source, help);
move(source, main);
moveToMain(amount-1, help, source);
}
/** Moves elements between helpers */
private void moveHelper(int amount, Deque<Integer> source, Deque<Integer> target) {
pushToMain(amount, source);
popFromMain(amount, target);
}
/** Merges top of main and helper to other helper */
private void mergeToHelp(int mainAmount, Deque<Integer> main, int helpAmount, Deque<Integer> help, Deque<Integer> target) {
ensureMain(main);
ensureHelpers(help, target);
if (mainAmount < 0) mainAmount = 0;
if (helpAmount < 0) helpAmount = 0;
while (mainAmount > 0 || helpAmount > 0) {
// while there is something to merge
int largestMain = valueOfLargest(mainAmount, main);
int largestHelp = valueOfLargest(helpAmount, help);
if (largestMain > largestHelp) {
// largest is in main
int index = firstIndexOfLargest(mainAmount, main);
if (index > 0) {
// move excess to help:
int mainTop = index;
int helpTop = elementsSmallerThan(help, largestMain);
if (helpTop > 0) {
// 1. move top of help to target
moveHelper(helpTop, help, target);
// 2. merge old top with excess from main
mergeToHelp(mainTop, main, helpTop, target, help);
} else {
moveFromMain(mainTop, help, target);
}
mainAmount -= mainTop;
helpAmount += mainTop;
}
move(main, target);
mainAmount--;
} else {
// largest is at bottom of help
int helpTop = helpAmount - 1; // largest is at bottom
// move top to main
pushToMain(helpTop, help);
mainAmount += helpTop;
// move largest to target
move(help, target);
helpAmount = 0;
}
}
}
private void pushToMain(int amount, Deque<Integer> from) {
for (; amount > 0; amount--) move(from, main);
}
private void popFromMain(int amount, Deque<Integer> to) {
for (; amount > 0; amount--) move(main, to);
}
private int firstIndexOfLargest(int height, Deque<Integer> stack) {
if (height == 0) throw new IllegalArgumentException("height == 0");
int topValue = 0;
int topIndex = 0;
int i = 0;
for (Integer e: stack) {
if (e > topValue) {
topValue = e;
topIndex = i;
}
if (++i == height) break;
}
return topIndex;
}
private int lastIndexOfLargest(int height, Deque<Integer> stack) {
if (height == 0) throw new IllegalArgumentException("height == 0");
int topValue = 0;
int topIndex = 0;
int i = 0;
for (Integer e: stack) {
if (e >= topValue) {
topValue = e;
topIndex = i;
}
if (++i == height) break;
}
return topIndex;
}
private int valueOfLargest(int height, Deque<Integer> stack) {
int v = Integer.MIN_VALUE;
for (Integer e: stack) {
if (height-- == 0) break;
if (e > v) v = e;
}
return v;
}
private int elementsSmallerThan(Deque<Integer> stack, int value) {
int i = 0;
for (Integer e: stack) {
if (e >= value) return i;
i++;
}
return i;
}
```
The testcase:
```
public static void main(String[] args) throws Exception {
HanoiSort hanoi = new HanoiSort();
int N = 6;
for (int len = 1; len <= N; len++) {
Integer[] input = new Integer[len];
List<Integer> inputList = Arrays.asList(input);
int max = N;
for (int i = 1; i < len; i++) max *= N;
for (int run = 0; run < max; run++) {
int n = run;
for (int i = 0; i < len; n /= N, i++) {
input[i] = (n % N)+1;
}
try {
hanoi.sort(inputList);
} catch (Exception e) {
System.out.println(inputList);
e.printStackTrace(System.out);
return;
}
}
}
hanoi.done();
}
```
[Answer]
**C/C++ Didn't measure moves** (pegs :p1, p2, p3)
Don't know how to add C++ code that uses STL(formating issue).
Loosing parts of code due to html tag formats in code.
1. Get n : count of top sorted elements in p1
2. Do a hanoi move of them (n) to p3 using p2(keeps the sorted property)
3. Move the next m elems (atleast 1) in reverse order from p1 to p2.
4. Merge move (n+m) data in p2 & p3 to p1.
```
4.1 merge sort p2 & P3 (reverse) to p1
4.2 move (n+m) to p3
4.3 hanoi p3 to p1 using p2
```
5. Call hanoi sort recursively which will sort atleast n+m+1 elements now.
6. Stop when n = size of p1.
```
#include
#include
using namespace std;
/******************************************************************************
Show the vector (Had to chance cout
*******************************************************************************/
void show(vector p, string msg)
{
vector::iterator it;
printf(" %s \n", msg.c_str());
for(it = p.begin(); it &fr, vector &inter, vector &to, int n) {
int d1;
if (n &p1, vector &p2, vector &p3) {
int d3, d2, d1;
int count,n;
bool d2_added;
d2 = p2.back(); p2.pop_back();
// data will be descending in p1
d2_added = false;
while (p3.size() > 0) {
d3 = p3.back(); p3.pop_back();
if (d2_added == false && d2 0) {
d1 = p1.back();p1.pop_back();
p3.push_back(d1);
--count;
}
//Move back with hanoi from p3 to p1
// use p2 as inter
hanoi(p3, p2, p1, n);
}
/*******************************************************************************
Gets the count of first sorted elements
*******************************************************************************/
int get_top_sorted_count(vector &p1) {
vector::iterator it;
int prev = 0;
int n =1;
for (it = --p1.end(); it >= p1.begin(); --it){
if (it == --p1.end()) {
prev = *it;
continue;
}
if (*it &p1, vector &p2, vector &p3) {
int n, d1;
n = get_top_sorted_count(p1);
if (n == p1.size()) {
return;
}
hanoi(p1, p2, p3, n);
p2.push_back(p1.back());
p1.pop_back();
merge_move(p1, p2, p3);
hanoi_sort(p1, p2, p3);
}
/*******************************************************************************
Sorts baed on hanoi
*******************************************************************************/
int main (void)
{
vector p1, p2, p3;
p1.push_back(5);
p1.push_back(4);
p1.push_back(7);
p1.push_back(3);
p1.push_back(8);
p1.push_back(2);
show(p1, "...Bef Sort...");
hanoi_sort(p1, p2, p3);
show(p1, "...Aft Sort...");
}
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.