title: Almost a Columbo episode

text:
# Question
Title: Almost a Columbo episode
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 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 , so the shortest answer in bytes wins!

## Test set

Here is a link to all 14252 possible inputs.

# Answer
# Stax, 294 bytes

```
ê(·▲[*▬è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

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

```
> 12 votes

# 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:.....o..@.S
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 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

```
> 8 votes

# Answer
# JavaScript (ES6), 634 bytes

*This submission **was meant to remain hidden** until an answer of less than 500 bytes was published. **Which has now been done**.*

```
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! (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.)
> 6 votes

# Answer
# Wolfram Language ~~1383~~ 1226 bytes

*EditDistance* finds the 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"

```
> 3 votes

# Answer
# Python 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!

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.
> 3 votes

# Answer
# 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!

Used this to compress the list.

This assumes that there is no movie which has exactly 2 characters different than another movie, which is proven here (output `1`).
> 2 votes

# Answer
# Ruby, ~~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!

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 "|"

```
> 2 votes

# 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.

Here is the code for the encoder.

```
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

```
> 2 votes

---
Tags: code-golf, string, error-correction
---


title: Digits in their lanes

text:
# Question
Title: Digits in their lanes
## Input:

A list of integers

## Output:

Put each digit (and the minus sign) in its own lane, in the order `-0123456789`, ignoring any duplicated digits.

## Example:

Input: `[1,729,4728510,-3832,748129321,89842,-938744,0,11111]`

Output:

```
-0123456789  <- Added as clarification only, it's not part of the output

  1
   2    7 9
 012 45 78
-  23    8
  1234  789
   2 4   89
-   34  789
 0
  1

```

## Challenge rules:

* Any duplicated digits in the number are ignored.
* I/O can be in any reasonable format. Input can be as a list/array of strings or character-array. Output can be as a list of strings, characters, character-matrix, etc.
* Trailing spaces are optional.
* Any amount of leading or trailing new-lines are optional (but not in between lines).
* Input will always contain at least one integer
* You'll have to support an integer range of at least `-2,147,483,648` though `2,147,483,647` (32-bit).
* The input-list will never contain `-0`, `00` (or more than two zeroes), or integers with leading zeroes (i.e. `012`).
* If you language uses a different symbol for negative numbers (like an upper `¯`), you are also allowed to use that instead, as long as it's consistent.
* You are allowed to have a space delimiter between digits (so a line without 5 or 8 can be `- 0 1 2 3 4 6 7 9` instead of `-01234 67 9`), as long as it's consistent (and therefore there should also be a space between `-` and `0`).

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Test cases:

```
Input: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]
Output:
  1
   2    7 9
 012 45 78
-  23    8
  1234  789
   2 4   89
-   34  789
 0
  1

Input: [4,534,4,4,53,26,71,835044,-3559534,-1027849356,-9,-99,-3459,-3459,-94593,-10234567859]
Output:
      4
     345
      4
      4
     3 5
    2   6
   1     7
  0  345  8
 -   345   9
 -0123456789
 -         9
 -         9
 -   345   9
 -   345   9
 -   345   9
 -0123456789

Input: [112,379,-3,409817,239087123,-96,0,895127308,-97140,923,-748]
Output:
  12
   3    7 9
-  3
 01 4   789
 0123   789
-      6  9
 0
  123 5 789
-01  4  7 9
   23     9
-    4  78

Input: [-15,-14,-13,-12,-11,10,-9,-8,-7,-5,-4,-3,-1,0,9,100,101,102,1103,104,105,106,116,-12345690]
Output:
- 1   5
- 1  4
- 1 3
- 12
- 1
-01
-         9
-        8
-       7
-     5
-    4
-   3
- 1
 0
          9
 01
 01
 012
 01 3
 01  4
 01   5
 01    6
  1    6
-0123456  9

Input: [99,88,77,66,55,44,33,22,11,10,0,0,0,-941]
Output:
          9
         8
        7
       6
      5
     4
    3
   2
  1
 01
 0
 0
 0
- 1  4    9

```

# Answer
> 4 votes
# Stax, 8 bytes

```
║V≡u╝─é╢

```

Run and debug it

It takes one number per line on standard input. It works by finding the target index of each character and assigning it into that index of the result. If the index is out of bounds, the array is expanded with zeroes until it fits. During output, `0` becomes a space. The rest are character codes.

Unpacked, ungolfed, and commented, this is what it looks like.

```
m       for each line of input, execute the rest of the program and print the result
 zs     put an empty array under the line of input
 F      for each character code in the line of input, run the rest of the program
  Vd    "0123456789"
  I^    get the index of the character in this string and increment
  _&    assign this character to that index in the original string

```

Run this one

# Answer
> 6 votes
# 05AB1E, 13 bytes

### Code:

```
v'-žh«DyмSð:,

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
v               # For each element in the input..
 '-žh«          #   Push -0123456789
      D         #   Duplicate this string
       yм       #   String subtraction with the current element
                    e.g. "-0123456789" "456" м  →  "-0123789"
         Sð:    #   Replace all remaining elements with spaces
                    e.g. "-0123456789" "-0123789" Sð:  →  "     456   "
            ,   #   Pop and print with a newline

```

# Answer
> 4 votes
# Haskell, 51 bytes

*-1 byte thanks to Laikoni.*

```
f l=[[last$' ':[n|n`elem`i]|n<-"-0123456789"]|i<-l]

```

Try it online!

This challenge is digitist. D:

# Answer
> 4 votes
# APL (Dyalog), ~~32~~ 12 bytes

*28 bytes saved thanks to @Adám and @ngn*

```
⊃¨⎕∘.∩'¯',⎕d

```

Try it online!

# Answer
> 4 votes
# JavaScript, ~~59~~ 58 bytes

Input & output as an array of strings.

```
a=>a.map(x=>`-0123456789`.replace(eval(`/[^${x}]/g`),` `))

```

---

## Try it

```
o.innerText=(g=s=>(f=
a=>a.map(x=>`-0123456789`.replace(eval(`/[^${x}]/g`),` `))
)(s.split`,`).join`\n`)(i.value="1,729,4728510,-3832,748129321,89842,-938744,0,11111");oninput=_=>o.innerText=g(i.value)
```

```
input{width:100%;}
```

```
<input id=i><pre id=o></pre>
```

---

## Original

Takes input as an array of strings and outputs an array of character arrays

```
a=>a.map(x=>[...`-0123456789`].map(y=>-~x.search(y)?y:` `))

```

```
o.innerText=(g=s=>(f=
a=>a.map(x=>[...`-0123456789`].map(y=>-~x.search(y)?y:` `))
)(s.split`,`).map(x=>x.join``).join`\n`)(i.value="1,729,4728510,-3832,748129321,89842,-938744,0,11111");oninput=_=>o.innerText=g(i.value)
```

```
input{width:100%;}
```

```
<input id=i><pre id=o></pre>
```

# Answer
> 3 votes
# 05AB1E, ~~17~~ 13 bytes

Saved 4 bytes thanks to *Adnan*

```
vðTúyvyÐd+ǝ},

```

Try it online!

**Explanation**

```
v               # loop over elements y in input
 ðTú            # push a space prepended by 10 spaces
    yv          # for each element y in the outer y
      y         # push y
       Ðd+      # push y+isdigit(y)
          ǝ     # insert y at this position in the space-string
           }    # end inner loop
            ,   # print

```

# Answer
> 3 votes
# Ruby, 42 bytes

Anonymous lambda processing the array of numbers:

```
->a{a.map{|n|"-0123456789".tr"^#{n}",?\s}}

```

Try it online!

Alternatively, a completely Perl-like full program is much shorter. I'd say `-pl` switches look quite funny in this context:

# Ruby `-pl`, 29 bytes

```
$_="-0123456789".tr"^#$_"," "

```

Try it online!

Finally, the following is possible if it is acceptable for the output strings to be quoted:

# Ruby `-n`, 27 bytes

```
p"-0123456789".tr ?^+$_,?\s

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 60 bytes

* Thank to @Andrew Taylor for reducing the join (8 chars)
* Thank to @Yair Rand for X.match (8 chars)

```
a=>a.map(X=>"-0123456789".replace(/./g,x=>X.match(x)?x:" "))

```

Try it online!

# Answer
> 2 votes
# Japt, 16 bytes

Input & output as an array of strings.

```
£Ao ¬i- ®iS gXøZ

```

Try it

---

## Explanation

```
£                    :Map over each element X
 Ao                  :  Range [0,10)
    ¬                :  Join to a string
     i-              :  Prepend "-"
        ®            :  Map over each character Z
         iS          :    Prepend a space
            g        :    Get the character at index
             XøZ     :      X contains Z? (true=1, false=0)

```

# Answer
> 2 votes
# Python 3, ~~77~~ 64 bytes

*-12 bytes thanks to @Rod*

```
lambda x:[[[" ",z][z in str(y)]for z in"-0123456789"]for y in x]

```

Try it online!

My first proper attempt at golfing in Python. Advice welcome!

Returns a 2D array of characters.

# Answer
> 2 votes
# MATL, 13 bytes

```
"45KY2ht@gm*c

```

Input is a cell array of strings. Try it online! Or verify all test cases.

### Explanation

```
         % Implicit input: cell array of strings, for example {'1','729',...,'11111'}
"        % For each cell
  45     %   Push 45 (ASCII code of '-')
  KY2    %   Push predefined literal '0123456789'
  h      %   Concatenate horizontally: gives '-0123456789'
  t      %   Duplicate
  @      %   Push current cell, for example {'729'}
  g      %   Convert cell to matrix. This effectively gives the cell's contents, '729'
  m      %   Ismember: gives an array of zeros and ones indicating membership of each
         %   char from '-0123456789' in '729'. The result in the example is
         %   [0 0 0 1 0 0 0 0 1 0 1]
  *      %   Multiply, element-wise. Chars are implicity converted to ASCII
         %   Gives the array [0 0 0 50 0 0 0 0 55 0 57]
  c      %   Convert ASCII codes to chars. 0 is displayed as space. Gives the string
         %   '   2    7 9'
         % Implicit end
         % Implicilly display each string on a different line

```

# Answer
> 2 votes
# Perl 5 `-pl`, 33 bytes

```
$_=eval"'-0123456789'=~y/$_/ /cr"

```

Try it online!

Takes input as line separated.

# Answer
> 2 votes
# Jelly, 12 bytes

```
ØD”-;¹⁶e?€Ʋ€

```

Try it online!

-2 thanks to Jonathan Allan reading a rule I didn't.

Note that the I/O format used in the TIO link is not the actual one, which is input as a list of string representations and output as a list of lines.

# Answer
> 2 votes
# , 32 27 bytes

-5 bytes thanks to FrownyFrog!

```
10|.":(10<."."0@[)}11$' '"0

```

Try it online!

## Original solution:

# , 32 bytes

```
(('_0123456789'i.[)}11$' '"0)@":

```

## Explanation:

`@":` convert to characters and

`}11$' '"0` change the content of an array of 11 spaces to these characters

`'_0123456789'i.[` at the places, indicated by the indices of the characters in this list

Try it online!

# Answer
> 2 votes
# Google Sheets, 124 bytes

```
=Transpose(ArrayFormula(If(IsError(Find(Mid("-0123456789",Row($1:$11),1),Split(A1,",")))," ",Mid("-0123456789",Row($1:$11),1

```

Input is a comma-separated list in cell `A1`. Output is in the range `B1:L?` where `?` is however many entries were input. (You can put the formula wherever you want, I just chose `B1` for convenience.) Note that Sheets will automatically add four closing parentheses to the end of the formula, saving us those four bytes.

Another test case and another test case

Explanation:

* `Mid("-0123456789",Row($1:$11),1)` picks out each of the 11 characters in turn.
* `Find(Mid(~),Split(A1,","))` looks for those characters in each of the input elements. This either returns a numeric value or, if it's not found, an error.
* `If(IsError(Find(~)," ",Mid(~))` will return a space if the character wasn't found or the character if it was. (I wish there was a way to avoid duplicating the `Mid(~)` portion but I don't know of one.)
* `ArrayFormula(If(~))` is what makes the multi-cell references in `Mid(~)` and `Find(~)` work. It's also what makes a formula in one cell return values in multiple cells.
* `Transpose(ArrayFormula(~))` transpose the returned array because it starts off sideways.

# Answer
> 2 votes
# Haskell, 47 bytes

```
map(\s->do d<-"-0123456789";max" "[d|elem d s])

```

Try it online!

Uses `max` to insert a space where no element exist, since a space is smaller than any digit or minus sign.

If an ungodly number of trailing spaces is OK, two bytes can be saved:

**45 bytes**

```
map(\s->do d<-'-':['0'..];max" "[d|elem d s])

```

Try it online!

# Answer
> 1 votes
# Perl 6, 35 bytes

```
{.map:{map {m/$^a/||' '},'-',|^10}}

```

Try it online!

Output is a character matrix containing either regex matches or space characters.

# Answer
> 1 votes
# , ~~96~~ 75 bytes

```
for(i in scan())cat(paste(gsub(paste0("[^",i,"]")," ","-0123456789"),"\n"))

```

Try it online!

Thanks to Kevin Cruijssen for suggesting this regex approach!

Takes input from stdin as whitespace separated integers, and prints the ascii-art to stdout.

# Answer
> 1 votes
# Java 8, 53 bytes

```
a->a.map(i->"-0123456789".replaceAll("[^"+i+"]"," "))

```

My own challenge is easier than I thought it would be when I made it..

Input and output both as a `java.util.stream.Stream<String>`.

**Explanation:**

Try it online.

```
a->                              // Method with String-Stream as both input and return-type
  a.map(i->                      //  For every String in the input:
    "-0123456789"                //   Replace it with "-0123456789",
    .replaceAll("[^"+i+"]"," ")) //   with every character not in `i` replaced with a space

```

# Answer
> 1 votes
# C (gcc), 159 bytes

```
f(A,l,j,k,b)long*A,k;{char*s,S[99];for(j=~0;++j<l;puts(""))for(sprintf(S,"%ld",k=A[j]),putchar(k<0?45:32),k=47;++k<58;putchar(b?32:k))for(b=s=S;*s;b*=*s++-k);}

```

Try it online!

# Answer
> 1 votes
# SOGL V0.12, ~~14~~ 13 bytes

```
{ø,{²²⁴WI1ž}P

```

Try it Here!

Explanation:

```
{ø,{²²⁴WI1ž}P

{            repeat input times
 ø,            push an empty string and the next input above that
   {       }   for each character in the input
    ²²           push "0123456789"
      ⁴          copy the character on top
       W         and get it's index in that string (1-indexed, 0 for the non-existent "-")
        I        increment that (SOGL is 1-indexed, so this is required)
         1ž      at coordinates (index; 1) in the string pushed earlier, insert that original copy of the character
            P  print the current line

```

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 85 bytes

```
I	X =INPUT	:F(END)
	S ='-0123456789'
R	S NOTANY(X ' ') =' '	:S(R)
	OUTPUT =S	:(I)
END

```

Try it online!

```
I	X =INPUT	:F(END)		;* read input, if none, goto end
	S ='-0123456789'		;* set the string
R	S NOTANY(X ' ') =' '	:S(R)	;* replace characters of S not in X + space with space
	OUTPUT =S	:(I)		;* print S, goto I
END

```

# Answer
> 1 votes
# Pyth, 14 bytes

```
VQm*d}dNs+\-UT

```

Takes input as list of strings and outputs a list of strings for each line.
Try it here

### Explanation

```
VQm*d}dNs+\-UT
VQ                For each string in the input...
  m     s+\-UT    ... and each character in "-0123456789"...
     }dN          ... check if the character is in the string...
   *d             ... and get that character or an empty string.

```

# Answer
> 1 votes
# Retina, 26 bytes

```
%"-0123456789"~`.+
[^$&]¶

```

Try it online! Note: Trailing space. Explanation: `%` executes its child stage `~` once for each line of input. `~` first executes its child stage, which wraps the line in `[^` and `]<CR><SP>`, producing a program that replaces characters not in the line with spaces. The `"-0123456789"` specifies that the input to that program is the given string (`$` substitutions are allowed but I don't need them).

# Answer
> 1 votes
# Perl 5 `-n`, 30 bytes

Wouldn't work if `-` could appear anywhere else than in the first position

```
#!/usr/bin/perl -n
say"-0123456789"=~s/[^$_]/ /gr

```

Try it online!

# Answer
> 1 votes
# Red, 94 bytes

```
func[b][foreach a b[s: copy"           "foreach c a[s/(index? find"-0123456789"c): c]print s]]

```

Takes input as a block of strings

Try it online!

# Answer
> 1 votes
# CJam, 20 bytes

```
qS%{'-10,+s_@-SerN}/

```

Try it online!

Accepts input as space separated list of integers. Pretty much the same approach as @adnans answer.

# Answer
> 1 votes
# C (gcc), ~~95~~ 94 bytes

```
c,d;f(l,n)char**l;{for(;n--;l++)for(c=0;c<12;)putchar(strchr(*l,d=c++?c+46:45)?d:d^58?32:10);}

```

Try it online!

Input in the form of a list of strings. Output to STDOUT.

# Answer
> 1 votes
# K4, ~~30~~ 27 bytes

**Solution:**

```
{?[a in$x;a:"-",.Q.n;" "]}'

```

**Example:**

```
q)k){?[a in$x;a:"-",.Q.n;" "]}'1 729 4728510 -3832 748129321 89842 -938744 0 11111
"  1        "
"   2    7 9"
" 012 45 78 "
"-  23    8 "
"  1234  789"
"   2 4   89"
"-   34  789"
" 0         "
"  1        "

```

**Explanation:**

Return "-0123..." or " " based on the input. Interpreted right-to-left. No competition for the APL answer :(

```
{?[a in$x;a:"-",.Q.n;" "]}' / the solution
{                        }' / lambda for each
 ?[      ;          ;   ]   / if[cond;true;false]
                .Q.n        / string "0123456789"
            "-",            / join with "-"
          a:                / save as a
       $x                   / convert input to string
   a in                     / return boolean list where each a in x
                     " "    / whitespace (return when false)

```

# Answer
> 0 votes
# APL+WIN, 33 bytes

Prompts for screen input as a string

```
n←11⍴' '⋄n['-0123456789'⍳s]←s←⎕⋄n

```

# Answer
> 0 votes
# Haskell, 49 bytes

```
map$(<$>"-0123456789").(%)
i%n|elem n i=n|1<3=' '

```

The first line defines an anonymous function which takes a list of strings and returns a list of strings. Try it online!

# Answer
> 0 votes
## Javascript 95 bytes

```
(a,t='-0123456789')=>a.map(a=>a+'').map(_=>[...t].map(b=>_.search(b)>=0?b:' ').join``).join`\n`

```

```
f=(a,t='-0123456789')=>a.map(a=>a+'').map(_=>[...t].map(b=>_.search(b)>=0?b:' ').join``).join`\n`

console.log(f([1,729,4728510,-3832,748129321,89842,-938744,0,11111]))

console.log(f([4,534,4,4,53,26,71,835044,-3559534,-1027849356,-9,-99,-3459,-3459,-94593,-10234567859]))
```

# Answer
> 0 votes
# ShellUtils, 85 bytes

There must be a better way of escaping the {} rather than using a double echo and piping through bash

```
xargs -i echo echo \\-0123456789 \|tr \$\(echo .0123456789- \|tr -d -- {} \) \' \'|sh

```

This takes the strings, one per line, from stdlin The inner tr takes -0123456789 and removes what's not in the input line. The {} represents this.

The second tr takes that output, and converts -0123456789 by replacing the input characters with spaces.

---
Tags: code-golf, ascii-art, number, integer
---


title: Make a Triangularity program valid

text:
# Question
Title: Make a Triangularity program valid
Triangularity is a new esolang developed by Mr. Xcoder where code structure has to follow a very specific pattern:

* For the `n`th line of code, there must be exactly `2n-1` characters of the program on it. This causes a triangular/pyramid shape, with the first line having only one character and the rest increasing by increments of 2.
* Each line must be padded with `.`s on the left and right, such that the characters are centered on their lines and all lines are padded to the same length. If `l` is defined as the number of lines in the program, each line in the program must have a length of `2 * l - 1`

For example, the program on the left is valid, but the program on the right isn't:

```
 Valid    |  Invalid
          |
...A...   |  ABCDE
..BCD..   |  FGH
.EFGHI.   |  IJKLMN
JKLMNOP   |  OPQRS

```

When laid out in the valid structure, the name becomes obvious.

## Task

Your task is to take a single line string as input, representing Triangularity code, and output it converted into valid code as described above.

Specifications for I/O:

* The input will only contain characters in the range `0x20 - 0x7e`
* The length of the input always will be a square number and thus paddable nicely.
* You must use dots for the output padding, not something else.

You may input and output through any acceptable method. This is a so the shortest code in *bytes* wins!

## Test cases

```
input
----
output

g
----
g

PcSa
----
.P.
cSa

DfJ0vCq7G
----
..D..
.fJ0.
vCq7G

7xsB8a1Oqw5fhHX0
----
...7...
..xsB..
.8a1Oq.
w5fhHX0

QNYATbkX2sKZ6IuOmofwhgaef
----
....Q....
...NYA...
..TbkX2..
.sKZ6IuO.
mofwhgaef

ABCDEF"$%& G8"F@
----
...A...
..BCD..
.EF"$%.
& G8"F@

ab.c
----
.a.
b.c

```

For those who know Triangularity, you'll notice from the last test case that strings don't have to be handled

# Answer
> 20 votes
# Triangularity, 127 bytes

```
.......).......
......2)1......
...../)IL^.....
....f)rMD@_....
...)2)1/)IL^...
..f+`"'.'*"+E..
.DWReD)2s^)Its.
D+@sh+s+})10cJ.

```

Try it online!

## Explanation

Removing the characters that make up for the padding, we get the following program:

```
)2)1/)IL^f)rMD@_)2)1/)IL^f+`"'.'*"+EDWReD)2s^)ItsD+@sh+s+})10cJ

```

... Which is quite length-ish, right? Let's break it down into pieces.

**Generating the integers \[0 … √len(input))**

```
)2)1/)IL^f)r – Subprogram #1.
)            – Creates a new stack entry, equal to 0. This must precede any integer
               literal, because each character in '0123456789' isn't parsed on its
               own as a literal, but rather they are commands which multiply the ToS
               by 10 and add the value of their digit equivalent.
 2           – ToS * 10 + 2 = 2.           || STACK: [2]
  )1         – The literal 1.              || STACK: [2, 1]
    /        – Division.                   || STACK: [1 / 2] = [0.5]
     )I      – Get the input at index 0.   || STACK: [0.5, input]
       L     – Length.                     || STACK: [0.5, len(input)]
        ^    – Exponentiation.             || STACK: [len(input) ** 0.5]
         f   – Trim decimals.              || STACK: [int(len(input) ** 0.5)]
          )r – Create the list [0 .. ToS). || STACK: [[0 ... int(len(input) ** 0.5))]

```

**Generating the dots**

```
MD@_)2)1/)IL^f+`"'.'*"+E – Subprogram #2.
MD                       – For each integer in the range, run some code on a separate
                           stack, preinitialised to two copies of the argument.
  @_                     – Increment and negate the ToS.
    )2)1/)IL^f           – The square root of the length of the input, again.
              +          – Add the two.
               `         – And cast the integer given to a string.
                "'.'*"+  – Prepends the literal "'.'*" to the string representation.
                       E – Evaluate as a Python expression (basically string repetition).

```

**Trimming the characters at the front**

```
DWReD)2s^)It – Subprogram #3.
D            – Duplicate the result of the expression above.
 W           – Wrap the whole intermediate stack to an array.
  Re         – Reverse the stack and dump the contents separately onto the stack.
    D        – Duplicate the result.
     )2      – Push the literal 2.
       s^    – Swap and perform exponentiation.
         )It – Push the input and trim the characters before that index.

```

**Trimming the characters at the end**

```
sD+@sh+s+ – Subprogram #4.
s         – Swap the top two elements on the stack.
 D+       – Double. Push twice and add.
   @      – Increment.
    sh    – Swap the top two elements and trim the characters after that index.
      +   – Append the first set of dots.
       s+ – And prepend the second set of dots.

```

**Ending the loop and pretty-printing**

```
})10cJ – Subprogram #5.
}      – End the loop.
 )10   – Push the literal 10.
    c  – Convert from code-point to character (yields '\n').
     J – And join the result by newlines.

```

# Answer
> 8 votes
# Japt, ~~15~~ ~~14~~ 10 bytes

Outputs an array of lines.

```
ò@°T¬v1Ãû.

```

Try it | Check all test cases

---

## Explantion

```
ò@     Ã       :Partition at characters where the following function returns true
  °T           :  Increment T (initially 0)
    ¬          :  Square root
     v1        :  Divisible by 1?
               :(Or, in other words, split after every character with a 1-based index that's a perfect square)
        û.     :Centre pad each element with .s to the length of the longest element

```

---

## Original Solution

```
Ê¬ÆsTT±X+°XÃû.

```

Try it

```
Ê                  :Length of input
 ¬                 :Square root
  Æ        Ã       :Range [0,Ê¬) and pass each X through a function
   s               :  Slice input
    T              :    from index T, initially 0
     T±X+°X        :    to index T incremented by X plus X incremented
            û.     :Centre pad each element with .s to the length of the longest element

```

# Answer
> 7 votes
# 05AB1E, ~~20~~ ~~19~~ 18 bytes

Saved a byte thanks to *Magic Octopus Urn*

```
ā·<£õKRvy'.N×.ø}r»

```

Try it online!

**Explanation**

```
ā                    # push the list [1 ... len(input)]
 ·<                  # multiply each by 2 and decrement each, making a list of odd numbers
   £                 # split the input into chunks of these sizes
    õK               # remove empty strings
      R              # reverse list
       vy      }     # for each y in the list
             .ø      # surround it with
         '.N×        # "." (dot) repeated N times, where N is the current iteration index
                r    # reverse the stack
                 »   # join stack by newlines

```

# Answer
> 7 votes
# Husk, 15 bytes

```
Ṡzö`JR2tR'.ṡCİ1

```

Try it online!

## Explanation

```
Ṡzö`JR2tR'.ṡCİ1  Implicit input, say s = "DfJ0vCq7G".
             İ1  List of odd positive integers: [1,3,5,7,..
            C    Cut s to those lengths: x = ["D","fJ0","vCq7G"]
           ṡ     Reversed indices of x: y = [3,2,1]
Ṡz               Zip x and y using this function:
                  Arguments are a string and a number, e.g. r = "fJ0" and n = 2.
        R'.       n copies of '.': ".."
       t          Drop first element: "."
     R2           Two copies of this: [".","."]
  ö`J             Join by r: ".fJ0."
                 Result is ["..D..",".fJ0.","vCq7G"]; implicitly print on separate lines.

```

# Answer
> 5 votes
# Python 2, 83 bytes

```
i=input();u=int(len(i)**.5)
for t in range(u):g="."*(u+~t);print g+i[t*t:][:t-~t]+g

```

Try it online!

# Answer
> 5 votes
# JavaScript (ES7), ~~82~~ 78 bytes

```
f=(s,k=1-s.length**.5*2,p='')=>s&&f(s.slice(0,k),k+2,p+'.')+`
`+p+s.slice(k)+p

```

### Test cases

```
f=(s,k=1-s.length**.5*2,p='')=>s&&f(s.slice(0,k),k+2,p+'.')+`
`+p+s.slice(k)+p

console.log(f('g'))
console.log(f('PcSa'))
console.log(f('DfJ0vCq7G'))
console.log(f('7xsB8a1Oqw5fhHX0'))
console.log(f('QNYATbkX2sKZ6IuOmofwhgaef'))
console.log(f('ABCDEF"$%& G8"F@'))
```

### Commented

```
f = (                       // f = recursive function taking:
  s,                        //   s = input string
  k = 1 - s.length**.5 * 2, //   k = additive inverse of the length of the base
  p = ''                    //   p = padding string
) =>                        //
  s &&                      // if s is not empty:
    f(                      //   do a recursive call with:
      s.slice(0, k),        //     s without the last -k characters
      k + 2,                //     the updated base length (2 less characters)
      p + '.'               //     the updated padding string
    ) +                     //   end of recursive call()
    `\n` +                  //   append a line feed
    p +                     //   append the left padding string
    s.slice(k) +            //   append the last -k characters of s
    p                       //   append the right padding string

```

# Answer
> 5 votes
# Jelly,  ~~22~~  19 bytes

```
J²‘Ṭœṗ⁸Ṛz”.Zµṙ"JC$Ṛ

```

A monadic link returning a list of lists of characters (the lines)

**Try it online!**

### How?

```
J²‘Ṭœṗ⁸Ṛz”.Zµṙ"JC$Ṛ - Link: list of characters e.g. "DfJ0vCq7G"
J                   - range of length               [1,2,3,4,5,6,7,8,9]
 ²                  - square (vectorises)           [1,4,9,16,25,36,49,64,81]
  ‘                 - increment                     [2,5,10,17,26,37,50,65,82]
   Ṭ                - untruth (1s at those indices) [0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,...]
      ⁸             - chain's left argument         "DfJ0vCq7G"
    œṗ              - partition at indexes          ["D","fJ0","vCq7G"]
       Ṛ            - reverse                       ["vCq7G","fJ0","D"]
         ”.         - literal '.'                   '.'
        z           - transpose with filler         ["vfD","CJ.","q0.","7..","G.."]
           Z        - transpose                     ["vCq7G","fJ0..","D...."]
            µ       - start a new monadic chain
                 $  - last two links as a monad:
               J    -   range of length             [1,2,3]
                C   -   complement (vectorises)     [0,-1,-2]
              "     - zip with:
             ṙ      -   rotate left by              ["vCq7G",".fJ0.","..D.."]
                  Ṛ - reverse                       ["..D..",".fJ0.","vCq7G"]

```

# Answer
> 2 votes
# MATL, 21 bytes

```
tnX^eRP&1ZvGyg(46y~(!

```

Try it online!

### Explanation

Consider input `'DfJ0vCq7G'` as an example. The stack contents are shown separated by commas, with the top element last. Rows in a 2D array use semicolon as separator.

```
t      % Implicit input: string. Duplicate
       % STACK: 'DfJ0vCq7G',
                'DfJ0vCq7G'
nX^    % Number of elements. Square root
       % STACK: 'DfJ0vCq7G',
                3
e      % Reshape with that many rows (in column major order)
       % STACK: ['D0q';
                 'fv7';
                 'JCG']
R      % Upper triangular part: set elements below diagonal to char(0)
       % (displayed as space)
       % STACK: ['D0q';
                 ' v7';
                 '  G']
P      % Flip vertically
       % STACK: ['  G';
                 ' v7';
                 'D0q']
&1Zv   % Reflect vertically
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G']
G      % Push input again
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G'],
                'DfJ0vCq7G'
yg     % Duplicate from below and convert to logical. This gives true for
       % for nonzero chars (the entries where input chars will be written)
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G'],
                'DfJ0vCq7G',
                [0 0 1;
                 0 1 1;
                 1 1 1;
                 0 1 1;
                 0 0 1]
(      % Assignment indexing: write values at those positions
       % STACK: ['  v';
                 ' fC';
                 'DJq';
                 ' 07';
                 '  G']
46     % Push 46, which is ASCII for '.'
       % STACK: ['  v';
                 ' fC';
                 'DJq';
                 ' 07';
                 '  G'],
                 46
y~     % Duplicate from below and apply logical negate. This gives true
       % for char(0) (the entries where '.' will be written)
       % STACK: ['  G';
                 ' v7';
                 'D0q';
                 ' v7';
                 '  G'],
                46
                [1 1 0;
                 1 0 0;
                 0 0 0;
                 1 0 0;
                 1 1 0]
(      % Assignment indexing: write value at those positions
       % STACK: ['..G';
                 '.v7';
                 'D0q';
                 '.v7';
                 '..G'],
!      % Transpose. Implicit display
       % STACK: ['..D..';
                 '.fJ0.';
                 'vCq7G']

```

# Answer
> 2 votes
# 05AB1E, 25 bytes

```
gÅÉ£õKð'ø‡.c¶¡ζøð'.‡'øð‡»

```

Try it online!

# Answer
> 2 votes
# Clean, ~~107~~ ~~94~~ ~~89~~ 88 bytes

```
import StdEnv
@s _[]=s
@s n r= @([['.':l]++['.']\\l<-s]++[take n r])(n+2)(drop n r)

```

```
@[]1

```

Try it online! Example usage: `@[]1 ['ABCDEF"$%& G8"F@']`.

# Answer
> 1 votes
# Red, 227 203 bytes

```
f: func[s][l: to-integer(length? s)** 0.5
n: 0 foreach m parse s[collect[(r: []repeat i l[append r reduce['keep i * 2 - 1
charset[not{Я}]]])r]][v: copy""insert/dup v"."l - n: n + 1 print rejoin[v m v]]]

```

Try it online!

Ungolfed:

```
f: func[s][
l: to-integer (length? s) ** 0.5
n: 0
foreach m parse s [
    collect [
        (r: []
        repeat i l [ append r reduce [
            'keep i * 2 - 1 charset [ not{Я} ]]])
    r ]]
    [v: copy ""
    insert/dup v "." l - n: n + 1
    print rejoin [v m v]]
]

```

# Answer
> 1 votes
# Haskell, ~~84~~ 68 bytes

```
[]%1
(s%n)[]=s
(s%n)r=(['.':l++"."|l<-s]++[take n r])%(n+2)$drop n r

```

Try it online!

Example usage: `[]%1 $ "abcd"` yields the list of lines `[".a.","bcd"]`.

# Answer
> 1 votes
# Perl, ~~56~~ 52 bytes

Includes `+3` for `-p`

```
#!/usr/bin/perl -p
$_=("."x y///c**.5)=~s%.%$'@{[$&x/$`$`./g]}$'
%rg

```

Give input on STDIN (in principle without final newline, but that only matters for the empty input)

# Answer
> 1 votes
# Charcoal, ~~21~~ 19 bytes

```
ＵＢ.Ｆ₂Ｌθ«Ｐ✂θＸι²Ｘ⊕ι²↙

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes by discovering `SquareRoot`. Explanation:

```
ＵＢ.                 Set the background fill to `.`
      θ             (First) input
     Ｌ              Length
    ₂               Square root
   Ｆ   «            Loop over implicit range
            ι   ι   Current value
               ⊕    Incremented
             ²   ²  Literal 2
           Ｘ  Ｘ     Power
         ✂θ         Slice the (first) input string
        Ｐ           Print without moving the cursor
                  ↙ Move down left

```

# Answer
> 1 votes
# Retina, ~~88~~ ~~72~~ 71 bytes

```
S1`
+m`^(.)+¶(?>(?<-1>.)+)..(?!¶)
$&¶
P^'.m`^.(?=(..)*)(?<-1>.)*
P'.`.+

```

Try it online! Edit: Saved ~~12~~ 13 bytes thanks to @MartinEnder. Explanation:

```
S1`

```

Split first character into its own line to get the ball rolling.

```
+m`^(.)+¶(?>(?<-1>.)+)..(?!¶)
$&¶

```

Chop each line two characters longer than the previous one.

```
P^'.m`^.(?=(..)*)(?<-1>.)*

```

Left-pad the first half of each line, effectively centring them.

```
P'.`.+

```

Right-pad all of the lines.

# Answer
> 0 votes
# Python 2, 84 bytes

```
s=input()
l=int(len(s)**.5)
for i in range(l):print s[i*i:][:i-~i].center(l*2-1,'.')

```

Try it online!

# Answer
> 0 votes
# Clean, 123 bytes

```
import StdEnv
?n l#(a,b)=splitAt n l
|b>[]=[a: ?(n+2)b]=[a]
$s#s= ?1s
=[c++l++c\\l<-s&i<-[1..],c<-[repeatn(length s-i)'.']]

```

Try it online!

# Answer
> 0 votes
# Ruby, ~~73~~ 66 bytes

```
->s{(1..z=s.size**0.5).map{|q|s[q*q-2*q+1...q*q].center 2*z-1,?.}}

```

Try it online!

-5 bytes: Return an array of strings instead of printing them

-2 bytes: Declare `z` in place instead of ahead of time

Ungolfed:

```
->s{
  (1..z=s.size**0.5).map{|q|   # Map the range [1,sqrt(s.size)]
    s[q*q-2*q+1...q*q]         # To the relevant portion of s,
      .center 2*z-1, ?.        #   padded left and right with . characters
  }
}

```

Declaring a variable `r=q-1` so that I can take `s[r*r...q*q]` saves exactly zero bytes.

Using `.center` instead of padding manually also saves zero bytes, but I like it better.

# Answer
> 0 votes
# Stax, 19 bytes

```
╚└÷2╬#►o┴X≡¥ΩåV∙¬?♥

```

Run and debug it

ASCII equivalent:

```
z;%|q{Hv,:/~]+F|Cm0]'.R

```

---
Tags: code-golf, string
---


title: Levi-Civita symbol

text:
# Question
Title: Levi-Civita symbol
The three-dimensional Levi-Civita symbol is a function `f` taking triples of numbers `(i,j,k)` each in `{1,2,3}`, to `{-1,0,1}`, defined as:

* `f(i,j,k) = 0` when `i,j,k` are not distinct, i.e. `i=j` or `j=k` or `k=i`
* `f(i,j,k) = 1` when `(i,j,k)` is a cyclic shift of `(1,2,3)`, that is one of `(1,2,3), (2,3,1), (3,1,2)`.
* `f(i,j,k) = -1` when `(i,j,k)` is a cyclic shift of `(3,2,1)`, that is one of `(3,2,1), (2,1,3), (1,3,2)`.

The result is the sign of a permutation of `(1,2,3)`, with non-permutations giving 0. Alternatively, if we associate the values `1,2,3` with orthogonal unit basis vectors `e_1, e_2, e_3`, then `f(i,j,k)` is the determinant of the 3x3 matrix with columns `e_i, e_j, e_k`.

**Input**

Three numbers each from `{1,2,3}` in order. Or, you may choose to use zero-indexed `{0,1,2}`.

**Output**

Their Levi-Civita function value from `{-1,0,1}`. This is code golf.

**Test cases**

There are 27 possible inputs.

```
(1, 1, 1) => 0
(1, 1, 2) => 0
(1, 1, 3) => 0
(1, 2, 1) => 0
(1, 2, 2) => 0
(1, 2, 3) => 1
(1, 3, 1) => 0
(1, 3, 2) => -1
(1, 3, 3) => 0
(2, 1, 1) => 0
(2, 1, 2) => 0
(2, 1, 3) => -1
(2, 2, 1) => 0
(2, 2, 2) => 0
(2, 2, 3) => 0
(2, 3, 1) => 1
(2, 3, 2) => 0
(2, 3, 3) => 0
(3, 1, 1) => 0
(3, 1, 2) => 1
(3, 1, 3) => 0
(3, 2, 1) => -1
(3, 2, 2) => 0
(3, 2, 3) => 0
(3, 3, 1) => 0
(3, 3, 2) => 0
(3, 3, 3) => 0

```

# Answer
# Jelly, 5 bytes

```
ṁ4IṠS

```

Try it online!

### Algorithm

Let's consider the differences **j-i, k-j, i-k**.

* If **(i, j, k)** is a rotation of **(1, 2, 3)**, the differences are a rotation of **(1, 1, -2)**. Taking the sum of the signs, we get **1 + 1 + (-1) = 1**.
* If **(i, j, k)** is a rotation of **(3, 2, 1)**, the differences are a rotation of **(-1, -1, 2)**. Taking the sum of the signs, we get **(-1) + (-1) + 1 = -1**.
* For **(i, i, j)** (or a rotation), where **i** and **j** may be equal, the differences are **(0, j-i, i-j)**. The signs of **j-i** and **i-j** are opposite, so the sum of the signs is **0 + 0 = 0**.

### Code

```
ṁ4IṠS  Main link. Argument: [i, j, k]

ṁ4     Mold 4; yield [i, j, k, i].
  I    Increments; yield [j-i, k-j, i-k].
   Ṡ   Take the signs, replacing 2 and -2 with 1 and -1 (resp.).
    S  Take the sum.

```
> 23 votes

# Answer
# Python 2, 32 bytes

```
lambda i,j,k:(i-j)*(j-k)*(k-i)/2

```

Try it online!

### Algorithm

Let's consider the differences **i-j, j-k, k-i**.

* If **(i, j, k)** is a rotation of **(1, 2, 3)**, the differences are a rotation of **(-1, -1, 2)**. Taking the product, we get **(-1) × (-1) × 2 = 2**.
* If **(i, j, k)** is a rotation of **(3, 2, 1)**, the differences are a rotation of **(1, 1, -2)**. Taking the product, we get **1 × 1 × (-2) = -2**.
* For **(i, i, j)** (or a rotation), where **i** and **j** may be equal, the differences are **(0, i-j, j-i)**. Taking the product, we get **0 × (i-j) × (j-i) = 0**.

Thus, dividing the product of the differences by **2** yields the desired result.
> 11 votes

# Answer
# x86, 15 bytes

Takes arguments in `%al`, `%dl`, `%bl`, returns in `%al`. Straightforward implementation using Dennis's formula.

```
 6: 88 c1                   mov    %al,%cl
 8: 28 d0                   sub    %dl,%al
 a: 28 da                   sub    %bl,%dl
 c: 28 cb                   sub    %cl,%bl
 e: f6 e3                   mul    %bl
10: f6 e2                   mul    %dl
12: d0 f8                   sar    %al
14: c3                      retq

```

Aside: I think I understand why `%eax` is the "accumulator" now...
> 7 votes

# Answer
# Wolfram Language (Mathematica), 9 bytes

```
Signature

```

Try it online!

---

# Wolfram Language (Mathematica), 18 bytes

Saved 2 bytes thanks to Martin Ender.

```
Det@{#^0,#,#^2}/2&

```

Try it online!
> 7 votes

# Answer
# Octave, 20 bytes

```
@(v)det(eye(3)(:,v))

```

Pretty direct implementation of the determinant formula. Permutes the columns of the identity matrix then takes the determinant.
> 6 votes

# Answer
# Haskell, 26 bytes

```
(x#y)z=(x-y)*(y-z)*(z-x)/2

```

Try it online!

Nasty IEEE floats...
> 5 votes

# Answer
# APL (Dyalog), ~~11~~ 9 bytes

*2 bytes saved thanks to @ngn*

```
+/×2-/4⍴⎕

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 38 bytes

Overcomplicated but fun:

```
(a,b,c,k=(a+b*7+c*13)%18)=>k-12?+!k:-1

```

Try it online!

---

# JavaScript (ES6), 28 bytes

Using the standard formula:

```
(a,b,c)=>(a-b)*(b-c)*(c-a)/2

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~7~~ 5 bytes

*1 byte saved thanks to @Emigna*

```
ĆR¥P;

```

Try it online!
> 4 votes

# Answer
# Ruby, 28 bytes

```
->a,b,c{(a-b)*(b-c)*(c-a)/2}

```

Try it online!
> 3 votes

# Answer
## CJam (16 bytes)

```
1q~{)1$f-@+:*\}h

```

Online demo. Note that this is based on a previous answer of mine which uses the Levi-Civita symbol to calculate the Jacobi symbol.
> 2 votes

# Answer
# Ruby, 56 bytes

```
->t{t.uniq!? 0:(0..2).any?{|r|t.sort==t.rotate(r)}?1:-1}

```

Try it online!

Once we rule out cases where the values of the triplet are not unique, `t.sort` is equivalent to (and shorter than) `[1,2,3]` or `[*1..3]`

```
->t{
  t.uniq! ? 0                     # If applying uniq modifies the input, return 0
          : (0..2).any?{|r|       # Check r from 0 to 2:
              t.sort==t.rotate(r) #   If rotating the input r times gives [1,2,3],
            } ? 1                 #     return 1;
              :-1                 #     else return -1
}

```
> 1 votes

# Answer
# Husk, 7 bytes

```
ṁ±Ẋ-S:←

```

Try it online!

# Explanation

Straight port of Dennis's Jelly answer. `S:←` copies the head of the list to the end, `Ẋ-` takes adjacent differences, and `ṁ±` takes the sign of each element and sums the result.
> 1 votes

# Answer
# Jelly, 8 bytes

```
⁼QȧIḂÐfḢ

```

Try it online!

Seems too ungolfed. :(
> 0 votes

# Answer
**SHELL**, **44 Bytes**

```
 F(){ bc<<<\($2-$1\)*\($3-$1\)*\($3-$2\)/2;}

```

tests :

```
 F 1 2 3
 1

 F 1 1 2
 0

 F  2 3 1
 1

 F 3 1 2
 1

 F 3 2 1
 -1

 F 2 1 3
 -1

 F 1 3 2
 -1

 F 1 3 1
 0

```

Explanation :

```
 The formula is : ((j - i)*(k - i)*(k - j))/2

```

**BC**, **42 Bytes**

```
 define f(i,j,k){return(j-i)*(k-i)*(k-j)/2}

```

tests:

```
 f(3,2,1)
 -1
 f(1,2,3)
 1
 f(1,2,1)
 0

```
> 0 votes

# Answer
# Japt, 7 bytes

```
änUÌ xg

```

Try it

---

## Explanation

```
            :Implicit input of array U
ä           :Get each consecutive pair of elements
 n          :Reduce by subtracting the first from the last
  UÌ        :But, before doing that, prepend the last element in U
     g      :Get the signs
    x       :Reduce by addition

```

---

## Alternative

Takes input as individual integers.

```
NänW ×z

```

Try it
> 0 votes

# Answer
# Add++, 13 bytes

```
L,@dV@GÑ_@€?s

```

Try it online!
> 0 votes

# Answer
# Stax, 8 bytes

```
äN§lüy²Å

```

Run and debug it

Translates to `-(b-a)(c-b)(a-c)/2`.
> 0 votes

# Answer
# , 12 bytes

```
1#.2*@-/\4$]

```

Try it online!

Direct translation of Uriel's APL solution into J.

## Explanation:

`4$]` Extends the list with its first item

`2 /\` do the following for all the overlapping pairs in the list:

`*@-` find the sign of their difference

`1#.` add up
> 0 votes

# Answer
# Java 8, 28 bytes

```
(i,j,k)->(i-j)*(j-k)*(k-i)/2

```

Port of *@Dennis*' Python 2 answer.

Try it online.
> 0 votes

# Answer
# Python, 33 bytes

```
lambda i,j,k:(i^j!=k or-~j-i)%3-1

```

Try it online!

I tried for a while to beat the product-of-differences approach, but the best I got was 1 byte longer.
> 0 votes

---
Tags: code-golf, permutations
---


title: Make Arrays/Lists start at one

text:
# Question
Title: Make Arrays/Lists start at one
# Introduction

For as long as programmers have been programming and as long as English teachers have been teaching, there's a controversy over the datasets called *Arrays* and *Lists* (or hashes).

Arrays have almost always had their first index at 0. Which, for the programmer, is understandable because of math. But along the way, as more and more languages have appeared, and more and more people start to program, they can't wrap their mind around the array.

They know it's a table of indexes with values assigned to each index, but they don't know why it starts at 0, because 0 typically means nothing. 0 is a quantitative value that we don't see (or can, but mostly in context).

# Task

It's simple: **Make your arrays/list/hashes/whatever start at one**

This doesn't require special tinkering to the compiler/interpreter. Make a user's array have their expected values at position 1.

Loopholes aren't allowed.

# Examples

A basic example (written in Pseudo):

```
list = [1,2,3]
lis = [null]
value = 1
Loop list Through 3 Times as Index_Value
    lis[value] = Index_Value
    value += 1
print(lis) // or return lis, doesn't matter

```

# Rules

1. No standard loopholes allowed
2. Languages that have arrays/lists/hashes that start at one OR are configurable to have settable index numbers.
3. Input will be given, you may expect a array. However, if the array requires certain types, assume the array is filled with integers. Basically, test for \[1, 2, 3, 4, 5, 6, 7, 8, 9, 10\] (I do encourage any answers that aren't for competition)
4. Output must be the fixed array. If the fixed array is assigned to value `a`, then `a[1] == 1`
5. Anything can be in the `a[0]` index, the user will not care. Though, preferably, **BUT NOT REQUIRED**, the value should be `null` or some other comparable value.

This is , so the shortest answer in bytes wins.

# Answer
> 4 votes
# Haskell, 4 bytes

```
(0:)

```

Try it online!

Just prepends 0.

```
data List a = Cons a (List a) | Emp
    deriving (Eq)

instance Show a => Show (List a) where
    show Emp            = "[]"
    show (Cons x Emp)   = "[" ++ show x ++ "]"
    show (Cons x xs)    = "[" ++ show x ++ ", " ++ tail (show xs)

len              :: Integral b => List a -> b
len Emp           = 0
len (Cons x xs)   = succ $ len xs

pre              :: a -> List a -> List a
pre               = Cons

app              :: a -> List a -> List a
app x Emp         = pre x Emp
app x (Cons y ys) = pre y $ app x ys

(!)              :: Integral b => List a -> b -> a
Emp ! i           = error "index too large"
(Cons x xs) ! 1   = x
(Cons x xs) ! i   = xs ! (pred i)

```

Try it online!

# Answer
> 2 votes
# C Macro, 17 bytes

```
#define F(t)(t-1)

```

# Answer
> 2 votes
## Inform 7, 97 bytes

This challenge seems like one that Inform 7 could actually accomplish, despite its enormous verbosity!

```
To decide what list of numbers is f (L - a list of numbers): add 0 at entry 1 in L; decide on L.

```

Prepends a zero.

# Answer
> 1 votes
# Java (OpenJDK 8), 67 bytes

```
a->{int c[]=new int[a.length+1],i=1;for(int u:a)c[i++]=u;return c;}

```

Try it online!

This was a fun little challenge in Java since Java arrays are static in size, but it seems like this is significantly less challenging in every language that can just slap a zero on for the first- excuse me, *zeroth* element

**Explanation:**

```
int i=1,c[]=new int[a.length+i];    ////Initialize counter and declare new array with length: 1 + input array length
for(int u:a)    //Loop through each element in input array
  c[i++]=u;    //Increment counter after shifting each element up one spot in the output array
return c;    //return new array starting at index 1

```

**Credit:**

-3 bytes thanks to Kevin Cruijssen!

# Answer
> 0 votes
## Python 3, 14 bytes

```
lambda s:[0]+s

```

Puts a zero at the start of the list. `None` would be a better null value but it's three bytes longer.

# Answer
> 0 votes
# JavaScript, 10 bytes

```
a=>[,...a]

```

a\[0\] is a *hole* after fix

# Answer
> 0 votes
# Perl 5 `-p`, 6 bytes

```
#!/usr/bin/perl -p
s//0 /

```

Try it online!

Prepends 0

The controversy mostly exist because people confuse counting and naming :-)

---
Tags: code-golf, array
---


title: ASCII Hexagon Chain

text:
# Question
Title: ASCII Hexagon Chain
# Problem

Draw a hexagon chain `x` long, each with side of `y` length

# Input

`x` \- the length of the chain \<= 50

`y` \- the length of each side \<= 50

# Examples

`x=1,y=1`

```
 _
/ \
\_/

```

`x=4,y=1`

```
 _   _
/ \_/ \_
\_/ \_/ \
  \_/ \_/

```

`x=3,y=2`

```
  __      __
 /  \    /  \
/    \__/    \
\    /  \    /
 \__/    \__/
    \    /
     \__/

```

# Rules

* The shortest valid answer in bytes wins.
* Leading and trailing newlines allowed.
* Trailing white space allowed.

# Answer
# Charcoal, 34 bytes

```
ＮθＦＮ«Ｍ∧﹪ι²⊗θ↓Ｐ×_θ←↖θ→↗θ×_θ↓↘θ←Ｐ↙θ↗

```

Try it online! Link is to verbose version of code. Takes the parameters in the order size, count. Explanation:

```
Ｎθ

```

Input the hexagon size.

```
ＦＮ«

```

Loop over the input number of hexagons.

```
Ｍ∧﹪ι²⊗θ↓

```

On alternate hexagons, move down a whole hexagon, so that the next hexagon is drawn to the lower right rather than the upper right.

```
Ｐ×_θ

```

Draw the bottom.

```
←↖θ

```

Draw the lower left side.

```
→↗θ

```

Draw the upper left side.

```
×_θ

```

Draw the top.

```
↓↘θ

```

Draw the upper right side.

```
←Ｐ↙θ

```

Draw the lower right side.

Assume the next hexagon is to the upper right.
> 8 votes

# Answer
# Python 2, ~~254~~ 224 bytes

```
def f(n,w):
 a=w*2
 for j in range(1+w*3):print''.join([[[' ',[' /'[i%w==-j%w],' \\'[i%w==~-j%w]][i/a+~-j/w&1]][(j>0)*(i/w>=(j>a))*((i/w/n<2)or(n%-2<~-j/w<3-n%2))],' _'[(j+i/w%4/2*w)%a<(i<n*a)]][i/w%2]for i in range(-~n*a)])

```

Try it online!

---

# Python 2, ~~264~~ 229 bytes

```
def f(n,w):
 c=2*w;r=[[' ']*(-~n*c)for _ in' '*(1+w*3)]
 for i in range(w):
  for j in range(n):a=i+j*2*w;b=j%2*w;r[b][w+a],r[c+b][w+i+j*c],r[b+w-i][a],r[b+c-i][a+c],r[b+w-~i][a],r[b-~i][a+c]=r'__//\\'
 for l in r:print''.join(l)

```

Try it online!
> 4 votes

# Answer
# SOGL V0.12, ~~32~~ 31 bytes

```
ā.{e╚øΚe╔*ο⁴↔±┼┼╬±fe«*If2%e*I╬5

```

Try it Here!

Explanation:

```
ā                              push an empty array - the canvas
 .{                            repeat input times
   e╚                            push a diagonal the length of the variable E (by default: next input)
     øΚ                          prepend a line to it
       e╔*ο                      push ["_"*E]
           ⁴                     copy that diagonal
            ↔±                   and reverse it horizontally
              ┼┼                 add the 3 parts together
                ╬±               and palindromize vertically - one hexagon is finished
                  fe«*I          push counter*E*2 + 1 (the counter is 0-based)
                       f2%e*I    push counter%2 * E + 1
                             ╬5  at [counter*E*2+1; counter%2*E+1] insert the hexagon in the canvas

```
> 3 votes

# Answer
# Befunge, ~~230~~ ~~228~~ 225 bytes

```
+&#92#<*:0< vp93*p92+1*3:p91:&+1p
>1+:29g-!#@_>:1-19g+:19g/1-:2*49p2%!2*:1+59p19g*\19g%+69p01v
,>*19g3*79g-1-69g-!2*49g1+0g2%*79g69g-!49g0g2%*++4g,1+:39g-v
^^3*!-*g95g91+1g96!-g95%4p04p01:`\g90p05`0::/g91:p97%*4g91:_$55+
 \/_

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 215 bytes

Takes input in currying syntax `(y)(x)`.

```
y=>(F=(x,c=!(p=y-1,w=x*y*2+y,a=[...(' '.repeat(w++)+`
`).repeat(3*y+1)],g=(d,k)=>k!=y?g(d,-~k,a[p+=d]='_\\/'[c%3]):c++))=>x--?F(x,g(1),g(w+1),p++,g(w-1),g(-1),p+=w,g(~w),p--,g(1-w),p+=(c/6&1?w:-w)*y-w+y*2):a.join``)

```

### Demo

```
let f =

y=>(F=(x,c=!(p=y-1,w=x*y*2+y,a=[...(' '.repeat(w++)+`
`).repeat(3*y+1)],g=(d,k)=>k!=y?g(d,-~k,a[p+=d]='_\\/'[c%3]):c++))=>x--?F(x,g(1),g(w+1),p++,g(w-1),g(-1),p+=w,g(~w),p--,g(1-w),p+=(c/6&1?w:-w)*y-w+y*2):a.join``)

O.innerText = f(3)(7)
```

```
<pre id=O></pre>
```
> 1 votes

# Answer
# Canvas, 25 bytes

```
ø╶｛╷⁷«×¹２％⁷×╵⁷⇵_× ⁷／∔×╬│╋

```

Try it here!

Explanation (some characters have been changed to look monospace):

```
ø╶{╷⁷«×¹2%⁷×╵⁷⇵_× ⁷/∔×╬│╋
ø                          push an empty canvas
 ╶{                        for 1..input
   ╷                         decrease (so this starts with 0)
    ⁷«×                      multiply by X*2; X coordinate of new hexagon done
       ¹2%                   push 0-indexed counter%2
          ⁷×                 multiply by X
            ╵                and increment; Y coordinate done
             ⁷⇵              push ceil(X/2), saving the remainder
               _×            repeat "_" that many times
                  ⁷/         push " " and an ASCII diagonal with size X
                    ∔        prepend verticall the space before the diagonal
                              done so there's space for the underscores
                     ×       and append the underscores horizontally to the diagonal
                      ╬│     quad-palindromize with Y overlap of 1
                              and X overlap of the remainder taken before
                        ╋    and at the before defined coords ((I-1)*X*2; (i%2)*X + 1)
                              insert the hexagon in the canvas

```
> 1 votes

---
Tags: code-golf, ascii-art, hexagonal-grid
---


# Question
Title: Generate the list [1, 0, -1, 0, 1, 0, -1, 0, ...]
In the spirit of a question on math.se: given an integer `n`, return the integer in position `n` of the sequence \[1, 0, -1, 0, 1, 0, -1, 0, ...\]. Assume `n >= 0`.

Rules:

1. You may only use the operations -x, x+y, x-y, x\*y, x/y, and xy, whatever their representations are in the language you choose.
2. Your function must be called `a`.
3. Your function must run in constant time for all `n`.

Example:

```
a=lambda n:((-1)**(n*n-n)//2)+(-1)**(n*n+n)//2))//2

```

Non-example (uses list subscripting operation and modulo operator):

```
a=lambda n:[1,0,-1,0][n%4]

```

Non-example (uses cos operation):

```
from math import *;a=lambda n:int(cos(n*pi/2))

```

Non-example (does not run in constant time and uses if operation):

```
a=lambda n:-a(n-2) if n>1 else 0 if n>0 else 1

```

**Clarifications:** Both integer and float division are allowed. Your solution may return either an integer or a float (or complex number, I suppose, since some answers already used it). If your solution returns a float: your solution should, if it were to theoretically be carried out to infinite precision, give the exact answer.

# Answer
### Ruby, 26 characters

```
a=->n{1-(k=n-n/4*4)+k/3*2}

```

Example:

```
> p (0..10).map{|n| a[n]}
[1, 0, -1, 0, 1, 0, -1, 0, 1, 0, -1]

```

Note: This solution assumes that integer division `/` is an allowed operation.
> 5 votes

# Answer
## Python, 29 chars

```
a=lambda n:(1j**n+(-1j)**n)/2

```

Kind of cheating, but fun.

## Edit:

Now that we can return complex numbers, this is competitive and no longer cheating (with Howard's suggestion).
> 3 votes

# Answer
## C, 36 chars

```
a(n){return(1-n+n/2*2)*(1-n+n/4*4);}

```

The same function used by Peter Taylor.
> 3 votes

# Answer
## Python, 36 chars

```
a=lambda n:(-1)**(n/2)*(1+(-1)**n)/2

```
> 2 votes

# Answer
## J, 18 characters

```
a=:[:{.[:+._1^2%~]

```

Works, but is probably cheating by the rules set out above.

Calculates -1 to the power of the given integer divided by 2 which gives `0j1` for any odd number. The `{.` and the `+.` return the real part so that the odd numbers give 0.

Usage:

```
   a 1
0
   a 6
_1

```

Edit: After feeling a bit smug about this I've just looked properly at Keith's answers and realized I've done essentially the same thing.
> 2 votes

# Answer
## GolfScript (20 19 chars)

```
{.4/4*-.3/2*)\-}:a;

```

This is a port of Howard's solution.

If, in addition to division, the remainder operation were permitted, this could be improved substantially (by 6 5 chars):

```
{.2%(\4%(*}:b;

```

Mathematically that's

```
x => (x%2 - 1) (x%4 - 1)

```

I can't see any logic behind excluding remainder, since it's *defined* in terms of permitted operations.
> 2 votes

# Answer
**Python, 34 chars**

Poor man's modulus... saves a whopping 2 chars over Keith Randall's solution. Take that! ;)

```
a=lambda n:(n-1-n/2*2)*(n-1-n/4*4)

```

edit: on reading others' solutions, this is the same as Peter Taylor's
> 1 votes

# Answer
## bc: 28 chars

```
echo 'a=4;(1-a+a/2*2)*(1-a+a/4*4)' | bc

```
> 0 votes

# Answer
# Python, 49 chars

```
a=lambda n:(lambda x:(x**3-3*x*x-x+3)/3)(n-n/4*4)

```

Note: In Python3 you'll have to replace n/4 with n//4 at the end.
> 0 votes

# Answer
**8086 Assembler** (14 bytes of machine code):

```
 ; ax holds the index into the sequence
 ; returns the sequence value in ax
 a: inc al
    shl al,6
    sar al,6
    cbw
    xor al,ah
    add al,ah
    cbw
    ret

```
> 0 votes

# Answer
# TI-Basic, 12 bytes

```
i^Ans+i^-Ans
Ans/2

```

Store in `prgmA` and run with `5:prgmA`, with the input in place of `5`.

TI-Basic implicitly returns the last evaluated value.
> 0 votes

# Answer
# Python 2, 28 bytes

```
a=lambda n:(n/2*2-n+1)*1j**n

```

Try it online!

Proof of validity for those who don't know Python:

The expression is `(n/2*2-n+1)*1j**n`. If you add parentheses, it becomes `((((n/2)*2)-n)+1)*(1j**n)`. `/` is integer division, since both `n` and `2` are integers in this case, `*` is multiplication, `-` is subtraction, `+` is addition and `**` is exponentiation.
> 0 votes

# Answer
# Java 8, 21 bytes

```
n->1-(n-=n/4*4)+n/3*2

```

Port of *@Howard*'s Ruby answer.

Try it online.
> 0 votes

---
Tags: code-golf, math, sequence, restricted-source, restricted-complexity
---