# Question
Title: How much do you win in the Bingo Golf Flax Lottery?
The challenge, should you accept it, is to determine how much you win in the Bingo Golf Flax Lottery. Based on but not equal to the BingoFlax lottery

The input is two lists of numbers (positive non-zero integers).

The first list always contains 24 potentially *non-unique* numbers that make up your board, a 5 x 5 grid of numbers from the list in reading order: Left to right, top to bottom. The mid cell is always a free cell (a "wild card") that matches any number and this is why the board input is 24 numbers and not 25 (=5\*5). Note: the same number may appear more than once.

The second input list is of any length. These are numbers that may or may not match numbers on your board.

Matching numbers may or may not end up making one or more winning patterns on your board.

The type of winning pattern if any determine how much you win.

If more than one winning pattern emerge, only the one with the most prize money matter. Don't sum up the patterns.

The winning patterns and their prize money are:

Your program or function should return 500000, 10000, 1000, 500, 200, 100, 50, 30 or 0 for no winning pattern.

**Example 1:**

Input: 5 21 34 51 74 3 26 39 60 73 2 28 59 67 12 30 33 49 75 10 17 40 50 66
and: 33 10 7 12 60 49 23 38 15 75 40 30
Winning pattern: horizontal line.
Result: **50**

**Example 2:**

Input: 5 21 34 51 74 3 26 39 *60* 73 2 28 59 67 12 *60* 33 49 75 10 17 40 50 66
and: 33 10 7 12 60 49 23 12 15 75 40 97 74 99
Two winning patterns: horizontal and forward diagonal since the mid cell is always free – only the most winning counts
Note: 60 appear twice on the board and since 60 is called from the second list both 60's counts as a match. The one 60 in the call list matches all 60's on the board.
Result: **500**

**Example 3:**

Input: 9 13 4 42 67 24 17 1 7 19 22 10 30 41 8 12 14 20 39 52 25 3 48 64
and: 9 2 4 13 11 67 42 24 41 50 19 22 39 64 52 48 3 25
Almost border, but missing 8. You still win 100 for the vertical line at the right edge.
Result: **100**

This is Code Golf, shortest answer wins.

# Answer
# Excel ms365, <sup>~~355,~~~~349,~~~~331,~~~~328~~ </sup>322 bytes

* -6 thanks to xigoi's tip to apply scientific notation;
* -18 due to change of regex-patterns;
* -3 due to the trick to multiply by 100 after recursion is done given by quarague;
* -6 deleted rf-string notation. Patterns no longer include backslashes.

Currently in Beta, use `=PY()` to open the python interpreter. I'm probably embarrasing myself here trying Python script but here goes:

```
import re
max([s[1]if re.match(s[0],re.sub('(?=.{12}$)','1',''.join([str(+(x in xl("B1:B14").values))for x in xl("A1:A24")[0]])))else 0 for s in[['1{6}(...11){3}1+$',5e3],['(1...1.1.1...){2}1',1e2],['.{6}(111..){3}',10],['.(...1){5}',5],['1(.{5}1){4}',2],['.*(1....){4}1',1],['(.{5})*1{5}',.5],['1...1.*1...1$',.3]]])*100

```
> 6 votes

# Answer
# Python 3, ~~263~~ ~~257~~ 250 bytes

```
lambda a,e:next((P[p]*c for p in P if all(a[k]in e for k in range(24)if p>>k&1)),0)
c=10.
P={16541247:5e5,9077073:1e4,235968:1e3,557328:5e2,8519745:2e2,541729:c,1083458:c,2162820:c,4329736:c,8659472:c,31:5,992:5,15360:5,507904:5,16252928:5,8912913:3}

```

Try it online!

Hardcodes the matches into a dictionary (can be improved).

## How it works?

`P` actually represents the following dictionary:

```
P = {
    0b1111110001100011000111111: 500000, # Border
    0b1000101010001000101010001: 10000,  # Cross
    0b0000001110011100111000000: 1000,   # Picture
    0b0000100010001000100010000: 500,    # Forward diagonal
    0b1000001000001000001000001: 200,    # Backward diagonal
    0b0000100001000010000100001: 100,    # Any vertical line
    0b0001000010000100001000010: 100,
    0b0010000100001000010000100: 100,
    0b0100001000010000100001000: 100,
    0b1000010000100001000010000: 100,
    0b0000000000000000000011111: 50,     # Any horizontal line
    0b0000000000000001111100000: 50,
    0b0000000000111110000000000: 50,
    0b0000011111000000000000000: 50,
    0b1111100000000000000000000: 50,
    0b1000100000000000000010001: 30,     # All corners
}

```

where each key is a mask to the actual grid. The 5 least-significant bits are the first row, the following 5 are the second row, and so on.

The dictionary is ordered by score, so the first entry matched will always evaluate to the highest score possible.

The solution is a function that accepts two arguments: a list of integers of length 24 containing the `a`ctual numbers to be matched, and a list of integers of variable length containing the `e`xpected matching numbers.

That said, the algorithm is as follows: for every `p`attern on `P`atterns, check for each 1-bit if their corresponding element on `a` is present on `e`. If they all match, then return the score associated with `p`.

If no pattern is matched, return 0.

---

*-6 bytes* by simplifying the score constants, altering @Joao-3's magnificent idea a little bit by keeping them integers.

*-7 bytes* by simplifying a bit more the score constants, now making them floats.
> 4 votes

# Answer
# APL+WIN, ~~216~~ 186 bytes

30 bytes saved with better board compression Prompts for vector of first numbers followed by second

```
⌈/0,(25=+⌿a=(a←((25⍴2)⊤33080895 18157905 473536 1118480 17043521 17825809),(⍉10 25⍴(∊25⍴¨(⍳¨5)=5⍴¨s),,⊃s∘.=5⍴¨s←⍳5))×⍉16 25⍴(r∊⎕)+(r←(12↑n),0,12↓n←⎕)=0)/10×5E4 1E3 1E2 50 20,3,(5⍴10),5⍴5

```

Try it online! Thanks to Dyalog Classic
> 3 votes

# Answer
# Jelly, 74 bytes

```
aṚḣ3ZƲ⁺FUḄ“¢Ị×O‘=&¥TṪ‘+Ị?5
e€ŒHj1s5µ,Z;ŒD,ŒdƊ§ŻŻ5eⱮTṪ»Çị“<d¥¥¦¥Þd‘HḢ;×\ƊŻ¤

```

A pair of links which is called as a dyad with the board as the left argument and the call sequence as the right. Returns a float containing the score.

This works by checking each of the possibilities programmatically. I started an alternative version (here) which uses a lookup table, but it’s already 65 bytes without converting to the score and so would be longer.

The test suite builds a sequence of sequences that yield every possible score for a given board (though the source sequence was constructed manually). The set-wise symmetric difference operator (`œ^`) is used in the footer to allow individual cells on the board to be toggled off as well as on since, for example, it’s otherwise not possible to build from a backwards diagonal to a forwards without ending up with a cross.

## Explanation

```
aṚḣ3ZƲ⁺FUḄ“¢Ị×O‘=&¥TṪ‘+Ị?5                       # Helper link: takes a 5x5 grid of binary digits and returns 2, 7, 8, 9 for all corners, picture, cross, border respectively and 1 if none of those
     Ʋ                                           # Following as a monad:
aṚ                                               # - And with reverse
  ḣ3                                             # - First three rows
    Z                                            # - Transpose
      ⁺                                          # Repeat the above monad again
       F                                         # Flatten
        U                                        # Reverse
         Ḅ                                       # Convert from binary digits
          “¢Ị×O‘=&¥                              # For each of 1, 176,  17, 79, bitwise and with the result of the previous step and check if unchanged ( &Ƒ= would also work for the same bytes)
                   T                             # Indices of truthy values
                    Ṫ                            # Tail (will be zero if no truthy values)
                     ‘+Ị?5                       # If 1 or zero, increment by 1, otherwise increment by 5

e€ŒHj1s5µ,Z;ŒD,ŒdƊ§ŻŻ5eⱮTṪ»Çị“<d¥¥¦¥Þd‘HḢ;×\ƊŻ¤  # Main link
e€                                               # For each number on left, check whether present in right argument
  ŒH                                             # Split into two pieces of equal length (both will be 12 binary digits)
    j1                                           # Join with 1
      s5                                         # Split into pieces of length 5
        µ                                        # Start a new monadic chain
         ,Z                                      # Pair with its transpose
           ;ŒD,ŒdƊ                               # Concatenate with the major diagonals paired with the minor diagonals
                  §                              # Sums of innermost lists
                   ŻŻ                            # Prepend with zero twice (to offset the lists by two)
                     5eⱮ                         # Check which of these lists include a 5 (so a complete line)
                        TṪ                       # Last truthy index
                          »Ç                     # Max of this and the result of calling the helper link on the same 5x5 binary grid
                            ị                 ¤  # Index into the following called as a nilad:
                             “<d¥¥¦¥Þd‘          # - [60,100,4,4,5,4,20,100]
                                       H         # - Half
                                        Ḣ;×\Ɗ    # - Head (30) Concatenated to the result of cumulative product of the other values
                                             Ż   # - Prepend zero

```

Created with the help of Luminespire.
> 3 votes

# Answer
# , ~~269~~ 224 bytes

```
\(x,y,`/`=c,z=x%in%y,`?`=diag,s=sapply,`~`=max)~.5/1/2/5/.3/10/100/5e3*(s(list(w<-matrix(z[1:12]/1/z[13:24],5),t(w),?w,?v=w[,5:1]),\(r)~rowSums(t(r))>4)/s(1/176/17/79,\(n)!~(m=n%/%2^(0:14)%%2)>m*((u=w*v)&u[5:1,])[1:3,]))*100

```

Attempt This Online!

A function that takes the board as the first argument and the call sequence as the second argument and returns the score.

*Thanks to @pajonk for saving three bytes!*
> 3 votes

# Answer
# JavaScript (ES6), 205 bytes

Expects `(board)(drawn_numbers)`, where *board* is an array of 24 integers and *drawn\_numbers* is a set of integers.

```
a=>s=>(m=~a.reduce((t,v,k)=>t|s.has(v)<<k+k/12,4096))&33080895?m&18157905?m&473536?m&1118480?m&17043521?a.map(h=v=(_,i)=>v|=!(h|=!(m&31<<i%5*5),m&1082401<<i))|v?100:h?50:m&17825809?0:30:200:500:1e3:1e4:5e5

```

Try it online!

---

# JavaScript (ES7), 212 bytes

Expects `(board)(drawn_numbers)`, where *board* is an array of 24 integers and *drawn\_numbers* is a set of integers.

```
a=>s=>"5115211111555553"[a.map((v,k)=>t|=s.has(v)<<k+k/12,t=4096),x=[33080895,18157905,473536,1118480,17043521,..."0"+17**6+8,17825809].findIndex(n=>!(~t&(n>9?n:n<6?1082401<<n:31<<n*5+2)))]*10**("661"[x]^3-x/9)|0

```

Try it online!
> 3 votes

# Answer
# Retina 0.8.2, 224 bytes

```
\b(\d+)\b(?=.*;.*\b(\1)\b)?(,|;.*)
$#2
13=`
1
1{6}(...11){3}1111
500000
(1...1.1.1...){2}1
10000
.{6}(111..){3}....
1000
....(1...){5}.
500
(1.{5}){4}1
200
.*(1....){4}1.*
100
(.{5})*1{5}(.{5})*
50
1...1.{15}1...1
30
.{25}
0

```

Try it online! Takes input as two lists of comma separated integers separated by a semicolon but link is to test suite that takes input in the example format for convenience. Explanation:

```
\b(\d+)\b(?=.*;.*\b(\1)\b)?(,|;.*)
$#2

```

Turn the first list into a bitmask of which integers are present in the second list and delete the second list.

```
13=`
1

```

Insert a `1` before the thirteenth bit. This simplifies the patterns below.

```
1{6}(...11){3}1111
500000
(1...1.1.1...){2}1
10000
.{6}(111..){3}....
1000
....(1...){5}.
500
(1.{5}){4}1
200
.*(1....){4}1.*
100
(.{5})*1{5}(.{5})*
50
1...1.{15}1...1
30
.{25}
0

```

Score according to the first matched pattern.
> 3 votes

# Answer
# JavaScript (Node.js), ~~197~~ 193 bytes

```
a=>s=>[17825809,31,1082401,17039425,1118480,473536,18153809,33080895].map(g=(v,i,p)=>p.map(j=>g=v&~a.reduce((t,v,k)=>t|s.has(v)<<k+k/12,4096)>>j%7*'051'[i]?g:[.3,.5,1,2,5,10,100,5e3][i]*100))|g

```

Try it online!

```
a=>s=>             // Entry
[17825809,31,1082401,17039425,1118480,473536,18153809,33080895]    // Pattern
.map(g=(v,i,p)=>   // For each. Init g to NaN
p.map(j=>g=        // Loop position
v&~a.reduce((t,v,k)=>t|s.has(v)<<k+k/12,4096)    // Arnauld's converter, outside is empty
>>j%7*'051'[i]     // j%7 == [1,2,0,6,4,5,3,1] covering [0,1,2,3,4]
?g:[.3,.5,1,2,5,10,100,5e3][i]*100    // If found then write to g
))|g               // Output. NaN => 0

```
> 3 votes

# Answer
# 05AB1E, ~~73~~ 64 bytes

```
å2ä`1š«D•1MÖ•₂вès5ô©Å/D®Å\DŠ«®Dø®4Fćˆøí}˜¯˜)P30₄;т·4°50x₄6°;)ć*à

```

Outputs `500` as `500.0` and `500000` as `5.0e5`. If integers are mandatory, a trailing `ï` (cast to integer) can be added for +1 byte.

Try it online or verify all test cases.

**Explanation:**

```
å               # Check for each value in the first (implicit) input-list whether it's
                # in the second (implicit) input-list, resulting in a list of 1s/0s
                # Insert the free middle cell:
2ä              #  Split it into two equal-sized parts
  `             #  Pop and push both lists to the stack
   1š           #  Prepend a 1 to the top/second list
     «          #  Merge the lists back together
                # Corners:
D               #  Duplicate the list
 •1MÖ•          #  Push compressed integer 70848
      ₂в        #  Convert it to base-26 as list: [4,0,20,24]
        è       #  Index it into the list
                # Main diagonal:
s               #  Swap so the list is at the top again
 5ô             #  Convert it to a 5x5 matrix
   ©            #  Store this matrix in variable `®` (without popping)
    Å/          #  Pop and push the main diagonal
                # Main anti-diagonal:
D               #  Duplicate the main diagonal
®               #  Push matrix `®` again
 Å\             #  Pop and push the main anti-diagonal
                # Cross:
D               #  Duplicate the main anti-diagonal
 Š              #  Triple-swap
  «             #  Merge the duplicated main diagonal/anti-diagonal togther
                # Rows:
®               #  Push matrix `®` again
                # Columns:
D               #  Duplicate it
 ø              #  Zip/transpose; swapping rows/columns
                # Picture:
®               #  Push matrix `®` again
 4F             #  Loop 4 times:
   ć            #  Extract head; push the remainder-matrix and first row separately
    ˆ           #  Pop and add the first row to the global array
    øí          #  Rotate the matrix once clockwise:
    ø           #   Zip/transpose; swapping rows/columns
     í          #   Reverse each inner list
  }˜            #  After the loop: flatten the remaining 3x3 center matrix
                # Borders:
¯               #  Push the global array
 ˜              #  Flatten it as well
)               # Wrap everything on the stack into a list
 P              # Take the product of each inner-most lists
30              # Push 30
  ₄;            # Push 500 (1000 halved)
    т·          # Push 200 (100 doubled)
      4°        # Push 10000 (10**4)
        50      # Push 50
          x     # Push 100 (double the 50 without popping)
           ₄    # Push 1000
            6°; # Push 500000 (10**6 halved)
)               # Wrap everything on the stack into a list again
 ć              # Extract its head with the checks
  *             # Multiply the values at the same positions in the two lists together
   à            # Pop and push the flattened maximum
                # (which is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•1MÖ•` is `70848` and `•1MÖ•₂в` is `[4,0,20,24]`.
> 3 votes

# Answer
# Charcoal, 112 bytes

```
Ｉ∨⌈ＥΦ⦃³⁰=__N⁵⁰”61∧V÷⊗Ｐ＆Πï⁹Ｋ∕⬤Ｙ⪪Ｓ”¹⁰⁰”{⊟∨✳⎇¡§_⁸ξ↷⊖⮌”²⁰⁰??^^⊘φ]W[Oφ_&8_×χφ=7ZN⊘×φφ YG ⦄⊙⪪⭆ιΦ⍘⁺³²℅λ²ξ²⁴⬤λ∨Ｉν№η§θξκ⁰

```

Attempt This Online! Link is to verbose version of code. Explanation: Creates a dictionary mapping scores to strings representing bitmaps of entries that are not part of the winning pattern, then filters them on winning entries, and outputs the highest key, or `0` if no entries win.

The best I could do without lookup tables was 123 bytes:

```
≔⪪⪫⪪⭆θ№ηι¹²1⁵θＩ∨⌈Φ⁺⁺Ｅθ⟦⁵⁰ι⟧Ｅθ⟦¹⁰⁰⭆θ§λκ⟧⪪⟦²⁰⁰⭆θ§ικ⊘φ⭆θ§ι⁻⁴κ³⁰⭆θΦι¬∨﹪κ⁴﹪μ⁴φ⭆θΦι∧﹪κ⁴﹪μ⁴×χφ⭆θΦι⁼↔⁻μ²↔⁻μ²⊘×φφ⭆θΦι¬∧﹪κ⁴﹪μ⁴⟧²Ｉ⌊⊟ι⁰

```

Try it online! Link is to verbose version of code. Explanation: Converts the first input to a string of binary digits representing whether the number is present or absent, inserts a `1` in the middle, splits it into a square array, then generates a list of pairs of scores and cells required by that score, filters on those pairs where all of the cells are present, then outputs the highest score, or `0` if there was no win. The pairs for scores of `50` and `100` are generated separately from the others and concatenated later. The pair for `200` comes before `30` because it saves a byte.
> 2 votes

---
Tags: code-golf
---


title: Find the child anagrams of a word

text:
# Question
Title: Find the child anagrams of a word
Select any word from https://websites.umich.edu/~jlawler/wordlist with length greater than 1. For each letter on that word, remove it and check if any rearrangement of the remaining letters is present in the wordlist. If it is, this rearrangement is a *child anagram* of the original word.

For example, `theism`:

* removing the `t` and rearranging `heism` gives nothing present in the wordlist
* removing the `h` and rearranging `teism` gives **`times`**, **`items`**, **`metis`** and **`smite`**
* removing the `e` and rearranging `thism` gives **`smith`**
* removing the `i` and rearranging `thesm` gives nothing present in the wordlist
* removing the `s` and rearranging `theim` gives nothing present in the wordlist
* removing the `m` and rearranging `theis` gives **`heist`**

Therefore, the child anagrams of "theism" are *"times", "items", "metis", "smite", "smith" and "heist"*.

Note that this needs to be done only once: you must not apply the algorithm again to "times", for example.

If the word contains any repeated letter, only a single instance of it must be considered. For example, the child anagrams of "lightning" are only *"tingling" and "lighting"* instead of *"tingling", "lighting"* (first *n* removed) *and "lighting"* (last *n* removed). In other words, remove child repeated anagrams.

Ignore words from the wordlist that contain additional characters apart from letters, such as "apparent(a)", "gelasma/gr" and "half-baked". They will not be passed as input and should not be handled as a child anagram of any other word.

## Input

A string of length ***l*** containing the word to be searched, where ***2 ≤ l ≤ 10***. This string is guaranteed of being on the wordlist and it'll not contain any characters apart from letters (no hyphens, all lowercase).

You don't necessarily need to include the wordlist in your source code (compressed or not) nor fetch it every time from the network: you can assume it's provided by any standard method (e.g. as a function argument, as additional STDIN lines, as a predefined saved file, etc).

## Output

All child anagrams of the input word.

You may output a list/array of strings or output them using any separator.

The output doesn't have to maintain the same order on each run, only the same elements.

Standard I/O applies.

### Test cases

```
theism -> times,items,smite,metis,smith,heist
lightning -> tingling,lighting
learning -> leaning
today -> tody,toad,toda
response -> persons,spenser
tongue -> genou,tonue,tongu
code -> doe,deo,ode,cod
many -> any,nay,mya,may,yam,man,nam
interested ->
something ->
masculine ->

```

Sandbox

# Answer
# JavaScript (ES6), 58 bytes

*-22 (!) thanks to @Neil*

Expects `(dictionary)(word)`, where *word* is given as an array of characters.

```
d=>w=>d.filter(W=>w.sort().some(c=>w==[...W+c].sort()+''))

```

Try it online!

### Commented

```
d =>             // d[] = dictionary (array of strings)
w =>             // w[] = word (array of characters)
d.filter(W =>    // for each word W in d[]:
  w.sort()       //   sort w[] in lexicographical order
  .some(c =>     //   for each character c in w[]:
    w ==         //     is w[] equal to ...
    [...W + c]   //     ...W + c turned into an array
    .sort() + '' //     and sorted in lexicographical order?
  )              //   end of some()
)                // end of filter()

```
> 7 votes

# Answer
# Charcoal, 20 bytes

```
ＷＳ¿⊙θ⬤⁺θι⁼№θμ№⁺ικμ⟦ι

```

Try it online! Link is to verbose version of code. Takes the original word as the first line of input followed by the newline-terminated wordlist to search. Explanation:

```
ＷＳ

```

Loop through all of the words. (On the first pass this will actually be the original word but that won't match the condition so it doesn't matter.)

```
¿⊙θ⬤⁺θι⁼№θμ№⁺ικμ

```

For each letter of the original word, check whether the current word plus that letter is an anagram of the original word.

```
⟦ι

```

Output the successful match on its own line.
> 3 votes

# Answer
# Python 3.8 (pre-release), 63 bytes

Python3 port of the Javascript answer.

```
lambda w,d:[i for i in d if sorted(w)in[sorted(i+c)for c in w]]

```

Try it online!
> 3 votes

# Answer
# Jelly, 8 bytes

```
Ṣe¥ƇṢ-Ƥ}

```

A dyadic Link that accepts the word list on the left and the word on the right and yields a list of the child anagrams.

**Try it online!** (using a reduced word list with some made-up edge cases for the "theism" example).

### How?

```
Ṣe¥ƇṢ-Ƥ} - Link: list of lists of characters, WordList; list of characters, Word
       } - using the right argument, Word:
     -Ƥ  -   for overlapping outfixes of length Length(Word)-1
    Ṣ    -   sort
            -> e.g. Word="order" -> ["derr", "deor", "eorr", "dorr", "deor"]
   Ƈ     - {Wordlist} filter keep those for which:
  ¥      -   last two links as a dyad - f(CandidateWord, Outfixes):
Ṣ        -     sort {CandidateWord}
 e       -     exists in {Outfixes}?

```
> 2 votes

# Answer
# Retina, 64 bytes

```
s`\w+(?<=^(\w+).*?)
$&,$&,$1,
/,\w+/_O`.
L$`,(.*)(.*),\1.\2,
$%`

```

Try it online! Link includes `theism` example compared against a selection from `/usr/share/dict/words` and therefore includes `emits` which isn't in the given wordlist for some reason. Takes the original word as the first line of input followed by the wordlist to search. Explanation:

```
s`\w+(?<=^(\w+).*?)
$&,$&,$1,

```

To each word append a copy of itself and a copy of the first line of input, all words being terminated by commas.

```
/,\w+/_O`.

```

For each copy, sort its characters.

```
L$`,(.*)(.*),\1.\2,
$%`

```

For each sorted word that's missing exactly one letter from the sorted first word, output its original word.
> 2 votes

# Answer
# Perl 5 Algorithm::Permute, 88 bytes

```
sub{($_,$d,%r)=@_;s{.}{@s="$`$'"=~/./g;permute{$$d{$w=join'',@s}&&$r{$w}++}@s}ge;keys%r}

```

Try it online!
> 2 votes

# Answer
# Google Sheets, 161 bytes

```
=let(_,lambda(w,join(,sort(mid(w,sequence(len(w)),1)))),l,len(B1),j,sequence(l),ifna(filter(A1:A,match(map(A1:A,_),map(sort(left(B1,j-1)&mid(B1,j+1,l-j)),_),))))

```

Paste the dictionary in cells `A1:A`, or add enough blank rows and put this formula in cell `A1`:

```
=importdata("https://websites.umich.edu/~jlawler/wordlist")

```

Put the search string in cell `B1` and the formula in cell `C1`.

### Commented

```
// function that sorts letters into alphabetical order; _("code") → cdeo
_, lambda(w, join(, sort(mid(w,sequence(len(w)),1)))),

// generate sequence 1,2,3..l
l, len(B1),
j, sequence(l),

// "code" → ode, cde, coe, cod → deo, cde, ceo, cdo
n, map(sort(left(B1, j - 1) & mid(B1, j + 1, l - j)), _),

// show words where _(word) appears in n
ifna(filter(A1:A, match(map(A1:A, _), n, )))

```

### Results

| A1 | B1 | C1 |
| --- | --- | --- |
| a | theism | heist |
| a-horizon |  | items |
| a-ok |  | metis |
| aardvark |  | smite |
| aardwolf |  | smith |
| ab |  | times |
| aba |  |  |
| abaca |  |  |
| abacist |  |  |
| aback |  |  |
| ... |  |  |
> 1 votes

# Answer
# 05AB1E, ~~10~~ 9 bytes

```
æ¤g<ù€œ˜Ã

```

Takes the dictionary-list as additional input.

Try it online. (It's too slow for a test suite of multiple test cases. The example dictionary-list is taken from *@Arnauld*'s answer.)

**Explanation:**

```
æ         # Get the powerset of the first (implicit) input-string
 ¤        # Push its last item (without popping), which is the first input itself
  g       # Pop and push its length
   <      # Decrease it by 1
    ù     # Keep all powerset strings of that length (inputLength-1)
     €    # Map over each remaining string:
      œ   #  Get all permutations
       ˜  # Flatten it
        Ã # Only keep those values from the second (implicit) input-list of words
          # (after which the resulting list is output implicitly)

```
> 1 votes

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


title: Stackable sequences

text:
# Question
Title: Stackable sequences
You deal cards labeled 0 to 9 from a deck one a time, forming stacks that start at 0 and count up by 1.

* When you deal a 0, you place it on the table to start a new stack.
* When you deal any other card, you stack it atop a card that's exactly one lower in value, covering it. If there's no such card, the deck isn't stackable.

Given a deck, determine whether it can be stacked when dealt in the order given. Equivalently, given a list of digits, decide whether it can be partitioned into disjoint subsequences each of the form `0,1,..,k`

**Example**

Take the deck `0012312425`. The first two cards are `0`, so they go on the table:

```
Stacks: 00

  Deck: 12312425

```

Next, we deal a `1`, which goes on a `0`, doesn't matter which:

```
        1
Stacks: 00

  Deck: 2312425

```

We then deal a `2` atop the just-placed `1`, and the `3` on top of it.

```
        3
        2
        1
Stacks: 00

  Deck: 12425

```

Next, the `1`, `2` and placed atop the first stack and `4` atop the second one.

```
        4
        3
        22
        11
Stacks: 00

  Deck: 25

```

Now, we need to place a `2`, but there's no `1` atop either stack. So, this deck was not stackable.

**Input:** A nonempty list of digits 0-9, or a string of them. You can't assume that 0 will always be in the input.

**Output**: One of two distinct consistent values, one for stackable sequences and one for non-stackable ones

**Test cases:**

Stackable:

```
0
01
01234
00011122234567890
012031
0120304511627328390

```

Not stackable:

```
1
021
0001111
0012312425
012301210
000112223

```

For convenience, as lists:

```
[0]
[0, 1]
[0, 1, 2, 3, 4]
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 0]
[0, 1, 2, 0, 3, 1]
[0, 1, 2, 0, 3, 0, 4, 5, 1, 1, 6, 2, 7, 3, 2, 8, 3, 9, 0]

[1]
[0, 2, 1]
[0, 0, 0, 1, 1, 1, 1]
[0, 0, 1, 2, 3, 1, 2, 4, 2, 5]
[0, 1, 2, 3, 0, 1, 2, 1, 0]
[0, 0, 0, 1, 1, 2, 2, 2, 3]

```

Grouped:

```
[[0], [0, 1], [0, 1, 2, 3, 4], [0, 0, 0, 1, 1, 1, 2, 2, 2, 3], [0, 1, 2, 0, 3, 1], [0, 1, 2, 0, 3, 0, 4, 5, 1, 1, 6, 2, 7, 3, 2, 8, 3, 9, 0]]
[[1], [0, 2, 1], [0, 0, 0, 1, 1, 1, 1], [0, 0, 1, 2, 3, 1, 2, 4, 2, 5]]

```

**Leaderboard:**

```
var QUESTION_ID=144201,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/144201/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 11 votes
# Python 2, ~~45~~ 43 bytes

*-2 bytes thanks to @TFeld*

```
s=[]
for c in input():s+=c,-1;s.remove(c-1)

```

Try it online!

# Answer
> 8 votes
# Husk, 9 bytes

```
Λ¬ḞS:o-→ø

```

Try it online!

Returns `1` for stackable decks and `0` for non-stackable decks.

It looks like Ørjan Johansen in his Haskell answer already came up with the same algorithm, but in Husk this is obviously much more concise.

### Explanation

We takle the problem from another side: flip the deck and make descending piles. If after going through all the deck all the piles have a 0 on the top, the deck is stackable.

```
Λ¬ḞS:(-→)ø
         ø    Starting with the empty list (each element of this list will be the top card
              of a stack)
  ḞS          Traverse the input from right to left. For each card:
      -→        Remove the successor of this card from our list (if present)
    :           Add this card to our list
Λ¬            At the end, check if all the cards in our list are zeroes (falsy)

```

# Answer
> 6 votes
# Haskell, 55 bytes

An anonymous function taking a list of integers and returning a `Bool`.

Usage: `(all(<1).foldr(?)[]) [0,1,2,3,4]`.

```
all(<1).foldr(?)[]
m?l|(p,r)<-span(/=m+1)l=m:p++drop 1r

```

Try it online!

# How it works

* `foldr(?)[]` folds its list argument from right to left using `?`, starting with an empty list. The result is the list of numbers in the list that didn't fit on top of a previous number.
* `all(<1)` tests if the only numbers not fitting on top of a previous number are zeroes.
* `m?l` prepends a number `m` to a list `l` of non-fitting numbers. If `m+1` is already in the list, it can now be removed as it fits on top of `m`.
    + `(p,r)<-span(/=m+1)l` splits the list `l` into two parts `p` and `r` at the first instance of the number `m+1`. If there aren't any, the right part `r` will be empty.
    + `m:p++drop 1r` prepends `m` to the split parts. If `r` is nonempty, then it must start with `m+1`, which is removed by `drop 1`.

# Answer
> 5 votes
# Jelly, ~~15~~ 11 bytes

```
‘Ṭ€+\I>0FS¬

```

Try it online!

# Answer
> 5 votes
## Retina, 42 bytes

```
O$#`(.)(?<=(\1.*?)*)
$#2
.
$*1,
^(,|1\1)+$

```

Try it online!

### Explanation

```
O$#`(.)(?<=(\1.*?)*)
$#2

```

This sorts the digits, stably, by how often that same digit has occurred before. In effect, this collates the various candidate subsequences together. The resulting string will first have the first occurrence of each digit, and then the second occurrence of each digit and so on. In a stackable input, the result will look something like `0123...0123...0123...`, where each of these substrings may terminate at any point.

It's easiest to determine whether the input has this kind of pattern in unary.

```
.
$*1,

```

We replace each digit **n** by **n** `1`s, followed by a comma to separate individual digits.

```
^(,|1\1)+$

```

Finally we make use of a forward reference to match consecutively increasing runs of digits. We try to match the entire string either by matching a single comma (representing a **0**, which starts a new run) or by matching the previous thing preceded by an additional `1`, which only works if the current digit is the successor of the previous one.

# Answer
> 4 votes
# JavaScript (ES6), 39 bytes

*-1 thanks to @tsh*

```
a=>a.every(k=>a[a[~k]=-~a[~k],-k]--|!k)

```

Try it online!

---

# JavaScript (ES6), ~~61~~ ~~45~~ 40 bytes

Takes input as a list.

```
a=>a.every(k=>a[~k]=!k|a[-k]--&&-~a[~k])

```

Try it online!

## How?

For each value ***0...9***, we keep track of the number of available stacks with the preceding card atop. These counters are stored in ***a\[-9\]*** to ***a\[0\]***, where ***a\[\]*** is the original input array. The only counter that collides with the input data is ***a\[0\]***, but we don't really care about this one because 1) cards labeled ***0*** are always allowed and have to be processed separately anyway and 2) the input value ***a\[0\]*** is processed before it has a chance to be updated.

```
a => a.every(k =>  // given the input array a, for each card k in a:
  a[~k] =          // the card is valid if:
    !k |           //   - it's a 0 or
    a[-k]-- &&     //   - there's at least one stack with the card k-1 atop
    -~a[~k]        // in which case we allow a new card k+1 and go on with the next card
)                  // otherwise, every() fails immediately

```

# Answer
> 4 votes
# C (gcc), 74 73 bytes

```
f(int*l){int s[10]={},r=1;for(;~*l;s[*l++]++)r*=!*l||s[*l-1]--;return r;}

```

Requires the input array to mark the end with -1. Example usage:

```
int main(int argc, char** argv) {
    int a[] = {0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1};
    printf("%d\n",  f(a));
    return 0;
}

```

# Answer
> 3 votes
# TI-Basic (83 series), 25 bytes (49 characters)

```
:min(seq(min(cumSum(Ans=I)≤cumSum(Ans=I-1)),I,1,9

```

## How it works

Takes input as a list in `Ans`. Outputs `1` for stackable inputs, `0` otherwise.

For each `I`, `cumSum(Ans=I)` computes a list of the number of times `I` has occurred in each initial segment, so `min(cumSum(Ans=I)≤cumSum(Ans=I-1))` is only 1 if, at every position, we've seen `I-1` at least as many times as `I`. The overall expression is `1` whenever this holds for each `I`.

# Answer
> 3 votes
# Nim, 133 bytes

```
proc s(d:seq[int]):int=
 var
  t= @[0]
  r=1
 for c in d:(t.add(0);var f=0;for i,s in t.pairs:(if s==c:(t[i]=c+1;f=1;break));r*=f)
 r

```

`1` if it works; `0` if it doesn't.

Had to pull some funky business to deal with mutability of variables in for-loops, oh well.

# Answer
> 2 votes
# MATL, 16 bytes

```
0*GQ"@yQy=f1)(]a

```

Input is an array of numbers.

The code outputs `1` in STDOUT if input is stackable, or exits with an error and empty output in STDOUT if input is not stackable.

**Try it online!**

# Answer
> 2 votes
# Retina, 110 bytes

```
+`0((.*?)1((.*?)2((.*?)3((.*?)4((.*?)5((.*?)6((.*?)7((.*?)8((.*?)9)?)?)?)?)?)?)?)?)?
$2$4$6$8$10$12$14$16$+
^$

```

Try it online! Link includes test cases. I don't often get to use `$16`...

# Answer
> 2 votes
# Mathematica, 80 bytes

```
Catch[Fold[#~Join~{-1}/.{{p___,#2-1,q___}:>{p,#2,q},-1:>Throw[1<0]}&,{},#];1>0]&

```

# Answer
> 2 votes
# Python 2, ~~69~~ ~~61~~ ~~55~~ ~~47~~ 46 bytes

```
s=[]
for c in input():s+=-1,;s[s.index(c-1)]=c

```

Try it online!

Output is `error`/ `no error`.

# Answer
> 2 votes
# , 88 bytes

```
function(d){s={}
for(e in d)if(!e)s=c(s,0)else{k=match(e,s+1)
if(is.na(k))T=F
s[k]=e}
T}

```

Try it online!

Function that takes an R vector; returns `TRUE` for stackable and `FALSE` for unstackable.

Explanation:

```
function(d){
 s <- {}              # initialize the stacks as empty
 for(e in d){         # iterate over the deck
  if(!e)              # if e is zero
   s <- c(s,0)        # start a new stack
  else {              # otherwise
   k <- match(e,s+1)  # find where e should go in s, NA if not there
   if(is.na(k))       # if no match (unstackable)
    T <- F            # set T to F (False)
   s[k] <- e          # set s[k] to e
  }
 T                    # return the value of T, which is TRUE by default and only gets changed in the loop to F.
}

```

# Answer
> 2 votes
# Jelly, 6 bytes

```
ċṪƊƤ⁺⁼

```

Try it online!

A monadic link taking a list of integers and returning 1 for stackable and 0 for not. Based on my answer to @WheatWizard’s near-duplicate puzzle.

# Answer
> 2 votes
# Haskell, 53 bytes

```
(a:b)#x=sum[1|i<-x,a==i]:b#(a:x)
y#x=y
f x=x#[]#[]==x

```

Attempt This Online!

Inches out the former best Haskell answer by implementing an algorithm from my challenge which turned out to be a duplicate of this.

We implement a function `(#[])` which replaces each value in a list with the number of times that value has already occurred.

If applying this function twice to a list gives back the original list it is stackable.

# Answer
> 2 votes
# Nekomata \+ `-e`, 5 bytes

```
Oᵐ{x=

```

Attempt This Online!

```
Oᵐ{x=
O       Find a set partition such that:
 ᵐ{     For each part:
   x=     The part is equal to [0,...,length(part)-1]

```

# Answer
> 1 votes
# Haskell, ~~77~~ 75 bytes

```
import Data.List
g[]=1<3
g(x:r)|s<-r\\[x-1]=g r&&(x<1||s/=r&&g s)
g.reverse

```

Try it online! Usage: `g.reverse $ [0,1,2]`. Returns `True` for stackable inputs and `False` otherwise.

This is a recursive solution which traverses a given list from back to front. It implements the observation that

* the empty list is stackable.
* a non-empty list with prefix `r` and last element `x` is stackable if `r` is stackable and either `x` is zero or both `x-1` appears in `r` and `r` with `x-1` removed is also stackable.

# Answer
> 1 votes
# Java 8, ~~168~~ ~~150~~ ~~142~~ 136 bytes

```
a->{int x[]=new int[a.length],s=0,i;A:for(int n:a){if(n<1)s++;else{for(i=s;i-->0;)if(x[i]==n-1){x[i]=n;continue A;}return 0;}}return 1;}

```

-6 bytes thanks to *@ceilingcat*.

Returns `0`/`1` whether it is correctly stackable or not.

**Explanation:**

Try it here.

```
a->{                        // Method with integer-array parameter & integer return-type
  int x[]=new int[a.length],//  Array for the stacks, (max) size equal to input-size
      s=0,                  //  Amount of stacks, starting at 0
      i;                    //  Index integer
  a:for(int n:a){           //  Loop A over the input
    if(n<1)                 //   If the current item is a zero:
      s++;                  //    Increase amount of stacks `s` by 1
    else{                   //   Else:
      for(i=s;i-->0;)       //    Inner loop (2) over the stacks
        if(x[i]==n-1){      //     If a top item of a stack equals the current item - 1:
          x[i]=n;           //      Set this item in the stacks-array
          continue A;}      //      And go to the next iteration of loop A
    return 0;}}             //    If we haven't encountered a `continue`, return 0
  return 1;}                //  Return 1 if we were able to correctly stack everything

```

# Answer
> 1 votes
# C, 248 bytes

Note: To print return status, type "echo $status" into the terminal

Return status 0: Not stackable

Return status 1: Stackable

Explanation: Increments array element with the index equivalent to the current-most digit in the stack. Then, the program checks if this just-now-incremented array element is larger than the element preceding it. If so, returns 0. Else if program makes it to the end of the array returns 1.

```
 main(int argc, char ** argv)
{
    static int stack[10];

    while ( *++argv != 0x0 )
    {
        stack[**argv - 0x30]++;

        if ( **argv - 0x30 > 0 )
        {
            if ( stack[**argv - 0x30] > stack[**argv - 0x30 - 1] )
            {
                return 0;
            }

        }

    }

    return 1;
}

```

# Answer
> 1 votes
# Jelly, 8 bytes

```
‘Ṭ€+\I’Ȧ

```

Try it online!

Essentially a port of my other answer, but with  to handle zero-indexing

# Answer
> 0 votes
# Jelly, 15 bytes

```
œp@ŒQẎµ0rṀ⁼Qµ¿Ẹ

```

A monadic link taking a list of non-negative integers and returning `0` if stackable or `1` if non-stackable.

**Try it online!**

### How?

```
œp@ŒQẎµ0rṀ⁼Qµ¿Ẹ - Link: list
             ¿  - while loop:
      µ     µ   - ...condition chain:
       0        -      literal zero
         Ṁ      -      maximum of current list
        r       -      inclusive range = [0,1,2,...,max(list)]
           Q    -      de-duplicate list (unique values in order of appearance)
          ⁼     -      equal?
                - ...do:
   ŒQ           -      distinct sieve (1s at first occurrences 0s elsewhere)
  @             -      use swapped arguments:
œp              -        partition (the list) at truthy values (of the distinct sieve)
     Ẏ          -      tighten (makes the list flat again ready for the next loop)
              Ẹ - any truthy? 1 if the resulting list has any non-zero integers remaining
                -           - effectively isNotEmpty for our purposes since a list of only
                -             zeros gets reduced to an empty list via the loop.

```

# Answer
> 0 votes
# Japt, 16 bytes

```
£=k_¥T©°T}T=0ÃUd

```

Test it online! Outputs `false` for stackable, `true` for non-stackable.

### Explanation

```
 £   = k_  ¥ T© ° T}T=0Ã Ud
UmX{U=UkZ{Z==T&&++T}T=0} Ud    Ungolfed
                               Implicit: U = input array
UmX{                   }       For each item X in the array:
                    T=0          Set T to 0.
      UkZ{         }             Remove the items Z where
          Z==T&&++T              Z == T (and if so, increment T).
                                 This has the effect of removing the largest stack.
    U=                           Reset U to the result.
                               This process is repeated U.length times, which is
                               evidently enough to handle any U.
                         Ud    Return whether there are any truthy items in U.
                               Any items not part of a stack are non-zero/truthy,
                               so this works for every possible case.

```

# Answer
> 0 votes
# 05AB1E, 25 bytes

```
ηε[DõQ#ZƒDNåiNõ.;Dëˆ#]¯OĀ

```

The challenge doesn't look all that difficult, but it's quite hard in 05AB1E (for me at least..)

Outputs `0` if stackable, and `1` if not stackable.

Try it online or verify all test cases.

**Explanation:**

```
η             # Prefixes of the (implicit) input
              #  i.e. '012031' → ['0','01','012','0120','01203','012031']
              #  i.e. `021` → ['0','02','021']
 ε            # Map each to:
  [           # Start an infinite inner loop
   D          # Duplicate the current value
    õQ#       # If it's an empty String, stop the infinite loop
   Z          # Get the maximum (without popping)
              #  i.e. '01203' → 3
              #  i.e. '02' → 2
    ƒ         # Inner loop `N` in the range [0,max]
     D        # Duplicate the current value
      Nåi     # If it contains the current digit `N`
              #  i.e. '01203' and 1 → 1 (truthy)
              #  i.e. '02' and 1 → 0 (falsey)
         Nõ.; # Remove the first one (by replacing the first `N` with an empty string)
              #  i.e. '1203' and 1 → '203'
         D    # And duplicate it again for the next iteration of the inner loop
      ë       # Else (does not contain the digit `N`):
       ˆ      # Push `N` to the global stack
        #     # And break the infinite loop
 ]            # Close the if-else, inner loop, infinite loop, and mapping (short for `}}}}`)
  ¯           # Push the global stack
   O          # Take the sum
              #  i.e. [] → 0
              #  i.e. ['2'] → 2
    Ā         # And get the trutified value of that (which we implicitly output as result)
              #  i.e. 0 → 0
              #  i.e. 2 → 1

```

# Answer
> 0 votes
# Java 8, 87 bytes

Instead of building the stacks I just calculate if an element is unstackable on the previous elements, and return 0 when an unstackable element is encountered. If I reach the end, the entire string is stackable and 1 is returned:

```
s->{int l[]=new int[10];for(int n:s)if(n!=0&&l[n]>=l[n-1]||l[n]++<0)return 0;return 1;}

```

Try it online!

**Explanation:**

```
s->{
  int l[]=new int[10];                # initialise the counts of each digit encountered prefix of element, all initialised to 0
  for(int n:s)                        # Iterate over all entries in input
    if(n!=0&&l[n]>=l[n-1]||++l[n]<0)  # Check if the element is stackable on the previous elements. Last check is always evaluated and false, but the sideeffect is to add the element to the handled, prefixed element og the next element.
      return 0;                       # Unstackable
  return 1;                           # No unstackable elements, so the result is stackable
}

```

# Answer
> 0 votes
# J, <sup>25</sup> 23 bytes

```
{{(-:\:~"1)+/\y=/i.10}}

```

<sup>-2 bytes thanks to Bubbler</sup>

<sup>Note: No TIO for this version as it relies on newer J feater called direct definition `{{...}}`</sup>

Working 24 byte TIO link

Just a port of caird's great answer to make sure I understood it.

# Answer
> 0 votes
# Uiua, 75 bytes

```
=0⋅⋅⋅⧻⍢⍜▽⍜⊢(□⊐⊂:)(((⊙⊙⊙⊙(⊂1)|∘).⊙⊙⊙◌⊃∊≡=:≡⊢,,⊙(-1.⊃⋅⊢↘1)|..0)=0⧻,)▽:□[¯1]⧻.

```

Test pad

---
Tags: code-golf, sequence, decision-problem, subsequence
---


title: Aircraft registration numbers

text:
# Question
Title: Aircraft registration numbers
Write a program that takes a United States aircraft registration number and returns a 24-bit ICAO hex code corresponding to that registration and vice-versa.

An aircraft registration number always begins with an N and is followed by 1 to 5 characters: 1 to 5 digits and then 0 to 2 uppercase letters. That is, one of the following three patterns:

* N plus 1 to 5 digits
* N plus 1 to 4 digits then one letter
* N plus 1 to 3 digits then two letters

The first digit cannot be 0 and the letters I and O are not used. The letters always follow the digits.

ICAO hex codes assigned to the US are numbers from A00001 to ADF7C7 (in hexadecimal). They are assigned in alphanumeric order (with letters before digits): A00001 corresponds to N1, A00002 corresponds to N1A, A00003 to N1AA, A00004 to N1AB, etc., up to ADF7C7 for N99999. That is, sorted in lexicographic order where A \< B \< C \< D \< ... \< Y \< Z \< 0 \< 1 \< ... \< 9.

Here is the order of some codes to help alleviate confusion: N1, N1A, N1AA, N1AB, N1AC, ... , N1AZ, N1B, N1BA, N1BB, ..., N1BZ, N1C, ..., N1Z, N1ZA, N1ZB, ..., N1ZZ, N10.

Alternatively, here's some poorly-written python code that generates the next registration number in order given one as input:

```
import re

valid=re.compile('N([1-9][0-9]?[0-9]?[A-Z]?[A-Z]?|[1-9][0-9]?[0-9]?[0-9]?[A-Z]?|[1-9][0-9]?[0-9]?[0-9]?[0-9]?)$')
ordering='ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'

def next_reg(reg,first=True):
    if first and valid.match(reg+'A') is not None:
        return reg+'A'
    last_char=reg[-1]
    if(last_char=='9'):
        return next_reg(reg[:-1],False)
    index=ordering.index(reg[-1])
    retval=reg[:-1]+ordering[index+1]
    if valid.match(retval) is None:
        return next_reg(reg[:-1],False)
    return retval

```

Some test cases:

| Registration | ICAO code (hex) | ICAO code (decimal) |
| --- | --- | --- |
| N17CA | A11707 | 10557191 |
| N1PP | A00155 | 10486101 |
| N959ZP | AD5863 | 11360355 |
| N999ZZ | ADF669 | 11400809 |
| N1000B | A0070E | 10487566 |

You can assume no invalid inputs will be given.

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

```
f=(x,s=(i=10384024,'N'))=>g=/\D{3}|.{7}|.\D\d/.test(s)?0:++i&&s==x?i:i^x?[...'ABCDEFGHJKLMNPQRSTUVWXYZ0123456789'].some(t=>f(x,s+t))&&g:s

```

Try it online!

Pass all tests

Output `0x9e7299 - 0x9fffff` for invalid input `N[A-Z]?|N0.*`, and `false` other invalid。 Double-way map

# Answer
> 2 votes
# Perl 5, 136 bytes

```
sub{map{//;map$n{$n{$x="N$'$_"}//=sprintf"A%05X",$i+=!/I|O/}=$x,sort(("",A..Z,AA..ZZ)[0..26*($_<1e3?27:$_<1e4)])}sort 1..99999;$n{+pop}}

```

Try it online!

Generates a list of all 915399 possible N-codes and stores it in hash %n which is also mirrored to convert the other way.

# Answer
> 2 votes
# JavaScript (Node.js), 122 bytes

*-8 thanks to @l4m2*

This is (now even more) similar to l4m2's answer.

```
x=>(n=0x9e7298,g=(s,h=k=>k>52?0:g(s+Buffer([48+k%43]))||h(k+1))=>/I|O|\D{3}|.{7}|.\D\d/.test(s)?0:x^++n?x==s?n:h(17):s)`N`

```

Try it online!

### Commented

```
x => (                   // x = input
  n = 0x9e7298,          // n = ICAO counter
  g = (                  // g = helper function taking:
    s,                   //   s = current registration number string
    h = k =>             //   h = helper function taking a counter k
    k > 52 ?             //     if k is greater than 52:
      0                  //       stop
    :                    //     else:
      g(                 //       do a recursive call to g
        s +              //         where s is completed with either
        Buffer([         //         an upper case letter A-Z (65-90)
          48 + k % 43    //         or a digit 0-9 (48-57)
        ])               //
      ) ||               //       end of recursive call
      h(k + 1)           //       if it failed, try h(k + 1)
  ) =>                   //
  /I|O|\D{3}|.{7}|.\D\d/ // if s contains a 'I' or a 'O', or has 3
  .test(s) ?             // consecutive letters, or is 7 char. long,
                         // or contains a digit after a letter (other
                         // than the leading 'N'):
    0                    //   invalid registration number -> abort
  :                      // else:
    x ^ ++n ?            //   increment n; if x is not equal to n:
      x == s ?           //     if x is equal to s:
        n                //       return n
      :                  //     else:
        h(17)            //       invoke h, starting with k = 17 for 'A'
    :                    //   else:
      s                  //     return s
)`N`                     // initial call to g with s = 'N'

```

# Answer
> 1 votes
# 05AB1E, ~~51~~ 46 bytes

```
5°<L§{A„ioмuÐâª˜{õšδ«˜'Nìʒg7‹}ā•¢β¡•+hø.ΔQà}IK

```

The output is wrapped in a list. This can be fixed at the cost of 1 trailing byte.

Try it online. (Very slow for values far into the sequence.)
The first portion of the program generates all pairs.

**Explanation:**

```
5°             # Push 10**5: 100000
  <            # Decrease it by 1: 99999
   L           # Pop and push a list in the range [1,99999]
    §          # Cast each integer to a string
     {         # Sort these strings lexographically
A              # Push the lowercase alphabet
 „ioм          # Remove the "i" and "o"
     u         # Uppercase the remaining letters
      Ð        # Triplicate it
       â       # Pop two, and create all pairs using the cartesian product
        ª      # Convert the remaining string to a list of characters,
               # and append this list of pairs
         ˜     # Flatten it to a single list
          {    # Sort these strings lexographically as well
           õš  # Prepend an additional empty string
δ              # Apply double-vectorized on the two lists:
 «             #  Append two strings together
  ˜            # Flatten it
   'Nì        '# Prepend an "N" before each
      ʒ   }    # Filter it, keeping those where:
       g       #  Their length
        7‹     #  is smaller than 7
               #  (to filter out invalid values like "N10000ZZ")
ā              # Push a list in the range [1,length] (without popping)
 •¢β¡•+        # Add compressed integer 10485760 to each ("A00000" in hexadecimal)
       h       # Then convert each integer to a hexadecimal string
ø              # Pair the values in the two lists together
.Δ             # Pop and find the first/only pair that's truthy for:
   à           #  Check if either of the two
  Q            #  equals the (implicit) input-string
 }IK           # After we've found our matching pair: remove the input from it
               # (after which the intended wrapped result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•¢β¡•` is `10485760`.

# Answer
> 1 votes
# Retina, 173 bytes

```
"G`$&\b¶$&|;¶"^~(`.+
99999*
L$`_
N$.>`
O`
2+%(`$
;26*
Y`\_`L
I|O

)L$`(;|(\w))(?<=(\w+);.*)
$3$2
A`.{7}
D^`
G`.
.+
$&;A,$>:&*
5+`;A,(_{16})*(_*)
;A,$#1*_,$.2
T`d`L`,1\d
,B?

```

No TIO link, since it needs about 9 hours to run. Explanation:

```
"G`$&\b¶$&|;¶"^~(`

```

Evaluate the rest of the program below, then select only the line containing the input word and delete the word and separator from that line, thus giving the matching code.

```
.+
99999*
L$`_
N$.>`
O`

```

Generate the numbers from `1` to `99999` in lexicographical order.

```
2+%(`
)`

```

Repeat twice for each line.

```
$
;26*
Y`\_`L
I|O

L$`(;|(\w))(?<=(\w+);.*)
$3$2

```

Append each letter except `I` and `O`.

```
A`.{7}
D^`
G`.

```

Remove illegal and duplicate entries.

```
.+
$&;A,$>:&*

```

Number the lines with an `A` prefix.

```
5+`;A,(_{16})*(_*)
;A,$#1*_,$.2
T`d`L`,1\d
,B?

```

Convert the numbers to five hexadecimal digits.

# Answer
> 1 votes
# Charcoal, ~~151~~ ~~147~~ 121 bytes

```
≔Ｉ⪪”)¶&*δ§Ｌ¶∧≧Ｔ∨›P”2η≔⪪⁻⁺⁻αI⭆χιO¹υ⊞υω¿›NθNＰθＦ∨¬ⅈ⁵«≔Ｅυ↥⍘⁺↨ＥΦ⁺⪫ＫＡωκν⊕⎇⁼ν⁴⌕υμ⎇№αμ×∨№α§ＫＡν²⁵⌕υμ⁺⁶⁰⁰×Ｉμ§ην¹⌈η¹⁶ζ⎇ⅈ§⮌υ⊕ΣＥζ›κθ⊟ζ

```

Try it online! Link is to verbose version of code. Explanation: Long because it doesn't use brute force, as that would probably take too long to verify correct program operation, so I've actually computed the result somewhat directly. Explanation:

```
≔Ｉ⪪”)¶&*δ§Ｌ¶∧≧Ｔ∨›P”2η

```

Get some compressed magic numbers.

```
≔⪪⁻⁺⁻αI⭆χιO¹υ⊞υω

```

Get the string `ABCDEFGHJKLMNPQRSTUVWXYZ0123456789`, split it into characters, and append the empty string.

```
¿›NθNＰθ

```

If this is a US registration, then print it without moving the cursor, otherwise print an `N`. Note that this means that the x-coordinate is now zero only for a US registration.

```
Ｆ∨¬ⅈ⁵«

```

Loop once for a US registration, otherwise `5` times.

```
≔Ｅυ↥⍘⁺↨ＥΦ⁺⪫ＫＡωκν⊕⎇⁼ν⁴⌕υμ⎇№αμ×∨№α§ＫＡν²⁵⌕υμ⁺⁶⁰⁰×Ｉμ§ην¹⌈η¹⁶ζ

```

Suffix each letter and digit to the partial US registration and see what the resulting ICAO codes are, plus also calculate the ICAO code for the US registration.

```
⎇ⅈ§⮌υ⊕ΣＥζ›κθ⊟ζ

```

For a US registration, overprint it with the ICAO code, but for an ICAO code, append any best letter or digit.

The values of the characters of a US registration are calculated as follows:

* The first digit is worth `101711` times its value plus `601`
* The second digit is worth `10111` times its value plus `601`
* The third digit is worth `951` times its value plus `601`
* The fourth digit is worth `35` times its value plus `601`
* The first letter is worth `25` times its position in the alphanumeric string plus `1` unless it's the fifth character
* The fifth character is worth its position in the alphanumeric string plus `1`

(In reality `600` is used instead of `601` and then `1` is added later for each digit.)

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


title: Emoticon facial expression recognition

text:
# Question
Title: Emoticon facial expression recognition
Write a program that accepts as input an emoticon and ouputs if the emoticon is happy or sad.

The program accepts a string as input or parameter, and should display the string "happy" if the input is in the happy emoticon list, or "sad" if the input is in the sad emoticon list.

You can assume the input is always a valid (happy or sad) emoticon, with no space or tabs around.

Here is a space separated list of happy emoticons:

```
:-) :) :D :o) :] :3 :c) :> =] 8) =) :} :^) :-D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D (-: (: (o: [: <: [= (8 (= {: (^:

```

Here is a space separated list of sad emoticons:

```
>:[ :-( :( :-c :c :-< :< :-[ :[ :{ 8( 8-( ]:< )-: ): >-: >: ]-: ]: }: )8 )-8

```

This is code-golf, so the shortest program wins.

# Answer
# Python, 86 bytes

I should be sent to prison.

```
x=lambda c: ["happy","sad"][c[0]+c[-1:]in open(__file__).read(88)[::-1]]#<][><:>{:}(:)

```

The shortest I could come up with was equivalent to Martin's CJam answer, so I decided I'd hide all the sad emojis (minus the middle character if any) in the reverse of my code and use Python's `__file__` quine cheat.

Muahahaha.
> 20 votes

# Answer
# CJam, ~~33~~ 32 bytes

*Thanks to Dennis for saving 1 byte.*

```
q)"[(c<{"&\"])>}"&|"sad""happy"?

```

Looks like it's shorter to do the same thing without a regex...

Test it here.

## Explanation

This based on the same observation as the Retina answer, but this time matching happy faces doesn't have any benefit, so we'll match sad faces instead (because there's one less mouth to take into account). The solution is otherwise exactly the same, except that it's not implemented via regex substitution:

```
q)             e# Read input and split off last character.
"[(c<{"&       e# Set intersection with the sad right-hand mouths.
\              e# Pull up remaining emoticon.
"])>}"&        e# Set intersection with the sad left-hand mouths.
|              e# Set union, which amounts to a logical OR in this case.
"sad""happy"?  e# Pick the correct string.

```
> 16 votes

# Answer
# Retina, ~~38~~ 36 bytes

```
.+[])D3>}]|[<[({].+
happy
^...?$
sad

```

We can recognise all emoticons by their mouths, because none of the mouths is used as a hat or eyes in the other set (only in the same set). The happy ones have one more mouth to take into account, but they have the benefit that the mouths don't appear in the other set at all, not even as noses (the opposite is not true: `c` is both a sad mouth and a happy nose). This means we can avoid using anchors but instead just ensure that there are more characters on the other side of the mouth.

So the valid mouths for happy faces are `] ) D 3 > }` on the right or `< [ ( {` on the left. We match those with `.+[])D3>}]|[<[({].+` and replace them with `happy`. If we didn't match there will be two or three characters in the string (the emoticon), but if we did there will be five (`happy`). So in a second step we replace two or three characters with `sad`.
> 10 votes

# Answer
# JavaScript (ES6), 46

Using a regexp to find sad emoticons, that are those beginning with `>)]}` or ending with `<([{c`. Side note: other regexps here may be shorter but I'm not sure to understand them.

Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably ~~not~~ newest Chrome but not MSIE. I tested on Firefox, Safari 9 could go)

**Big news** It seems arrow functions finally arrived to Chrome land! Rel 45, august 2015

```
F=s=>/^[\])}>]|[[({<c]$/.test(s)?'sad':'happy'

//Same length
X=s=>/[\])}>].|.[[({<c]/.test(s)?'sad':'happy'

Y=s=>s.match`].|[)}>].|.[[({<c]`?'sad':'happy'

//TEST
out=x=>O.innerHTML+=x+'\n';

sad='>:[ :-( :( :-c :c :-< :< :-[ :[ :{ 8( 8-( ]:< )-: ): >-: >: ]-: ]: }: )8 )-8'.split` `
happy=':-) :) :D :o) :] :3 :c) :> =] 8) =) :} :^) :-D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D (-: (: (o: [: <: [= (8 (= {: (^:'.split` `

out('The sad faces')
sad.forEach(x=>out(x + ' is ' + F(x)))
out('\nThe happy faces')
happy.forEach(x=>out(x + ' is ' + F(x)))
```

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

# Answer
# Julia, 87 69 bytes - saved 18 bytes thanks to Alex A.

```
s=readline();print(s[end-1] in")D]3>}"||s[1] in"([<{"?"happy":"sad")

```
> 4 votes

# Answer
# Python 3, ~~77~~ ~~75~~ ~~74~~ ~~72~~ ~~61~~ 55 bytes

```
lambda e:('happy','sad')[e[-1]in'[(c<{'or e[0]in'])>}']

```

Try it online!

## How does it work

If a face string starts with `])>}` or ends with `[(c<{`, it is sad, otherwise it is happy. Tuple indexing is used as `if`.
> 4 votes

# Answer
# Brachylog, 50 bytes

```
(rh{,"[(c<{":Im?};?h{,"])>}":Im?}),"sad".;"happy".

```

### Explanation

```
(                              ),"sad".;"happy".  § If what's in the parentheses is true,
                                                  § output "sad", else output "happy".

 rhA                                              § Unify A with the last char of the input
    ,"[(c<{":ImA                                  § True if A is a char of "[(c<{"
                ;                                 § OR
                 ?hA                              § Unify A with the first char of the input
                    ,"])>}":ImA                   § True if A is a char of "])>}"

```
> 3 votes

# Answer
# Python, 159 bytes.

```
i,e=raw_input(),0
for c in i:e=(e,i.index(c))[c in":=8xXB"]
f,s,h=i[:e],i[e+1:],0
for c in f:h+=c in"[(c<{"
for c in s:h+=c in")]}>D"
print["Sad","Happy"][h>0]

```
> 2 votes

# Answer
# MATLAB, ~~85~~ 83 bytes

There must be a way to reduce the size here.

```
e=input('');if any([e(end)=='[(c<{',e(1)=='])>}']),'sad';else 'happy';end,disp(ans)

```

Input is a smiley string. First and last characters will be compared to determine whether it's sad. If not, it's happy.

I was able to save 2 bytes by not displaying either, but assigning them to MATLAB's default variable (ans) instead and then displaying ans after the if-statement. But I'm convinced it can be improved somehow.

2 bytes improvement by changing *function s(e),* to *e=input('');*.
> 2 votes

# Answer
# PowerShell, 92 Bytes

```
param([char[]]$a)if("<[({".IndexOf($a[0])+"})D3]>".IndexOf($a[-1])-eq-2){"sad"}else{"happy"}

```

A little wordy, but as a bonus, it doesn't use regex!

This takes advantage of the .NET `<string>.IndexOf()` function that returns `-1` if the character *isn't* found in the string. So, if the first character isn't a "happy" character, the first `IndexOf()` will be -1 -- likewise for the last character. So, if it's a sad face, the `IndexOf()`s will always sum to -2, meaning the `-eq-2` is `$TRUE`, and thus `sad` gets printed.

---

### Bonus variant: PowerShell with Regex, 95 bytes

```
param([char[]]$a)if(($a[0]-match"[<\[\(\{]")-or($a[-1]-match"[\}\)D3\]>]")){"happy"}else{"sad"}

```
> 1 votes

# Answer
# Python 3, 75 bytes

```
lambda y:"sad"if re.match("(.*[[(c<{]$)|(^[\])>}])",y)else"happy"
import re

```

Try it online

The regex import makes it a bit too long, as well as the inability to use `None` as an array index. But I like regex :)
> 1 votes

# Answer
# Java 8, 52 bytes

```
e->e.matches(".+[\\[(c<{]|[)>\\]}].+")?"sad":"happy"

```

Try it online.

**Explanation:**

```
e->          // Method with String as both parameter return-type
  e.matches( ".+[\\[(c<{]|[)>\\]}].+")
             //  Checks if the input matches the regex
   ?"sad"    //  If it does: output "sad"
   :"happy"  //  Else: output "happy"

```

Java's `String#matches` implicitly adds `^...$` to match the entire String, which is why it is shorter to check for sad faces instead of checking for happy faces like most other answers do with `.+[\\])D3>}]|[<\\[({].+` (because my regex would fail in *@MartinEnder*'s Retina answer for example, due to the happy test case `:c)`).

**Regex explanation:**

```
^.+[\\[(c<{]|[)>\\]}].+$
^                           Start of the string
 .+                          One or more characters,
   [\\[(c<{]                 followed by one of "[(c<{"
            |               Or
             [)>\\]}]        One of ")>]}",
                     .+      followed by one or more characters
                       $    End of the string

```
> 1 votes

# Answer
# \[AutoHotkey\], 78 bytes

```
InputBox,e
MsgBox % RegExMatch(e,"(^[\])>}].+$)|(^.+[\[(c<{]$)")?"sad":"happy"

```

## How does it work

Using RegEx and ternary operator. Nothing new, as some answers used this method too. If input string starts with `])>}` or ends with `[(c<{`, it is sad, otherwise it is happy.
> 1 votes

# Answer
# Perl 5 `-p`, 33 bytes

```
$_=/.[[(c<{]$|[\])>}]./?sad:happy

```

Try it online!
> 1 votes

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


title: Remove every N-th N

text:
# Question
Title: Remove every N-th N
## The task

In this challenge, your input is a non-empty list of positive integers, given in the native format of your language. Your output is that same list, in the same format, with some elements removed. You shall remove every occurrence of `1`, every second occurrence of `2`, every third occurrence `3`, and so on. In general, for every positive integer `N`, you shall remove every `N`th occurrence of `N` from the list, starting with the `N`th occurrence.

## Example

Consider the input list

```
[3,2,6,1,1,6,2,3,2,6,6,6,6,1,6,6,3,3,7,2]

```

First, we remove every occurrence of `1`:

```
[3,2,6,    6,2,3,2,6,6,6,6,  6,6,3,3,7,2]

```

Then every second occurrence of `2`:

```
[3,2,6,    6,  3,2,6,6,6,6,  6,6,3,3,7  ]

```

Then every third occurrence of `3`:

```
[3,2,6,    6,  3,2,6,6,6,6,  6,6,  3,7  ]

```

The numbers `4` and `5` don't occur in the input, so they can be skipped. Next, we remove every sixth occurrence of `6`:

```
[3,2,6,    6,  3,2,6,6,6,    6,6,  3,7  ]

```

There's only one occurrence of `7`, so that can be skipped as well. Thus the correct output is

```
[3,2,6,6,3,2,6,6,6,6,6,3,7]

```

## Rules and scoring

You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

```
[1] -> []
[2] -> [2]
[1,1,1] -> []
[2,2,2] -> [2,2]
[1,1,2,2,2,3,3,3,3] -> [2,2,3,3,3]
[1,2,3,1,2,3,1,2,3,1,2,3] -> [2,3,3,2,3]
[3,2,6,1,1,6,2,3,2,6,6,6,6,1,6,6,3,3,7,2] -> [3,2,6,6,3,2,6,6,6,6,6,3,7]
[5,4,5,4,3,5,4,5,4,5,4,3,5,4,5,3,3,3,4,5,4,5,4,5,4,3,3,3,5,4] -> [5,4,5,4,3,5,4,5,4,3,5,4,5,3,3,4,5,5,4,4,3,3,5,4]
[6,4,5,8,2,9,3,1,8,5,3,5,5,6,3,5,1,2,3,9,3,5,8,7,5,9,1,3,4,8,2,3,4,7,8,5,8,5,3,1] -> [6,4,5,8,2,9,3,8,5,3,5,5,6,3,9,3,5,8,7,5,9,4,8,2,3,4,7,8,5,8,5,3]
[4,4,9,12,9,4,4,4,12,9,12,9,12,4,12,4,4,9,4,9,12,4,12,4,4,12,4,4,9,12,9,12,9,4,9,12,4,9,12,9,12,9,4,9,12,12,4,4,12,4] -> [4,4,9,12,9,4,4,12,9,12,9,12,4,12,4,9,4,9,12,4,12,4,12,4,4,9,12,9,12,4,9,12,9,9,12,9,4,9,12,12,4,4,12]
[2,2,11,11,11,11,6,2,2,6,6,2,2,2,2,6,11,6,11,11,2,11,2,6,6,11,2,11,6,2,6,6,6,6,6,11,2,11,11,6,6,6,11,6,2,6,2,6,6,2,11,2,2,11,11,11,11,2,6,2] -> [2,11,11,11,11,6,2,6,6,2,2,6,11,6,11,11,2,11,6,11,2,11,6,6,6,6,6,2,11,11,6,6,6,11,6,2,6,6,11,2,11,11,11,11,2,6]
[20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102] -> [20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,101,102,20,21,22,100,102,20,21,22,100,101,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102]

```

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If you want to include multiple numbers in your header, make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=70091,OVERRIDE_USER=32014;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Jelly, ~~10~~ 8 bytes

```
=;\S€%af

```

*Thanks to @Sp3000 for golfing off 2 bytes!*

Try it online!

### How it works

```
=;\S€%af    Main link. Input: A (list)

 ;\         Compute the cumulative concatenations of the elements of A, i.e., the
            list of A's prefixes.
=           Compare the elements of the nth prefix with the nth element of A.
   S€       Compute the sum of the resulting arrays.
     %      Take the nth sum modulo the nth element of A.
      a     Logical AND; replace the nth remainder with the nth element of A
            if the remainder is non-zero.
        f   Filter; remove the zeroes (which do not occur in A) from the result.

```
> 16 votes

# Answer
## awk, 10 bytes

Input is expected on STDIN, one number per line.

```
++a[$1]%$1

```

### Explanation

Keeps a counter for each number in an associative array, prints only if the counter value modulo `n` is not zero. Printing is implicit. Long version:

```
++a[$1]%$1{print $0}

```
> 34 votes

# Answer
# Pyth, ~~18~~ ~~15~~ ~~14~~ ~~10~~ 9 bytes

```
f%/aYTTTQ

```

I think this is the first code I've written that has five consecutive variable references in nine bytes.

I wish the array manipulation solution (`u.DG%HgxHGH{QQ`, 14 bytes) weren't so long.

```
f%/aYTTTQ       Implicit: Q=input
                 lambda T:
    Y              Variable: starts as empty list.
   a T             Append T to Y. Mutates Y.
  /   T           Number of elts of Y that equal T.
 %     T         Modulo by T
f       Q       Filter that lambda over Q.

```

Try it here.
> 20 votes

# Answer
## Python, 57 bytes

```
lambda l:[n for i,n in enumerate(l)if l[:i+1].count(n)%n]

```
> 10 votes

# Answer
# Perl 6, 28 bytes

```
{$_=$;grep {++.{$^n}%$n},@_}

```

Explanation

```
{
  $_=$;        # put $_ in a clean state
  grep {
    ++.{$^n}   # increment $_{ $n } and declare $n as an argument
    % $n       # check if the count is not divisible by $n
  }, @_        # the input
}

```

Usage:

```
# give it a lexical name for ease of use
my &code = {...}

sub check ( @a, @b ){
  say try { so all code(@a) »==« @b } // False
}

check [1], []; # True
check [2], [2]; # True
check [1,1,1], []; # True
check [2,2,2], [2,2]; # True
check [1,1,2,2,2,3,3,3,3], [2,2,3,3,3]; # True
check [1,2,3,1,2,3,1,2,3,1,2,3], [2,3,3,2,3]; # True
check [3,2,6,1,1,6,2,3,2,6,6,6,6,1,6,6,3,3,7,2], [3,2,6,6,3,2,6,6,6,6,6,3,7]; # True

```

Double check that the correct elements are being thrown out

```
# have to change it to a pure number
# when checking $_         V
my &code = {$_=$;grep {++.{+$^n}%$n},@_}
# only matters here because we are using
# a subclass of Int but want it to use
# the same key as a normal Int

sub F ( Int $v ) { IntStr.new: $v, "Fail($v)" }
# prove that it passes through unchanged
say [F(2)];
# (Fail(2))

say code [3,2,6,F(1),F(1),6,F(2),3,2,6,6,6,F(6),F(1),6,6,F(3),3,7,F(2)];
# (3 2 6 6 3 2 6 6 6 6 6 3 7)

```
> 9 votes

# Answer
## Seriously, ~~22~~ 17 bytes

```
k╗,;`;;╜o;╗c%`M@░

```

Hex Dump:

```
6bbb2c3b603b3bbd6f3bbb6325604d40b0

```

Try It Online

Explanation:

```
k╗                                Put empty list in reg0
  ,;                              Two copies of input
    `        `M                   Map over the list
     ;;                           Make 2 extra copies of n
       ╜o                         Load reg0 and push the n onto it
         ;╗                       Put a copy back in reg0
           c                      Count the number of copies of n in the list
            %                     Take the result modulo n
               @░                 Filter the original list with the resulting list

```
> 6 votes

# Answer
## JavaScript ES6, 34 bytes

```
a=>a.filter(v=>f[v]=-~f[v]%v,f=[])

```

Turned out to be the same as Brad's Perl algorithm.

Edit: Saved 2 bytes thanks to @edc65.
> 6 votes

# Answer
## Mathematica, ~~40~~ ~~38~~ 36 bytes

```
Select[(f@#=#)&/@#,++f[#]~Mod~#>0&]&

```

This is an unnamed function taking and returning a `List`. It defines a named function `f` when executed (to keep track of the numbers), but takes care of resetting the relevant definitions of `f` beforehand.

### Explanation

The way functions (or function definitions) work in Mathematica is really powerful. As in Haskell (for instance), functions cannot only be overloaded and defined for certain types, but also for individual values (or arbitrary patterns of arguments, actually). But it is even more powerful than Haskell in that a) these values can be defined as side effects during control flow and b) the values can also be redefined at any time. That means functions are actually pretty powerful lookup tables (that can optionally *compute* the looked-up value instead of just storing it).

If we remove the golfitude from the code it would look a bit like this:

```
g[list_] := (
  Map[
    (f[#] = #) &,
    list
  ];
  Select[
    list,
    Mod[++f[#], #] > 0 &
  ]
)

```

So first, we loop over the input and define `f[x] = x`, for all `x` in the list. `f` will ultimately be used to keep track of how often each number has already appeared in the list. Why do we not count from `0`? The loop over the list is a `Map`. The expression `f[x] = y` returns `y` (in addition to storing the function definition). So by setting `f[x]` to `x`, the map will evaluate to the input list itself. That saves two bytes because then we don't need to provide `list` again explicitly to `Select`. Starting from `x` instead of `0` doesn't affect the computation at all since we're only ever interested in `Mod[f[x], x]`.

(Normally we could simply use something like `f[_] = 0` as a fallback definition to avoid the `Map`, but we don't know if our function has been used before, which would leave some previous values defined that would mess with our counting.)

Then `Select` filters the list by keeping only those elements where the unnamed function passed as the second argument yields `True`. That function *first* increments the value of `f[x]` (where `x` is the current list element), in order to count the occurrences, and then it takes the resulting count modulo `x`. We want to discard all elements where this yields `0`.
> 5 votes

# Answer
## CJam, 17 bytes

```
Lq~{:X+_Xe=X%},p;

```

Just beat... J? Not sure what my expectations are for this challenge, really. Note that `""` is CJam's representation of an empty array.

Try it online | Test suite (the last case is too long for the permalink)

### Explanation

```
L                     Push empty array (let's call it L)
 q~                   Push input and evaluate

   {         },       Filter the array elements by...
    :X                   Save number to variable X
      +                  Append to L

       _                 Duplicate
        Xe=              Count occurences of X
           X%            Take modulo X

                      The top element is popped to determine whether or not to keep that
                      element, with the updated L kept on the stack for the next iteration

               p      Print the resulting filtered array
                ;     Pop L, which is now equal to the input array

```
> 5 votes

# Answer
# JavaScript ES6, 55 bytes

```
a=>a.filter((v,i)=>a.filter((w,j)=>j<=i&v==w).length%v)

```

### Explanation

```
a=>                            //a -> input array
 a.filter(                     //filter array. only keep elements if inside function returns truthy
      (v,i)=>                  //inside function to decide whether to keep items. v -> item; i -> index
           a.filter((w,j)=>    //get all ocurrences of v that occur before index i
                j<=i&v==w      //(this is done by keeping all items w at index j, if j <= i and v == w
           ).length%v          //get length (count ocurrences), and mod v.
                               //this will only be falsy if the number of ocurrences of v up to this index is divisible by v. (0 -> falsy, positive -> truthy)
 )                             //so, we don't keep every second 2, every third 3, etc.

```
> 4 votes

# Answer
# J, 18 bytes

```
#~((0<]|+/@:=){:)\

```

Usage:

```
   (#~((0<]|+/@:=){:)\) 1 2 3 1 2 3 1 2 3 1 2 3
2 3 3 2 3

```

Pretty straightforward method. We count the occurrences of a number up to it and select the number only if the number divides the count.

More explanation comes later.

Try it online here.
> 4 votes

# Answer
## PowerShell, 56 bytes

```
param($a)$b=,0*($a|sort)[-1];$a|%{if(++$b[$_-1]%$_){$_}}

```

Uses a similar helper-array-trick as Rainer P's answer, which I developed independently but I apparently got FGITW'd.

Takes input as an array with `param($a)`. We then create our helper array `$b` as a populated-with-zeros array by using the comma operator coupled with the overloaded multiplication operator. This creates `$b` to be equal to `@(0,0,0...0)` with `$b.length` equal to the maximal number in `$a`.
<sub>(Quick plug for my "Showcase your language" answer where I describe this in detail)</sub>

Next is our output. We loop over every element of our input array `$a|%{...}` and each loop check an `if` statement. The conditional pre-increments the value in our helper array that corresponds with the current element, then checks whether it's a multiple of the current element with the modulo operator. If it is a multiple, the `%` will equal `0` which is falsey, so the `if` doesn't execute. Otherwise, we output the current element.

Takes advantage of implicit typecasting to save on output formatting. If a function or program returns multiple elements, and you save the results to a variable, PowerShell will dynamically create that variable as an array. Example:

```
PS C:\Tools\Scripts\golfing> $testc = .\remove-every-nth-n.ps1 @(2,2,2)

PS C:\Tools\Scripts\golfing> $testc
2
2

PS C:\Tools\Scripts\golfing> $testc.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

```
> 2 votes

# Answer
# Haskell, ~~58~~ 56 bytes

*2 bytes saved by xnor*

```
q w=[x|(n,x)<-zip[1..]w,0<mod(sum[1|u<-take n w,u==x])x]

```

Try it online!
> 2 votes

# Answer
# Perl 5, 24 + 1 `-p`= 25 bytes

```
$\.=$_ if++$k{0|$_}%$_}{

```

Try it online!

Input has each entry on a separate line
> 2 votes

# Answer
# R, ~~110~~ ~~98~~  ~~99~~ 92 Bytes

```
function(a){for(i in 1:max(a))for(j in seq_along(b<-which(a==i)))if(j%%i<1)a[b[j]]=0;a[a>0]}

```

Edit complete rewrite fixes bug with test case 2/3 Edit 2 Save 7 bytes thanks to @Alex-A
> 1 votes

# Answer
# MATL, 20 bytes

```
tu"t@=f@@h0h)0w(]tg)

```

This uses current release (10.2.1) of the language/compiler.

**Try it online!**

### Explanation

```
tu        % implicitly input array. Duplicate and get unique elements
"         % for each unique element, say "i"
  t       % duplicate
  @=f     % indices of occurrences of i
  @@h0h   % build index representing i-th occurrences (Matlab's i:i:end)
  )       % keep only indices of i-th occurrences
  0w(     % set those entries to 0
]         % end for loop
tg)       % keep nonzeros only. Implicit display

```
> 1 votes

# Answer
# R, 63 bytes

```
f=function(z){n=seq(z);for(i in n)z[which(z==i)[n*i]]=0;z[z>0]}

```
> 1 votes

# Answer
## C#, 224 bytes

```
List<int>R(List<int>l,int n=1){l=l.Where(w=>w!=0&&w!=1).ToList();for(int i=0,t=0;i<l.Count;i++){if(l[i]==n&&++t==n){l[i]=0;t=0;}}return !l.Any()||n>l.Max()?l:R(l,++n);}

```

This code uses recursion. With `using` statements that's 224 bytes (160 for the method code itself).

Try it online.

```
List <int> R(List <int> l, int n = 1)
{
    l = l.Where(w => w > 1).ToList();
    for (int i = 0, t = 0; i < l.Count; i++)
    {
        if (l[i] == n && ++t == n)
        {
            l[i] = 0;
            t = 0;
        }
    }
    return !l.Any() || n > l.Max() ? l : R(l, ++n);
}

```
> 1 votes

# Answer
# Haskell, 78 bytes

```
f l=[l!!n|n<-[0..length l-1],0/=mod(1+(length.filter(==l!!n)$take n l))(l!!n)]

```

Try it Online!
> 1 votes

# Answer
# Factor, 61 bytes

```
[ H{ } clone '[ _ 2dup inc-at over of swap mod 0 > ] filter ]

```

Try it online!

The idea is to have a hash table that keeps a running count of each element. Then we reject each element from the input that is divisible by its current count.
> 1 votes

# Answer
# C# - 177 Bytes

```
void r(List<int> i){for(int c=1,k=1,m=i.Max();k<=m;k++){var n=new List<int>();foreach(var o in i)if(o==k&&c++==k)c = 1;else n.Add(o);i=n;}Console.WriteLine(string.Join(" ",i));}

```

Ungolfed

```
void r(List<int> i)
{
    for (int c = 1, k = 1, m = i.Max(); k <= m; k++)
    {
        var n = new List<int>();
        foreach (var o in i)
            if (o == k && c++ == k)
                c = 1;
            else
                n.Add(o);
        i = n;
    }
    Console.WriteLine(string.Join(" ", i));
}

```
> 0 votes

# Answer
## Mathematica, 63 bytes

```
Fold[Delete[#,Position[#,#2][[#2;;;;#2]]~Check~{}]&,#,Union@#]&

```

Quite interesting to golf! Ignore the occasional message that pops up.
> 0 votes

# Answer
# Ruby, 120 bytes

```
->a{1.upto(a.max).each{|i|k=0;a.length.times.each{|j|k+=1if a[j]==i;a[j]=''if k%i==0&&a[j]==i;a[j]}};a.select{|i|i!=''}}

```
> 0 votes

# Answer
## TI-BASIC, 47 bytes

```
Input X
For(I,1,dim(∟X
∟X(I
If fPart(sum(∟X=Ans),1,I)/Ans
Ans→L₁(1+dim(L₁
End
L₁

```

This uses the fact that, on a fresh calculator, `L₁` is initialized and cleared. Note that trying to display an empty list in TI-BASIC throws an error.
> 0 votes

# Answer
## APL, 16 chars

```
{⍵/⍨×⍵|+/¨⍵=,\⍵}

```

In English:

* `,\⍵`: vector of the vector prefixes up to the nth-element of the argument
* `+/¨⍵=`: per prefix vector, count how many are equal to the n-th element itself
* `×⍵|`: signs of the mod's (that is: 0 if the remainder of the division is 0, 1 otherwise)
* `⍵/⍨`: of the argument keep only the element where the mod is 0
> 0 votes

# Answer
## Racket 179 bytes

```
(λ(l)(define m(apply max l))(let g((n 1)(c 0))(set! l(for/list((i l))(if(= i n)(begin
(set! c(+ 1 c))(if(= 0(modulo c n))0 i))i)))(if(< n m)(g(+ 1 n)0)(filter(λ(x)(> x 0))l))))

```

Ungolfed:

```
(define f
  (λ(l)
    (define m (apply max l))
    (let loop ((n 1) (c 0))
      (set! l (for/list ((i l))
                (if (= i n)
                    (begin
                      (set! c (+ 1 c))
                      (if (= 0 (modulo c n))
                          0 i ))                  ; replace by 0
                    i )))
      (if (< n m)
          (loop (+ 1 n) 0)
          (filter (λ(x)(> x 0)) l)                ; remove all 0s
          ))))

```

Testing:

```
(f '[1])
(f '[2])
(f '[1 1 1])
(f '[2 2 2])
(f '[1 1 2 2 2 3 3 3 3])
(f '[1 2 3 1 2 3 1 2 3 1 2 3])
(f '[3 2 6 1 1 6 2 3 2 6 6 6 6 1 6 6 3 3 7 2])

```

Output:

```
'()
'(2)
'()
'(2 2)
'(2 2 3 3 3)
'(2 3 3 2 3)
'(3 2 6 6 3 2 6 6 6 6 6 3 7)

```
> 0 votes

# Answer
# 05AB1E, 8 bytes

```
ʒˆ¯y¢yÖ_

```

Inspired by *@RainerP.*'s awk answer.

Try it online or verify all test cases.

**Explanation:**

```
ʒ         # Filter the (implicit) input-list by:
 ˆ        #  Pop and add the current integer to the global array
    ¢     #  Count how many times
   y      #  the current integer
  ¯       #  occurs in the global array
       ≠  #  Check that this count is NOT
      Ö   #  evenly divisible
     y    #  by the current integer
          # (after which the filtered list is output implicitly as result)

```
> 0 votes

# Answer
# Haskell \+ hgl, 27 bytes

```
gj<<fn(by**(ce~<gj)$gj)<pxn

```

Attempt This Online!

## Explanation

This code is a rats nest. That's in part because to do the glue for this program I tried structuring it a bunch of different ways, plugging things into the pointfree converted until I ran out of ideas and using the shortest one.

It's rather difficult to truly explain it, but the rough idea is as follows:

First we use `pxn` to get all the prefixes of the list. Then we perform a filter to filter out prefixes where their last element occurs in the prefix a number of times divisible by that last element. Then we get the last element of each prefix.

The rats nest is in the part where we "filter out prefixes where their last element occurs in the prefix a number of times divisible by that last element". By the description it seems like that is a rather complex operation.

## Reflection

There are a couple of things I think would have been really helpful.

* It would be nice to have a combined zip and filter. What I'd really like is something like
```
(Alternative f, Zip f) => (a -> b -> Bool) -> f a -> f b -> f a

```
But I'd happily settle for:
```
(Alternative f, Zip f) => f a -> f Bool -> f a

```
which seems like it would have more general use.
* Speaking of odd filters. Why not have prefix/suffix filters? This solution is doing a filter on the prefix list, and I can imagine it happening again in the future. There are a couple of ways to do this. The best motivated types seem to be
```
(a -> List a -> Bool) -> List a -> List a

```
and
```
(List a -> Bool) -> List a -> List (List a)

```
> 0 votes

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