title: Pyth Practice 2

text:
# Question
Title: Pyth Practice 2
Time for another Pyth practice. I present here 8 problem statements with a Pyth solution each. These solutions are written by a Pyth beginner. He is quite happy about these solutions, since they are a lot shorter than his Python answers. Your task however is to show him better. Create equivalent but shorter programs.

This is a challenge about the the tricks and optimizations that can be used when golfing in Pyth. Pyth golfers may recognize many of the tricks involved, that lead to shorter solutions. However some problems will require some unusual approaches that are rarely used. Some of the tricks I've actually never seen in the wild. But no solution requires any bugs or strange behavior, that was not intentional by the designer(s) of Pyth. All answers must be valid for the most recent Pyth commit (2b1562b) as of this question's posting. You can use the Pyth interpreter for testing. It is up-to-date right now and I don't expect any big changes in Pyth, that will invalidate optimal solutions or make shorter solutions possible. The online interpreter also features the new Character Reference. Since it is pretty new, you can (should) also use the old docs, in case something is incorrect or missing.

**Goal:** The reference solutions total 81 bytes. Your goal is to beat that by as much as possible. The submission that solves all 8 problems with the smallest total number of bytes wins. Tiebreaker is the submission date.

Of course only submissions are valid, which contain solutions for all 8 problems. You can use the reference implementation, if you can't improve the score of one (or more) particular problem.

Your solutions must print the exact same output as the reference solutions. Except for an optional trailing newline.

Since this is a Pyth practice, only programs written in the language Pyth are allowed.

**Answering:** Please spoiler your entire answer, except for your total score. It is intended that you do not look at other people's answers before submitting your own. You can create spoilers by putting \>! in front of every line, like:

```
>! Problem 1: V9m?>dNd0S9 (11 bytes)
>! Problem 2: VTN)VGN (7 bytes)
>! ...

```

I hope I haven't chosen too difficult or too trivial problems. Hoping for a lots of participators and for everyone to gain a few new insights into Pyth. **Happy golfing!**

### Problem 1:

Create the following 9x9 matrix and print it:

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

```

Reference solution (Link):

```
V9m?>dNd0S9 (11 bytes)

```

### Problem 2:

Print all digits and all letters on separate lines:

```
0
...
9
a
...
z

```

Reference solution (Link):

```
VTN)VGN (7 bytes)

```

### Problem 3:

Find the lexicographically smallest palindrome, that is lexicographically bigger or equal than an input string containing lowercase letters and is of the same than the input string.

```
a -> a
abc -> aca
adcb -> adda

```

Reference solution (Link):

```
hf&gTzqT_T^Glz (14 bytes)

```

### Problem 4:

Check, if a number is in the range \[0, input number). This should also work for floats.

```
4, 6 -> True
5.5, 6 -> True
6, 6 -> False
6, 6.1 -> True

```

Reference solution (Link):

```
&gQ0<QE (7 bytes)

```

The reference format is `to be tested value<newline>end value`. You can choose a different input format however. Important is only, that you accomplish the problem statement and produce the correct results.

### Problem 5:

Parse an input string of the format "\d+\[a-zA-Z\]+". Notice that the number really has to be a number, not a string containing digits.

```
'123Test' -> [123, 'Test']

```

Reference solution (Link):

```
A.ggk\Az,sGH (12 bytes)

```

### Problem 6:

Compute the sum of numbers, that are separated by one or multiple commas. You can assume that there is at least one number in the string.

```
11,2,,,3,5,,8 -> 29

```

Reference solution (Link):

```
svM:z",+"3 (10 bytes)

```

### Problem 7:

Read positive integers from the input until you get the number 0. Print the sum of all numbers.

Reference solution (Link):

```
WJE=+ZJ)Z (9 bytes)

```

### Problem 8:

Sum up all elements of a square matrix, except the ones of the main diagonal (left upper corner to right bottom corner).

Reference solution (Link):

```
-ssQs.e@bkQ (11 bytes)

```

# Answer
> 2 votes
# 54 bytes

Here are the intended solutions. Except for task 8 all solutions were found.

> 1. j.tmLdS9Z (9 bytes) using map for left-map, transpose and fill with zeros
> 2. \nMTjG (5 bytes) use newlines for map
> 3. h.f\_IZ1z (8 bytes) generate the possible strings with .f
> 4. %IQE (4 bytes) found a usecase, where the invariant operator needs 2 parameters
> 5. ,J.vz-zJ (8 bytes) .v evaluates only the first statement of a string and ignores the rest
> 6. ssMcz\\, (7 bytes) s"" = 0
> 7. u+GE0 (5 bytes) reduce until it reaches a know number
> 8. ss.DVQUQ (8 bytes) delete the diagonal using vectorization

# Answer
> 9 votes
# ~~59~~ ~~58~~ 56 bytes

Problem 1:

> `j.tmLdS9Z` (9 bytes)

Problem 2:

> `MTjG` (5 bytes) (The first character is a newline)

Problem 3:

> `h.f_IZ1z` (8 bytes)

Problem 4:

> `%IQE` (4 bytes)

Problem 5:

> `,J.vz-zJ` (8 bytes)

Problem 6:

> `srXz\,d7` (8 bytes)

Problem 7:

> `u+GE0` (5 bytes)

Problem 8:

> `ss.DR~hZQ` (9 bytes)

# Answer
> 2 votes
# 66 bytes

> 1. 10 bytes: `V9+mZN}hN9`
> 2. 6 bytes: `jUT)jG`
> 3. 8 bytes: `h.f_IZ1z`
> 4. (reference implementation) 7 bytes: `&gQ0<QE`
> 5. 11 bytes: `,sK-rzZG-zK`
> 6. 7 bytes: `ssMcz\,`
> 7. 8 bytes: `s<.Qx.QZ`
> 8. 9 bytes: `ss.eXbkZQ`

# Answer
> 2 votes
## ~~68~~ ~~67~~ ~~66~~ 65 bytes

Task 1

> 10 bytes: `V9m*d>dNS9`

Task 2

> 5 bytes: `\nMTjG`, where `\n` is a newline

Task 3

> 9 bytes: `h.fqZ_Z1z`

Task 4

> 5 bytes: `qQ%QE`

Task 5

> Reference solution, 12 bytes: `A.ggk\Az,sGH`

Task 6

> 7 bytes: `ssMcz\,`

Task 7

> 8 bytes: `s<.Qx.Q0`

Task 8

> 9 bytes: `ss.DVQUlQ`

# Answer
> 1 votes
# ~~60 59~~  57 bytes

> 1. **9 bytes**: `j.tmRdS9Z`

---

> 2. **6 bytes**: `jbUTjG`

---

> 3. **8 bytes**: `h.f_IZ1z`

---

> 4. **4 bytes**: `}sEU`

---

> 5. **8 bytes**: `,K.vz-zK`

---

> 6. **7 bytes**: `ssMcz\,`

---

> 7. **8 bytes**: `s<FxB.Q0`

---

> 8. **~~11 10~~ 7 bytes**: `ss.DVQU` Previous version: `ss.e+<bk>bh`

Note that I developed this solutions **completely** independently of other answers, although I am quite late to the party.

---
Tags: code-golf, multiple-holes, pyth
---


title: Bijective function ℤ → ℤⁿ

text:
# Question
Title: Bijective function ℤ → ℤⁿ
It is trivially possible to create a bijective function from \\$\mathbb{Z}\\$ (the set of all integers) to \\$\mathbb{Z}\\$ (e.g. the identity function).

It is also possible to create a bijective function from \\$\mathbb{Z}\\$ to \\$\mathbb{Z}^2\\$ (the set of all pairs of 2 integers; the cartesian product of \\$\mathbb{Z}\\$ and \\$\mathbb{Z}\\$). For example, we could take the lattice representing integer points on a 2D plane, draw a spiral from 0 outwards, and then encode pairs of integers as the distance along the spiral when it intersects that point.

(A function which does this with natural numbers is known as a pairing function.)

In fact, there exists a family of these bijective functions:

$$f\_k(x) : \mathbb{Z} \to \mathbb{Z}^k$$

## The Challenge

Define a family of functions \\$f\_k(x)\\$ (where \\$k\\$ is a positive integer) with the property that \\$f\_k(x)\\$ bijectively maps integers to \\$k\\$-tuples of integers.

Your submission should, given inputs \\$k\\$ and \\$x\\$, return \\$f\_k(x)\\$.

This is , so the shortest valid answer (measured in bytes) wins.

## Specifications

* Any family \\$f\_k(x)\\$ can be used as long as it fulfills the above criteria.
* You are encouraged to add a description of how your function family works, as well as a snippet to compute the inverse of the function (this is not included in your byte count).
* It is fine if the inverse function is uncomputable, as long as you can prove it the function is bijective.
* You can use any suitable representation for signed integers and lists of signed integers for your language, but you must allow inputs to your function to be unbounded.
* You only need to support values of \\$k\\$ up to 127.

# Answer
## Alice, ~~14~~ 12 bytes

```
/O
\i@/t&Yd&

```

Try it online!

Inverse function (not golfed):

```
/o     Q
\i@/~~\ /dt&Z

```

Try it online!

### Explanation

Alice has a built-in bijection between  and **2**, which can be computed with `Y` (unpack) and its inverse `Z` (pack). Here is an excerpt from the docs explaining the bijection:

> The details of the bijection are likely irrelevant for most use cases. The main point is that it lets the user encode two integers in one and extract the two integers again later on. By applying the pack command repeatedly, entire lists or trees of integers can be stored in a single number (although not in a particularly memory-efficient way). The mapping computed by the pack operation is a bijective function **2 → ℤ** (i.e. a one-to-one mapping). First, the integers **{..., -2, -1, 0, 1, 2, ...}** are mapped to the natural numbers (including zero) like **{..., 3, 1, 0, 2, 4, ...}** (in other words, negative integers are mapped to odd naturals and non-negative integers are mapped to even naturals). The two natural numbers are then mapped to one via the Cantor pairing function, which writes the naturals along the diagonals of the first quadrant of the integer grid. Specifically, **{(0,0), (1,0), (0,1), (2,0), (1,1), (0,2), (3,0), ...}** are mapped to **{0, 1, 2, 3, 4, 5, 6, ...}**. The resulting natural number is then mapped back to the integers using the inverse of the earlier bijection. The unpack command computes exactly the inverse of this mapping.

As alluded to above, we can use this unpack operation to map  to **k** as well. After applying it to the initial integer, we can unpack the second integer of the result again, which gives us a list of three integers. So **k-1** applications of `Y` give us **k** integers as the result.

We can compute the inverse by packing the list up with `Z` from the end.

So the program itself has this structure:

```
/O
\i@/...d&

```

This is just a basic template for a program which reads a variable number of decimal integers as input and prints a variable number as the result. So the actual code is really just:

```
t   Decrement k.
&   Repeat the next command k-1 times.
Y   Unpack.

```

One thing I'd like to address is "why would Alice have a built-in for a **ℤ → ℤ2** bijection, isn't that golfing language territory"? As with most of Alice's weirder built-ins, the main reason is Alice's design principle that every command has two meanings, one for Cardinal (integer) mode and one for Ordinal (string) mode, and these two meanings should be *somehow* related to give Cardinal and Ordinal mode the feeling that they are mirror universes where things are sort of the same but also different. And quite often I had a command for one of the two modes I wanted to add, and then had to figure out what other command to pair it with.

In the case of `Y` and `Z` Ordinal mode came first: I wanted to have a function to interleave two strings (zip) and separate them again (unzip). The quality of this that I wanted to capture in Cardinal mode was to form one integer from two and be able to extract the two integers again later, which makes such a bijection the natural choice.

I also figured that this would actually be very useful outside of golfing, because it lets you store an entire list or even tree of integers in a single unit of memory (stack element, tape cell or grid cell).
> 20 votes

# Answer
# Python, ~~96~~ 93 bytes

```
def f(k,x):
 c=[0]*k;i=0
 while x:v=(x+1)%3-1;x=x//3+(v<0);c[i%k]+=v*3**(i//k);i+=1
 return c

```

This works in principle by converting the input number `x` to balanced ternary, and then distributing the trits (ternary digits) least-significant first between the different coordinates in a round-robin fashion. So for `k=2` for example, every even positioned trit would contribute to the `x` coordinate, and every odd positioned trit would contribute to the `y` coordinate. For `k=3` you'd have the first, fourth and seventh trits (etc...) contributing to `x`, while the second, fifth and eighth contribute to `y`, and the third, sixth and ninth contribute to `z`.

For example, with `k=2`, lets look at `x=35`. In balanced ternary, `35` is `110T` (using the Wikipedia article's notation where `T` represents a `-1` digit). Dividing the trits up gives `1T` (the first and third trits, counting from the right) for the `x` coordinate and `10` (second and fourth trits) for the `y` coordinate. Converting each coordinate back to decimal, we get `2, 3`.

Of course, I'm not actually converting the whole number to balanced ternary at once in the golfed code. I'm just computing one trit at a time (in the `v` variable), and adding its value directly to the appropriate coordinate.

Here's an ungolfed inverse function that takes a list of coordinates and returns a number:

```
def inverse_f(coords):
    x = 0
    i = 0
    while any(coords):
        v = (coords[i%3]+1) % 3 - 1
        coords[i%3] = coords[i%3] // 3 + (v==-1)
        x += v * 3**i
        i += 1
    return x

```

My `f` function is perhaps notable for its performance. It uses only `O(k)` memory and takes `O(k) + O(log(x))` time to find the results, so it can work with very large input values. Try `f(10000, 10**10000)` for instance, and you'll get an answer pretty much instantly (adding an extra zero to the exponent so `x` is `10**100000` makes it take 30 seconds or so on my old PC). The inverse function is not as fast, mostly because it's hard for it to tell when it's done (it scans all the coordinates after each change, so it takes something like `O(k*log(x))` time). It could probably be optimized to be faster, but it's probably fast enough for normal parameters already.
> 11 votes

# Answer
# Husk, 10 bytes

```
§~!oΠR€Θİ±

```

Try it online!

The inverse function is also 10 bytes.

```
§o!ȯ€ΠRΘİ±

```

Try it online!

## Explanation

Forward direction:

```
§~!oΠR€Θİ±  Implicit inputs, say k=3 and x=-48
        İ±  The infinite list [1,-1,2,-2,3,-3,4,-4,..
       Θ    Prepend 0: [0,1,-1,2,-2,3,-3,4,-4,..
 ~    €     Index of x in this sequence: 97
§    R      Repeat the sequence k times: [[0,1,-1,..],[0,1,-1,..],[0,1,-1,..]]
   oΠ       Cartesian product: [[0,0,0],[1,0,0],[0,1,0],[1,1,0],[-1,0,0],[0,0,1],..
  !         Index into this list using the index computed from x: [-6,1,0]

```

Reverse direction:

```
§o!ȯ€ΠRΘİ±  Implicit inputs, say k=3 and y=[-6,1,0]
     ΠRΘİ±  As above, k-wise Cartesian product of [0,1,-1,2,-2,..
   ȯ€       Index of y in this sequence: 97
§o!         Index into the sequence [0,1,-1,2,-2,.. : -48

```

The Cartesian product built-in `Π` behaves nicely for infinite lists, enumerating each **k**-tuple exactly once.
> 9 votes

# Answer
# Wolfram Language (Mathematica), 61 bytes

```
SortBy[Range[-(x=2Abs@#+Boole[#>=0]),x]~Tuples~#2,#.#&][[x]]&

```

Try it online!

(Takes the integer and then the length of the tuple as input.)

Inverse:

```
If[OddQ[#],#-1,-#]/2&@Tr@Position[SortBy[Range[-(x=Ceiling@Norm@#),x]~Tuples~Length@#,#.#&],#]&

```

Try it online!

# How it works

The idea is straightforward: we turn the integer input into a positive integer (by mapping 0,1,2,3,... to 1,3,5,7,... and -1,-2,-3,... to 2,4,6,...) and then index into all the *k*-tuples, sorted by distance from the origin and then by Mathematica's default tie-breaking.

But we can't use an infinite list, so when we're looking for the *n*th *k*-tuple, we only generate *k*-tuples of integers in the range {-*n*,...,*n*}. This is guaranteed to be enough, because the *n*th smallest *k*-tuple by norm has norm less than *n*, and all tuples of norm *n* or less are included in this list.

For the inverse, we just generate a long enough list of *k*-tuples, find the position of the given *k*-tuple in that list, and then invert the "fold into a positive integer" operation.
> 7 votes

# Answer
# J, 7 Bytes

`#.,|:#:`

The J code to do this embarrassingly simple

A very simple pairing function (or, tupling function) is to simply interleave the digits of the binary expansion of each of the numbers. So, for instance `(47, 79)` would be paired as such:

```
1_0_0_1_1_1_1
 1_0_1_1_1_1
-------------
1100011111111

```

or, 6399. Obviously, we can trivially generalize to any n-tuple.

Let's examine how this works verb by verb.

`#:` is anti-base two, when used monadically it returns the binary expansion of a number. `#: 47 79` gives the result:

```
0 1 0 1 1 1 1
1 0 0 1 1 1 1

```

`|:` is the transpose operator, which simply rotates an array. Rotating the result of `#: 47 79` gives:

```
0 1
1 0
0 0
1 1
1 1
1 1
1 1

```

When used monadically, `,` is the ravel operator, it produces a 1-dimensional list from an table:

```
0 1 1 0 0 0 1 1 1 1 1 1 1 1

```

Finally, `#.` converts the binary expansion back, giving us the result `6339`.

This solution will work for any string of integers.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 107 bytes

```
(-1)^#⌈#/2⌉&@Nest[{w=⌊(√(8#+1)-1)/2⌋;x=#-w(w+1)/2,w-x}~Join~{##2}&@@#&,{2Abs@#-Boole[#<0]},#2-1]&

```

Try it online!

## Inverse, 60 bytes

```
(-1)^#⌈#/2⌉&@Fold[+##(1+##)/2+#&,2Abs@#-Boole[#<0]&/@#]&

```

Try it online!

## Explanation:

Z -\> N0 via `f(n) = 2n if n>=0 and -2n-1 if n<0`

N0 -\> N0^2 via inverse of the pairing function

N0 -\> N0^k Repeatedly apply the above to the leftmost number until we get length `k`

N0^k -\> Z^k via `f(n) = (-1)^n * ceil(n/2)`, element-wise

---

# Mathematica, 101 bytes

```
(-1)^#⌈#/2⌉&@Nest[{a=#~IntegerExponent~2+1,#/2^a+1/2}~Join~{##2}&@@#&,{2Abs@#+Boole[#<=0]},#2-1]&

```

Similar to above (uses N instead of N0), but uses the inverse of the bijection f: N^2 -\> N via `f(a, b) = 2^(a - 1)(2b - 1)`
> 2 votes

# Answer
# JavaScript, 155 bytes

```
f=k=>x=>(t=x<0?1+2*~x:2*x,h=y=>(g=(v,p=[])=>1/p[k-1]?v||t--?0:p.map(v=>v&1?~(v/2):v/2):[...Array(1+v)].map((_,i)=>g(v-i,[...p,i])).find(u=>u))(y)||h(y+1))(0)

```

```
f=k=>x=>(t=x<0?1+2*~x:2*x,h=y=>(g=(v,p=[])=>1/p[k-1]?v||t--?0:p.map(v=>v&1?~(v/2):v/2):[...Array(1+v)].map((_,i)=>g(v-i,[...p,i])).find(u=>u))(y)||h(y+1))(0)
```

```
<p>k = <input id=k value=2>
<p>from <input id=a value=-5>
<p>to <input id=b value=5>
<p><button type="button" onclick="for(o.value='',i=+a.value;i<=b.value;i++)o.value+=[i,f(+k.value)(i)].join(':')+'\n';">generate</button>
<p><pre><output id=o>
```

Prettify version:

```
k => x => {
  // Map input to non-negative integer
  if (x > 0) t = 2 * x; else t = 2 * -x - 1;
  // we try to generate all triples with sum of v
  g = (v, p = []) => {
    if (p.length === k) {
      if (v) return null;
      if (t--) return null;
      // if this is the t-th one we generate then we got it
      return p;
    }
    for (var i = 0; i <= v; i++) {
      var r = g(v-i, [...p, i]);
      if (r) return r;
    }
  }
  // try sum from 0 to infinity
  h = x => g(x) || h(x + 1);
  // map tuple of non-negative integers back
  return h(0).map(v => {
    if (v % 2) return -(v + 1) / 2
    else return v / 2;
  });
}

```
* First, we map all integers to all non-negative integers one by one:
    + if n \> 0 then result = n * 2
    + otherwise result = -n * 2 - 1
* Second, we give all tuples with k-length non-negative integers an order:
    + calculate sum of all element, smaller one comes first
    + if sum is equal, compare from left to right, smaller one comes first
    + As a result, we got the map for all non-negative integers to tuples with k non-negative integers
* Finally, map non-negative integers in tuple given in second step to all integers with similar formula in first step
> 2 votes

# Answer
# Perl 6, 148 bytes

```
my@s=map ->\n{|grep {n==abs any |$_},(-n..n X -n..n)},^Inf;my&f={$_==1??+*!!do {my&g=f $_-1;my@v=map {.[0],|g .[1]},@s;->\n{@v[n>=0??2*n!!-1-2*n]}}}

```

Try it online!

Ungolfed:

```
sub rect($n) {
    grep ->[$x,$y] { abs($x|$y) == $n }, (-$n..$n X -$n..$n);
}

my @spiral = map { |rect($_) }, ^Inf;

sub f($k) {
    if ($k == 1) {
        -> $_ { $_ }
    } else {
        my &g = f($k-1);
        my @v = map -> [$x, $y] { $x, |g($y) }, @spiral;
        -> $_ { $_ >= 0 ?? @v[2*$_] !! @v[-1-2*$_] }
    }
}

```

Explanation:

* `rect($n)` is a helper function that generates the coordinates of the integral points on the edge of a rectangle from coordinates `(-$n,$n)` to `($n, $n)`.
* `@spiral` is a lazy, infinite list of the integral points on the edges of rectangles of increasing size, starting from 0.
* `f($k)` returns a function which is a bijection from the integers to `$k`-tuples of integers.

If `$k` is `1`, `f` returns the identity mapping `-> $_ { $_ }`.

Otherwise, `&g` is the recursively obtained mapping from the integers to `$k-1`-tuples of integers.

Then, we `@spiral` out from the origin, and at each point form a `$k`-tuple by taking the X-coordinate and the flattened result of calling `g` with the Y-coordinate. This lazily generated mapping is stored in the array `@v`.

`@v` contains all `$k`-tuples starting with index 0, so to extend the indexing to the negative integers, we just map positive inputs to the even numbers and negative inputs to the odd numbers. A function (closure) is returned which looks up elements of `@v` in this way.
> 2 votes

# Answer
# JavaScript, 112 bytes

```
k=>x=>(r=Array(k).fill(''),[...`${x<0?2*~x+1:2*x}`].map((c,i,s)=>r[(s.length-i)%k]+=c),r.map(v=>v&1?~(v/2):v/2))

```
1. convert to non-negative
2. (n\*k+i)th digit to i-th number
3. convert back
> 1 votes

# Answer
# 05AB1E, 20 bytes

```
[D_#>3‰`<s])sô0ζεR3β

```

Try it online! Port of @Blckknght's answer. Inverse, 17 bytes:

```
[Z_#>3‰ø`<s])˜R3β

```

Try it online!
> 1 votes

# Answer
# Jelly, 15 bytes

```
µ<1ạḤðŒRṗAS$Þ⁸ị

```

Try it online!

1-indexed.

Inverse:

```
AṀ×LŒRṗLAS$Þiµ:2NḂ}¡

```

Try it online!
> 0 votes

---
Tags: code-golf, math, number, open-ended-function
---


title: Gimli, make it even shorter?

text:
# Question
Title: Gimli, make it even shorter?
I'm one of the authors of Gimli. We already have a 2-tweet (280 chars) version in C but I would like to see how small it can get.

Gimli (paper,website) is a high speed with high security level cryptographic permutation design that will be presented at the Conference on Cryptographic Hardware and Embedded Systems (CHES) 2017 (September 25-28).

# The task

> As usual: to make the smalled usable implementation of Gimli in the language of your choice.
>
> It should be able to **take as input 384 bits** (or 48 bytes, or 12 unsigned int...) and **return (may modify in place if you use pointers) the result of Gimli** applied on these 384 bits.

Input conversion from decimal, hexadecimal, octal or binary is allowed.

## Potential corner cases

Integer encoding is assumed to be little-endian (e.g. what you probably already have).

You may rename `Gimli` into `G` but it must still be a function call.

## Who wins?

This is code-golf so the shortest answer in bytes wins! Standard rules apply of course.

A reference implementation is provided below.

## Note

Some concern has been raised:

> "hey gang, please implement my program for free in other languages so I don't have to" (thx to @jstnthms)

My answer is as follow:

> I can easily do it in Java, C#, JS, Ocaml... It is more for the fun. Currently We (the Gimli team) have it implemented (and optimized) on AVR, Cortex-M0, Cortex-M3/M4, Neon, SSE, SSE-unrolled, AVX, AVX2, VHDL and Python3. :)

---

## About Gimli

### The state

Gimli applies a sequence of rounds to a 384-bit state. The state is represented as a parallelepiped with dimensions 3×4×32 or, equivalently, as a 3×4 matrix of 32-bit words.

Each round is a sequence of three operations:

* a non-linear layer, specifically a 96-bit SP-box applied to each column;
* in every second round, a linear mixing layer;
* in every fourth round, a constant addition.

### The non-linear layer.

The SP-box consists of three sub-operations: rotations of the first and second words; a 3-input nonlinear T-function; and a swap of the first and third words.

### The linear layer.

The linear layer consists of two swap operations, namely Small-Swap and Big-Swap. Small-Swap occurs every 4 rounds starting from the 1st round. Big-Swap occurs every 4 rounds starting from the 3rd round.

### The round constants.

There are 24 rounds in Gimli, numbered 24,23,...,1. When the round number r is 24,20,16,12,8,4 we XOR the round constant (0x9e377900 XOR r) to the first state word.

### reference source in C

```
#include <stdint.h>

uint32_t rotate(uint32_t x, int bits)
{
  if (bits == 0) return x;
  return (x << bits) | (x >> (32 - bits));
}

extern void gimli(uint32_t *state)
{
  int round;
  int column;
  uint32_t x;
  uint32_t y;
  uint32_t z;

  for (round = 24; round > 0; --round)
  {
    for (column = 0; column < 4; ++column)
    {
      x = rotate(state[    column], 24);
      y = rotate(state[4 + column],  9);
      z =        state[8 + column];

      state[8 + column] = x ^ (z << 1) ^ ((y&z) << 2);
      state[4 + column] = y ^ x        ^ ((x|z) << 1);
      state[column]     = z ^ y        ^ ((x&y) << 3);
    }

    if ((round & 3) == 0) { // small swap: pattern s...s...s... etc.
      x = state[0];
      state[0] = state[1];
      state[1] = x;
      x = state[2];
      state[2] = state[3];
      state[3] = x;
    }
    if ((round & 3) == 2) { // big swap: pattern ..S...S...S. etc.
      x = state[0];
      state[0] = state[2];
      state[2] = x;
      x = state[1];
      state[1] = state[3];
      state[3] = x;
    }

    if ((round & 3) == 0) { // add constant: pattern c...c...c... etc.
      state[0] ^= (0x9e377900 | round);
    }
  }
}

```

### Tweetable version in C

This might not be the smallest usable implementation but we wanted to have a C standard version (thus no UB, and "usable" in a library).

```
#include<stdint.h>
#define P(V,W)x=V,V=W,W=x
void gimli(uint32_t*S){for(long r=24,c,x,y,z;r;--r%2?P(*S,S[1+y/2]),P(S[3],S[2-y/2]):0,*S^=y?0:0x9e377901+r)for(c=4;c--;y=r%4)x=S[c]<<24|S[c]>>8,y=S[c+4]<<9|S[c+4]>>23,z=S[c+8],S[c]=z^y^8*(x&y),S[c+4]=y^x^2*(x|z),S[c+8]=x^2*z^4*(y&z);}

```

### Test vector

The following input generated by

```
for (i = 0;i < 12;++i) x[i] = i * i * i + i * 0x9e3779b9;

```

and "printed" values by

```
for (i = 0;i < 12;++i) {
  printf("%08x ",x[i])
  if (i % 4 == 3) printf("\n");
}

```

thus:

```
00000000 9e3779ba 3c6ef37a daa66d46
78dde724 1715611a b54cdb2e 53845566
f1bbcfc8 8ff34a5a 2e2ac522 cc624026

```

should return:

```
ba11c85a 91bad119 380ce880 d24c2c68
3eceffea 277a921c 4f73a0bd da5a9cd8
84b673f0 34e52ff7 9e2bef49 f41bb8d6

```

# Answer
> 4 votes
## CJam (114 chars)

```
{24{[4/z{[8ZT].{8\#*G8#:Mmd+}__)2*\+.^W%\[_~;&8*\~@1$|2*@@&4*].^Mf%}%z([7TGT]R=4e!=\f=(2654435608R-_4%!*^\@]e_}fR}

```

This is an anonymous block (function): if you want to name it `G` then append `:G`. In CJam assigned names can only be single upper-case letters. There's space to append a comment `e# Gimli in CJam` and have characters left in a single tweet.

Online test

### Dissection

```
{                                e# Define a block
  24{                            e# For R=0 to 23...
    [                            e#   Collect values in an array
      4/z                        e#     Transpose to columns
      {                          e#     Map over each column
        [8ZT].{8\#*G8#:Mmd+}     e#       Rotations, giving [x y z]
        __)2*\+.^W%\             e#       => [y^z x^y x^z*2] [x y z]
        [_~;&8*\~@1$|2*@@&4*].^  e#       => [x' y' z']
        Mf%                      e#       Map out any bits which overflowed
      }%
      z                          e#    Transpose to rows
      ([7TGT]R=4e!=\f=           e#    Permute first row
      (2654435608R-_4%!*^        e#    Apply round constant to first element
      \@                         e#    Put the parts in the right order
    ]e_                          e#  Finish collecting in array and flatten
  }fR
}

```

# Answer
> 16 votes
# C (gcc), 237 bytes

```
#define P(a,l)x=a;a=S[c=l>>r%4*2&3];S[c]=x;
r,c,x,y,z;G(unsigned*S){
for(r=24;r;*S^=r--%4?0:0x9e377901+r){
for(c=4;c--;*S++=z^y^8*(x&y))
x=*S<<24|*S>>8,y=S[4]<<9|S[4]>>23,z=S[8],S[8]=x^2*z^4*(y&z),S[4]=y^x^2*(x|z);
S-=4;P(*S,33)P(S[3],222)}}

```

I probably gained bytes with my swapping method, but it's too cute not to use.

# Answer
> 4 votes
## C, 268 chars (268 bytes) using uint32\_t

NB Since the original code uses `<stdint.h>` and types `S` as `uint32_t *`, I think the use of `long` is a cheat to get into 280 chars at the cost of the portability which is the reason for using `uint32_t` in the first place. If for fairness of comparison we require consistent use of `uint32_t` and the explicit signature `void gimli(uint32_t *)`, the original code is really 284 chars, and orlp's code is 276 chars.

```
#include<stdint.h>
#define R(V)x=S[V],S[V]=S[V^y],S[V^y]=x,
void gimli(uint32_t*S){for(uint32_t r=24,x,y,z,*T;r--;y=72>>r%4*2&3,R(0)R(3)*S^=y&1?0x9e377901+r:0)for(T=S+4;T-->S;*T=z^y^8*(x&y),T[4]=y^x^2*(x|z),T[8]=x^2*z^4*(y&z))x=*T<<24|*T>>8,y=T[4]<<9|T[4]>>23,z=T[8];}

```

---

This can be split into two tweets with continuation markers as

```
#include<stdint.h>
#define R(V)x=S[V],S[V]=S[V^y],S[V^y]=x,
void gimli(uint32_t*S){for(uint32_t r=24,x,y,z,*T;r--;y=72>>r%4*2&3,R(0)R(3)// 1

```

and

```
*S^=y&1?0x9e377901+r:0)for(T=S+4;T-->S;*T=z^y^8*(x&y),T[4]=y^x^2*(x|z),T[8]=x^2*z^4*(y&z))x=*T<<24|*T>>8,y=T[4]<<9|T[4]>>23,z=T[8];}// 2/2

```

# Answer
> 2 votes
# Java (OpenJDK 8), ~~351~~ ~~343~~ ~~339~~ ~~320~~ ~~318~~ 247 + 56 bytes

Just a near 1:1 port of the reference to start golfing from.

```
void f(int[]x,int y,int z){int q=x[y];x[y]=x[z];x[z]=q;}

s->{for(int r=24,c,x,y,z;r>0;--r){for(c=0;c<4;x=s[c]<<24|s[c]>>>8,y=s[4+c]<<9|s[4+c]>>>23,z=s[8+c],s[8+c]=x^z<<1^(y&z)<<2,s[4+c]=y^x^(x|z)<<1,s[c++]=z^y^(x&y)<<3);if((r&3)==2){f(s,0,2);f(s,1,3);}if((r&3)<1){f(s,0,1);f(s,2,3);s[0]^=0x9e377900|r;}}}

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 231 bytes

```
s=>{for(r=25;--r;[a,b,c,d,...e]=s,s=r&1?s:r&2?[c,d,a,b,...e]:[b,a,d,c,...e],s[0]^=r&3?0:0x9e377900|r)for(c=4;c--;x=s[c]<<24|s[c]>>>8,y=s[j=c+4]<<9|s[j]>>>23,z=s[c+8],s[c+8]=x^z*2^(y&z)*4,s[j]=y^x^(x|z)*2,s[c]=z^y^(x&y)*8);return s}

```

### Demo

```
let f =

s=>{for(r=25;--r;[a,b,c,d,...e]=s,s=r&1?s:r&2?[c,d,a,b,...e]:[b,a,d,c,...e],s[0]^=r&3?0:0x9e377900|r)for(c=4;c--;x=s[c]<<24|s[c]>>>8,y=s[j=c+4]<<9|s[j]>>>23,z=s[c+8],s[c+8]=x^z*2^(y&z)*4,s[j]=y^x^(x|z)*2,s[c]=z^y^(x&y)*8);return s}

console.log(
  f([
    0x00000000, 0x9e3779ba, 0x3c6ef37a, 0xdaa66d46,
    0x78dde724, 0x1715611a, 0xb54cdb2e, 0x53845566,
    0xf1bbcfc8, 0x8ff34a5a, 0x2e2ac522, 0xcc624026
  ])
  .map(x=>(x >>> 0).toString(16)).join(' ')
)
```

# Answer
> 1 votes
## 32-bit x86 assembler (112 bytes)

(\__cdecl calling convention)

```
            pusha
            mov     ecx, 9E377918h
    loc_6:  mov     esi, [esp+24h]
            push    esi
            push    4
            pop     ebx
    loc_E:  lodsd
            ror     eax, 8
            mov     ebp, [esi+0Ch]
            rol     ebp, 9
            mov     edx, [esi+1Ch]
            push    eax
            push    ebp
            lea     edi, [edx+edx]
            and     ebp, edx
            shl     ebp, 2
            xor     edi, ebp
            xor     eax, edi
            mov     [esi+1Ch], eax
            pop     ebp
            pop     eax
            push    eax
            push    ebp
            xor     ebp, eax
            or      eax, edx
            shl     eax, 1
            xor     ebp, eax
            mov     [esi+0Ch], ebp
            pop     ebp
            pop     eax
            xor     edx, ebp
            and     eax, ebp
            shl     eax, 3
            xor     edx, eax
            push    edx
            dec     ebx
            jnz     short loc_E
            pop     esi
            pop     ebp
            pop     ebx
            pop     eax
            pop     edi
            mov     dl, cl
            and     dl, 3
            jnz     short loc_5B
            xchg    eax, ebx
            xchg    esi, ebp
            xor     eax, ecx
    loc_5B: cmp     dl, 2
            jnz     short loc_63
            xchg    eax, ebp
            xchg    esi, ebx
    loc_63: stosd
            xchg    eax, ebx
            stosd
            xchg    eax, ebp
            stosd
            xchg    eax, esi
            stosd
            dec     cl
            jnz     short loc_6
            popa
            retn

```

Tweetable version (z85-format Base85 encoding):

```
v7vb1h>C}HbQuA91y51A:oWYw48G)?I=H/]rGf9Na>sA.DWu06{6f#TEC^CM:#IeA-cstx7:>!VfVf#u*YB&mP(tuCl*+7eENBP)$:)Lh!k}t$^wM51j%LDf$HMAg2bB^MQP
```

---
Tags: code-golf, cryptography
---


title: Uniquify Identifiers

text:
# Question
Title: Uniquify Identifiers
# Introduction

By definition, unique identifiers should be unique. Having multiple identifiers that are the same causes one to retrieve unexpected data. But with data arriving concurrently from multiple sources, it can be difficult to ensure uniqueness. Write a function the uniquifies a list of identifiers.

This is possibly the worst puzzle fluff I have written, but you get the idea.

# Requirements

Given a list of zero or more positive integers, apply the following rules to each number from first to last:

* If the number is the first of its kind, keep it.
* If the number has previously been encountered, replace it with the lowest positive integer not found anywhere in the entire input list or any existing output.

For the solution:

* The solution may be a program or a function.
* The input may be a string, an array, passed as arguments, or keyboard input.
* The output may be a string, an array, or printed to the screen.
* All numbers in the output list are distinct.

# Assumptions

* The input list is clean. It only contains positive integers.
* A positive integer has the range from 1 to 231-1.
* Less than 256 MB of memory is available for your program's variables. (Basically, no 2,147,483,648-element arrays are permitted.)

# Test Cases

```
Input:  empty
Output: empty

Input:  5
Output: 5

Input:  1, 4, 2, 5, 3, 6
Output: 1, 4, 2, 5, 3, 6

Input:  3, 3, 3, 3, 3, 3
Output: 3, 1, 2, 4, 5, 6

Input:  6, 6, 4, 4, 2, 2
Output: 6, 1, 4, 3, 2, 5

Input:  2147483647, 2, 2147483647, 2
Output: 2147483647, 2, 1, 3

```

# Scoring

Just a simple code golf. Lowest byte count by this time next week wins.

# Answer
> 11 votes
# Brachylog, 8 bytes

```
{|∧ℕ₁}ᵐ≠

```

Try it online!

### Explanation

```
{    }ᵐ     Map on the Input:
              Input = Output…
 |            …or…
  ∧ℕ₁         …Output is in [1,+inf)
       ≠    All elements of the output must be different
            (Implicit labeling)

```

# Answer
> 8 votes
# Java 8, ~~158~~ 144 bytes

```
a->{int m=0;String r="",c=",",b=r;for(int x:a)b+=x+c;for(int x:a)if(r.contains(x+c)){for(;(r+b).contains(++m+c););r+=m+c;}else r+=x+c;return r;}

```
* `.contains(m+c);m++)` to `.contains(++m+c);)` to save 1 byte, and simultaneously converted to Java 8 to save 13 more bytes.

**Explanations:**

Try it here.

```
a->{                      // Method with integer-array parameter and String return-type
  int m=0;                //  Lowest integer
  String r="",            //  Result-String
         c=",",           //  Comma delimiter for result String
         b=r;for(int x:a)b+=x+c;
                          //  Input array as String
  for(int x:a)            //  Loop (2) over the integers in the array
    if(r.contains(x+c)){  //   If the result already contains this integer
      for(;(r+b).contains(++m+c););
                          //    Inner (3) as long as either the result-String or array-String contains the lowest integer
                          //     and raise the lowest integer before every iteration by 1
      r+=m+c;             //    Append the result with this lowest not-present integer
    }else                 //   Else:
      r+=x+c;             //    Append the result-String with the current integer
                          //  End of loop (2) (implicit / single-line body)
  return r;               //  Return the result-String
}                         // End of method

```

# Answer
> 7 votes
# Ruby, 63 bytes

```
->a{r=*0..a.size;r.map{|i|[a[i]]-a[0,i]==[]?a[i]=(r-a)[1]:0};a}

```

Try it online!

**Explanation**

```
->a{                                    # Anonymous function with one argument
    r=*0..a.size;                       # Numbers from 0 to array size
    r.map{|i|                           # For all numbers in range:
        [a[i]]                          #  Get array with just a[i]
              -a[0,i]                   #  Remove elements from array that are
                                        #    also in a[0..i-1]
                    ==[]?               #  Check if result is an empty array
                        a[i]=           #  If true, set a[i] to:
                             (r-a)      #   Remove elements from number range
                                        #     that are also in input array
                                  [1]   #   Get second element (first non-zero)
                        :0};            #  If false, no-op
                            a}          # Return modified array

```

# Answer
> 7 votes
## JavaScript (ES6), 49 bytes

```
a=>a.map(g=(e,i)=>a.indexOf(e)-i?g(++n,-1):e,n=0)

```

# Answer
> 6 votes
# 05AB1E, ~~17~~ ~~16~~ 18 bytes

```
vy¯yåi¹gL¯K¹K¬}ˆ}¯

```

Try it online!

**Explanation**

```
v                    # for each y in input
 y                   # push y
  ¯yåi               # if y exist in global list
      ¹gL            # push [1 ... len(input)]
         ¯K          # remove any number that is already in global list
           ¹K        # remove any number that is in the input
             ¬       # get the first (smallest)
              }      # end if
               ˆ     # add to global list
                }¯   # end loop, push and output global list

```

# Answer
> 6 votes
# PHP, 121 Bytes

```
<?$n=array_diff(range(0,count($g=$_GET)),$g);sort($n);$r=[];foreach($g as$v)$r[]=in_array($v,$r)?$n[++$i]:$v;print_r($r);

```

Online Version

Expanded

```
$n=array_diff(range(0,count($g=$_GET)),$g); # create array of ascending values which are not in input array plus zero
sort($n); # minimize keys
$r=[];  # empty result array
foreach($g as$v) # loop input array
  $r[]=in_array($v,$r)?$n[++$i]:$v; # if value is not in result array add value else take new unique value skip zero through ++$i
print_r($r); # output result array

```

# Answer
> 5 votes
# Haskell, ~~79~~ 76 bytes

EDIT:

* -3 bytes: @nimi saw that `head` could be replaced by a pattern match.

`([]#)` is an anonymous function taking and returning a list. Use like `([]#)[2147483647, 2, 2147483647, 2]`.

```
(?)=notElem
s#(x:y)|z:_<-[x|x?s]++filter(?(s++y))[1..]=z:(z:s)#y
_#n=n
([]#)

```

Try it online!

# How it works

* `?` is an abbreviated operator for checking if an element is absent from a list.
* `s#l` handles the list of integers `l`, given a list `s` of integers already used.
    + `x` is the next integer to look at, `y` the remaining ones.
    + `z` is the integer chosen for the next spot. It's `x` if `x` is not an element of `s`, and the first positive integer neither in `s` nor in `y` otherwise.
    + `(z:s)#y` then recurses with `z` added to the used integer list.
    + `n` is an empty list, since nonempty lists have been handled in the previous line.
* The main function `([]#)` takes a list, and calls `#` with it as second argument, and an empty list for the first argument.

# Answer
> 5 votes
# Python 2, 77 79 bytes

```
a=input();u=[];j=1
for x in a:
 u+=[[x,j][x in u]]
 while j in u+a:j+=1
print u

```

Takes keyboard input, like `[3, 3, 3, 3, 3, 3]`.

Just keep track of the smallest positive integer `j` not used so far. For each element `x` of the input, output `x` if `x` hasn't already been used, otherwise output `j`. Finally, update `j` each time you output something.

EDITED: to fix a mistake handling input of `[6, 6, 4, 4, 2, 2]`. Thanks to @Rod for pointing out the mistake as well as a fix. The mistake was that, in the event of a duplicate entry, it would output the smallest number unused to that point in the list, even if that output appeared later in the input. (This was wrong, as clarified in the post and the comments, but I still messed it up somehow.) Anyway, the fix was to simply add the input list, `a`, to the set of values that could not be output in that case.

# Answer
> 4 votes
# APL (Dyalog 16.0), 34 bytes

```
(s↑v~⍨⍳⌈/v+s←+/b←(⍳≢v)≠⍳⍨v)@{b}v←⎕

```

# Answer
> 3 votes
# Pyth, ~~21~~ 20 bytes

```
~~.b?}NPY@-UhlQQ=hZNQ._~~
m?}edPd@-SlQQ~hZed._

```

Test suite

I'll add an explanation when I have the time.

# Answer
> 3 votes
# C, ~~169 bytes~~ 133 bytes

input = array a, output = modified array a

```
i=1,j,k,l;void f(int*a,int n){for(;i<n;i++)for(j=i-1;j>=0;j--)if(a[i]==a[j]){l=1;for(k=0;k<n;)if(l==a[k])k=l++?0:0;else k++;a[i]=l;}}

```

formatted

```
int i, j, k, l;
void f(int* a, int n)
{
    for (i = 1; i<n; i++)
        for (j = i - 1; j >= 0; j--)
            if (a[i] == a[j])
            {
                l = 1;
                for (k = 0; k<n;)
                    if (l == a[k])
                        k = l++ ? 0 : 0;
                    else
                        k++;
                a[i] = l;
            }
}

```

Too many bytes wasted for these loop. Does anybody think of shorten the code by inventing a new algorithm (which use less loop)? I was thinking but havent found one.

# Answer
> 3 votes
## C#, 135 bytes

---

### Golfed

```
(int[] i)=>{for(int x=1,v,m=0,l=i.Length,y;x<l;x++){v=i[x];for(y=0;y<l&&v==i[x]?y<x:y<l;y++)if(i[y]==v){v=++m;y=-1;}i[x]=v;}return i;};

```

---

### Ungolfed

```
( int[] i ) => {
   for( int x = 1, v, m = 0, l = i.Length, y; x < l; x++ ) {
      v = i[ x ];

      for( y = 0; y < l && v == i[ x ] ? y < x : y < l ; y++ )
         if( i[ y ] == v ) {
            v = ++m;
            y = -1;
         }

      i[ x ] = v;
   }

   return i;
};

```

---

### Ungolfed readable

```
// Takes an array of Int32 objects ( 32-byte signed integers )
( int[] i ) => {

   // Cycles through each element on the array
   //   x: Scan position, starts at the 2nd element
   //   v: Value being processed
   //   m: The next minimum value to replace
   //   l: Size of the array, to save some byte count
   for( int x = 1, v, m = 0, l = i.Length, y; x < l; x++ ) {

      // Hold the value
      v = i[ x ];

      // Re-scan the array for a duplicate value up the the current position ( 'x' ) IF
      //   ... the currently hold value hasn't been modified
      //   ... otherwise, re-scans the entire array to find a suitable value to replace
      for( y = 0; y < l && v == i[ x ] ? y < x : y < l ; y++ )

         // Check if 'v' shares the same value with other element
         if( i[ y ] == v ) {

            // Set 'v' to the minimum value possible
            v = ++m;

            // Reset the scan position to validate the new value
            y = -1;
         }

      // Set the 'v' to the array
      i[ x ] = v;
   }

   // Return the array
   return i;
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
         Func<Int32[], Int32[]> f = ( int[] i ) => {
            for( int x = 1, v, m = 0, l = i.Length, y; x < l; x++ ) {
               v = i[ x ];

               for( y = 0; y < l && v == i[ x ] ? y < x : y < l ; y++ )
                  if( i[ y ] == v ) {
                     v = ++m;
                     y = -1;
                  }

               i[ x ] = v;
            }

            return i;
         };

         List<Int32[]>
            testCases = new List<Int32[]>() {
               new Int32[] { },
               new Int32[] { 5 },
               new Int32[] { 1, 4, 2, 5, 3, 6 },
               new Int32[] { 3, 3, 3, 3, 3, 3 },
               new Int32[] { 6, 6, 4, 4, 2, 2 },
               new Int32[] { 2147483647, 2, 2147483647, 2 },
            };

         foreach( Int32[] testCase in testCases ) {
            Console.WriteLine( $" Input: {String.Join( ",", testCase )}\nOutput: {string.Join( ",", f( testCase ) )}\n" );
         }

         Console.ReadLine();
      }
   }
}

```

---

### Releases

* **v1.0** \- `135 bytes` \- Initial solution.

---

### Notes

* None

# Answer
> 3 votes
# Python 2, 101 bytes

```
x=input()
for i,n in enumerate(x):x[i]=[n,list(set(range(1,len(x)+9))-set(x))[0]][n in x[:i]]
print x

```

Try it online! or Try all test cases

# Answer
> 3 votes
# , 39 ~~46~~ bytes

Creates a vector from the input, then replaces the duplicated values with a range from 1 to a million that has the input values removed. Returns a numeric vector. No input will return the empty vector numeric(0).

```
i[duplicated(i)]=(1:1e6)[-(i=scan())];i

```

Try it online!

This will throw a warning about the length of the replacement vector

```
                           i=scan()     # set i as input
                 (1:1e6)                # 1 to a million (could go higher)
                 (1:1e6)[-(i=scan())]   # without input values
  duplicated(i)                         # duplicate values in i
i[duplicated(i)]=(1:1e6)[-(i=scan())]   # set duplicate i values to reduced range vector
                                     ;i # return result

```

# Answer
> 2 votes
## Clojure, 72 bytes

```
#(reduce(fn[r i](conj r(if((set r)i)(nth(remove(set r)(range))1)i)))[]%)

```

A basic reduction. If `i` is contained in the output list so far, we'll take the 2nd element (1 when 0-indexed) from the infinite list of integers `(range)` from which we have removed those numbers that have already been used. Range starts from zero so we cannot take the first element but the second.

# Answer
> 2 votes
# C# 7, 116 bytes

```
int[]f(int[]c){int j=0;int h()=>c.Contains(++j)?h():j;return c.Select((e,i)=>Array.IndexOf(c,e)<i?h():e).ToArray();}

```

**Indented**

```
int[] f(int[] c)
{
    int j = 0;
    int h() => c.Contains(++j) ? h() : j;
    return c
        .Select((e, i) => Array.IndexOf(c, e) < i ? h() : e)
        .ToArray();
}

```

**Explained**

* first occurrence of a number is always left as-is
* consecutive occurrences of a number are drawn from `[1, 2, 3, ...]`, skipping values present in the input.

**Online Version**

# Answer
> 1 votes
# R, 74 bytes

reads the list from stdin; returns NULL for an empty input.

```
o=c();for(i in n<-scan())o=c(o,`if`(i%in%o,setdiff(1:length(n),o)[1],i));o

```

explanation:

```
o=c()                                #initialize empty list of outputs
for(i in n<-scan())                  # loop through the list after reading it from stdin
    o=c(o,                           # set the output to be the concatenation of o and
      `if`(i%in%o,                   # if we've seen the element before
           setdiff(1:length(n),o)[1] # the first element not in 1,2,...
           ,i))                      # otherwise the element
o                                    # print the output

```

`1:length(n)` may be used since we are guaranteed to never need a replacement from outside that range.

Try it online!

# Answer
> 0 votes
# Axiom, 169 bytes

```
f a==(r:List INT:=[];for i in 1..#a repeat(~member?(a.i,r)=>(r:=concat(r,a.i));for j in 1..repeat if~member?(j,r)and(~member?(j,a)or j=a.i)then(r:=concat(r,j);break));r)

```

ungolf and result

```
ff(a)==
  r:List INT:=[]
  for i in 1..#a repeat
      ~member?(a.i,r)=>(r:=concat(r,a.i))
      for j in 1.. repeat
            if~member?(j,r)and(~member?(j,a) or j=a.i)then(r:=concat(r,j);break)
  r

(3) -> f([])
   (3)  []
                                                       Type: List Integer
(4) -> f([5])
   (4)  [5]
                                                       Type: List Integer
(5) -> f([1,4,2,5,3,6])
   (5)  [1,4,2,5,3,6]
                                                       Type: List Integer
(6) -> f([3,3,3,3,3,3])
   (6)  [3,1,2,4,5,6]
                                                       Type: List Integer
(7) -> f([6, 6, 4, 4, 2, 2])
   (7)  [6,1,4,3,2,5]
                                                       Type: List Integer
(8) -> f([2147483647, 2, 2147483647, 2])
   (8)  [2147483647,2,1,3]
                                                       Type: List Integer

```

---
Tags: code-golf, set-theory
---


title: ASCII rhombic grid

text:
# Question
Title: ASCII rhombic grid
Write the shortest code measured by byte count to generate an ASCII grid composed of rhombi, given the following parameters:

* m - number of complete rhombi in one row
* n - number of rows
* s - side of the smallest rhombus
* r - level of nesting - how many rhombi are there inside the "base ones" (which are fonud between the intersections of the grid)

## Examples

```
1. Input: 5 3 1 0
Output:

/\/\/\/\/\
\/\/\/\/\/
/\/\/\/\/\
\/\/\/\/\/
/\/\/\/\/\
\/\/\/\/\/

A 5x3 grid of rhombi with side 1, no nesting

2. Input: 3 2 2 0
Output:

 /\  /\  /\
/  \/  \/  \
\  /\  /\  /
 \/  \/  \/
 /\  /\  /\
/  \/  \/  \
\  /\  /\  /
 \/  \/  \/

A 3x2 grid of rhombi with side 2, no nesting

3. Input: 5 2 1 2
Output:

///\\\///\\\///\\\///\\\///\\\
///\\\///\\\///\\\///\\\///\\\
///\\\///\\\///\\\///\\\///\\\
\\\///\\\///\\\///\\\///\\\///
\\\///\\\///\\\///\\\///\\\///
\\\///\\\///\\\///\\\///\\\///
///\\\///\\\///\\\///\\\///\\\
///\\\///\\\///\\\///\\\///\\\
///\\\///\\\///\\\///\\\///\\\
\\\///\\\///\\\///\\\///\\\///
\\\///\\\///\\\///\\\///\\\///
\\\///\\\///\\\///\\\///\\\///

A 5x2 grid of rhombi with side 1 (the smallest rhombus), level of nesting is 2

4. Input: 4 2 2 1
Output:

 //\\  //\\  //\\  //\\
///\\\///\\\///\\\///\\\
//  \\//  \\//  \\//  \\
\\  //\\  //\\  //\\  //
\\\///\\\///\\\///\\\///
 \\//  \\//  \\//  \\//
 //\\  //\\  //\\  //\\
///\\\///\\\///\\\///\\\
//  \\//  \\//  \\//  \\
\\  //\\  //\\  //\\  //
\\\///\\\///\\\///\\\///
 \\//  \\//  \\//  \\//

A 4x2 grid of rhombi with side 2 with level of nesting 1

5. Input: 4 2 3 3
Output:

  ////\\\\    ////\\\\    ////\\\\    ////\\\\
 /////\\\\\  /////\\\\\  /////\\\\\  /////\\\\\
//////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\
//////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\
/////  \\\\\/////  \\\\\/////  \\\\\/////  \\\\\
////    \\\\////    \\\\////    \\\\////    \\\\
\\\\    ////\\\\    ////\\\\    ////\\\\    ////
\\\\\  /////\\\\\  /////\\\\\  /////\\\\\  /////
\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\//////
\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\//////
 \\\\\/////  \\\\\/////  \\\\\/////  \\\\\/////
  \\\\////    \\\\////    \\\\////    \\\\////
  ////\\\\    ////\\\\    ////\\\\    ////\\\\
 /////\\\\\  /////\\\\\  /////\\\\\  /////\\\\\
//////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\
//////\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\
/////  \\\\\/////  \\\\\/////  \\\\\/////  \\\\\
////    \\\\////    \\\\////    \\\\////    \\\\
\\\\    ////\\\\    ////\\\\    ////\\\\    ////
\\\\\  /////\\\\\  /////\\\\\  /////\\\\\  /////
\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\//////
\\\\\\//////\\\\\\//////\\\\\\//////\\\\\\//////
 \\\\\/////  \\\\\/////  \\\\\/////  \\\\\/////
  \\\\////    \\\\////    \\\\////    \\\\////

A 4x2 grid of rhombi with side 3, level of nesting 3

```

Be sure to display the partially visible rhombi at the edges and corners where necessary.

# Answer
> 17 votes
# SOGL V0.12, 20 bytes

```
ā.I∫e+H╚╬8}:±№╬8╬¡∙*

```

Try it Here! Takes the input in the reversed order of what they are in the examples - r, s, n, m.

Explanation:

```
ā                     push an empty array - canvas
 .I∫      }           for each in range(input) (1-indexed)
    e+                  add the second input
      H                 decrement
       ╚                create a diagonal of that size
        ╬8              insert into the canvas
           :          create a duplicate of the canvas
            ±№        reverse it vertically and horizotally
              ╬8      insert that into the canvas
                ╬¡    quad-palindromize
                  ∙   multiply vertically by the next input
                   *  multiply horizontally by the next input

```

# Answer
> 9 votes
# Charcoal, ~~48~~ ~~39~~ 37 bytes

```
ＵＯ⊕Ｉε\Ｆ⊖ＩζＣ¹¦¹‖ＭL≔⊗⁺ＩζＩεδＦ⊖ＮＣδ⁰Ｆ⊖ＮＣ⁰δ

```

Try it online! Link is to verbose version of code. Explanation:

```
ＵＯ⊕Ｉε\

```

Draw a square of size `r + 1`. This is a quarter of a nested diamond of size 1.

```
Ｆ⊖ＩζＣ¹¦¹

```

Copy the square 1 square right and down `s - 1` times to get it to the right size.

```
‖ＭL

```

Reflect it to become a full nested diamond.

```
≔⊗⁺ＩζＩεδ

```

Compute the size of this nested diamond.

```
Ｆ⊖ＮＣδ⁰

```

Copy the diamond to the right `m - 1` times.

```
Ｆ⊖ＮＣ⁰δ

```

Copy the diamond downwards `n - 1` times.

# Answer
> 8 votes
# Python 2, ~~160~~ ~~159~~ 158 bytes

<sup>-1 byte thanks to Jonathan Frech</sup>

```
m,n,s,r=input()
l=~-s*' '+'/'*(r-~r)+~-s*' '
for x in range(n*2):print'\n'.join(m*(l[i:i+s+r]+l.replace(*'/\\')[i:i+s+r][::-1])for i in range(r+s))[::1-x%2*2]

```

Try it online!

This uses the fact that the bottom of the rhombus is the top inverted (`[::-1]`), iterating over `range(n*2)` and using `~x%2*2-1` to control if it is the top or the bottom.
For the top (and the bottom) the right side is just the left side inverted and replacing `/` with `\` -\> `l.replace(*'/\\')..[::-1]`
To generate the pattern / nesting `~-s*' '+'/'*(1+r*2)+~-s*' '` is used to make a string like  `///`  that will be iterated and chopped :

```
   '|  //|/  '
  ' | ///|  '
 '  |/// | '
'  /|//  |'

```

# Answer
> 7 votes
# Julia 0.6, 190 bytes

```
g(n,m,s,r)=(s+=r+1;f(i,j,u=mod(i-j+r,2s),v=mod(j+i+r,2s))=(" \\/")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)];
for i=1:2(s-1)m println((f(i+(i-1)÷(s-1),s+j+(j-1)÷(s-1))for j=1:2(s-1)n)...)end)

```

This is a functional solution which computes for every index pair `i,j` what the symbol should be displayed.

Try it online!

### Illustration

Start with a grid

```
f(i,j,u=mod(i,2s),v=mod(j,2s))=(" -|*")[1+(u==0)+2(v==0)]
for i=1:2(s-1)m println((f(i-1,j)for j=1:2(s-1)n)...)end

---------*---------*----
         |         |
         |         |
         |         |
         |         |
         |         |
         |         |
         |         |
         |         |
         |         |
---------*---------*----
         |         |
         |         |
         |         |
         |         |
         |         |

```

`r > 0` means thicker lines

```
f(i,j,u=mod(i+r,2s),v=mod(j+r,2s))=(" -|*")[1+(u<=2r)+2(v<=2r)]
for i=1:2(s-1)m println((f(i,j)for j=1:2(s-1)n)...)end

**-----*****-----*****--
**-----*****-----*****--
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
**-----*****-----*****--
**-----*****-----*****--
**-----*****-----*****--
**-----*****-----*****--
**-----*****-----*****--
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||

```

Handle the corners by checking which line on the original grid is closest

```
f(i,j,u=mod(i+r,2s),v=mod(j+r,2s))=(" -|")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)]
for i=1:2(s-1)m println((f(i,j)for j=1:2(s-1)n)...)end

|-------|||-------|||---
||-----|||||-----|||||--
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||-----|||||-----|||||--
|-------|||-------|||---
---------|---------|----
|-------|||-------|||---
||-----|||||-----|||||--
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||
||     |||||     |||||

```

A fairy tells us to remove every `s-1` line

```
f(i,j,u=mod(i+r,2s),v=mod(j+r,2s))=(" -|")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)]
for i=1:2(s-1)m println((f(i+(i-1)÷(s-1),s+j+(j-1)÷(s-1))for j=1:2(s-1)n)...)end

---||------||------||---
--||||----||||----||||--
  ||||    ||||    ||||
  ||||    ||||    ||||
  ||||    ||||    ||||
  ||||    ||||    ||||
--||||----||||----||||--
---||------||------||---
---||------||------||---
--||||----||||----||||--
  ||||    ||||    ||||
  ||||    ||||    ||||
  ||||    ||||    ||||
  ||||    ||||    ||||
--||||----||||----||||--
---||------||------||---

```

Traverse diagonally and done

```
f(i,j,u=mod(i-j+r,2s),v=mod(j+i+r,2s))=(" \\/")[abs(u-r)<abs(v-r)?1+(u<=2r):1+2(v<=2r)]
for i=1:2(s-1)m println((f(i+(i-1)÷(s-1),s+j+(j-1)÷(s-1))for j=1:2(s-1)n)...)end

 ///\\\  ///\\\  ///\\\
////\\\\////\\\\////\\\\
////\\\\////\\\\////\\\\
///  \\\///  \\\///  \\\
\\\  ///\\\  ///\\\  ///
\\\\////\\\\////\\\\////
\\\\////\\\\////\\\\////
 \\\///  \\\///  \\\///
 ///\\\  ///\\\  ///\\\
////\\\\////\\\\////\\\\
////\\\\////\\\\////\\\\
///  \\\///  \\\///  \\\
\\\  ///\\\  ///\\\  ///
\\\\////\\\\////\\\\////
\\\\////\\\\////\\\\////
 \\\///  \\\///  \\\///

```

# Answer
> 3 votes
## JavaScript (ES6), 154 bytes

```
f=
(m,n,s,r)=>[...Array((s+=r)*n*2)].map((_,i)=>[...Array(s*m*2)].map((_,j)=>i/s&1^j/s&1?`\\ `[g(j%s)]:`/ `[g(s-1-j%s)],g=j=>i%s-j>r|j-i%s>r).join``).join`
`
```

```
<div oninput=o.textContent=f(+m.value,+n.value,+s.value,+r.value)>
m: <input type=number min=0 id=m><br>
n: <input type=number min=0 id=n><br>
s: <input type=number min=0 id=s><br>
r: <input type=number min=0 id=r></div>
<pre id=o>
```

Directly calculates the character at each cell of the output.

# Answer
> 2 votes
# CJam, 44

```
q~:R+,_ff{-zR>}{_W%:~\+"\ /"f=}%_W%Wf%+*f*N*

```

Try it online

**Explanation:**

```
q~           read and evaluate the input
:R+          save the last number in variable R, then add the last 2 numbers (s+r)
,_           make an array [0 1 … s+r-1] and duplicate it
ff{…}        make a matrix, calculating for each (x,y) pair from the 2 arrays:
  -z         abs(x-y)
  R>         compared with R (1 if greater, 0 if not)
{…}%         transform each row of the matrix:
  _W%        duplicate and reverse it
  :~         bitwise-NOT each element (0 → -1, 1 → -2)
  \+         prepend to the original row
  "\ /"f=    replace numbers with characters from this string (by index):
              0 → '\'; 1, -2 → ' '; -1 → '/'
              this generates the "/\" part
_W%          duplicate the matrix and reverse the rows
Wf%+         reverse each row, then append (by rows) to the original matrix
              this adds the "\/" part
*            repeat the matrix (by rows) n times
f*           repeat each row m times
N*           join the rows with newlines

```

# Answer
> 2 votes
# C# (.NET Core), 167 bytes

```
(c,r,s,n)=>{int w=s+n,i=0,j;var g="";for(;i<r*2*w;i++,g+="\n")for(j=0;j<c*2*w;){int y=i%w,q=(j/w+i/w+1)%2,p=~-w*q+j++%w*(1-2*q);g+=p>y+n|p<y-n?' ':"\\/"[q];}return g;}

```

Try it online!

I'm surprised by the size I managed; I was initially expecting a longer solution. In saying this, I'm sure there are other tricks I've missed.

### DeGolfed

```
(c,r,s,n)=>{
    int w=s+n, // rhombus quadrant width, and height
        i=0, // string row
        j; // string column

    var g="";

    // go through every character row and column
    for(; i < r*2*w; i++, g += "\n")
        for(j = 0; j < c*2*w;)
        {
            int y = i % w, // vertical position in the quadrant
                q = ( j / w + i / w + 1) % 2, // Get the rhombus quadrant as a 0 or 1
                p = ~-w * q + j++ % w * (1-2*q); // horizontal position in quadrant. the value is either ascending or descending depending on the quadrant

            // select which character to use at this [i,j] position
            g += p > y + n | p < y - n ? ' ' : "\\/"[q];
        }

    return g;
}

```

# Answer
> 1 votes
# Python 2, ~~201~~ 189 bytes

```
def f(m,n,s,r):Z=range(s+r);R=[r-~min(i,s+~i+r,min(s-1,r))for i in Z];L=[m*(' '*(s+~i)+'/'*R[i]+'  '*(i-r)+'\\'*R[i]+' '*(s+~i))for i in Z];print'\n'.join((L+[l[s+r:]+l[:s+r]for l in L])*n)

```

Try it online!

Uses the fact that the bottom is the same as the top, but shifted:

```
Top:       /\/\/\
Bottom:     /\/\/\

```

Saved 22 bytes thanks to Jonathan Frech

# Answer
> 1 votes
# Perl 5, 159 + 3 (-anl) bytes

```
($m,$n,$s,$r)=@F;$s=$"x($s+$r-1);$_="$s/\\$s"x$m;$n*=2;{$t=$_;map$t=~s, ?(\S) ?,$1x$&=~y///c,ge,1..$r;print$t;redo if s, /,/ ,g&&s,\\ , \\,g||y,/\\,\\/,&&--$n}

```

Try It Online

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


title: Limerick Hello World

text:
# Question
Title: Limerick Hello World
A rhyming program you write
Attempting to win the fight
For winning the contest and vote
It must compute "Hello World"
Then print it very polite

The most popular poem will win.

The requirements are:

* The poem should be of 5 lines with rhymes AABBA
* It can print whatever you want, but the output should contain "hello world" (uppercase/lowercase does not matter, quotes not included in the output)
* Symbols are read aloud. For example, the fourth line above is read: It must compute quote hello world quote
* Post below your code, on another code preview, the "read-aloud" version of your code for disambiguation on special symbols.

Excluded are poems:

* including dead code, or characters which could be safely removed without changing the rhymes or the functionality
* Using comments as a way to rhyme (except if there is a good reason for that)
* using the same symbol as end of phrase for rhyme.

In case of a tie, programs outputting a poem will win. If there is still a tie, shorter programs will win.

New lines do not count. spaces, tabs and newlines are not read aloud. For example, "Hello, world!" would be read aloud "double-quote hello comma world exclamation point double-quote".

# Answer
## Whitespace

```
A rhyming program I	wrote

this poem of whitespace and bloat

because newlines don't count

despite the amount

so deserves your sincerest upvote

```

Wikipedia: Whitespace (programming language)
Online Interpreter to Test Answer

Output:

```
Hello World

```
> 84 votes

# Answer
**HTML**

```
<html>
<body><span
    class="poem"
    > Hello World! I'm a goat
</span></body></html><!-- Pecan -->

```

I had to get a little liberal with pronunciation of the last line. I hope it doesn't break the rules. It's also not 100% valid per W3C, but works in most browsers.

```
<!--
less than aich tee em el greater than,
less than body not equal to span,
class equals quote poem end quote,
greater than Hello World Bang I'm a goat
close span close body close root comment pecan
-->

```
> 61 votes

# Answer
## Javascript

I know this isn't within the rules, but I couldn't resist

```
var girl, attractive = true;    // There once was a beautiful girl
var boy; girl = ' World';       // And a boy who thought she was his world
boy = 'Hello' + girl;           // When the boy said hello
if (boy != attractive)          // She said 'my goodness no!'
    alert(window['boy']);       // And the boy through the window she hurled.

```
> 29 votes

# Answer
Python

```
a = [
'hello world']
print ''.\
join(a##
)

```

or,

```
a equals open square bracket
quote hello world quote close square bracket
print quote quote dot backslash
join paren a hash hash
and finally close unmatched bracket

```

I'm voluntarily signing up to additional rules, because I think (1) that limericks should have good metre and (2) that the best ones have a surprise in the last line.

(With the ending being interpreted in plain English, I figure you can work out for yourself what kind of bracket is unmatched. As to the no dead code requirement, nothing in there can be removed without changing at least one of rhyme, rhythm or output).
> 23 votes

# Answer
# Haskell

Taking some liberties with the pronunciation of certain symbols, i.e. Tuple construction `(,,)` and function application `($)`.

```
main = something that we wrote
     where something x y z = bloat
           bloat = flip ($) m putStrLn
           (that,we,wrote) = undefined
           m = "hello world"

```

The reading is supposed to be:

```
main is something that we wrote
where something x y z is bloat
bloat is flip apply m putStrLine
Tuple that we wrote is undefined
misquote hello world quote.

```
> 14 votes

# Answer
## JavaScript

```
if (!!1) // and
  alert('❤ ❤ the world') // and
Burn = $.cache
return 1 > his_parts.the_sum

```

> If in brackets one follows exclaiming marks
>
> and alert the world inside brackets after entity hearts
>
> slash, slash and burn
>
> equals cash, cash, return
>
> one is greater than the sum of his parts
> 12 votes

# Answer
# BASIC

More specifically, Chipmunk Basic. The syntax rules have been stretched almost to breaking point, so it may be impossible to run this in other dialects without modification.

**Source:**

```
read hi$, u$, q
print hi$ " world how are you
  print "Or as they say
  print u$ q "day
data Hello, How R U, 2

```

**"Read-aloud" version:**

```
read hi string comma u string comma q
print hi string quote world how are you
  print quote Or as they say
  print u string q quote day
data Hello comma How R U comma 2

```

**Notes:**

* There are no line numbers in the source code, but it will still load and run without any problems (see below).
* The `$` sigil is read as *"string"* in the context of BASIC programs (see, e.g., this Wikipedia page).

And here's proof that it does actually work:
> 8 votes

# Answer
**Bash**

As the answer is only forced to *contain* the phrase "Hello World", the easiest solution should be:

```
echo A rhyming program you write
echo Attempting to win the fight
echo For winning the contest and vote
echo It must compute "Hello World"
echo Then print it very polite

```
> 6 votes

# Answer
# Ruby

```
comma = ""<<44
print "Hello" or
more = ""<<32
print comma if true
puts("World!") unless print more

```

Live: https://ideone.com/sirBBc

Pronounced as follows (with stressed syllables capitalized)

```
comma Equals quote-QUOTE cons four-FOUR
print QUOTE hello END quote OR
more equals QUOTE quote cons three-TWO  # ok, that was squished
print COMma if TRUE
puts QUOTE world QUOTE UNless print MORE

```
> 6 votes

# Answer
## Java

```
public static void main(String[] boat
){ int i = 1.0f
  ;if(i<2
  )System.out.println
("Hello world");} //hello world wrote

public static void main paren String arr boat
paren brace int i is one-point-oh float
sem-col if paren i is less than two
paren system dot out dot print line new //for some reason it's println, not printnl
paren quote hello world quote paren sem-col brace slash-slash hello world wrote

```

Note that comments are not really optional in Java
> 6 votes

# Answer
## Haskell

```
main = print . repeat
  $ head $ lines . init
     $ "Hello \
       \World!" #
         Just where (#) = const . id

```

> Main equals printful stop repeat
> Dollar head dollar line's full stop i'nnit?
> Dollar quote hello back slash
> Back slashworld bang quote hash
> Just where parenthised hash equals constful, stop it!

This describes, hopefully, quite well the actual behaviour of the program.
> 4 votes

# Answer
## TeX

I apologize in advance, because this code does not count as a limeric if you pronounce the names of each of the individual symbols (especially if you treat each letter unto itself as a token, which perhaps you ought). I have written it this way to produce the nicest possible output, which itself comes just short of being a poem.

You could safely turn it into an answer which complies with the rules by getting rid of `\it` and every non-alphabetic, non-whitespace character except for the final `\bye` (read aloud as *backslash bye*) and perhaps the first `!` (read aloud as *bang*).

```
A \TeX\ program I think would comply,

And I'll tell you the reason for why:

``Hello world!'' tells the setter:

{\it ``Print each subsequent letter!''}

And we terminate with \bye.

```
> 2 votes

# Answer
# Brainf\*ck

Ok, chide me now for the numerous rule violations. But I couldn't help making this.

```
++++++++[>+++++++++<-
]>.---.$#
+++++++..+
++.++++++++
.--------.+++.------.--------.

```

And the output (first violation of many: no space):

```
HELLOWORLD

```

Try it here: http://www.iamcal.com/misc/bf\_debug/

The reading of it:

```
Eight plus left more nine plus less dash
Right more dot three dash dot cash hash
Sevén plus dot dot plus
Plus plus dot eight plus
Dot eight dash dot three plus dot six dash dot eight dash.

```
* Note that the final dot in the program is placed as the period at the end of the limerick :) \[second violation; this is cheap\]. Also, the `$` and `#` are ignored by the interpreter (I was very proud of myself for this line).
* The accent on `Sevén` is to show the stress: seh-VEN
* This violates the rule of using different symbols. But honestly I have a very limited symbol set and no space to add in other (ignored) characters.
* I used all caps because those are faster to access in ASCII. I had no room for a space, unfortunately.

Finally: yes, I know the last line is terrible. Any suggestions to improve it? I'm not sure if you could compress this program anymore; maybe by storing repeated letters in their at their own positions?
> 2 votes

# Answer
**C#**

I've taken a few slight liberties with the rules as truly phonetic C variants would involve far too much use of "semi-colon" which, as we all know, isn't a particularly good rhyme for anything.

```
{
     string unfurled = "Hello World!";
     Console.WriteLine(unfurled);
}

```

open brace, string called unfurled

created to read "hello world"

console write line

the string we defined

a final brace, one that is curled
> 2 votes

# Answer
## Batch

```
@echo off >dull
set /p "=Hello "<nul
set w=World
echo %w%! || Furled
del dull || cull

```

> at echo off to dull
> set slash p quote equal Hello quote from nul
> set w equal World
> echo percent w percent bang pipe pipe Furled
> del dull pipe pipe cull
> 1 votes

# Answer
# Java

```
class Hello {public static void main
(String[] args)
{yellow = System; yellow
.out.print("Hello
world");} }

class Hello brace public static void main
paren string bracket bracket args paren
 brace yellow equals system sem-col yellow
 dot out dot print paren quote hello
world quote paren sem-col brace and brace again

```
> 1 votes

# Answer
# CSS

```
title>me
,body lets go party
only a stylesheet,html
:after { content: 'hello world'; font-family:Rockwell
; color: #adad20

```

Outputs:

> title greater than me
>
> comma body lets go party
>
> only a stylesheet comma html
>
> colon after bracket content colon quote hello world quote semicolon font-family colon Rockwell
>
> semicolon color colon hashtag a dad twenty

Tested in Firefox and Chrome
> 1 votes

# Answer
```
#include <stdio.h> //
void main (void){
printf("Hello, World");
//just for rhyme I say stolon
} /**/

```

hash include less than stdio dot h greater than double slash after a space

void main left paren void right paren left brace

printf left paren quote Hello comma World quote right paren semi colon

double slash just for rhyme I say stolon

right brace and double asterisk between slashes at the last place
> 1 votes

# Answer
## Windows Batch

The spoken words are also saved within the batch file, and skipped with the last line of actual code.

```
@echo off >nul
set hi=Hello World
rem Now print the string,
echo !hi!
goto :) to skip the words

at echo off, greater than nul,
set H I equals sign, Hello World,
rem Now print the string,
echo pling, H I, pling
goto smile, to skip the words

:)

```

Edit: You'll need delayed expansion enabled for the script to work. Use `cmd /v:on` and run it from there.
> 0 votes

# Answer
**Python (3)**

```
print('''Nose
No punctuation hear close
Hello World
Hurled and swerled
Goodbye now''')

```

Print open quote quote quote nose, No punctuation hear close, Hello World, Hurled and swerled, Goodbye now quote quote quote close.
> 0 votes

---
Tags: popularity-contest, hello-world
---


title: Chess-olition Derby

text:
# Question
Title: Chess-olition Derby
What could be more polar opposites than chess and demolition derby. You would think that no one who enjoys one would enjoy the other... until today.

# Rules

The starting position is a standard chess board:

```
RNBQKBNR
PPPPPPPP

PPPPPPPP
RNBQKBNR

```

Looks normal enough, until you find out it's an **EVERY PIECE FOR ITSELF, LAST PIECE STANDING** competition:

* On every turn, each piece on the board gets to make one randomly\*-selected valid move (using it's standard move rules). However, the order the pieces move in is **randomized** every turn.
* A piece can capture **ANY PIECE**, even if it's the same color as it, even a king.
* Pawns can capture **FORWARD**, as well as diagonal. Moreover, like normal, if there is an empty space in front of it, a pawn can move two spaces on its first move (they can also capture that way.) Furthermore, pawns promote to any random piece (including king) other than a pawn.
* The winner is the last piece standing. However if after **1000 turns**, there is more than one piece left, all of the remaining pieces are winners.
* No En Passants, Checks, Castles, etc.

# Output

After every turn output the turn number, and what the board looks like. After a piece is killed it is removed from the board. After the first turn, the board may look like this:

```
1.
   K
RBQ N BR
NP  P P
  PP P P
R PP
BPN PNP
    K  R
       Q

```

After 1000 moves the board may look like this:

```
1000.
  Q  K

P  N R

 R  B N

  Q

```

And the game ends.

Or Maybe after 556 turns the board look like this:

```
556.

     R

```

So the game ends there.

\*Please ensure all randomization done in this challenge is uniform (every possibility has an equal chance of occurring).

# Answer
> 3 votes
# Python 2, ~~862~~ ~~846~~ 844 bytes

```
from random import*
A=-1;a,b=[(0,1),(0,A),(A,0),(1,0)],[(A,A),(A,1),(1,A),(1,1)]
r=range(8)
C='RNBQK';q=C+'BNR'
def m(x,y,B,t):
 P=B[y][x];M=[]
 for w,z in dict(zip('pP'+C,[[],[],a,zip([A,1,-2,2]*2,[2,2,1,1,-2,-2,A,A]),b]+[a+b]*2))[P]:
	for i in r[1:]:
	 X,Y=x+z*i,y+w*i;M+=(X,Y),
	 if P in'NK'or 1-(8>X>A<Y<8)or' '<B[Y][X]:break
 if P in'pP':d=[A,1][P<'p'];M=zip((x-1,x,x+1)[B[y+d][x-1]<'!':2+(B[y+d][-~x%8]>' ')],(y+d,)*3)+[(x,y+2*d)]*(t*B[y+d][x]<'!')
 return choice([(X,Y)for X,Y in M if-1<X<8>Y>A])
B=map(list,[q,'P'*8]+[' '*8]*4+['p'*8,q])
t=0
while t<1e3:
 t+=1;p=[(x,y)for y in r for x in r if' '<B[y][x]];shuffle(p)
 if len(p)<2:break
 while p:x,y=p.pop();Z=X,Y=m(x,y,B,t<2);B[Y][X],B[y][x]=B[y][x],' ';Z in p and p.remove(Z)
 for j in 0,7:
	for i in r:
	 if B[j][i]in'pP':B[j][i]=choice(C)
 print t
 for l in B:print''.join(l).upper()

```

Try it online!

Saved 18 bytes thanks to Jonathan Frech

# Answer
> 0 votes
# PHP, 1849 bytes

```
<?$z=[R,N,B,Q,K,B,N,R];$y=[_,_,_,_,_,_,_,_];$u=shuffle;$b=[$z,[P,P,P,P,P,P,P,P],$y,$y,$y,$y,[p,p,p,p,p,p,p,p],$z];$z=[R,N,B,Q,K];for($i=0;$i<8;$i++)for($j=0;$j<8;$j++)$r[]=[$i,$j];for(;$c++<=999;){for($i=$_=0;$i<8;$i++)for($j=0;$j<8;$j++)if($b[$i][$j]!=_)++$_;if($_<2)break;$u($r);$n=[];foreach($r as$l){list($y,$x)=$l;$a=$y+1;$d=$y-1;$j=$x+1;$t=$x-1;$p=$b[$y][$x];if($n[$y][$x]!=1&&$p!=_){$v=$e=$f=$g=$h=$k=$o=$q=$s=[];if($p==R||$p==K||$p==Q){$m=($p==K)?2:9;for($i=1;$i<$m;$i++){if(!$e&&$y-$i>=0){$v[]=[$y-$i,$x];if($b[$y-$i][$x]!=_)$e=1;}if(!$f&&$y+$i<8){$v[]=[$y+$i,$x];if($b[$y+$i][$x]!=_)$f=1;}if(!$g&&$x-$i>=0){$v[]=[$y,$x-$i];if($b[$y][$x-$i]!=_)$g=1;}if(!$h&&$x+$i<8){$v[]=[$y,$x+$i];if($b[$y][$x+$i]!=_)$h=1;}}}if($p==B||$p==K||$p==Q){$m=($p==K)?2:9;for($i=1;$i<$m;$i++){if(!$k&&$y-$i>=0&&$x-$i>=0){$v[]=[$y-$i,$x-$i];if($b[$y-$i][$x-$i]!=_)$k=1;}if(!$o&&$y-$i>=0&&$x+$i<8){$v[]=[$y-$i,$x+$i];if($b[$y-$i][$x+$i]!=_)$o=1;}if(!$q&&$y+$i<8&&$x-$i>=0){$v[]=[$y+$i,$x-$i];if($b[$y+$i][$x-$i]!=_)$q=1;}if(!$s&&$y+$i<8&&$x+$i<8){$v[]=[$y+$i,$x+$i];if($b[$y+$i][$x+$i]!=_)$s=1;}}}if($p==N){if($y-2>=0&&$t>=0)$v[]=[$y-2,$t];if($y-2>=0&&$j<8)$v[]=[$y-2,$j];if($d>=0&&$x-2>=0)$v[]=[$d,$x-2];if($d>=0&&$x+2<8)$v[]=[$d,$x+2];if($a<8&&$x-2>=0)$v[]=[$a,$x-2];if($a<8&&$x+2<8)$v[]=[$a,$x+2];if($y+2<8&&$t>=0)$v[]=[$y+2,$t];if($y+2<8&&$j<8)$v[]=[$y+2,$j];}if($p==P){if($y==1&&$b[$a][$x]==_)$v[]=[$y+2,$x];if($j<8&&$b[$a][$j]!=_)$v[]=[$a,$j];if($t>=0&&$b[$a][$t]!=_)$v[]=[$a,$t];$v[]=[$a,$x];}if($p==p){if($y==6&&$b[$d][$x]==_)$v[]=[$y-2,$x];if($j<8&&$b[$d][$j]!=_)$v[]=[$d,$j];if($t>=0&&$b[$d][$t]!=_)$v[]=[$d,$t];$v[]=[$d,$x];}$u($v);$v=$v[0];$b[$y][$x]=_;$w=$p;if($w==P&&$v[0]>6&&$u($z)&&$w=$z[0]);if($w==p&&$v[0]<1&&$u($z)&&$w=$z[0]);$b[$v[0]][$v[1]]=$w;$n[$v[0]][$v[1]]=1;}}echo $c.".
";foreach($b as$a)echo str_replace([_,p],[' ',P],join("",$a))."
";}

```

Try it online!

It can *definitely* be golfed more, and it looks somewhat like the workings of a madman (which, I suppose, it may be).

I am impressed at how fast random moves can clear the board (I've seen 15 moves do it). Also, I think the only one I saw hit the 1000 limit was two bishops on different colors dancing.

---
Tags: code-golf, random, chess, simulation
---


title: Seqindignot sequence

text:
# Question
Title: Seqindignot sequence
*Title is made up, from 'Sequence Index Digit Not'.*

## Challenge:

Given an integer `n` which is `>= 0`, output the `n`'th number of the following sequence.
Here are the first 50 items, with it's (0-indexed) index above it:

```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
1 0 3 2 5 4 7 6 9 8 22 20 30 24 23 26 25 28 27 32 11 33 10 14 13 16 15 18 17 31 12 29 19 21 50 40 41 42 44 45 35 36 37 51 38 39 52 53 55 56 34

```

## How does this sequence work?

The number at index `n` must be the first in order that does not have any digits in common with `n`, and hasn't occurred yet for previous indexes. So when we look at normal sequence like this from `0-60`:

```
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

```

We define the `n`'th values like this:

* `0`: The first number (`0`) contains the same digit, so we look for the next (`1`), which does not contain the same digit. So `n=0` outputs `1`.
* `1`: The first number (`0`) does not contain the same digit, so `n=1` outputs `0`.
* `2`: We've already encountered `0` and `1`, and the next digit (`2`) contains the same digit, so we look for the next (`3`), which does not contain the same digit. So `n=2` outputs `3`.
* ...
* `10`: We've already encountered `0-9`, so the next in line is `10`. `10-19` contain the matching digit `1`, `20` contains the matching digit `0`, `21` contains the matching digit `1` again, `22` is valid, so `n=10` outputs `22`.
* etc.

## Challenge rules:

* If your language is 1-indexed (or you choose to) you are allowed to start the sequence at `3 2 5 4 7 ...` (skipping the `1` at `n=0` and the `0` at `n=1`).
* The minimum largest index you should support is `25,000`. *NOTE: The sequence stops at index `1,023,456,788`, because the next index in line contains all 10 digits.*
* You are also allowed to output / return an array/list of the entire sequence up to and including index `n` if you want to.

## General rules:

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

## Test cases:

*This sequence actually created pairs regarding index and outputs. If index `n` outputs `o`, index `o` outputs `n`.* So you can input either the left or right, and the output will be the other side:

```
0      <->  1       (this test case is optional)
2      <->  3
10     <->  22
12     <->  30
34     <->  50
89     <->  100
111    <->  200
112    <->  300
199    <->  322
2231   <->  4456
9605   <->  11118
19235  <->  46000
23451  <->  60668
25000  <->  13674

```

Here is a pastebin of the first 25,001 test cases if you want to try others.

# Answer
# Pyth, 18 bytes

```
u+Gf!|}TG@`H`T0hQY

```

**Try it here!** or **Check more test cases!**

Note that this returns the entire sequence up to index **N**, but the link returns the last number only, by prepending an `e` (end). If you want to see the raw value returned by this program, just remove it.

## How it works

```
u+Gf!|}TG@`H`T0hQY  - Full program.

u     ...      hQY  - Reduce hQ (the input incremented) from left to right, with the
                       function ...(G, H), with starting value Y (the empty list).
                       G is the current value and H is the iteration index.
   f          0     - First integer starting from 0, that satisfies the following:
      }TG             - Appears in G...
     |   @`H`T        - Or its (string) intersection with the current index (H) is
                        non-empty.
    !                 - Logical NOT (boolean negation).
 +G                 - Append the value obtained above to the current value (G).
                      This becomes the given value for the next iteration.
                    - Implicitly print all intermediate results, or add e to print
                      the last one.

```
> 3 votes

# Answer
# Python 2, ~~92~~ ~~91~~ ~~89~~ 88 bytes

```
a=()
i=0
exec"x=0\nwhile set(`x`)&set(`i`)or x in a:x+=1\na+=x,;i+=1;"*-~input()
print a

```

Try it online!

Prints a list of the first `n+1` numbers

---

Different approach, which is a lot faster:

# Python 2, 96 bytes

```
n=input()
r=range(9*n)
i=0
exec"x=0\nwhile set(`r[x]`)&set(`i`):x+=1\nprint r.pop(x),;i+=1;"*-~n

```

Try it online!
> 6 votes

# Answer
## Haskell, ~~80~~ 69 bytes

```
f n=[x|x<-[0..],all(`notElem`show n)$show x,all(/=x)$f<$>[0..n-1]]!!0

```

Try it online!

Very slow for large `n`.

```
f n=
    [x|x<-[0..]     ] !!0          -- pick the first of all 'x' from [0..]
                                   -- where
      all(`notElem`show n)$show x  -- no digit of 'n' appears in 'x', and
      all(/=x)                     -- 'x' is not seen before, i.e. not in the list
               f<$>[0..n-1]        -- 'f' mapped to [0..n-1]

```

Edit: @Laikoni saved 10 bytes. Thanks!
> 3 votes

# Answer
# Java (OpenJDK 8), ~~218~~ ~~217~~ ~~213~~ ~~210~~ ~~202~~ ~~200~~ ~~172~~ ~~171~~ ~~170~~ ~~168~~ 167 bytes

I cannot believe that I didn't just return `k` all this time...

```
i->{int j=-1,k=0,y=1;for(String r=" ",e=r;j++<i;r+=~-k+e,y=1)for(k=0;y>0;k++)for(int f:(k+(y=0)+"").getBytes())y+=(e+j).indexOf(f)<0&!r.contains(e+k+e)?0:1;return~-k;}

```

Try it online!
> 2 votes

# Answer
# APL (Dyalog), 39 bytes

```
0∘{0=⍵:1⋄(~⍺∊0∇¨⍳⍵)∧⊃∧/≠/⍕¨⍺⍵:⍺⋄⍵∇⍨⍺+1}

```

Uses `⎕IO←0`.

Try it online!

**How?**

Recursion.

`0=⍵:1` \- take a guess.

`~⍺∊0∇¨⍳⍵` \- left arg (accumulator) is not already in previous results

`∧⊃∧/≠/⍕¨⍺⍵` \- and the string representation of the accumulator and `n` are different

`:⍺` \- then return the accumulator.

`⍵∇⍨⍺+1` \- otherwise, increment accumulator and recurse.
> 2 votes

# Answer
# Python 3, 92 bytes

```
o=1,
for i in range(int(input())):
 x=0
 while{*str(x),x}&{*str(~i),*o}:x+=1
 o+=x,
print(o)

```

Try it online!

This prints all the terms up to the **N**th one. Thanks to Dennis for  ~~-4~~  -5 bytes!
> 2 votes

# Answer
# JavaScript (ES6), ~~103 88~~ 81

**Edit** Revised including *many* clever ideas by @Neil

```
n=>eval("for(r=[j=i=0];i<=n;)j=r[j]||(i+'').match(`[${j}]`)?j+1:!(r[k=j]=++i);k")

```

*Starting point*

Basic idea: a loop from 0 to n, and an inner loop checking values still not used

```
n=>{
  var r=[]
  for(i=0;i<=n;i++)
  {
    s=new Set(i+'')
    for(j=-1;s;)
    {
      if (!r[++j] && ![...j+''].some(d=>s.has(d)))
      {
        r[j]=1
        console.log(i,j)
        s=0
      }
    }
  }
  return j
}

```

*Current version more readable*

```
n=>{
  for(r = [j=i=0]; i <= n; )
    if (r[j] || (i+'').match(`[${j}]`))
      ++j
    else
      r [k=j] = ++i,
      j = 0;
  return k
}

```

**Test**

```
var f=
n=>eval("for(r=[j=i=0];i<=n;)j=r[j]||(i+'').match(`[${j}]`)?j+1:!(r[k=j]=++i);k")

update=_=>{
  var i=+I.value
  if (i < 1e4 || confirm("Really?")) {
    O.textContent=i + ' -> ...'
    setTimeout(_=>O.textContent=i + ' -> ' + f(i), 100)
  }
}

update()
```

```
<input id=I value=100 type=number max=1023456788>
<button onclick='update()'>Go</button>
(slow when input > 1000)
<pre id=O></pre>
```
> 2 votes

# Answer
# Go, ~~217~~ 205 bytes

```
package g;import("fmt";"strconv";"strings");var(
d=make(map[int]int)
a=strconv.Itoa)
func G(L int){k,i:=0,0;for;i<=L;i++{s:=a(i);k=0;for d[k]>0||strings.ContainsAny(a(k),s){k++;}
d[k]=1;}
fmt.Print(a(k));}

```

Alternate version (program instead of a package): Try it online!

Improvements:

* removed space after outer `for` by using multiple assignment for `i,k`
* importing `"fmt";` \+ `fmt.Print` is shorter than `os.Stdout.WriteString` (holdover from `package main` when os.Args was needed)
> 2 votes

# Answer
# Octave, 114 bytes

```
N=input("");o=[1];for i=1:N;j=0;while(any(o==j)||nnz(ismember(int2str(i),int2str(j))));j++;end;o=[o,j];end;[0:N;o]

```

Try it online!

Thanks to Kevin Cruijssen and Dlosc for the character comparison golfing.

## Ungolfed

```
N=input("");o=[1];

for i=1:N;
    j=0;
    while(any(o==j)||nnz(ismember(int2str(i),int2str(j))));
        j++;
    end;
    o=[o,j];
end;
[0:N;o]

```

Basic explanation:

* Outer loop and inner loop, one for index `i`, and another for value to add `j`
* For each `i`, continue to increment `j` if either of the following are met:

1. Any `j` has been used before
    2. This one gets fun. First, split each numeric value into a vector of digits (e.g., `10` becomes `[1 0]`) using `int2str`. Then, compare the two numbers using `ismember`(e.g., `[1 0]` and `[2 1]` would return `[1 0]`) and then `nnz` to see if any columns matched.
* If none of the above are met, you have the next number! Append to `o`, the output matrix
* Print original indices with output matrix
> 2 votes

# Answer
# Perl 5, 60 bytes

**59 bytes code + 1 for `-p`.**

```
$_="@{[0..($;=++$_)*9]}";$_=eval's/\b[^ $-]+ //;$-++;$&;'x$

```

Try it online! (Includes `-l` for visual purposes and `$-=0;` to reset each iteration)
> 1 votes

# Answer
# Pip, 30 bytes

29 bytes of code, +1 for `-p` flag.

```
Fn,a+1{Y0WyNl|_NyMSn++ylPBy}l

```

Try it online!

Outputs the whole list. Warning: highly inefficient; the `2231` input case has been running for 35+ minutes on my laptop and still hasn't finished.

### Explanation

```
                               a is cmdline arg, l is [] (implicit)
Fn,a+1{                    }   For each n in range(a+1):
       Y0                       Yank 0 into y
         W                      While...
          yNl|                  y is in l, or...
              _Ny               lambda function: arg is in y
                 MSn            mapped to digits of n and result list summed
                                (i.e., any digit of n is in y):
                    ++y          Increment y
                       lPBy     Once we have a y that meets the criteria, push it to
                                the back of l
                            l  Output l (formatted with -p flag)

```
> 1 votes

# Answer
# Visual Basic .NET (.NET 4.5), ~~260~~ 259 bytes

*-1 byte thanks to Kevin Cruijssen*

```
Function A(n)
Dim p=New System.Collections.Generic.List(Of Long),j="0",g=0
For i=0To n
j=0
While 1
If Not p.Contains(j)Then
g=1
For Each c In i.ToString
If j.Contains(c)Then g=0
Next
If g Then Exit While
End If
j+=1
End While
p.Add(j)
Next
A=p(n)
End Function

```

Loops through, generating previous terms in the sequence to then compare later. Then iterates the number as a string looking for matches.

Abuses VB.NET's typing system. For example, `j` is a string, but adding one converts to an integer for me. Integers are converted to Booleans where `0` is `False` and the rest are `True`.

Try it online!
> 1 votes

# Answer
# Jelly, 20 bytes

Pyth beats Jelly. Go Mr. Xcoder!

```
Df⁹LD¤ȯeṆ
0ç1#ɓ;
1Ç¡

```

A full program taking input from STDIN and outputting in the list format option using Jelly's list representation\*. Uses the standard 0 based indexing.

* single element lists have no surrounding `[]`, so `0` outputs `1`, while `1` outputs `[1, 0]` etc.

**Try it online!**

### How?

```
Df⁹LD¤ȯeṆ - Link 1, can append n to current? n, number; current, list
D         - convert n to decimal list
     ¤    - nilad followed by link(s) as a nilad:
  ⁹       -   chain's right argument, current
   L      -   length
    D     -   convert to a decimal list
 f        - filter discard from left if not in right
       e  - n exists in current?
      ȯ   - left logical OR right (empty lists are falsey)
        Ṇ - logical NOT

0ç1#ɓ; - Link 2, append next number: current, List
   #   - n find (count up finding first n matches):
  1    - ...finding: 1 match
0      - ...stating at: n=0
 ç     - ...doing: the last link as a dyad (left=n, right=current)
    ɓ  - new swapped-arg-dyadic chain (left = current, right = list of the found n)
     ; - concatenate

1Ç¡ - Main link: no arguments
1   - initialise the return value to 1
  ¡ - repeat input() times:
 Ç  -   last link (2) as a monad
    - implicit print

```
> 1 votes

---
Tags: code-golf, number, sequence, integer
---