title: Russian Caesar cipher

text:
# Question
Title: Russian Caesar cipher
# The objective

Given a Russian text, encrypt it with Caesar cipher with key 16.

# The basic Cyrillic alphabets

The basic Cyrillic alphabets are: (U+0410 – U+042F)

```
АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ

```

By the Caesar cipher, they are mapped to:

```
РСТУФХЦЧШЩЪЫЬЭЮЯАБВГДЕЖЗИЙКЛМНОП

```

The small letters (U+0430 – U+044F) are also mapped likewise.

Note the absence of `Ё`.

# Rules

1. Ё (U+0401) and ё (U+0451) are not considered basic, and are mapped to Х̈ (U+0425 U+0308) and х̈ (U+0445 U+0308), respectively.
2. Any other characters are preserved.

# Example

The following sentence:

```
В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!

```

Is encrypted to:

```
Т зрйре оур цшы сл жшвагб? Фр, эю дрымиштлщ нъчхьяыпа!

```

# Answer
> 5 votes
# 05AB1E, ~~16~~ ~~40~~ ~~39~~ 33 bytes

```
63ÝD16^‚Ž4K+ç`‡•2.w2γ•3äçDl‚vy`«:

```

Would be just the first 15 bytes without the edge case of mapping `Ёё` to `Х̈х̈`.

-7 bytes thanks to *@Grimy*.

Try it online.

**Explanation:**

```
63Ý              # Push a list in the range [0,63]
   D             # Duplicate it
    16^          # Bitwise-XOR each value with 16: [16..31, 0..15, 48..63, 33..47]
        ‚        # Pair it with the initial [0,63] list we duplicated
         Ž4K     # Push compressed integer 1040
            +    # Add it to each integer in the inner lists
             `   # Push both lists separated to the stack again
              ‡  # Transliterate the characters in the first list to the second list
                 # in the (implicit) input-string
•2.w2γ•          # Push compressed integer 10251061776
       3ä        # Spit it into three parts: [1025,1061,776]
         ç       # Convert each to a character: ["Ё","Х","̈"]
Dl               # Create a lowercase copy: ["ё","х","̈"]
  ‚              # Pair them together: [["Ё","Х","̈"],["ё","х","̈"]]
   v             # Loop over both these lists `y`:
    y`           #  Push the characters of the current list separated to the stack
      «          #  Append the top two together: Х̈/х̈
       :         #  And replace the Ё/ё with Х̈/х̈ in the (modified) input-string
                 # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž4K` is `1040` and `•2.w2γ•` is `10251061776`.

# Answer
> 6 votes
# JavaScript (ES6),  ~~148 ... 110~~  108 bytes

*Saved 12 bytes thanks to @Grimy!*

This function applies some maths to the code points.

```
s=>s.replace(/./g,s=>String.fromCharCode(...(n=s.charCodeAt()-304)%80-1?[(n^16*(n>0))+304]:[1060+n%48,776]))

```

Try it online!

### How?

For each character in the input string, we define \\$n\\$ as its code point minus \\$304\\$.

```
 characters    | code points  | n
---------------+--------------+---------------
 А to Я        | 1040 to 1071 | 736 to 767
 а to я        | 1072 to 1103 | 768 to 799
 Ё             | 1025         | 721
 ё             | 1105         | 801
 ASCII         | 0 to 126     | -304 to -178

```

Then we apply the following logic:

```
// neither 'Ё' nor 'ё'?
n % 80 - 1 ?
  // output a single code point
  [
    // invert the case if this is a Cyrillic character
    (n ^ 16 * (n > 0))
    // and restore the original offset
    + 304
  ]
:
  // output two code points
  [
    // the first one is either 1061 (Х) or 1093 (х)
    1060 + n % 48,
    // the 2nd one is the combining diaeresis
    776
  ]

```

# Answer
> 5 votes
# Retina 0.8.2, 41 bytes

```
T`А-Па-пя-рЯ-Р`Ro
Ё
Х̈
ё
х̈

```

Try it online! Just a transliteration and a fixup of the two special cases. The characters to be transliterated are listed in mirror order so that `Ro` can be used to specify the reverse order for the transliteration.

# Answer
> 4 votes
# Perl 5 (`-pC -Mutf8 -MUnicode::Normalize=NFD`), 37 bytes (27 chars)

```
$_=NFD$_;y;А-я;Р-ЯА-Пр-яа-п

```

Try it online!

# Answer
> 3 votes
# Red, ~~236~~ 166 bytes

```
func[s][rejoin collect[foreach c s[keep
case[c =#"Ё"["Х̈ "]c =#"ё"["х̈"]c < #"А"[c]any[c > #"Џ"c < #"ѐ"][(pick[#"А"#"а"]c < #"а")+ to 1 c - 1024 % 32]]]]]

```

Try it online!

# Answer
> 1 votes
# PHP (7.4), 199 chars, 333 bytes

```
<?=strtr($argn,array_combine(($s=str_split)(АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяёЁ,2),[...$s(РСТУФХЦЧШЩЪЫЬЭЮЯАБВГДЕЖЗИЙКЛМНОПрстуфхцчшщъыьэюяабвгдежзийклмноп,2),х̈,Х̈ ]));

```

Try it online!

Just a string replacement.

# Answer
> 1 votes
# PowerShell, ~~103~~ ~~102~~ 101 bytes

```
-join$(switch -c($args){Ё{'Х̈'}ё{'х̈'}default{[char](2*(($_-band16)-8)*($_-in1040..1103)+$_)}})

```

Try it online!

This script takes a splatted string. Unrolled:

```
-join$(
    switch -CaseSensitive ($args){
        Ё{'Х̈'}
        ё{'х̈'}
        default {
            $offset  = 2*(($_ -band 16)-8) # -band is 'Bitwise AND'
            $offset *= ($_ -in 1040..1103) # is basic Cyrillic alphabet?
            [char]($offset+$_)

        }
    }
)

```

# Answer
> 1 votes
# Charcoal, 53 bytes

```
ＦＳ¿⁼Ё↥ι⁺§хХ⁼Ёϊ¿№…А¦ѐι℅⁺℅ι⎇‹↥ιР¹⁶±¹⁶ι

```

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

```
ＦＳ

```

Loop over the characters in the input.

```
¿⁼Ё↥ι

```

If the uppercase is equal to `Ё`...

```
⁺§хХ⁼Ёϊ

```

... then print the appropriate `х` or `Х` with its combining character...

```
¿№…А¦ѐι

```

... otherwise if it's a Cyrillic letter...

```
℅⁺℅ι⎇‹↥ιР¹⁶±¹⁶

```

... do some maths on its ordinal to create the character to output...

```
ι

```

... otherwise output the input character.

---
Tags: code-golf, string, cryptography, unicode, encryption
---


# Question
Title: Number of distinct tilings of an n X n square with free n-polyominoes
The newest "nice" OEIS sequence, A328020, was just published a few minutes ago.

> Number of distinct tilings of an n X n square with free n-polyominoes.

This sequence counts tilings up to symmetries of the square. The sequence has six terms, but I'd like to see if folks here can extend it further.

# Example

For `n=4` there are 22 such grids, as shown in this image from the OEIS.  *Credit: Jeff Bowermaster, Illustration of A328020(4).*

# Challenge

Like this previous challenge, the goal of this challenge is to compute as many terms as possible in this sequence, which begins `1, 1, 2, 22, 515, 56734` and where the n-th term is the number of tilings of the n X n grid with n-polyominoes.

Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code to generate it. If two users post the same number of terms, then whoever posts their last term earliest wins.

# Answer
### An extension to @Grimy's code gets N=8

This just underlines that @Grimy deserves the bounty:

I could prune the search tree by extending the code to check, after each finished polyomino, that the remaining free space is not partitioned into components of size not divisible by N.

On a machine where the original code took 2m11s for N=7, this takes 1m4s, and N=8 was computed in 33h46m. The result is 23437350133.

Here is my addition as a diff:

```
--- tilepoly.c  2019-10-11 12:37:49.676351878 +0200
+++ tilepolyprune.c     2019-10-13 04:28:30.518736188 +0200
@@ -51,6 +51,30 @@
     return 1;
 }

+static int check_component_sizes(u64 occupied, u64 total){
+    u64 queue[N*N];
+    while (total<N*N){
+        u64 count = 1;
+        u64 start = ctz(~occupied);
+        queue[0] = start;
+        occupied |= 1ul << start;
+        for(u64 current=0; current<count; ++current){
+            u64 free_adjacent = adjacency_matrix[queue[current]] & ~occupied;
+            occupied |= free_adjacent;
+            while (free_adjacent){
+                u64 next = ctz(free_adjacent);
+                free_adjacent &= ~(1ul << next);
+                queue[count++] = next;
+            }
+        }
+        if (count % N){
+            return 0;
+        }
+        total += count;
+    }
+    return 1;
+}
+
 static void recurse(u64 mino, u64 cell, u64 occupied, u64 adjacent, u64 forbidden)
 {
     if (cell >= N) {
@@ -61,6 +85,9 @@
             return;
         }

+        if(!check_component_sizes(occupied,N*mino))
+            return;
+
         u64 next = ctz(~occupied);
         board[next] = mino;
         recurse(mino, 1, occupied | 1ul << next, adjacency_matrix[next], 0);

```

Try it online!
> 9 votes

# Answer
# C, 7 terms

The seventh term is **19846102**. (The first six are 1, 1, 2, 22, 515, 56734, as stated in the question).

```
#include <stdio.h>
#include <string.h>
#include <stdint.h>

#define N 7
#define ctz __builtin_ctzl

typedef uint64_t u64;

static u64 board[N*N] = { 0 };
static u64 adjacency_matrix[N*N] = { 0 };
static u64 count = 0;

static u64 check_symmetry()
{
    static const u64 symmetries[7][3] = {
        { 0,     +N, +1 },
        { N-1,   -1, +N },
        { N-1,   +N, -1 },
        { N*N-1, -1, -N },
        { N*N-1, -N, -1 },
        { N*N-N, +1, -N },
        { N*N-N, -N, +1 },
    };

    int order[N];

    for (u64 i = 0; i < 7; ++i) {
        u64 start = symmetries[i][0];
        u64 dcol = symmetries[i][1];
        u64 drow = symmetries[i][2];
        memset(order, 0xFF, N*sizeof(int));

        for (u64 row = 0, col = 0; col < N || (col = 0, ++row < N); ++col) {
            u64 base = board[col + N*row];
            u64 symmetry = board[start + dcol*col + drow*row];
            u64 lex = 0;

            while (order[lex] != symmetry && order[lex] != -1)
                ++lex;
            order[lex] = symmetry;

            if (lex < base)
                return 0;

            if (base < lex)
                break;
        }
    }

    return 1;
}

static void recurse(u64 mino, u64 cell, u64 occupied, u64 adjacent, u64 forbidden)
{
    if (cell >= N) {
        ++mino;

        if (mino == N) {
            count += check_symmetry();
            return;
        }

        u64 next = ctz(~occupied);
        board[next] = mino;
        recurse(mino, 1, occupied | 1ul << next, adjacency_matrix[next], 0);
        return;
    }

    adjacent &= ~occupied & ~forbidden;
    while (adjacent) {
        u64 next = ctz(adjacent);
        adjacent &= ~(1ul << next);
        forbidden |= 1ul << next;
        board[next] = mino;
        recurse(mino, cell + 1, occupied | 1ul << next, adjacent | adjacency_matrix[next], forbidden);
    }
}

int main(void)
{
    for (u64 i = 0; i < N*N; ++i) {
        if (i % N)
            adjacency_matrix[i] |= 1ul << (i - 1);
        if (i / N)
            adjacency_matrix[i] |= 1ul << (i - N);
        if (i % N != N - 1)
            adjacency_matrix[i] |= 1ul << (i + 1);
        if (i / N != N - 1)
            adjacency_matrix[i] |= 1ul << (i + N);
    }

    recurse(0, 2, 3, 4 | 3 << N, 0);
    printf("%ld\n", count);
}

```

Try it online! (for N=6, since N=7 would time out.)

On my machine, N=6 took 0.171s, and N=7 took 2m23s. N=8 would take a few weeks.
> 14 votes

---
Tags: code-challenge, sequence, combinatorics, grid, polyomino
---


title: Are my triangles similar?

text:
# Question
Title: Are my triangles similar?
Given (in any *structure*; flat list, two lists of lists, a tuple of matrices, a 3D array, complex numbers,…) the coordinates for two non-degenerate triangles `ABC=[[Ax,Ay],[Bx,By],[Cx,Cy]]` and `PQR=[[Px,Py],[Qx,Qy],[Rx,Ry]]`, determine if they are similar, that is,

> they both have the same shape, or one has the same shape as the mirror image of the other. More precisely, one can be obtained from the other by uniformly scaling (enlarging or reducing), possibly with additional translation, rotation and reflection.\[Wikipedia\]

You may assume that all coordinates are integers.

You must either return a truthy/falsey value indicating similar/dissimilar respectively, or two consistent values; please state your choice.

Failing on some cases due to limitations in floating point precision is acceptable so long as the algorithm is correct in principle.

**Bonus task:** Add a comment to this post stating whether you would like the same challenge generalised to polygons in N-space.

## Walked-through example case

`ABC=[[0,0],[1,0],[0,1]]` and `PQR=[[1,0],[-1,0],[1,-2]]`

1. Reflect `ABC` in the x-axis: `[[0,0],[-1,0],[0,1]]`
2. Reflect in the y-axis: `[[0,0],[-1,0],[0,-1]]`
3. Enlarge by a factor of 2: `[[0,0],[-2,0],[0,-2]]`
4. Translate right by 1 unit: `[[1,0],[-1,0],[1,-2]]`

This gives us `PQR`.

## Test cases

### Similar

`[[8,4],[5,-5],[0,0]]` and `[[-4,-1],[5,-1],[-1,5]]`

`[[-2,1],[4,-2],[6,2]]` and `[[-1,-1],[2,-1],[-1,1]]`

`[[-1,0],[1,0],[0,2]]` and `[[-2,5],[2,5],[0,1]]`

### Dissimilar

`[[0,0],[-1,0],[0,1]]` and `[[1,0],[-1,0],[2,-3]]`

`[[2,1],[4,2],[6,2]]` and `[[-1,-1],[2,-1],[-1,1]]`

`[[-1,0],[1,0],[0,3]]` and `[[-2,5],[2,5],[0,1]]`

# Answer
> 11 votes
# MATL, ~~15~~ 12 bytes

```
,i4:)d|S]/da

```

The program inputs two 3×1 vectors of complex numbers representing the coordinates; and outputs `0` for similar, `1` for not similar.

Try it online! Or verify all test cases.

### Explanation

The code checks if the side lengths, sorted for each triangle, are proportional between the two triangles.

```
,      % Do twice
  i    %   Take input: 3×1 vector of complex numbers
  4:)  %   Modular index to repeat 1st number after the 3rd. Gives a 4×1 vector
  d    %   Consecutive differences
  |    %   Absolute value, element-wise
  S    %   Sort
]      % End
/      % Divide, element-wise
d      % Consecutive differences
a      % Any: gives 0 if and only if all values are 0
       % Implicit display

```

# Answer
> 5 votes
# 05AB1E, 11 bytes

*Port of Luis Mendo's MATL answer.*

Outputs 1 for similar, 0 otherwise.

```
vyĆüαnO{}/Ë

```

Try it online!

# Answer
> 5 votes
# Jelly, 9 bytes

```
ṁ4IAṢ)÷/E

```

A monadic Link accepting a list of two triangles - lists of complex numbers (coordinates on the Cartesian plane). Similar triangles yield `1`, dissimilar ones yield `0`.

**Try it online!** (includes footer to translate from coordinate pairs for ease of use)
Or see the test-suite.

### How?

```
ṁ4IAṢ)÷/E - Link: list       [[a, b, c], [d, e, f]]
     )    - for each:
ṁ4        -   mould like 4   [[a, b, c, a], [d, e, f, d]]
  I       -   deltas         [[b-a,c-b,a-c],[e-d,f-e,d-f]] (i.e. vectors of sides as complex numbers)
   A      -   absolute value (i.e. side lengths)
    Ṣ     -   sort           (ordered side lengths = [[G, H, I], [J, K, L]])
       /  - reduce by:
      ÷   -   division       [G÷J, H÷K, I÷L]
        E - all equal?

```

# Answer
> 3 votes
# JavaScript (ES7),  ~~122 120 117~~  112 bytes

Takes input as `(a)(b)`, where both parameters are in the format used in the challenge.

Returns *false* for similar or *true* for dissimilar.

```
a=>b=>(g=a=>a.map((c,i)=>(h=j=>(c[j]-a[-~i%3][j])**2)(0)+h(1)).sort((a,b)=>a-b))(a).some((x,i)=>a-(a=x/g(b)[i]))

```

Try it online!

### Commented

```
a => b =>                    // a[] = 1st triangle; b[] = 2nd triangle
  ( g = a =>                 // g is a helper function that computes the squared lengths
                             // of the sides of the triangle a[] and sorts them:
      a.map((c, i) =>        //   for each pair c[] of coordinates [x,y] at position i:
        ( h = j =>           //     h is a helper function that computes ...
          ( c[j] -           //       ... the difference between either x(i) and x(i+1)
            a[-~i % 3][j]    //           or y(i) and y(i+1) (in a circular way)
          ) ** 2             //       and squares it
        )(0)                 //     compute (x(i) - x(i+1))²
        + h(1)               //     add (y(i) - y(i+1))²
      )                      //   end of map()
      .sort((a, b) => a - b) //   sort the results in numerical order
  )(a)                       // computes the squared lengths for a[]
  .some((x, i) =>            // for each squared length x at position i:
    a -                      //   compute the difference between the previous ratio
    (a = x / g(b)[i])        //   and the new ratio defined as x / g(b)[i]
                             //   (always NaN for the 1st iteration)
  )                          // end of some()

```

# Answer
> 3 votes
# Python 3, 85 bytes

```
lambda a:len({i/j for i,j in zip(*[sorted(map(abs,[p-q,q-r,r-p]))for p,q,r in a])})<2

```

Try it online!

*-17 bytes thanks to FlipTack*

*-7 bytes thanks to tsh*

Takes a list of lists of coordinates represented by complex numbers as input. Calculates the distances between all points in each set and sorts by magnitude. Then, it checks for all pairs of distances between the two sets if there is a common scaling factor. If so, the triangles are similar.

# Answer
> 3 votes
# , ~~39~~ ~~34~~ 32 bytes

```
1=[:#@~.%&([:/:~#:@3 5 6|@-/@#])

```

Try it online!

Takes input as 3 complex numbers for each triangle.

For each triangle, we get each possible pair of points using a boolean mask filter. Ie, `#:@3 5 6` translates 3, 5, and 6 to their binary representations, and each row selects one possible pair:

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

```

We then get the euclidean distances between of each of these pairs `|@-/` and then sort them `/:~`.

Finally we pairwise divide the 3 sorted sides of the triangle `%`, take the length of the unique elements of that result `#@~.` and test if it equals one `1=`.

# Answer
> 3 votes
# APL+WIN, 40 bytes

Prompts for the co-ordinates of each triangle as a 4 x 2 matrix with first row repeated as last row. Confirmed with OP that this is compliant with the input rules

```
 0=+/2-/(y[⍋y←⍎c])÷x[⍋x←⍎c←'+/(-2-⌿⎕)*2']

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 3 votes
# Python 3, 84 bytes

```
lambda*M:len({x/y for x,y in zip(*[sorted(abs(3*x-sum(l))for x in l)for l in M])})<2

```

Try it online!

Takes input as 3 complex numbers. Outputs True for similar, False for dissimilar. The first test case fails due to a float precision issue with two extremely close float values being unequal; the challenge allows this.

This uses a bit of a different method than other answers that fingerprint congruent triangles by their edges having equal length. Instead of taking the distance between pairs of vertices, we use the distance between each vertex and the center-of-mass of the three vertices, that is their average.

To demonstrate that a unique triangle satisfies this up to congruence, note that the three vectors emanating from the center of mass to the vertices must add by zero by definition, which means these vectors must themselves be able to make a triangle. Since their lengths are fixed and we only get to choose their angles (slopes), this is the same as arranging three sticks as the edges of a triangle, which as noted before is unique up to congruence.

To check similarity, we sort the respective distances and check that their ratios are all equal.

This alternative method is shorter, but I haven't proved that it doesn't give false positives.

**79 bytes**

```
lambda a,b:g(a)==g(b)
g=lambda l:{abs((x-y)/(3*x-sum(l)))for x in l for y in l}

```

Try it online!

# Answer
> 2 votes
# Brachylog, ~~23~~ 21 bytes

```
{{{⊇Ċ-^₂}ᶠ}ᵐz+ᵐo}ᵐz/ᵛ

```

-2 bytes thanks to Unrelated String

A predicate that only accepts similar triangles. Note that for negative values you have to type `_1` instead of `-1`

Try it online!

# Answer
> 2 votes
# Ruby, ~~87 82 77~~ 74 bytes

```
->*a{a.map!{|a,b,c|x,y,z=[a-b,b-c,a-c].map(&:abs).sort;[x/z,y/z]}.uniq!=a}

```

Try it online!

Given the 2 triangles as vectors of 3 complex numbers, calculate length of the three sides as distance between points, sort ascending, then check if a/b and a/c are the same for both.

# Answer
> 1 votes
# Julia 1.0, 65 bytes

```
!x=sort(abs.(diff(push!(x,x[1]))))
g(a,b,z=!a./!b)=all(z.≈z[1])

```

Revised to not abuse the "any input structure" statement, as people seemed down on that. Found extra golfing, so it's only 1 byte longer. The input is two vectors of complex numbers. `!` is a helper function that appends the first element to the end of each input list and returns the result, then takes the difference ob subsequent elements, elementwise absolute value, and sorts. Then calculate the ratios of the sorted lengths of the sides and check that they are all approximately equal. It costs the same number of bytes to compare square side lengths (replace `abs` with `abs2` and  by `==`).

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), 38 bytes

```
Equal@@Sort/@PolygonAngle/@Polygon/@#&

```

~~Try it online!~~

Takes a list containing two lists of coordinates.

Checks if the two triangles' angles are equal. As `PolygonAngle` was introduced in version 12.0, this code does not (yet) work on TIO.

# Answer
> 1 votes
# Charcoal, 46 bytes

```
≔ＥＡＥιΣＸＥλ⁻ν§§ι⊕μξ²θＵＭθ×⟦⌊ι⌈ιΣι⟧Σ§θ¬κ⬤⊟θ⁼ι§§θ⁰κ

```

Try it online! Link is to verbose version of code. Outputs `-` for similar, nothing for dissimilar. Accepts triangles in any N-dimensional space. Explanation:

```
≔ＥＡＥιΣＸＥλ⁻ν§§ι⊕μξ²θ

```

Input the two triangles and calculate the squared lengths of their sides.

```
ＵＭθ×⟦⌊ι⌈ιΣι⟧Σ§θ¬κ

```

Calculate the shortest, longest and sum of the squared sides of each triangle, then scale by the sum of the squared sides of the other triangle.

```
⬤⊟θ⁼ι§§θ⁰κ

```

Check that the shortest and longest and sum of the squared sides are equal. (The middle squared side is the difference between the sum and the other two sides individually, so if they are all equal then the middle squared sides are also equal.)

# Answer
> 0 votes
# Zsh, ~~156 122~~ 116 bytes

```
s(){m=
for a b x y;m+=($[(a-x)**2+(b-y)**2])
n+=(${(n)m})}
s $=1
s $=2
((r=(n[1]+0.)/n[4],r*n[5]-n[2]||r*n[6]-n[3]))

```

~~Try it online! Try it online!~~  Try it online!

Saves 34 bytes by abusing "any structure" for input. Given a pair of triangles:

```
[[1,2],[3,4],[5,6]] and [[7,8],[9,10],[11,12]]

```

The input should be the two strings:

```
'1 2 3 4 3 4 5 6 5 6 1 2' '7 8 9 10 9 10 11 12 11 12 7 8'

```

I believe this is within the rules; there is no calculation done beforehand, simply duplication. No sorting criteria is applied either.

I provide a helper function in the TIO link to prepare an argument list from a string in almost any format (it removes all non-numeric characters and splits).

Here is the first **156 byte** answer, which takes the input in a less abusive format. The abusive format removes line 2 in `s`, and reduces line 3:

```
s() { # helper function, calculates squares and sorts them for one triangle
    m=                             # unset m in case it was already used
    t=(${@:^argv} $1)              # t=('x1 y1' 'x1 y1' 'x2 y2' 'x2 y2' 'x3 y3' 'x3 y3' 'x1 y1'
    for a b x y (${=t:1})          # Remove first element of $t, and split on spaces:
        m+=($[(a-x)**2+(b-y)**2])  # (a b x y): (x1 y1 x2 y2) (x2 y2 x3 y3) (x3 y3 x1 y1)
    m=(${(n)m})                    # sort squared lengths in numeric order
}

s $@[1,3]                          # run s with the first three arguments
n=($m)                             # save first result in n
s ${@:4}                           # run s with the last three arguments
((r=(n[1]+0.)/m[1], r*m[2]-n[2] || r*m[3]-n[3]))  # returns truthy if not similar

```

---
Tags: code-golf, math, number, decision-problem, trigonometry
---


title: Tips for golfing in Keg

text:
# Question
Title: Tips for golfing in Keg
What general tips do you have for golfing in Keg? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Keg (e.g. "remove comments" is not an answer).

Please post one tip per answer.

# Answer
> 6 votes
# Brackets autocomplete

This is my biggest tip for anyone golfing in Keg: when writing programs, brackets used in loops or if-statements are automatically balanced if there are unclosed brackets.

For example:

```
(9|0.)

```

Can be shortened to:

```
(9|0.

```

And:

```
{:1=[1.]}

```

Can be shortened to:

```
{:1=[1.

```

# Answer
> 2 votes
## Use Unicode characters when possible

In Keg, you can represent large constants using simply Unicode characters. Sometimes this is really hard to do, sometimes it is easy and can lead to creative solutions. And there is almost nothing to say about this; this is a canonical feature for golfed Keg programs.

# Answer
> 1 votes
## Using the `;` operator

The `;` operator in Keg can be very powerful. For example for building NOT gates for if statements;

```
11$-[Blah|Blah2]

```

Can be golfed into:

```
1;[Blah|Blah2]

```

# Answer
> 1 votes
# There's A Dictionary!

Like other golfing languages, Keg has a built-in ~60.5k word (~6.05 times better than 05AB1E's) dictionary that is available to be used. There are 6 ways to access the goodness that is `words.txt`:

* Standard Spaceless Strings (Done with backticks)
* Standard Spaceful Strings (Done with )
* SCC-Only Spaceless Strings (Done with )
* SCC-Only Spaceful Strings (Done with )
* Special Spaceless Strings (Done with )
* Special Spaceful Strings (Done with `«`)

**Note that when the terms *spaceful* and *spaceless* are used, they refer to whether or not the string will place spaces between string compression codes when expanding.**

I feel like I should take the time to explain what **S**tring **C**ompression **C**odes are:

Every word within the Keg dictionary has a two byte code associated with it. These range from `00` through to `↫↫`. When the uncompressor sees a string, it will go through and expand each SCC with it's corresponding word from the dictionary (for example, `H%` is `Hello`,  is `World` and  is `Good`). Even though all of the examples had uppercase letters, there are words starting with lower case letters.

## Obtaining SCCs

The best and easiest way to find out what the required SCCs for programs is to navigate to `uncompress.py` and run the program (preferably in some sort of terminal/something that *isn't* IDLE). "But that's a *library*, not a user-friendly program!", I hear you say. Well, when run by a user as a program, it will branch into `if __name__ == "__main__"` and run a helpful session for golfing. If a word is in the dictionary, the corresponding SCC will be printed (single character SCCs start with `0`), otherwise, `-1` will be printed. Here's an example session:

```
Enter a search term: Hello
H% [43, 66]

Enter a search term: world
⬥ [188]

Enter a search term: Keg
-1

Enter a search term: keg
←z [130, 35]

Enter a search term: Um
-1

Enter a search term: Keg
-1

Enter a search term: isn't
4 [4, 239]

Enter a search term: in
-1

Enter a search term: the
0 [0]

Enter a search term: dictionary
V¿ [57, 88]

```

Don't mind the fact that Keg isn't in the dictionary.

# Answer
> 0 votes
# Use Functions where possible

Functions are defined using `@` and store code that would potentially be repeated many times.

---
Tags: code-golf, tips
---


title: North Korean dictionary order

text:
# Question
Title: North Korean dictionary order
# The objective

Given a string of Hangul syllables, sort the characters in North Korean dictionary order.

# Introduction to Hangul syllables

Hangul(한글) is the Korean writing system invented by Sejong the Great. Hangul syllables are allocated in Unicode point U+AC00 – U+D7A3. A Hangul syllable consists of an initial consonant, a vowel, and an optional final consonant.

The initial consonants are:

```
ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ

```

The vowels are:

```
ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ ㅙ ㅚ ㅛ ㅜ ㅝ ㅞ ㅟ ㅠ ㅡ ㅢ ㅣ

```

The final consonants are:

```
(none) ㄱ ㄲ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅆ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ

```

For example,  has initial consonant , vowel , and final consonant .

# South Korean dictionary order

The consonants and vowels above are sorted in South Korean dictionary order. The syllables are firstly sorted by initial consonants, secondly by vowels, and finally by (optional) final consonants.

The Unicode block for Hangul syllables contains every consonant/vowel combinations, and is entirely sorted in South Korean dictionary order.

The Unicode block can be seen here, and the first 256 characters are shown for illustrative purpose:

> 가각갂갃간갅갆갇갈갉갊갋갌갍갎갏감갑값갓갔강갖갗갘같갚갛개객갞갟갠갡갢갣갤갥갦갧갨갩갪갫갬갭갮갯갰갱갲갳갴갵갶갷갸갹갺갻갼갽갾갿걀걁걂걃걄걅걆걇걈걉걊걋걌걍걎걏걐걑걒걓걔걕걖걗걘걙걚걛걜걝걞걟걠걡걢걣걤걥걦걧걨걩걪걫걬걭걮걯거걱걲걳건걵걶걷걸걹걺걻걼걽걾걿검겁겂것겄겅겆겇겈겉겊겋게겍겎겏겐겑겒겓겔겕겖겗겘겙겚겛겜겝겞겟겠겡겢겣겤겥겦겧겨격겪겫견겭겮겯결겱겲겳겴겵겶겷겸겹겺겻겼경겾겿곀곁곂곃계곅곆곇곈곉곊곋곌곍곎곏곐곑곒곓곔곕곖곗곘곙곚곛곜곝곞곟고곡곢곣곤곥곦곧골곩곪곫곬곭곮곯곰곱곲곳곴공곶곷곸곹곺곻과곽곾곿

For example, the following sentence (without spaces and punctuations):

```
키스의고유조건은입술끼리만나야하고특별한기술은필요치않다

```

is sorted to:

```
건고고기끼나다리만별술술스않야요유은은의입조치키특필하한

```

In C++, if the string is in `std::wstring`, the sorting above is plain `std::sort`.

# North Korean dictionary order

North Korean dictionary has different consonant/vowel order.

The initial consonants are sorted like:

```
ㄱ ㄴ ㄷ ㄹ ㅁ ㅂ ㅅ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ㄲ ㄸ ㅃ ㅆ ㅉ ㅇ

```

The vowels are sorted like:

```
ㅏ ㅑ ㅓ ㅕ ㅗ ㅛ ㅜ ㅠ ㅡ ㅣ ㅐ ㅒ ㅔ ㅖ ㅚ ㅟ ㅢ ㅘ ㅝ ㅙ ㅞ

```

The final consonants are sorted like:

```
(none) ㄱ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ㄲ ㅆ

```

Like South, the syllables are firstly sorted by initial consonants, secondly by vowels, and finally by (optional) final consonants.

If the sentence above is given, the output must be:

```
건고고기나다리만별술술스조치키특필하한끼않야요유은은입의

```

# Rules

1. If the input contains a character not within U+AC00 – U+D7A3, it falls in *don't care* situation.
2. As this is a code-golf, the shortest code in bytes wins.

# Answer
# 05AB1E, ~~47~~ ~~45~~ 38 bytes

```
Σ•¡®šúIтÝ„Š’#„λ†x!·“•4B33¡€.ā`ââyÇ68+è

```

Try it online!

```
Σ                        # sort characters of the input by:
 •...•                   #  compressed integer 13096252834522000035292405913882127943177557
      4B                 #  converted to base 4: 211211121231211111033010101010231002310010331121111111111111111121111111
        33¡              #  split on 33: [2112111212312111110, 010101010231002310010, 1121111111111111111121111111]
           €.ā           #  enumerate each (pairs each digit with its index)
              `ââ        #  reduce by cartesian product (yields a list with 11172 elements)
                 yÇ      #  codepoint of the current character
                   68+   #  + 68
                      è  #  index into the large list (with wraparound)

```
> 1 votes

# Answer
# JavaScript (ES6),  ~~150 148~~  137 bytes

*Saved 10 bytes thanks to @Grimy*

I/O: arrays of characters.

```
a=>a.map(c=>"ANBCODEFPGQSHRIJKLM"[(n=c.charCodeAt()-44032)/588|0]+"AKBLCMDNERTOFGSUPHIQJ"[n/28%21|0]+~(n%28%18==2)+c).sort().map(s=>s[4])

```

Try it online!

### Splitting Hangul syllables

Given a Hangul character of code point 0xAC00 + \\$n\\$, the initial consonant \\$I\\$, vowel \\$V\\$ and final consonant \\$F\\$ are given by:

$$I=\left\lfloor\frac{n}{588}\right\rfloor,\ V=\left\lfloor\frac{n}{28}\right\rfloor\bmod 21,\ F=n\bmod 28$$

### Commented

```
a => a.map(c =>                  // for each character c in the input:
  "ANBCODEFPGQSHRIJKLM"[         //   start with a letter from 'A' to 'S'
    (n = c.charCodeAt() - 44032) //   for the initial consonant
    / 588 | 0                    //
  ] +                            //
  "AKBLCMDNERTOFGSUPHIQJ"[       //   append a letter from 'A' to 'U'
    n / 28 % 21 | 0              //   for the vowel
  ] +                            //
  ~(                             //   append "-2" for ㄲ or ㅆ (the only North
    n % 28 % 18 == 2             //   Korean final consonants that are sorted
  ) +                            //   differently) or "-1" otherwise
  c                              //   append the original character
)                                // end of map()
.sort()                          // sort in lexicographical order
.map(s => s[4])                  // isolate the original characters

```
> 7 votes

# Answer
# Charcoal, 80 bytes

```
Ｆ”&→∧⁶⍘⎚%γD¦ρJG”Ｆ”E⎇↓Ｎη⊙��⭆Ｗs@}4”Ｆ”E↖hＹ9 t⟧⊙γIO↶5ε∧¬⁶⦃”Φθ⁼℅μΣ⟦⁴⁴⁰³²×⌕βι⁵⁸⁸⍘⁺κλ²⁸

```

Try it online! Link is to verbose version of code. Explanation: Works by generating all 11172 Hangul syllables in North Korean dictionary order and checking to see which ones are present in the input (so all other characters get deleted; also somewhat slow: takes 18 seconds on TIO). Explanation:

```
Ｆ”&→∧⁶⍘⎚%γD¦ρJG”

```

Loop over the compressed string `acdfghjmopqrsbeiknl`. This represents the list of South Korean initial consonants (numbered using the Western lowercase alphabet) in North Korean dictionary order.

```
Ｆ”E⎇↓Ｎη⊙��⭆Ｗs@}4”

```

Loop over the compressed string `02468cdhik1357bgj9eaf`. This represents the list of South Korean vowels (numbered using ASCII digits and lowercase alphabet) in North Korean dictionary order.

```
Ｆ”E↖hＹ9 t⟧⊙γIO↶5ε∧¬⁶⦃”

```

Loop over the compressed string `013456789abcdefghijlmnopqr2k`. This represents the list of South Korean final consonants (using the same numbering as the vowels) in North Korean dictionary order.

```
Φθ⁼℅μΣ⟦⁴⁴⁰³²×⌕βι⁵⁸⁸⍘⁺κλ²⁸

```

Concatenate the vowel and final consonant and decode as a base 28 number, then add on 588 times the initial vowel and 0xAC00. Print all characters from the input that have that as their ordinal.
> 1 votes

---
Tags: code-golf, string, sorting, natural-language, unicode
---


title: Tips for golfing in Forth

text:
# Question
Title: Tips for golfing in Forth
What general tips do you have for golfing in Forth (and its clones)? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Forth (e.g. "remove comments" is not an answer).

# Answer
## Avoid explicit loops at all costs

Forth has two looping constructs, `x y do` ... `loop`, and lesser known `[begin]` ... `[until] x y` where `x` and `y` are values for limit and index, or conditions to be noted, respectively.

These are very slow, very wordy (haha) and overall rather bloaty, so only use them if you need to.

Instead, like a proper functional language (which Forth is, really), one should prefer recursivity over explicit loops because it tends to be shorter and makes a better use of the language.
> 5 votes

# Answer
Forth has a **lot** of cool builtin words, many of which are helpful for crafting the sorts of algorithms found on PPCG.

A bad but illustrative example of this are the words for increment (`1+`) and decrement (`1-`). They save a byte over writing `1 +` to increment the top of the stack.

Additonally, here is a handy list of many (probably not all) words found in modern distributions like `gforth`.
> 3 votes

# Answer
## Leave the junk

Programs aren't required to be stack-safe.

Instead, they can leave extra junk on the stack if it saves you bytes. In Forth, the "return value" is leaving something on top of the stack. It probably doesn't matter what junk you have below that on the stack unless you're using recursion and stack depth matters.
> 3 votes

# Answer
## Watch the stack

When writing your code, pay attention to what happens on the stack at each command. I usually draw it out as I go, like so:

```
6       6
7       7 6
* DUP   42 42

```

As you go like this, you may find it easier to recognize when you can make use of stack operations like `ROT`, `-ROT`, `2DUP`, `2OVER`, etc...
> 1 votes

# Answer
# Try using various double-cell words

This includes double-cell arithmetic, bitwise, number comparison and stack manipulation words. Double-cell integer literals also count.

* Appending a period on an integer literal (e.g. `1.`) gives a double-cell literal. For small numbers, it means pushing an extra zero at the cost of only one byte.
* `m+` = `0 d+` ~= `under+` (not exactly, since overflow may occur.)
* `d2*` and `d2/` could be used to extract/push one bit from a word.
* `a b c d d=` = `a c = b d = and`
* `a b c d d<>` = `a c <> b d <> or`
* Words that copy two numbers at once, e.g. `2dup`, `2over`, `2tuck` have a good chance to win over local variables.
> 1 votes

# Answer
## (gforth-specific) Utilize the separate floating-point stack

gforth has a separate stack for floating-point numbers. Even if you're only dealing with integers, offloading some work and storage to the FP stack may result in shorter code overall, either by avoiding explicit stack manipulation or using FP-specific operations not available on the main stack. Returning to the FP stack is also a perfectly valid option (except when the task is to return a boolean).

* FP-related operations (arithmetic, stack manipulation) usually cost one more byte each (the `f` prefix, as in `f+`, `fdup` etc.). FP number literals also cost one more byte (postfix `e`, as in `1e`), but some numbers can tie or even save a byte (e.g. `1e3` instead of `1000`).
* Some operations are missing on the FP stack, probably the most painful being `1+` and `1-`.
* FP stack's unique operations include `f**` (power), `falog` (power of 10), `fsqrt`, and various exp, log, trigonometry-related ones.
* You can move numbers between main and FP stacks via `s>f` (single to float), `f>s` (float to single), `d>f` (double to float), `f>d` (float to double). At times, the "double" variations may be used to produce or consume an extra zero.
> 1 votes

---
Tags: code-golf, tips
---


title: Tips for golfing in CJam

text:
# Question
Title: Tips for golfing in CJam
CJam is a GolfScript-inspired stack-based golfing language, created by PPCG user aditsu.

So, in the vein of other language-specific tips questions:

What general tips do you have for golfing in CJam? Please post *one tip* per answer.

# Answer
# Correct modulo for negative numbers

It's often annoying that the result of the modulo operation gives the same sign as the first operand. E.g. `-5 3%` gives `-2` instead of `1`. More often than not you want the latter. The naive fix is to apply modulo, add the divisor once and apply modulo again:

```
3%3+3%

```

But that's long and ugly. Instead, we can use the fact that array indexing is always modular and *does* work correctly with negative indices. So we just turn the divisor into a range and access that:

```
3,=

```

Applied to `-5`, this gives `1` as expected. And it's only one byte longer than the built-in `%`!

If the modulus is a power of 2, you can save another byte using bitwise arihmetic (which is also a lot faster). Compare:

```
32,=
31&

```

For the special case of `65536 == 2^16` another byte can be saved by making use of the wrapping behaviour of the character type:

```
ci

```
> 23 votes

# Answer
# Pushing concatenated character ranges

* The string containing all digits `"0123456789"` can be written as

```
A,s

```
* The uppercase ASCII letters (`A-Z`) can be pushed as

```
'[,65>

```

which generates the string of all characters up to **Z**, then discards the first 65 (up to **@**).
* All ASCII letters (`A-Za-z`) can be pushed as

```
'[,65>_el+

```

which works as above, then creates a copy, converts to lowercase and appends.

But there's a shorter way to do it!

Then often overlooked `^` operator (symmetric differences for lists) allows to create the same ranges while saving three bytes:

```
'[,_el^

```

`'[,` creates the range of all ASCII characters up to **Z**, `_el` creates a lowercase copy and `^` keeps only characters of both strings that appear in one but not both.

Since all letters in the first string are uppercase, all in the second are lowercase and all non-letter characters are in both strings, the result in the string of letters.
* The RFC 1642 Base64 alphabet (`A-Za-z0-9+/`) can be pushed using the above technique and appending the non-letters:

```
'[,_el^A,s+"+/"+

```

An equally short way of pushing this string makes use solely of symmetric differences:

```
"+,/0:[a{A0":,:^

```

How can we find the string at the beginning?

All used character ranges (`A-Z`, `a-z`, `0-9`, `+`, `/`) can be pushed as the symmetric difference of to range that start at the null byte, namely `'A,'[,^`, `'a,'{,^`, `'0,':,^`, `'+,',,^` and `'/,'0,^`.

Therefore, executing `:,:^` on `"A[a{):+,/0"` will push the desired characters, but not in the right order.

How do we find the right order? Brute force to the rescue! The program

```
'[,_el^A,s+"+/"+:T;"0:A[a{+,/0"e!{:,:^T=}=

```

iterates over all possible permutations of the string, applies `:,:^` and compares the result to the desired output (permalink).
* The radix-64 alphabet used, e.g, by crypt (`.-9A-Za-z`) can be generated using the above method:

```
".:A[a{":,:^

```

This is the shortest method I know.

Since all characters in the desired output are in ASCII order, iterating over permutations isn't needed.
* Not all concatenated character ranges can be pushed in the desired order using `:,:^`.

For example, the range `0-9A-Za-z;-?` cannot be pushed by executing `:,:^` on any permutation of `"0:A[a{;@"`.

However, we can find a rotated variation of the desired string that can, by using the code

```
A,'[,_el^'@,59>]s2*:T;"0:A[a{;@"e!{:,:^T\#:I)}=Ip

```

which will print (permalink) the following:

```
10
0:@[a{A;

```

This means that

```
"0:@[a{A;":,:^Am>

```

has the same effect as

```
A,'[,_el^'@,59>]s

```

which can only be used with an empty stack without prepending a `[`.
> 13 votes

# Answer
# Avoid {…}{…}?

Assume you have an integer on the stack. If it is odd, you want to multiply it by 3 and add 1; otherwise you want to divide it by 2.

A "normal" if/else statement would look like this:

```
_2%{3*)}{2/}?

```

However, using blocks is usually not the way to go, since `{}{}` already adds four bytes. `?` can also be used to select one of two items on the stack:

```
_2%1$3*)@2/?

```

This is one byte shorter.

---

Block-? with an empty if statement is always a no-go. For example,

```
{}{2/}?

```

is two bytes longer than

```
{2/}|

```

If instead you have

```
{2/}{}?

```

and the thing you are checking on is non-negative integer, you can do

```
g)/

```

---

The new `{}&` and `{}|` are handy, but sometimes problematic if you cannot clutter the stack.

Still, in the case of

```
_{…}{;}?

```

you can use a temporary variable instead:

```
:T{T…}&

```
> 11 votes

# Answer
# Golfing common array and string values

There are certain short arrays or strings that crop up every now and then, e.g. to initialise grids. Naively, these can cost 4 or more bytes, so it's worth looking for operations on built-in values which will give the same result. Especially base conversion is often useful.

* `[0 1]` can be written as `2,`.
* `[1 0]` can be written as `YYb` (i.e. 2 in binary).
* `[1 1]` can be written as `ZYb` (i.e. 3 in binary).
* The matrix `[[0 1] [1 0]]` can be written as `2e!`.
* `[LL]` can be written as `SS/` (splitting a single space by spaces).
* `"\"\""` can be written as `L``.
* `"{}"` can be written as `{}s`.

The latter can be extended to cases where you want all bracket types to save another byte:

* `"[{<()>}]"` can be written as `{<()>}a``.
* `"()<>[]{}"` can be written as `{<()>}a`$`.

Especially the base conversion trick can be useful to keep in mind for some obscurer cases that pop up every now and then. E.g. `[3 2]` would be `E4b` (14 in base 4).

In even rarer cases you might even find the factorisation operator `mf` useful. E.g. `[2 7]` is `Emf`.

Please feel free to extend this list if you come across any other examples.
> 11 votes

# Answer
# Switch statements

CJam doesn't have switch statements. Nested if statements work just as well, but `{{}{}?}{}?` is already 12 bytes long...

If we can transform the condition into a small, non-negative integer, we can transform all case statements in a delimited string and evaluate the corresponding result.

For example, if we want to execute `code0` if the integer of the stack is **0**, `code1` if it is **1**, and `code2` if it is **2**, we can either use

```
_{({code2}{code1}?}{;code0}?

```

or

```
[{code0}{code1}{code2}]=~

```

or

```
"code0 code1 code2"S/=~

```

`S/` splits the string into `["code0" "code1" "code2"]`, `=` extracts the corresponding chunk, and `~` evaluates the code.

Click here to see switch statements in action.

Finally, as suggested by suggested by @jimmy23013 and @RetoKoradi, we can shorten the switch even more in some cases. Say `code0`, `code1` and `code2` have lengths **L0**, **L1** and **L2**, respectively.

If **L0 = L1 ≥ L2**

```
"code0code1code2"L/=~

```

can be used instead, where `L` is **L0**. Instead of splitting at a delimiter, `/` splits the string into chunks of equal length here.

If **L0 ≥ L1 ≥ L2 ≥ L0 \- 1**,

```
"cccooodddeee012">3%~

```

can be used instead. `>` removes 0, 1 or 2 elements from the beginning of the string, and `3%` extracts every third element (starting with the first).
> 11 votes

# Answer
## Clearing the stack

If you just want to clear the entire stack, wrap it in an array and pop it:

```
];

```

What's a bit more tricky is, if you've done a lot of computations, but only want to keep the top stack element and discard everything beneath. The naive approach would be to store the top element in a variable, clear the stack, push the variable. But there's a much shorter alternative: wrap the stack in an array and extract the last element:

```
]W=

```

(Thanks to Optimizer who showed this to me the other day.)

Of course, if there's only two elements on the stack, `\;` is shorter.
> 10 votes

# Answer
# Euclidean norms

The straightforward way of calculating the Euclidean norm of a vector, i.e., the square root of the sum of the squares of its elements, is

```
2f#:+mq

```

However, there's a much shorter way.

`mh`, the hypotenuse operator, pops two integers **a** and **b** from the stack and pushes **sqrt(a2 \+ b2)**.

If we have a vector **x := \[x1 … xn\], n \> 1** on the stack, `:mh` (reduce by hypotenuse) will achieve the following:

* First **x1** and **x2** are pushed and `mh` is executed, leaving **sqrt(x12 \+ x22)**, on the stack.
* Then, **x3** is pushed and `mh` is executed again, leaving
**sqrt(sqrt(x12 \+ x22)2 \+ x32) = sqrt(x12 \+ x22 \+ x32)** on the stack.
* After **xn** has been processed, we're left with **sqrt(x12 \+ … xn2)**, the Euclidean norm of **x**.

If **n = 1** and **x1 \< 0**, the above code will produce an incorrect result. `:mhz` works unconditionally. (Thanks to @MartinBüttner for pointing that out.)

I've used this trick for the first time in this answer.
> 9 votes

# Answer
# `e` and powers of ten

As in oh-so-many other languages, you can write `1e3` instead of `1000` in CJam.

This works for non-integer bases and even for non-integer exponents as well. For example, `1.23e2` pushes **123.0** and `1e.5` pushes **3.1622776601683795** (square root of **10**).

What's not immediately obvious is that `1e3` is actually *two* tokens:

* `1` pushes the integer **1** on the stack.
* `e3` multiplies it by **1000**.

Why is that important?

* You can call `e<numeric literal>` on something that's already on the stack.

```
2 3 + e3 e# Pushes 5000.

```
* You can map `e<numeric literal>` over an array.

```
5 , :e3  e# Pushes [0 1000 2000 3000 4000].

```
> 9 votes

# Answer
# Convert from base n with a list of numbers greater than n

CJam converts a list to a number with this formula: A0\*nl \+ A1\*nl-1 \+ A2\*nl-2 \+ Al\*n0 (with nonnegative `n`). `n` is the base and `l` is the list length. This means Ai can be any integer, which doesn't have to be in the range of `[0,n)`.

Some examples:

* `0b` extracts the last item and cast it to integer. Works like `W=i` and saves a byte if it wasn't integer. But everything else in the list must also be able to cast into integer.
* `1b` returns the sum. Works like `:i:+` and saves two bytes if they weren't integers. It also works with empty lists while `:+` doesn't.
* `[i{_1&9 32?_@\m2/}16*;]W%:c` converts a character to a string of line endings and tabs, which can be converted back with `2bc`. The encoding function isn't easy to be golfed in a code-golf program, though. But you don't usually need that.
* You can use the following code to convert a string to Unicode characters not in 16 bit, which can be converted back with `2A#b128b:c`. (Explanations will be added later. Or perhaps I'll write a new version later.)

```
128b2A#b         " Convert to base 1024. ";
W%2/)W%\:+       " Convert to two base 1024 digit groups. ";
[0X@
{
  _54+
  @I+_Am>@\-
  _Am<@+ 0@-@1^
}fI
]);)
@\+[~+]2A#b_2G#<!{2A#b}*
\W%+:c

```

The similar method works with any set of `n` integers which have different values mod `n`, if you can find some way to get rid of the most significant digit.
> 8 votes

# Answer
# Using `$` as ternary if

When you don't mind leaking memory, i.e., leaving unused elements on the stack that you'll later clear with `];`, the copy operator `$` can be a handy substitute for the ternary operator `?`.

`?` works well if you manage to compute the condition before pushing the two items to choose from, but more often than not, the condition actually depends on those items, and having it on top of them results much more natural.

If you have `A B C` on the stack, you can execute

```
!$

```

instead of

```
\@?

```

to copy `B` if `C` is truthy and `A` otherwise.

If `C` is an actual Boolean (`0` or `1`), you can execute

```
$

```

instead of

```
@@?

```

to copy `A` if `C` is truthy and `B` otherwise.
> 8 votes

# Answer
# Map for Nested Lists

Say you've got a nested list, like a matrix:

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

```

Or an array of strings:

```
["foo""bar"]

```

And you want to map a block onto the nested level (i.e. apply it to each number or each character). The naive solution is a nested `%`:

```
{{...}%}%

```

However, you can actually push the inner block onto the stack and then use `f%`. `f` is "map with additional parameter", so it will map `%` onto the outer list, using the block as the second parameter:

```
{...}f%

```

Saves two bytes.

Another neat trick to do something like `for (i=0; i<5; ++i) for (j=0; j<5; ++j) {...}` is

```
5,_f{f{...}}

```

The outer `f` will map onto the first range, supplying the second range as an additional parameter. But now, if you use `f` again, only the top stack element is an array, so you `f` maps the inner block onto that, supplying the outer "iteration variable" as an additional parameter. This means the inner block is runs with `i` and `j` on the stack.

This has the same number of characters as just mapping a block onto a Cartesian product (although the latter gets shorter if you need the pairs as arrays):

```
5,_m*{~...}%

```

The difference is that this version yields a single array of results for all pairs, whereas the double-`f` yields a nested list, which can be useful if you want to store the results in a grid, with the iterator variables being the coordinates.

Thanks to Dennis for showing me this trick.

## 0.6.4 Update

`f` and `:` have now been immensely improved by taking any other operator including themselves. This means you can save even more bytes now. Mapping an operator onto a nested list got even shorter now:

```
{:x}%
{x}f%
::x

```

This doesn't really help with mapping blocks onto nested lists though.

As for the applying blocks or operators to the Cartesian product, this also got shorter now, for blocks as well as operators:

```
5,_f{f{...}}
5,_ff{...}

5,_f{fx}
5,_ffx

```

What's nice is that you can now nest these. So you can apply an operator just as easily to the third level down a list:

```
:::x

```

Or a block with some trickery:

```
{...}ff%

```
> 7 votes

# Answer
# Vectorized operators for ASCII art

For many ASCII art challenges, it is useful to generate two different patterns to superpose them later. Vectorized operators can be very helpful to achieve different types of superpositions.

One useful property of operator vectorization is that the operator is only executed once for each element of the shorter string/array, while the elements of the larger one that do not have counterparts remain untouched.

* ### `.e<`

The minimum operator `e<` work for pairs of strings, characters, arrays and integers; it pops two items from the stack and pushes the lower on e back.

Since a space has a lower code point than all other printable ASCII characters, `.e<` can be used to "erase" parts of a generated pattern:

```
"\/\/\/\/\/" "    " .e<

e# This pushes "    \/\/\/".

```

For a full example, see my answer to Me Want Honeycomb.
* ### `.e>`

The maximum operator `e>` works as the minimum operator, with the opposite result.

Again, because of the low code point of the space, `.e>` can be used to insert a pattern of printable characters in a block of spaces:

```
[[" " " " " " " "] [" " " " " " " "]][["+" "" "-" ""]["" "*" "" "/"]] ..e>

e# This pushes [["+" " " "-" " "] [" " "*" " " "/"]].

```

For a full example, see my answer to Seven Slash Display.
* ### `.e&`

The logical AND operator `e&` pushes its left argument if it is falsy and its right argument otherwise.

If neither pattern contains falsy elements, this can be used to inconditionally impose one pattern over another one:

```
"################" " * * * *" .e&

e# This pushes " * * * *########".

```

For a full example, see my answer to Print the American Flag!.
* ### `.e|`

The logical OR operator `e|` can be used as above, with reversed argument order:

```
" * * * *" "################" .e|

e# This pushes " * * * *########".

```
> 7 votes

# Answer
# Use `&` to check if an item is in a list

For

```
1 [1 2 3] #W>
1 [1 2 3] #)

```

You can use

```
1 [1 2 3] &,
1 [1 2 3] &

```

instead, which returns 0/1 and truthy/falsey respectively.
> 6 votes

# Answer
# `z` and non-rectangular arrays

The zip operator `z` transposes the rows and columns of a two-dimensional1 array **A**, whose elements can also be iterables.

For non-rectangular arrays – unlike the built-in `zip` functions in, e.g., Python (truncates the rows to the same length) or Ruby (pads the rows with `nil`) – CJam simply converts the columns of the array into rows, ignoring their lengths and gaps.

For example, zipping the array

```
[
  [1]
  [2 4]
  [3 5 6]
]

```

is equivalent to zipping the array

```
[
  [1 4 6]
  [2 5]
  [3]
]

```

or the array

```
[
  [1]
  [2 4 6]
  [3 5]
]

```

as all three actions push

```
[
  [1 2 3]
  [4 5]
  [6]
]

```

on the stack.

While this means that `z` is not an involution (which would be useful on occasions), it has a few applications.

For example:

* We can align the columns of an array to the top (i.e., turn the first array into the second) by zipping twice:

```
zz

```
* Minor modifications of the above method can be used for similar problems.

For instance, to align the columns of an array to the bottom (i.e., to turn the second array into the first), we can zip twice with reversed row order:

```
W%zzW%

```
* Given an array of strings, we can compute the length of the longest string like this:

```
:,:e>

```

However, by zipping and calculating the number of rows of the result, we can save three bytes:

```
z,

```

---

1 If any of the "rows" of **A** is not iterable, `z` treats them as singletons, so zipping works for arbitrary arrays.
> 6 votes

# Answer
# Exceptions

All exceptions are fatal in CJam. Since output to STDERR is ignored by default, we can use this to our advantage.

All operator in CJam work by popping zero or more elements from the stack, perform some task and push zero or more elements on the stack. Exceptions occur while the task is performed, so this still pops the elements, but nothing is pushed in return.

Here are a few use cases:

* **Clearing a small stack**

To clear a stack that contains two elements, `@` can be used. `@` tries to pop three stack elements, but fails after popping the second.

Any other operator that pops three elements would serve the same purpose.

See it in action here.
* **Removing two or three elements from the stack**

Any operator that is not implemented for these particular elements can be used to pop two or three elements from the stack right before exiting.

To pop two elements, `b` works if one of them is a character or none of them is an integer.

To pop three elements, `t` works if none of the bottom-most two is an iterable, the bottom-most iterable is empty or none of them is an integer.
* **Exiting from a loop**

On occasions, we need to exit from a loop when an integer becomes zero or a string becomes too short. Rather than testing for these conditions, if the involved operations fail for zero, the empty string or singletons, we can simply let the program take its natural course.

For an example involving arithmetic, see here.

For an example involving strings, see here.
* **Conditional execution**

If the source code should not be executed for certain types of input, we sometimes can use an operator that fails that kind of input.

For example, `i` will fail for strings that do not evaluate to an integer and `ew` will fail for strings of length 0 or 1.

See it in action here.
> 6 votes

# Answer
## Max/Min from an array

Here is one for starters!

When you need to find the maximum or minimum number from an array, the easiest and smallest way is to sort the array and then take out the first or last element.

So if the array is in variable `A`

```
A$W=

```

is the maximum and

```
A$0=

```

is the minimum.

Get both at the same time is also possible

```
A$)\0=

```

This might seem obvious after reading, but anyone's first attempt tends to go towards the usage of `e<` or `e>` via iterating through the array, which goes like

```
A{e<}*

```

which is 2 bytes longer, and even longer if you want both max and min.
> 5 votes

# Answer
# Use a timestamp for large numbers

If you need a very large, but arbitrary number, you'll usually either use scientific notation like `9e9` or raise one of the large built-in variables to a similar power, like `KK#`. However, if you don't care what the actual number is, and it doesn't need to be consistently the same (e.g. as the upper bound for a random number), you can do it in two bytes using

```
es

```

instead. This gives the current timestamp in milliseconds, and is on the order of 1012
> 5 votes

# Answer
# Checking that two strings/arrays are not equal

Sometimes you want a truthy value when two strings or arrays are not equal, and a falsy value if they are. The obvious solution is two bytes:

```
=!

```

Check for equality, and invert the result. However, under some conditions you can use

```
#

```

When `#` is applied to two arrays it actually searches for the second array as a subarray of the first (and gives you the index where the subarray starts). So if the two arrays are the same, the subarray will be found right at the start and give `0`, which is falsy. But if the second array cannot be found, it will give `-1` which is truthy.

The reason we need some additional condition on the two arrays is that this also yields a falsy value if the second array is a non-trivial prefix of the first, e.g.:

```
"abc""ab"#

```

gives `0` although the strings are not the same. The simplest condition which rules out this case is if you know that both arrays will be the same length - in that case if one is a prefix of the other, you know that they are equal. But in specific circumstances there may be weaker conditions that are also sufficient. For instance, if you know that the strings are sorted, a prefix would always be the first string, not the second.
> 5 votes

# Answer
# `c` and 16-bit integers

To add (or subtract) unsigned 16-bit integers with proper wrapping, you can use `+65536%` or `+2G#%`.

However,

```
+ci

```

is a lot shorter. Characters wrap arround at **65536**, so casting to Character (`c`) then to Long (`i`) has a similar effect to `65536%`, with the added benefit that the result will not be negative.

The same trick can be used to push **65535**:

```
Wci

```
> 5 votes

# Answer
# Power sets

Say you have an array and you want an array with all possible subsets of that array. The trick is to start with an empty array, and then, for each element, duplicate the subsets you already have, and add the new element to them (keeping previous result where the element *wasn't added*). Note that you need to initialise the stack with the base case, i.e. an array containing only an empty array: That could look like this:

```
[1 2 3 4 5]La\{1$f++}/

```

The nice thing about this is, you can immediately run some computation on the subset, potentially without added characters. Say you want the products of all subsets. In that case, the base case is an array containing `1`, and at each step, you take the previous list of possible products, duplicate it, and multiply everything in the duplicate by the new element:

```
[1 2 3 4 5]1a\{1$f*+}/

```
> 4 votes

# Answer
# Check if items in a list are all the same

I think this also worth mentioning. Use:

```
)-

```

Returns truthy if not all the same, or empty list if all the same. Errors if the list is empty.

In case the item extracted might be an array (or string) itself:

```
)a-

```

Use `!` or `!!` to get boolean values. In case the item extracted might be an array, and there are at most two kind of different items, and you want it to be 1 if not all the same, this is shorter:

```
_|,(

```
> 4 votes

# Answer
# `0=` for strings

To retrieve the first element of an array, you have to use `0=` (or `(`, if you don't mind leaving the rest of the array on the stack).

However, if that array is a string, casting to character is sufficient.

### Example

```
"xyz"c e# Pushes 'x.

```
> 4 votes

# Answer
# Rotating an array (or the stack) one unit to the left

CJam has the *rotate left* operator `m<`, which is normally what you should use to rotate an array an arbitrary number of units to the left.

In *some* cases, you can also use `(+` to shift and append:

```
[1 2 3]       (+ e# Pushes [2 3 1].
[[1] [2] [3]] (+ e# Pushes [[2] [3] 1].

```

The second example did not work because the arrays first element is also an iterable, so `+` concatenated instead of appending.

Also, if you want to dump the rotated array on the stack, you can use `:\` (reduce by swapping) unconditionally:

```
[1 2 3]       :\ e# Pushes 2 3 1.
[[1] [2] [3]] :\ e# Pushes [2] [3] [1].

```

As long as you don't have an open `[`, this trick can also be used to rotate the entire stack, i.e., to bring the bottom-most stack item to the top:

```
]:\

```
> 4 votes

# Answer
# Printing a list and clearing the stack

Lets say your stack has a list of strings/numbers/etc. on top and some other extra items below it. i.e.

```
123 "waste" ["a" "b" "rty" "print" "me" "please"]

```

Now you are interested in printing the last list only, so you do

```
S*]W=

```

which outputs

```
a b rty print me please

```

Which seems really smart as we use the clearing the stack trick and only print the list joined with spaces (which might not be the desired way of printing a list at times).

This can be golfed further!

```
p];

```

**That's 2 bytes shorter**!

and if you have only 1 item on stack other than the list, its even shorter!

```
p;

```

The beauty of `p` is that it removes the top most item from stack, stringifies it (also adds a newline at the end) and prints to STDOUT instantly, without waiting for completion of the code.

So the above code will output

```
["a" "b" "rty" "print" "me" "please"]

```

which is the exact representation of a list when it was in stack!
> 3 votes

# Answer
# Cartesian products or all possible combinations of two or more sets

CJam has an inbuilt Cartesian product calculator `m*` which takes the top two arraylists/strings on stack and create all possible pairs from it. For example

```
[1 2 3 4]"abc"m*

```

leaves

```
[[1 'a] [1 'b] [1 'c] [2 'a] [2 'b] [2 'c] [3 'a] [3 'b] [3 'c] [4 'a] [4 'b] [4 'c]]

```

as the stack

But what if you want all possible combinations from more than 2 lists/strings. You use `m*` that many times ? For example

```
[1 2 3 4][5 6]"abc"m*m*

```

will leave the following on stack

```
[[1 [5 'a]] [1 [5 'b]] [1 [5 'c]] [1 [6 'a]] [1 [6 'b]] [1 [6 'c]] [2 [5 'a]] [2 [5 'b]] [2 [5 'c]] [2 [6 'a]] [2 [6 'b]] [2 [6 'c]] [3 [5 'a]] [3 [5 'b]] [3 [5 'c]] [3 [6 'a]] [3 [6 'b]] [3 [6 'c]] [4 [5 'a]] [4 [5 'b]] [4 [5 'c]] [4 [6 'a]] [4 [6 'b]] [4 [6 'c]]]

```

Notice that the products are still pairs, where one of the item is a pair itself. This is not expected and we want flattened combinations.

There is an easy way to do that. Just wrap every list that you want for your cartesian product in an array, pairwise create Cartesian products and flatten it each time:

```
[1 2 3 4][5 6]"abc"]{m*{(+}%}*

```

This leaves

```
[['a 5 1] ['b 5 1] ['c 5 1] ['a 6 1] ['b 6 1] ['c 6 1] ['a 5 2] ['b 5 2] ['c 5 2] ['a 6 2] ['b 6 2] ['c 6 2] ['a 5 3] ['b 5 3] ['c 5 3] ['a 6 3] ['b 6 3] ['c 6 3] ['a 5 4] ['b 5 4] ['c 5 4] ['a 6 4] ['b 6 4] ['c 6 4]]

```

on stack.

**Want the order maintained ?**, simply swap the before adding the popped item back to the array. i.e.

```
{m*{(\+}%}*

```

**Want only permutations ?**

```
{m*{(+$}%_&}*

```

**Want only unique elements in the combinations ?**

```
{m*{(+_&}%}*

```

That's all folks. *for now*.
> 3 votes

# Answer
# Operating on strings

Sometimes if you are working with a complex data structure, while the items in it are simple, converting to strings may help.

For example, if you want to get the first or last few items in a 2D array of bits, and don't care about the returned type, `sA<` saves a byte from `0=A<` or `:+A<`.

Or if you want to modify some bits in the input, you can modify the string before evaluating it.

Or if you got this structure and want to convert it to a simple list:

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

```

You can do it with many characters in other ways:

```
[a{~)\}h;]W%

```

But it can be much shorter with strings:

```
s:~

```

It's shorter even if it may have numbers with more than one digit:

```
[`La`-~]

```

Or:

```
`']-~]

```

If you don't need another array containing many of such arrays.
> 3 votes

# Answer
# Using `N` instead of `La`

In many cases you need something initialized to an array containing an empty array as its only element, which is `La`, seemingly unnecessarily 1 byte longer.

In many cases you also need to add a newline after each element before printing, which would be something like `No` or `N*`.

But if both are true, sometimes you may find out that you can just initialize the array with `N`, which has the newline character as its only element. Make sure you only prepend things to the elements in the rest of your code, and the first thing to prepend is always a character or an array. Or only append, if a leading newline is acceptable and that makes it shorter.

Sometimes `S` also works if you need to separate the output with spaces.

In rarer cases, the initial element has to be a string. But you still can use `Na` which might be shorter than appending the newline afterwards.
> 3 votes

# Answer
# Splitting on one or more occurrences

Say you have a string `"abbcdbbfghbdbb"` and you want to split it on `b`

```
"abbcdbbfghbdbb"'b/

```

This leaves on stack:

```
["a" "" "cd" "" "fgh" "d" "" ""]

```

Notice the empty strings ? Those are there because two `b` were together and nothing was in between them. At times, you want to avoid this. You can do this by

```
"abbcdbbfghbdbb"'b/La-

```

or filtering out empty strings

```
"abbcdbbfghbdbb"'b/{},

```

but that is 3 extra bytes.

A little less known operator for this particular use case is `%`. Apart from doing mod and map and splitting based on number (`"abcd"2%` = `"ac"`), `%` can also split on strings/arrays. So for the above use case:

```
"abbcdbbfghbdbb"'b%

```

will leave

```
["a" "cd" "fgh" "d"]

```

on stack.

Thanks for @user23013 for pointing this out in one of my answers today.
> 2 votes

# Answer
## Use fold/reduce as infix foreach

We have `:x` as a shorthand for `{x}%` and or `{x}*` (depending on whether `x` is unary or binary). Unfortunately, there is no equivalent infix operator to shorten `{x}/`. However, very often when we do `{x}/`, `x` is actually a binary operator which repeatedly modifies the item lying underneath on the stack. If that's the case, and said item is not an array, we can save a byte by abusing fold/reduce as foreach:

```
5 [1 2 3 4]{-}/  e# Gives -5
5 [1 2 3 4]+:-

```

This works because fold always leaves the first element untouched. Unfortunately, it doesn't save a byte, when the modified element is an array, because adding it would unwrap it. However, sometimes you're lucky enough that your array already contains that element at the front, in which case reduce should be kept in mind (instead of manually removing the element before using `{}/` on the remainder).
> 2 votes

# Answer
# print and println

CJam has `print` operator: `o`. It works but stack is printing immediately after all the code has executed. You can stop it if you clear the stack at the end of program. Simply put this at the end:

```
];

```

To println you can use `oNo` or `p` (works as ``oNo`)
> 2 votes

# Answer
## Modify an element instead of deleting it

If you need the sum of a list except for the last element, increased by T, instead of:

```
W<:+T+

```

You can use:

```
WTt:+

```

Or if you just need the sum of a list except for element K, which isn't the first or last element, you can use:

```
K0t:+

```

Except for the case there are only 3 elements and K=1, where this is shorter:

```
2%:+

```
> 2 votes

# Answer
## Understand How Array Literals Work

The `[` and `]` characters in CJam are not part of any special syntax; they are *operators*.

What `[` does is puts a "flag" on the stack. Attempting to pop from the stack will pop from below it, but pushing to the stack will push above it.

This means that this:

```
1 2 [+]

```

Will result in the stack looking like this:

```
[3]

```

This can be used for golfing. For example, if I wanted to duplicate the final element in an array (i.e. turn `["foo" "bar" "baz"]` into `["foo" "bar" "baz" "baz"]`), I could do this:

```
_W=a+

```

But I can shorten this by 1 byte:

```
[~_]

```

If I wanted to put the top two stack elements into an array, I'd do:

```
a\a\+

```

But again, I can shorten this:

```
[\\]

```

If I was doing some computation earlier that pushed the two values onto the stack, I could wrap part of it in `[]`. This means I don't need the `\\`, which saves even more bytes.

You can manipulate this in even crazier ways. For example, you can accumulate an array (`[1 2 3]` -\> `[1 3 6]`) using:

```
[{1$+}*]

```

(I still wish CJam had a builtin for that, though, as I find myself needing it oftentimes.)

In general, this technique allows us to treat stack elements as array elements and vice versa.
> 2 votes

# Answer
# Check if array contains sub-array

**Note**: If you're only looking for a single element use jimmy's method.

If you want to see if an array contains a specific sub-array, use `#)`. `#` is "index of" and `)` increases it by 1. If the sub-array is not in the array `#` returns -1. When you increment it by 1, you get 0 which is falsey. If the sub-array is in the array `#` returns a number that is at least 0, which when incremented by 1 returns a truthy value.

`&` and `e=` don't work for sub-arrays.
> 1 votes

# Answer
# Index into an array, use a default value or run code if not in range

This could be done using a single character: `j`.

For example, this code would output `GolfScript`, `CJam`, `Pyth` for 0, 1, 2, and `Seriously` for all other cases:

```
ri"GolfScript CJam Pyth"S/{;"Seriously"}j

```

Compared to:

```
ri3,#"GolfScript CJam Pyth Seriously"S/=

```

Actually used more characters. But it might be considerable if the type is not string or you have to run code in a block anyway.
> 1 votes

---
Tags: code-golf, tips, cjam
---


title: Digit Date Range

text:
# Question
Title: Digit Date Range
*NOTE: Since I'm Dutch myself, all dates are in the Dutch `dd-MM-yyyy` format in the challenge description and test cases.*

## Challenge:

**Inputs:**
Start date \\$s\\$; End date \\$e\\$; Digit \\$n\\$

**Outputs:**
All dates within the range \\$\[s,e\]\\$ (including on both sides), which contain \\$n\\$ amount of unique digits in their date.

**Example:**

*Inputs:* Start date: `12-11-1991`; End date: `02-02-1992`; Digit: `4`

*Outputs:*
With leading 0s for days/months:

```
[20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 01-12-1991, 02-12-1991, 09-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 01-01-1992, 02-01-1992, 09-01-1992, 10-01-1992, 11-01-1992, 12-01-1992, 19-01-1992, 20-01-1992, 21-01-1992, 22-01-1992, 29-01-1992, 01-02-1992, 02-02-1992]

```

Without leading 0s for days/months:

```
[20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 3-12-1991, 4-12-1991, 5-12-1991, 6-12-1991, 7-12-1991, 8-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 3-1-1992, 4-1-1992, 5-1-1992, 6-1-1992, 7-1-1992, 8-1-1992, 10-1-1992, 13-1-1992, 14-1-1992, 15-1-1992, 16-1-1992, 17-1-1992, 18-1-1992, 20-1-1992, 23-1-1992, 24-1-1992, 25-1-1992, 26-1-1992, 27-1-1992, 28-1-1992, 31-1-1992]

```

## Challenge rules:

* The input and output dates may be in any reasonable (date-)format. Can be as a string in any `dMy` format (including optional separators), list of three integers, your language's native Date-object, etc. Output may be a list/array/stream, printed to STDOUT, a single delimited String, etc.
* You are allowed to include or exclude leading 0s for days/months in your outputs. **Please specify which of the two you use in your answer**, since it will cause different results. I.e. `1-1-1991` has 2 unique digits, but `01-01-1991` as 3 unique digits.
* You don't have to deal with leap years and differences of Gregorian vs Julian calendars. You can assume the date-ranges given in the test cases will never go over February 28th/March 1st for years divisible by 4.
* The input-digit \\$n\\$ is guaranteed to be in the range \\$\[1,8\]\\$, so dealing with \\$n=0\\$ is unspecified (returning an empty list would be most reasonable, but giving an error or incorrect result is fine as well; you won't have to deal with that input).

## 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 with default I/O rules, 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 (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Inputs: [12-11-1991, 02-02-1992], 4
Outputs with leading 0s:    [20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 01-12-1991, 02-12-1991, 09-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 01-01-1992, 02-01-1992, 09-01-1992, 10-01-1992, 11-01-1992, 12-01-1992, 19-01-1992, 20-01-1992, 21-01-1992, 22-01-1992, 29-01-1992, 01-02-1992, 02-02-1992]
Outputs without leading 0s: [20-11-1991, 23-11-1991, 24-11-1991, 25-11-1991, 26-11-1991, 27-11-1991, 28-11-1991, 30-11-1991, 3-12-1991, 4-12-1991, 5-12-1991, 6-12-1991, 7-12-1991, 8-12-1991, 10-12-1991, 13-12-1991, 14-12-1991, 15-12-1991, 16-12-1991, 17-12-1991, 18-12-1991, 20-12-1991, 23-12-1991, 24-12-1991, 25-12-1991, 26-12-1991, 27-12-1991, 28-12-1991, 31-12-1991, 3-1-1992, 4-1-1992, 5-1-1992, 6-1-1992, 7-1-1992, 8-1-1992, 10-1-1992, 13-1-1992, 14-1-1992, 15-1-1992, 16-1-1992, 17-1-1992, 18-1-1992, 20-1-1992, 23-1-1992, 24-1-1992, 25-1-1992, 26-1-1992, 27-1-1992, 28-1-1992, 31-1-1992]

Inputs: [19-09-2019, 30-09-2019], 5
Outputs (same with and without leading 0s): [23-09-2019, 24-09-2019, 25-09-2019, 26-09-2019, 27-09-2019, 28-09-2019, 30-09-2019]

Inputs: [19-09-2019, 30-09-2019], 8
Output (same with and without leading 0s): []

Inputs: [20-06-1749, 30-06-1749], 8
Outputs with leading 0s:    [23-06-1749, 25-06-1749, 28-06-1749]
Outputs without leading 0s: []

Inputs: [10-12-1969, 12-01-1970], 6
Outputs (same with and without leading 0s): [30-12-1969]

Inputs: [10-12-1969, 12-01-1970], 5
Outputs with leading 0s:    [10-12-1969, 13-12-1969, 14-12-1969, 15-12-1969, 17-12-1969, 18-12-1969, 20-12-1969, 23-12-1969, 24-12-1969, 25-12-1969, 27-12-1969, 28-12-1969, 31-12-1969, 02-01-1970, 03-01-1970, 04-01-1970, 05-01-1970, 06-01-1970, 08-01-1970, 12-01-1970]
Outputs without leading 0s: [10-12-1969, 13-12-1969, 14-12-1969, 15-12-1969, 17-12-1969, 18-12-1969, 20-12-1969, 23-12-1969, 24-12-1969, 25-12-1969, 27-12-1969, 28-12-1969, 31-12-1969, 2-1-1970, 3-1-1970, 4-1-1970, 5-1-1970, 6-1-1970, 8-1-1970, 12-1-1970]

Inputs: [11-11-1111, 11-11-1111], 1
Output (same with and without leading 0s): [11-11-1111]

```

# Answer
> 2 votes
# Japt, 23 bytes

Takes the date inputs as Unix timestamps, outputs an array of strings with formatting and leading `0`s dependent on your locale. Would be 1 byte shorter in Japt v2 but there seems to be a bug when converting `Date` objects to strings.

```
òV864e5@ÐX s7Ãf_¬â Ê¶WÄ

```

Try it

```
òV864e5@ÐX s7Ãf_¬â Ê¶WÄ     :Implicit input of integers U=s,V=e & W=n
òV                          :Range [U,V]
  864e5                     :  With step 86,400,000 (24*60*60*1000)
       @                    :Map each X
        ÐX                  :  Convert to Date object
           s7               :  Convert to locale date string
             Ã              :End map
              f             :Filter
               _            :By passing each through the following function
                ¬           :  Split
                 â          :  Deduplicate
                   Ê        :  Length
                    ¶       :  Is equal to
                     WÄ     :  W+1, to account for the inclusion of the delimiting "/" or "-"

```

# Answer
> 5 votes
# , 81 bytes

```
function(s,e,n,x=seq(s,e,1))x[lengths(sapply(strsplit(paste(x),""),unique))==n+1]

```

Try it online!

Uses R’s native date format and has leading zeros on day and month.

# Answer
> 3 votes
# Red, 93 bytes

```
func[a b n][until[if n = length? exclude d: rejoin[a/4"-"a/3"-"a/2]"-"[print d]b < a: a + 1]]

```

Try it online!

Without leading 0s for days/months.

Too bad that Red converts internally `09-10-2019` to `9-Oct-2019` \- that's why I need to extract the day/month/year individually.

# Answer
> 2 votes
# Python 3.8 (pre-release), 84 bytes

-6 bytes thanks to Gloweye

```
lambda s,e,n:[d for i in range((e-s).days+1)if-len(set(d:=str(s+type(e-s)(i))))==~n]

```

An unnamed function which returns a list of strings (counting/including leading zeros) that accepts three arguments:

* `s`, the *start* \- a `datetime.date` object;
* `e`, the *end* \- a `datetime.date` object; and
* `n`, the number of days - an `int` object.

**Try it online!**

Note: As the function accepts `datetime.date` objects I have not counted the import code for that (and have worked around importing the `datetime.timedelta` object as it is indirectly accessible via subtraction of these input objects).

# Answer
> 2 votes
# Ruby `-rdate`, 54 bytes

Takes 2 Date objects and a number as input, and returns a list of Date objects as output. Handles leap years and uses leading zeroes.

```
->a,b,n{(a..b).select{|d|d.to_s.chars.uniq.size==n+1}}

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 91 bytes

Takes input as `(n)(end)(start)`, where the dates are expected as Unix timestamps in milliseconds. Returns a space-separated list of dates in format `yyyy-mm-dd`.

Leading 0s are included.

```
n=>b=>g=a=>a>b?'':(new Set(d=new Date(a).toJSON().split`T`[0]).size+~n?'':d+' ')+g(a+864e5)

```

Try it online!

# Answer
> 1 votes
# PHP, 90 bytes

```
for([,$s,$e,$n]=$argv;$s<=$e;)$n-count(count_chars($d=date(Ymd,86400*$s++),1))||print$d._;

```

Try it online!

This is with leading 0s. Inputs are command arguments (`$argv`) and dates are Unix timestamps in days (basically standard seconds / 86400), I used this format as we don't need the time in this challenge and it allowed me to golf 1 more byte. Keeps adding a day to start until it reaches the end and prints any dates with `$n` unique digits in it, separated by `_` in `Ymd` format.

Also have a 89 bytes alternative which prints dates to output in same format as input (Unix timestamps in days).

# Answer
> 1 votes
# Java (JDK), 86 bytes

```
(s,e,n)->s.datesUntil(e.plusDays(1)).filter(d->(""+d).chars().distinct().count()==n+1)

```

Try it online!

I chose to use leading `0`s.

## Credits

* -24 thanks to Kevin Cruijssen who didn't know he could golf away that much :p

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler)

# Without leading 0s, ~~104~~, 103 bytes

```
(s,e,n)=>new int[(e-s).Days+1].Select((x,i)=>s.AddDays(i)).Where(x=>$"{x:yyyMd}".Distinct().Count()>=n)

```

Try it online!

# With leading 0s, ~~106~~ 105 bytes

```
(s,e,n)=>new int[(e-s).Days+1].Select((x,i)=>s.AddDays(i)).Where(x=>$"{x:yyyMMdd}".Distinct().Count()>=n)

```

Try it online!

# Answer
> 0 votes
# Kotlin, 119 bytes

```
fun f(a:LocalDate,b:LocalDate,c:Long)=a.datesUntil(b.plusDays(1)).filter{it.toString().chars().distinct().count()==c+1}

```

Without leading 0s, takes in two `java.time.LocalDate` and a `Long`, returns a `Stream` of `LocalDate`s

---
Tags: code-golf, number, date
---