title: Leaving the Nest

text:
# Question
Title: Leaving the Nest
Given a non-flat list of integers, output a list of lists containing the integers in each nesting level, starting with the least-nested level, with the values in their original order in the input list when read left-to-right. If two or more lists are at the same nesting level in the input list, they should be combined into a single list in the output. The output should not contain any empty lists - nesting levels that contain only lists should be skipped entirely.

You may assume that the integers are all in the (inclusive) range `[-100, 100]`. There is no maximum length or nesting depth for the lists. There will be no empty lists in the input - every nesting level will contain at least one integer or list.

The input and output must be in your language's native list/array/enumerable/iterable/etc. format, or in any reasonable, unambiguous format if your language lacks a sequence type.

## Examples

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

[3, 1, [12, [14, [18], 2], 1], [[4]], 5] => [[3, 1, 5], [12, 1], [14, 2, 4], [18]]

[2, 1, [[5]], 6] => [[2, 1, 6], [5]]

[[54, [43, 76, [[[-19]]]], 20], 12] => [[12], [54, 20], [43, 76], [-19]]

[[[50]], [[50]]] => [[50, 50]]

```

# Answer
> 5 votes
# Pyth, 17

```
 us-GeaYsI#GQ)S#Y

```

The leading space is important. This filters the list on whether the values are invariant on the `s` function, then removes these values from the list and flatten it one level. The values are also stored in `Y` and when we print we remove the empty values by filtering if the sorted value of the list is truthy.

Test Suite

Alternatively, a 15 byte answer with a dubious output format:

```
 us-GpWJsI#GJQ)

```

Test Suite

### Expansion:

```
 us-GeaYsI#GQ)S#Y     ##   Q = eval(input)
 u          Q)        ##   reduce to fixed point, starting with G = Q
        sI#G          ##   get the values that are not lists from G
                      ##   this works because s<int> = <int> but s<list> = flatter list
      aY              ##   append the list of these values to Y
     e                ##   flatten the list
   -G                 ##   remove the values in the list from G
              S#Y     ##   remove empty lists from Y

```

# Answer
> 5 votes
# Mathematica, ~~56~~ ~~54~~ 52 bytes

*-2 bytes due to Alephalpha.*

*-2 bytes due to CatsAreFluffy.*

```
Cases[#,_?AtomQ,{i}]~Table~{i,Depth@#}/.{}->Nothing&

```

Actually deletes empty levels.

# Answer
> 3 votes
# Python 2, 78 bytes

```
f=lambda l:l and zip(*[[x]for x in l if[]>x])+f(sum([x for x in l if[]<x],[]))

```

# Answer
> 1 votes
# Mathematica ~~55 64~~ 62 bytes

```
#~Select~AtomQ/.{}->Nothing&/@Table[Level[#,{k}],{k,Depth@#}]&

```

---

```
%&[{1, 2, {3, {4, 5}, 6, {7, {8}, 9}}}]

```

> {{1, 2}, {3, 6}, {4, 5, 7, 9}, {8}}

# Answer
> 1 votes
# Retina, 79

I *know* the Retina experts will golf this more, but here's a start:

```
{([^{}]+)}(,?)([^{}]*)
$3$2<$1>
)`[>}],?[<{]
,
(\d),+[<{]+
$1},{
<+
{
,*[>}]+
}

```

Try it online.

# Answer
> 1 votes
# JavaScript, ~~112~~ 80 bytes

```
F=(a,b=[],c=0)=>a.map(d=>d!==+d?F(d,b,c+1):b[c]=[...b[c]||[],d])&&b.filter(d=>d)

```

Thanks Neil for helping shave off 32 bytes.

# Answer
> 1 votes
# Jelly, 24 bytes

```
fFW®;©ṛ¹ḟF;/µŒḊ’$¡W®Tị¤;

```

Try it online!

If newline-separated lists were allowed, this could be golfed down to **14 bytes**.

```
fFṄ¹¹?ḟ@¹;/µ¹¿

```

Try it online!

# Answer
> 1 votes
# Jelly, 6 bytes

```
ŒJẈĠịF

```

Try it online!

Jelly has substantially improved in the past 5 years

## How it works

```
ŒJẈĠịF - Main link. Takes a list L on the left
ŒJ     - Multi-dimensional indices
  Ẉ    - Get the length of each element
         This yields the depth (starting at 1 for flat elements) of each element
   Ġ   - Group the indices of this list by the values
     F - Flatten L
    ị  - Index into

```

Huh? The way that `ŒJẈĠ` works is kinda confusing without an example. Let's take `L = [3, 1, [12, [14, [18], 2], 1], [[4]], 5]` and work through it

`ŒJ` is one of a series of multi-dimensional commands that reflect the behaviour of their one-dimensional versions. Specifically, this is the "multi-dimensional indices" command, a multi-dimensional version of `J`, the "indices" command.

Picture `L` arranged like this:

```
3 1 12 14 18 2 1 4 5
    12 14 18 2 1 4
       14 18 2   4
          18

```

That is, each element is repeated down a number of times equal to it's depth. `ŒJ` doesn't quite leave the elements like this (it changes the specific values, not the shape), but it's enough.  then calculates the length of each i.e. how many rows each element goes down:

```
1 1 2 3 4 3 2 3 1

```

`Ġ` the takes this list as it's argument. First, it's generates this list's indices: `[1, 2, 3, 4, 5, 6, 7, 8, 9]`. We then group these indices by the values of the argument. So because the values at indices `3` and `7` are equal (they're both `2`), `[3, 7]` is grouped. The final result of this is `[[1, 2, 9], [3, 7], [4, 6, 8], [5]]` as the groups are sorted by the values they're grouped by.

Finally, we index into the flattened `L` using this list of groups, which yields the intended output

# Answer
> 0 votes
# Python, ~~108~~ 99 bytes

This seems a bit long to me, but I couldn't make a one-liner shorter, and if I try using `or` instead of `if`, I get empty lists in the results.

```
def f(L):
    o=[];i=[];j=[]
    for x in L:[i,j][[]<x]+=[x]
    if i:o+=[i]
    if j:o+=f(sum(j,[]))
    return o

```

**Try it online**

Edit: Saved 9 bytes thanks to Stack Overflow

# Answer
> 0 votes
# MATL, 37 bytes

```
j']['!=dYsXKu"GK@=)'[\[\],]'32YXUn?1M

```

**Try it online!**

Works with current release (13.0.0) of the language/compiler.

This produces the output as lines of space-separated values, where each line corresponds to the same nesting level, and different nesting levels are separated by newlines.

```
j            % read input as string (row array of chars)
']['!        % 2x1 array containing ']'  and '['
=            % test for equality, all combinations
d            % row array obtained as first row minus second row
Ys           % cumulative sum. Each number is a nesting level
XK           % copy to clibdoard K
u            % unique values: all existing nesting levels
"            % for each nesting level
  G          %   push input
  K          %   push array that indicates nesting level of each input character
  @          %   push level corresponding to this iteration
  =          %   true for characters corresponding to that nesting level
  )          %   pick those characters
  '[\[\],]'  %   characters to be replaced
  32         %   space
  YX         %   regexp replacement
  U          %   only numbers and spaces remain: convert string to array of numbers
  n?         %   if non-empty
    1M       %     push that array of numbers again
             %   end if implicitly
             % end for each implicitly

```

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

As ever, stupid Python 2 features like comparing `int`s and `list`s mean that Python 3 comes out behind. Oh well...

```
def d(s):
 o=[]
 while s:
  l,*n=[],
  for i in s:
   try:n+=i
   except:l+=[i]
  if l:o+=[l]
  s=n
 return o

```

# Answer
> 0 votes
# Perl, 63 bytes

```
{$o[$x++]=[@t]if@t=grep{!ref}@i;(@i=map{@$_}grep{ref}@i)&&redo}

```

Input is expected in `@i`, output produced in `@o`. (I hope this is acceptable).

Example:

```
@i=[[54, [43, 76, [[[-19]]]], 20], 12];                              # input

{$o[$x++]=[@t]if@t=grep{!ref}@i;(@i=map{@$_}grep{ref}@i)&&redo}      # the snippet

use Data::Dumper;                                                    # print output
$Data::Dumper::Indent=0;  # keep everything on one line
$Data::Dumper::Terse=1;   # don't print $VAR =
print Dumper(\@o);

```

Output:

```
[[12],[54,20],[43,76],[-19]]

```

# Answer
> 0 votes
## Clojure, 119 bytes

**(116 with seq? and input as lists, a trivial modification)**

```
(defn f([v](vals(apply merge-with concat(sorted-map)(flatten(f 0 v)))))([l v](map #(if(number? %){l[%]}(f(inc l)%))v)))

```

Better intended:

```
(defn f([v]  (vals(apply merge-with concat(sorted-map)(flatten(f 0 v)))))
       ([l v](map #(if(number? %){l[%]}(f(inc l)%))v)))

```

When called with two arguments (the current level and a collection) it either creates an one-element unordered-map like `{level: value}`, or calls `f` recursively if a non-number (presumambly a collection) is seen.

These mini-maps are then merged into a single `sorted-map` and key collisions are handled by `concat` function. `vals` returns map's values from first level to the last.

If a number is the only one at its level then it remains a `vec`, others are converted to lists by `concat`.

```
(f [[54, [43, 76, [[[-19]]]], 20], 12])
([12] (54 20) (43 76) [-19])

```

If input was a `list` instead of `vec` then `number?` could be replaced by `seq?`, oddly vector isn't `seq?` but it is `sequential?`. But I'm too lazy to implement that version, re-do examples etc.

# Answer
> 0 votes
## Racket 259 bytes

```
(let((ol'())(m 0))(let p((l l)(n 0))(cond[(empty? l)][(list?(car l))(set! m(+ 1 n))
(p(car l)(+ 1 n))(p(cdr l)n)][(set! ol(cons(list n(car l))ol))(p(cdr l)n )]))
(for/list((i(+ 1 m)))(flatten(map(λ(x)(cdr x))(filter(λ(x)(= i(list-ref x 0)))(reverse ol))))))

```

Ungolfed:

```
(define (f l)
  (define ol '())
  (define maxn 0)
  (let loop ((l l)              ; in this loop each item is added with its level
             (n 0))
    (cond
      [(empty? l)]
      [(list? (first l))
       (set! maxn (add1 n))
       (loop (first l) (add1 n))
       (loop (rest l) n)]
      [else
       (set! ol (cons (list n (first l)) ol))
       (loop (rest l) n )]))

  ; now ol is '((0 1) (0 2) (1 3) (2 4) (2 5) (1 6) (2 7) (3 8) (2 9))

  (for/list ((i (add1 maxn)))   ; here similar levels are combined
    (flatten
     (map (λ (x) (rest x))      ; level numbers are removed
          (filter (λ (x) (= i(list-ref x 0)))
                  (reverse ol))))))

```

Testing:

```
(f '[1 2 [3 [4 5] 6 [7 [8] 9]]])

```

Output:

```
'((1 2) (3 6) (4 5 7 9) (8))

```

# Answer
> 0 votes
# Stax, 18 bytes

```
é╔óó)₧ú↔u.≤∟╦Ç╟·○`

```

Run and debug it

I rhought I'd be able to beat pyth, but ¯\\\_(○-○)\_/¯

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


title: The sequence is too meta

text:
# Question
Title: The sequence is too meta
We start with a blank 1-indexed sequence:

```
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,...

```

In the nth step, we fill in every a(n) blanks with the integers greater than 1 starting at the first remaining blank, where a(n) is the nth entry in the sequence.

After the first step:

```
2,_,3,_,4,_,5,_,6,_,7,_,8,_,9,_,10,_,11,_,12,_,13,_,...

```

Note that a(1) has to be 2 because the first integer greater than 1 is 2.

In the second step, we fill in every a(2) blanks. It will be apparent that a(2) must be 2.

```
2,2,3,_,4,3,5,_,6,4,7,_,8,5,9,_,10,6,11,_,12,7,13,_,...

```

In the third step, we fill in every a(3) blanks. From the sequence, a(3) = 3.

```
2,2,3,2,4,3,5,_,6,4,7,_,8,5,9,3,10,6,11,_,12,7,13,_,...

```

In the fourth step, we fill in every a(4) blanks. From the sequence, a(4) = 2.

```
2,2,3,2,4,3,5,2,6,4,7,_,8,5,9,3,10,6,11,3,12,7,13,_,...

```

Eventually:

```
2,2,3,2,4,3,5,2,6,4,7,2,8,5,9,3,10,6,11,3,12,7,13,2,...

```

## Task

Given n, return the nth element of the sequence.

The first 10,000,000 terms of the sequence can be found here.

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
# Haskell, ~~80~~ 67 bytes

```
g~(a:b)|let k!l=k:take(a-1)l++(k+1)!drop(a-1)l=2!g b
m=g m
(!!)$0:m

```

Try it online!

Haskell is the perfect language for defining an infinite list in terms of itself.
> 26 votes

# Answer
## C, 123 bytes

```
f(n){int*p=calloc(n,4),i=0,j,k;for(*p=p[1]=2;i<n;++i)for(j=0,k=i/2?0:2-i;j<n;++j)p[j]||k++%p[i]||(p[j]=k/p[i]+2);n=p[n-1];}

```

Try it online!

## Walkthrough

```
f(n){int*p=calloc(n,4),

```

Allocate an array of *n* integers to store the first *n* elements of the sequence. This hardcodes `sizeof(int)` as `4`, which is a safe assumption in most cases and certainly one I'm willing to make in the context of code golf. :)

```
i=0,j,k;

```

These are all counters: `i` for the index of the step we're on, `j` to loop through the sequence looking for empty spaces, and `k` to count how many empty spaces have been seen.

```
for(*p=p[1]=2;i<n;++i)

```

Before we start our main loop, we sneak in an initialization of the first two elements of the sequence to `2`. (`p[0]` = `*(p + 0)` = `*p`.) This throws off the count for `k`, though, but...

```
for(j=0,k=i/2?0:2-i;j<n;++j)

```

... we also do a sneaky initialization of `k`, which tests to see if `i` is less than `2` and corrects the starting value of `k` if so. The inner loop also starts here, which iterates over the entire sequence-so-far during each step.

```
p[j]||k++%p[i]||(p[j]=k/p[i]+2);

```

This line could really use some explaining. We can expand this to:

```
if (!(p[j] || ((k++) % p[i]))) {
    p[j] = k / p[i] + 2;
}

```

by short circuiting, and then by De Morgan's laws and the fact that `0` is falsy in C:

```
if (p[j] == 0 && ((k++) % p[i]) == 0) {
    p[j] = k / p[i] + 2;
}

```

This essentially states: "if this space is empty, increment `k`. And if `k` was previously a multiple of the step size, run the following statement." Hence, we run the statement on every *step size* elements, which is exactly how the sequence is described. The statement itself is simple; all it does is generate `2`, `3`, `4`, ....

```
n=p[n-1];}

```

Using the tricky-return-without-a-return that works with `gcc`, we "return" the last element of the first *n* terms in the sequence, which happens to be the *n*th term.
> 11 votes

# Answer
# Pyth, 29 bytes

```
M?tH?eJ.DtHg1GghG-tHhJ+2hJ2g1

```

Try it online

### How it works

Instead of fooling around with lists, this uses a plain recursive formula.

```
M                                def g(G, H):
 ?tH                                 if H - 1:
      J.DtHg1G                           J = divmod(H - 1, g(1, G))
    ?e                                   if J[-1]:
              ghG-tHhJ                       return g(G + 1, H - 1 - J[0])
                                         else:
                      +2hJ                   return 2 + J[0]
                                     else:
                          2              return 2
                           g1Q   print(g(1, eval(input())))

```
> 3 votes

# Answer
# Haskell, 67 bytes

```
0%j=2
i%j|d<-div i$f j=last$d+2:[(i-d-1)%(j+1)|d*f j<i]
f=(%1).pred

```

Try it online!

A recursive arithmetical solution that turned out basically the same method as Anders Kaseorg's Pyth answer.

This code is covered in warts -- ugly parts that look like they could be golfed away, but I didn't see how.

The function `i%j` really wants to use a guard to check whether `mod i(f j)>0` and evaluate one of corresponding two expression. But, both expressions use `div i(f j)`. Binding that in a guard won't make it apply to both sides. As far as I know, a guard can't be made to "distribute" over other guards. `let` and `where` are too long. So, the code uses `last` to pick one of two expressions while the guard binds the variable. Ugh.

Ideally we'd use `divMod` because both the `div` and `mod` are used, but `(d,m)<-divMod ...` is a long expression. We instead hackily check of the mod is nonzero by seeing if the `div` value times the divisor falls short of the original value.

The `0%j=2` case would not be needed if Haskell short-circuited `div 0`, which it doesn't. The `.pred` converts the 1-indexed input to zero-indexed, or else there would be `-1` corrections everywhere.
> 3 votes

# Answer
# Husk, ~~20~~ 16 bytes

```
!ƒψΣz`:tNΘC←←¹²t

```

Try it online!

A golfed port of the mind-bending Haskell answer by Anders Kaseorg

### Explanation

This answer builds this meta list with a self-referential process.

Let's get a few things out of the way before we can look at how the list is actually built: `!` simply takes an item from the list, since the challenge asks to return the element at a given list. `ƒ` is the fixpoint operator, it takes a function and applies the function to itself ad infinity, i.e. `ƒg` = `g(g(g(g(g(g(...`; this is what allows us to define the list in terms of the list itself. `ψ` is a way to write a recursive function in Husk: the following commands define a function of one argument where  (or `¹`) marks the argument, and `²` marks the function itself.

The inner code (with implicit parameters made explicit) is this:

```
Σz`:tNΘC←←⁰²t⁰    Takes an infinite list as input, returns an infinite list
           ²      Apply the function recursively
            t⁰      to the tail of the list
         ←⁰       then take the head of the input list
        ←          -1
       C          and cut the resulting list in groups of that length
      Θ           Prepend an empty group
 z           For each group
  `:          append
    tN        a natural number (starting from 2)
Σ            Then concatenate all groups together

```

What this function does is taking the current `a(n)` and the list of values that are marked as blanks in step `n`, and add `2,3,4,5...` at the right locations between those "blanks".

It would be shorter (and more natural) to prepend a number to each group (each value 2,3,4... goes at the *beginning* of the group of a(n) blanks, after all), but to do that we wouldn't be able to generate the first element of the list until we generate the first group of blanks, and since this definition is self-referential we couldn't generate the first element of the first group of blanks until we generate the first group of blanks after that, and so on forever. By adding an empty group at the beginning and putting values at the end of groups instead, we can generate the initial `2` without having to look at the rest of the list, and this is enough to kickstart the whole process that will generate the infinite list recursively.
> 3 votes

# Answer
# JavaScript (ES6),  ~~98 93 91~~ 87 bytes

*Saved 4 bytes thanks to @l4m2*

A recursive function that stops as soon as the result is available.

```
f=(n,p,a=[])=>a[n-1]++||f(n,-~p,[...a].map(c=>c?c:i?i++%(a[p]||2)?c:++v:(i=1,v=2),i=0))

```

Try it online!
> 2 votes

# Answer
# Java 8, 124 bytes

```
(i)->{int j=1,a[]=new int[i+1],k,s,n;for(;a[i]<2;){for(k=0,n=2;a[++k]>0;);for(s=a[j++]|2*k;k<=i;k+=s)a[k]=n++;}return a[i];}

```

Lambda expression.

Creates an integer array and continually populates it until the nth value gets populated.

Pre-declaring variables at the top to cut down on as many declarations as possible as each `int` costs 4 bytes of space as opposed to adding `,n` which is 2.

On the `j`'th iteration of calculation, the number of 'blanks' one has to skip is equal to `a[j]` (or 2, if blank). It works out that if the first blank space we have to fill in is at position `k`, `k * a[j]` gives us the 'step' (`s`).
> 1 votes

# Answer
# C (gcc), 104 bytes

```
j;k;f(n){int*p=calloc(n,4)-4,i=1,y;for(;j=k=p[n],!j;++i)for(y=p[i]?:2;j++<n;)p[j]||k++%y||(p[j]=k/y+2);}

```

Try it online!

Trying to golf the last C solution but it's just too hard to understand

```
f(n){
    int*p=calloc(n,4)-4,i=0,j,k,y;         // p as Array[1..n]
    for(;j=k=p[n],!j;++i)                  // Once p[n] is filled we're over
                                           // and that's what we want
                                           // Otherwise j and k are inited to 0
        for(;j++<n;) p[j]||                // For zeros
            k++%(y=p[i]?:2)||(p[j]=k/y+2); // On correct time fill them
}

```
> 1 votes

# Answer
# Stax, 23 bytes

```
ü→è«wε⌠╒└I◄►¼═Öà=╬à╞⌐-Ω

```

Run and debug it

A direct implementation of the procedure.

Uses zeroes as placeholders till the array is fully filed, and take the last element.

## Explanation

```
z({c:0ni@i1>s2?::{i^^&F}x*H Input: x
z                           empty list
 (                          pad with x zeroes (call this S)
  {                    }x*  perform the following x times:
   c:0                      get the falsy indices
         i1>  ?             if iteration index >1 :
      ni@                   get nth element of S
            2               else push 2
               ::           get every nth element of the falsy indices
                 {    F     for each index:
                  i^^&      replace with iteration index + 2

```
> 1 votes

---
Tags: code-golf, sequence
---


title: BF memory layout optimizer

text:
# Question
Title: BF memory layout optimizer
Given a BF program consisting of only the characters `+-[]<>.,` with the property that there's an equal number of `<` and `>` between every matching pair of `[]`.

You have to find the shortest program that can be achieved with the optimal memory layout (by rearranging the cells on the tape).

If there are multiple such programs, output any of them.

*For such a program, it's possible to tell exactly where (on which memory cell) the memory pointer is for each instruction executed. The memory can be rearranged such that the program is shorter, without changing the program execution.*

### Example input/output

```
Input : Output
,>>, : ,>,
,<++[->>+<<] : ,>++[->+<]
+<><>+ : ++

```

---

### Background

**Note that the challenge is well-defined (see the "formal description" section below) even without this section.**

Background on the language:

> Brainfuck operates on an array of memory cells, each initially set to zero. \[...\]. There is a pointer, initially pointing to the first memory cell. The commands are:
>
> | Command | Description |
> | --- | --- |
> | \> | Move the pointer to the right |
> | \< | Move the pointer to the left |
> | + | Increment the memory cell at the pointer |
> | - | Decrement the memory cell at the pointer |
> | . | Output the character signified by the cell at the pointer |
> | , | Input a character and store it in the cell at the pointer |
> | \[ | Jump past the matching \] if the cell at the pointer is 0 |
> | \] | Jump back to the matching \[ if the cell at the pointer is nonzero |

(Source: brainfuck - Esolang)

For the purpose of this challenge, assume that the tape is unbounded on both ends.

Therefore, for all programs that are valid input for this challenge,

* the memory cell that the pointer is on is completely determined by the instruction that is going to be executed, and
* there's only a finite number of accessed memory cells.

(Note that the program might not terminate.)

Now assume that the memory layout is rearranged so that whatever a cell `x` is used (by a command not in `<>`) in the original program, the cell `f(x)` is used in the new program. Then the new program might be shorter than the original program.

Your task is to find the shortest program that can be obtained by rearranging the memory layout, **without changing the execution or order of the other commands**.

For example, assume that the cells are numbered `-1, 0, 1, 2,...`, the starting position is `0`, and `>` and `<` increases/decreases the position of the memory pointer respectively.

Consider the program `,>>,`. It executes `,` on cell `0`, then move to cell `2`, then executes `,` again.

If the cells 2 and 1 are swapped, then the new program should execute `,` on cell 0, then move to cell `1`, then execute `,` again, which can be achieved by `,>,`. This is the shortest possibility.

Note that you can swap cell 2 and -1, so the resulting program is `,<,`, which is just as short.

However, the new memory layout must not rearrange two different cells to the same cell, so it's invalid to read to cell 0 both times (program `,,`).

---

### FAQ

I'm not sure what questions people may have, in any case refer to the formal description.

* The amount and order of the non-`<>` in the input and output must be the same.
* If two (non-`<>`) commands in the original program access the same cell, the two corresponding commands must access the same cell in the shortened program. (i.e., if `a` and `b` accesses the same cell in program 1, and their corresponding character in program 2 are `a'` and `b'`, then `a'` and `b'` must access the same cell)
* Assume that all branches are reachable (that memory is corrupted or something). (you can't assume that there's no unreachable code, however)

---

### Formal definition

Define the set `S` to be the set of strings that consists of only the characters in `.,<>+-[]`, the `[]` forms matching pairs, and between every pairs of matching `[]` there's an equal number of `<` and `>`.

Let `s` be a string. Then define `value(s) :: String -> Integer` = (number of `>` in `s`) - (number of `<` in `s`).

Consider a string `A` in `S`, where the number of characters in `A` and not in `<>` is `n`.

Consider an injective function `f :: Integer -> Integer`. There exists exactly one shortest string `A'` such that:

* There are exactly `n` characters in `A'` not in `<>`, and the corresponding characters in `A` and `A'` have the same value.
* For each corresponding character `a` in `A` and `a'` in `A'`, let `p` be the string formed by concatenating in order all the characters before the character `a` in `A`, and define `p'` similarly, then `f(value(p)) == value(p')`.

Given the string `A`, you have to find the shortest string `A'`, for all possible functions `f`.

# Answer
> 1 votes
# JavaScript (Node.js), 239 bytes

```
s=>(x=[],i=n=s.length,s.map(t=>t<'<'|t>'>'?x.push([i,t]):i+=t<'>'?1:-1),f=(r,i=0)=>{2*n in r?(i=n,y='',x.map(([j,t])=>y+=((j=r[j]-i)<0?'<':'>').repeat(j>0?j:-j,i+=j)+t),s[y.length]&&(s=y)):i>2*n||f(r,i+1,r.includes(i)||f([...r,i]))},f``,s)

```

Try it online!

Badly golfed

```
s=>(
    x=[],
    i=n=s.length,
    s.map(t=>t<'<'|t>'>'?x.push([i,t]):i+=t<'>'?1:-1), // pack each []+-,. into (pos,instr)
    f=(r,i=0)=>{
        2*n in r?(
            i=n,y='',
            x.map(([j,t])=>y+=((j=r[j]-i)<0?'<':'>').repeat(j>0?j:-j,i+=j)+t), // generate instr
            s[y.length]&&(s=y)
        ):
        i>2*n||f(r,i+1,r.includes(i)||f([...r,i]))     // r be all rearrangements of [0,2n]
    },f``,s
)

```

---
Tags: code-golf, brainfuck
---


title: Shortest path for a chess knight

text:
# Question
Title: Shortest path for a chess knight
Your program should compute the number of moves it takes a chess knight to reach each square of the chess board. The input will be two space-separated integers representing coordinates of the starting square (horizontal then vertical coordinate, 0-7 inclusive each). Your program should output a number grid containing the minimum number of moves a chess knight needs to make to reach each square.

***examples***

**input**

```
0 0

```

**output**

```
03232345
34123434
21432345
32323434
23234345
34343454
43434545
54545456

```

**input**

```
3 1

```

**output**

```
21232123
32303232
21232123
34121432
23232323
32323234
43434343
34343434

```

Shortest code wins.

# Answer
## Ruby 1.9, 146 ~~151~~ characters

```
g=(?9*8+".
")*8
r=->x,a=0{x<0||a<g[x].to_i&&(g[x]=a.to_s;[21,19,12,8].map{|i|r[x+i,a+1];r[x-i,a+1]})}
r[eval gets.split*?++"*10"]
puts g.tr(?.,"")

```
> 4 votes

# Answer
# APL (Dyalog Classic), 55 bytes

```
{⍵⌊d⍴1+⌊/¨⌷∘⍵¨¨a/⍨¨Ö↓2=×/↑|∘.-⍨a←,⍳d}⍣≡0@(⊂⌽⎕)⊢9⍴⍨d←8 8

```

```
{⍵⌊d⍴1+⌊/¨⌷∘⍵¨¨a/⍨¨Ö↓2=×/↑|∘.-⍨a←,⍳d}⍣≡0@(⊂⌽⎕)⊢9⍴⍨d←8 8
                                       0@(⊂⌽⎕)⊢9⍴⍨d←8 8 ⍝ create an 8x8 grid of 9s with a 0 at the start position
                           ∘.-⍨a←,⍳d                    ⍝ all differences between coordinates
                     2=×/↑|                             ⍝ is 2 equal to the product of the absolute values?
               a/⍨¨Ö↓                                   ⍝ filter where true (finds knight moves)
          ⌷∘⍵¨¨                                         ⍝ index into the board
     1+⌊/¨                                              ⍝ 1 plus the minimum (finds minimum distance)
   d⍴                                                   ⍝ 8x8 reshape
 ⍵⌊                                                     ⍝ the minimum of the new and old moves
{                                   }⍣≡                 ⍝ apply until converged (minimum distances found)

```

Try it online!
> 5 votes

# Answer
# Haskell, 255 236 231 229 bytes

```
import Data.List
k x y=unlines[[toEnum$findIndices(elem(i,j))(scanl(\s _->filter(\(z,w)->z`elem`n&&w`elem`n)$(\(a,b)->[(a+c,b+d)|(c,d)<-zip[1,1,-1,-1,-2,-2,2,2][2,-2,2,-2,1,-1,1,-1]])=<<s)[(x,y)]n)!!0+48|j<-n]|i<-n]where n=[0..7]

```

D:

This is my first attempt at golfing. Also somewhat new to Haskell.

Test suite:

```
import System.Environment

main :: IO ()
main = do
    args <- getArgs
    let readArgs = map read args
    let out = k (readArgs !! 0) (readArgs !! 1)
    putStr out

```
> 4 votes

# Answer
## Windows PowerShell, 178 ~~183~~ ~~188~~

```
filter f($n){if($d[($p=$_)]-gt$n){$d[$p]=$n
12,8,21,19|%{$p+$_
$p-$_}|f($n+1)}}$d=,0*20+(0..7|%{,9*8+0,0})+,0*20
$x,$y=-split$input
20+"$y$x"|f 0
2..9|%{-join$d[(10*$_).."$_`7"]}

```

Passes both test cases.
> 2 votes

# Answer
## JavaScript, ~~426~~ 408 bytes

```
for(a=[],i=0;i<8;i++){a[i]=[];for(j=0;j<8;j++)a[i][j]=99}m=[[2,1],[2,-1],
[-2,1],[-2,-1],[1,2],[-1,2],[1,-2],[-1,-2]];function s(f,g,e,b){b&&(a[f][g]=0);
for(var b=[],c=0;c<m.length;c++){var d=[f+m[c][0],g+m[c][1]];a[d[0]]&&
a[d[0]][d[1]]&&a[d[0]][d[1]]>e&&(a[d[0]][d[1]]=e,b.push(d))}for(c=0;c<b.length;c++)
s(b[c][0],b[c][1],e+1)}function _(f,g){s(g,f,1,1);for(e="",b=0;b<8;b++)e+=
a[b].join("")+"\n";return e}

```

JavaScript is not the most concise language out there... But my coding style is a little verbose too.

Usage: `_(0, 0)` etc.
> 1 votes

---
Tags: code-golf, chess
---


# Question
Title: Display 0 - 1000 - 0 each on a separate line
I've tried this question on two forums and have been told this is the best place for this type of question. I'm trying to print from 0 to 1000 then back to 0 again (and all numbers in-between), printing 1000 only once. Also, each number must be on a separate line using vanilla PHP.

My current code is 60 characters long. Is there a way to do the same thing but in less characters?

### PHP, 60 bytes

```
echo implode("<p>",array_merge(range(0,999),range(1000,0)));

```

Try it online!

# Answer
# PHP, 38 bytes

```
for(;$i-=1|$x|=$i/1001;)echo~$i,"<p>";

```

Try it online!

A one-byte improvement by JoKing. The idea is that by decrementing `$i` instead of incrementing it, we can save on the minus in the `1|-$x` construction by having `$x` become `-1` instead of `1` as a signal. This is achieved by using `$i/1001`, which is `0` if `$i>-1001` and `-1` otherwise. This would break even if not for the fact we can now use `~$i` instead of `$i-1`.

### PHP, 39 bytes

```
for(;$i+=1|-$x|=$i>1e3;)echo$i-1,"<p>";

```

Try it online!

In collaboration with primo on the code.golf discord.

The idea is to have a signal variable `$x` that is zero until `$i` hits 1000 then is 1 afterwards. We use the bitwise construction `1|-$x` which is a shorter version of `$x ? -1 : 1` to select whether to go upwards or downwards.
> 20 votes

# Answer
# PHP,  ~~56~~  49 bytes

*Saved 7 bytes thanks to @Sisyphus and @xnor*

My PHP is rusty, but here is a first attempt.

```
for(;$n<2e3;)echo 1e3-abs(1e3-$n++),'<p>';echo 0;

```

Try it online!

# 47 bytes

A shorter version suggested by @Neil:

```
echo 0;for(;$n<2e3;)echo'<p>',min(++$n,2e3-$n);

```

Try it online!

# 43 bytes

If the output can end with an extra `<p>`:

```
for(;$n<2001;)echo 1e3-abs(1e3-$n++),'<p>';

```

Try it online!
> 4 votes

# Answer
# PHP, 51 bytes

```
echo join("<p>",[...range(0,999),...range(1e3,0)]);

```

Try it online!

There's already shorter versions, but I just wanted to show the OP how the original code can be shortened with the old alias `join` and the spread operator that is now available in PHP

**Depending on your rules, even shorter:**

**49** bytes with `<?=`

```
<?=join("<p>",[...range(0,999),...range(1e3,0)]);

```

or even **47** with a literal new line, if your output can be wrapped in `<pre><code>`

```
<?=join("
",[...range(0,999),...range(1e3,0)]);

```
> 3 votes

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


# Question
Title: Quandle Quandary Episode I: Identifying Finite Quandles
Write a program that will determine if a given matrix represents a quandle. A quandle is a set equipped with a single (non-commutative, non-associative) operation \\$◃\\$ which obeys the following axioms:

* The operation is closed, meaning that \\$a◃b = c\\$ is always an element of the set if \\$a\\$ and \\$b\\$ are elements of the set.
* The operation is right-self-distributive: \\$(a◃b)◃c = (a◃c)◃(b◃c)\\$.
* The operation is right-divisible: For any chosen pair of \\$a\\$ and \\$b\\$, there is a single unique \\$c\\$ such that \\$c◃a = b\\$
* The operation is idempotent: \\$a◃a = a\\$

A finite quandle can be represented as a square matrix. Below is an example of an order-\\$5\\$ quandle (source).

```
0 0 1 1 1
1 1 0 0 0
3 4 2 4 3
4 2 4 3 2
2 3 3 2 4

```

The value located at the \\$n\\$-th row and \\$m\\$-th column (0-indexed) is the value of \\$n◃m\\$. For example, in this quandle, \\$4◃1 = 3\\$. Some of the quandle properties are easy to see from this matrix:

* It is closed because only values \\$0-4\\$ appear in this \\$5\times5\\$ matrix.
* It is idempotent because the matrix diagonal is \\$0, 1, 2, 3, 4\\$
* It is right-divisible because no column contains any duplicate values. (The rows can, and usually will.)

The property of right-self-distributivity is harder to test. There might be a shortcut, but the simplest method is to iterate over each possible combination of three indexes to verify that `m[m[a][b]][c] = m[m[a][c]][m[b][c]]`.

## Input

Input will be the list of rows of a square matrix, using either 0-indexing or 1-index (your choice). Each entry will be a single digit number from `0` to `8` (or `1` through `9`). I will be flexible on the input format. Some acceptable formats include:

* Your language's most natural formatting for matrices or lists, such as `[[0 0 0][2 1 1][1 2 2]]` or `(0,0,0,2,1,1,1,2,2)`.
* The list of values delimited by whitespace, newlines, commas, etc.
* A single string consisting of all values concatenated together, such as `000211122`.

You are also allowed to take the transpose of the matrix as input (swapping rows with columns). Just be sure to state this in your answer.

## Output

A single truthy/falsey value indicating the matrix's status as a quandle.

## Examples of quandles

```
0

0 0
1 1

0 0 0
2 1 1
1 2 2

0 0 1 1
1 1 0 0
3 3 2 2
2 2 3 3

0 3 4 1 2
2 1 0 4 3
3 4 2 0 1
4 2 1 3 0
1 0 3 2 4

```

## Examples of non-quandles

**not closed**

```
1

0 0 0
2 1 1
1 9 2

```

**not right-self-distributive**

```
0 0 1 0
1 1 0 1
2 3 2 2
3 2 3 3

(3◃1)◃2 = 2◃2 = 2
(3◃2)◃(1◃2) = 3◃0 = 3

```

**not right-divisible**

```
0 2 3 4 1
0 1 2 3 4
3 4 2 2 2
3 3 3 3 3
4 1 1 1 4

0 1 2 3
3 1 2 0
3 1 2 3
0 1 2 3

```

**not idempotent**

```
1 1 1 1
3 3 3 3
2 2 2 2
0 0 0 0

2 1 0 4 3
3 4 2 0 1
4 2 1 3 0
1 0 3 2 4
0 3 4 1 2

```

# Answer
> 7 votes
## Haskell, 100 bytes

This answer uses **transposed** input.

```
q m=and$(elem<$>v<*>m)++[a#a==a&&a#b#c==a#c#(b#c)|a<-v,b<-v,c<-v]where v=[0..length m-1];i#j=m!!j!!i

```

Seems like I can't use a pattern guard to bind an infix operator, so I'm using `where` in this case.

(First version was 108 bytes but missed idempotency test, fixed version was 120 bytes, later versions had 108, 103 and 98 bytes but I had to realize thanks to @nimi that they were all wrong: of course I need to do the right-divisibility test (which implies closedness) before doing any dangerous `!!` operations, but I could still use most of my later golfing ideas and with one more, it was 102 bytes, now improved by changing the operand order of `#` (which is nicer anyway to compensate the transposition) to make better use of its associating to the left)

Use like this:

```
*Main> q [[0,1,2,3],[0,1,3,2],[1,0,2,3],[0,1,2,3]]
False

```

# Answer
> 6 votes
# Python 2, ~~104~~ ~~103~~ 102 bytes

```
t=input();e=enumerate
[0%(a==A[a]in B>C[B[a]]==t[C[b]][C[a]])for(a,A)in e(t)for(b,B)in e(t)for C in t]

```

Input is transposed. Output is via exit code, so **0** (success) is truthy and **1** (failure) is falsy.

Try it online!

### How it works

`e(t)` returns the enumerated rows of the input matrix **t** – which represents an operator  – as (index,row) pairs. `for(a,A)in e(t)`, e.g., iterates over these, storing the index in **a** and the row itself in **A**, so `A` becomes a shortcut for `t[a]`.

Between the former, `for(b,B)in e(t)`, and `for C in t`, we iterate over all possible ordered tuples **(a, b, c)** in the Cartesian power **t3**.

For each of these tuples, we evaluate the expression

```
0%(a==A[a]in B>C[B[a]]==t[C[b]][C[a]])

```

The value of the parenthesized Boolean is *False* if and only if one or more of the following individual comparisons do the same.

* `a==A[a]` will fail (for some value of **a**) iff  is not idempotent.
* `A[a]in B` will fail if **B** doesn't contain all indices of **A**.

Since **A** has **n** indices and **B** has **n** elements, non-failure means that the elements of **B** match the indices of **A**, so  is closed and right-divisible.
* `B>C[B[a]]` is a tautology, since Python 2 considered numbers "smaller" than iterables.
* `C[B[a]]==t[C[b]][C[a]]` will fail for some value if  is not right-self-distributive.

If any one of the comparisons returns *False*, the expression `(0%...)` will throw a *ZeroDivisionError*. Also, if  is not closed `A[a]` or `C[b]` may also throw an *IndexError*. In both cases, the program exits with status code **1** (failure).

If all test passed, the program will exit normally with status code **0** (success).

# Answer
> 4 votes
# Python 2, 138 bytes

```
def f(m):R=range(len(m));return all(m[i][i]==i<set(zip(*m)[i])==set(R)>m[m[j][k]][i]==m[m[j][i]][m[k][i]]for i in R for j in R for k in R)

```

`m` is a list of lists of integers.

Try it online!

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

```
a=>!(a.some((b,i)=>b[i]-i)|a.some(b=>[...new Set(b)].sort()+''!=[...b.keys()])||a.some((_,i)=>a.some((_,j)=>a.some((b,k)=>b[a[j][i]]-a[b[j]][b[i]]))))

```

Takes input as an array of column arrays of integers.

# Answer
> 3 votes
# Mathematica, 122 bytes

```
(n_±m_:=#[[m,n]];#&@@Union[Sort/@#]==Range@l==Array[#±#&,l=Length@#]&&And@@Flatten@Array[±##2±#==(#2±#)±(#3±#)&,{l,l,l}])&

```

Pure function taking a 2D array of integers (1-indexed) as input, with rows and columns reversed from the convention in the question, and returning `True` or `False`. The first line defines the binary infix operation `n_±m_` to be the quandle operation.

For an `l` x `l` array, closed and right-divisible is equivalent to every row (in my case) being some permutation of `{1, ..., l}`, and idempotent is equivalent to the main diagonal being exactly `{1, ..., l}`. So `#&@@Union[Sort/@#]==Range@l==Array[#±#&,l=Length@#]` detects for these three conditions. (The use of `Sort/@#` here is why I chose to swap rows and columns.)

For right-distributive, we literally check all possibilities using `Array[±##2±#==(#2±#)±(#3±#)&,{l,l,l}])`. (Note that `±##2±#` automatically expands to `(#2±#3)±#`, since `##2` represents the sequence of the second and third arguments to the three-variable pure function being arrayed over.) Then `&&And@@Flatten@` checks whether every single test was passed. For some non-closed quandles, errors might be thrown when it tries to access a part of a matrix that doesn't exist, but the correct answer is still returned.

# Answer
> 2 votes
# Jelly, ~~38~~ 36 bytes

```
ŒDḢJƑ;ZQƑ€$;Jṗ3Ṗịṛ/ịⱮ¥œịʋ=Ṫṭœị⁺ʋɗ€ƲẠ

```

Try it online!

Takes input as a matrix. The Footer converts the test case formats into matrix formats for you.

Truly a monstrosity of a program. This is broken into 3 stages, each of which checks a different axiom (except closedness as this is implied by right-divisibility):

```
ŒDḢJƑ - Checks for idempotentness
ZQƑ€  - Checks for right-divisibility and closedness
Jṗ3Ṗịṛ/ịⱮ¥œịʋ=Ṫṭœị⁺ʋɗ€ - Checks for right-self-distributiveness

```

We group these 3 results together using `;` and check that ll are true.

## How each stage works

We use `œị` to calculate \\$b ◃ a\\$, when the left argument is `[a, b]` and the right argument is `M`. `œị` is the "multi-dimensional index-into" command, which retrieves the `b`th element of the `a`th row of `M`. As we're checking every triple of coordinates, and the arguments are reversed for both sides of the indexing equality, the fact that we're calculating \\$b ◃ a\\$ instead of \\$a ◃ b\\$ doesn't matter. That means that instead of checking that \\$(a◃b)◃c=(a◃c)◃(b◃c)\\$, we instead check that \\$c◃(b◃a) = (b◃c)◃(a◃c)\\$ for all triples \\$a, b, c\\$.

Each stage is run as a "monadic link", meaning that the only argument passed to it is the inputted matrix.

```
ŒDḢJƑ - Argument: an n×n matrix M
ŒD    - Yield the diagonals of M
  Ḣ   - Extract the first i.e. the main diagonal
   JƑ - Is it in the form [1, 2, 3, ..., n]?

ZQƑ€ - Argument: an n×n matrix M
Z    - Transpose M
   € - Over each row:
 QƑ  -   Is it unchanged when deduplicated?

Jṗ3Ṗịṛ/ịⱮ¥œịʋ=Ṫṭœị⁺ʋɗ€ - Argument: an n×n matrix M
J                      - Extract n and yield [1, 2, 3, ..., n]
 ṗ3                    - Yield all triples of elements of [1, 2, 3, ..., n]
                    ɗ€ - Over each triple [a,b,c], do the following, with M as the right argument:
              =        -   Are the two following results equal?
             ʋ         -     First result:
   Ṗ                   -       Yield [a,b]
         ¥             -       Group the previous 2 links into a dyad:
     ṛ/                -         Yield c
        Ɱ              -         Over each row in M:
       ị               -           Get the c'th element
                                  This returns a list [1◃c, 2◃c, 3◃c, ..., n◃c]
    ị                  -       Get the a'th and b'th elements
                                  This yields [a◃c, b◃c]
          œị           -       Calculate (b◃c)◃(a◃c); See above
                     ʋ   -     Second result:
               Ṫ         -       Yield c and replace the left argument with [a, b]
                 œị     -        Calculate (b◃a)
                ṭ        -       Tack on c; [b◃a, c]
                    ⁺    -       Repeat the previous link (œị), yielding c◃(b◃a)
              =          -     Does c◃(b◃a) equal (b◃c)◃(a◃c)?

```
* The first yields either `1` or `0`, depending on whether the matrix is idempotent or not.
* The second yields an array of \\$n\\$ `1`s or `0`s, for each row in `M`. `M` is only right-divisible and closed iff all of these are `1`
* The third yields a list of \\$n^3\\$ `1`s if `M` is right-self-distributive, or a list with at least one `0` if not.

Finally, we concatenate all of these results into a single list. If that list contains a `0`, then `M` is not a quandle, otherwise it is.

# Answer
> 0 votes
# C++14, 175 bytes

As unnamed lambda, assuming `n` to be like `std::vector<std::vector<int>>` and returning via reference parameter. 0 is false, everything else is true.

```
#define F(x);for(x=-1;++x<s;){
[](auto m,int&r){int s=r=m.size(),a,b,c F(a)auto A=m[a];r*=s==A.size()&&A[a]==a;int u=0 F(b)u|=1<<m[b][a];r*=A[b]<s F(c)r*=m[A[b]][c]==m[A[c]][m[b][c]];}}r*=!(u-(1<<s)+1);}}

```

Ungolfed and usage:

```
#include<vector>
#include<iostream>

auto f=
#define F(x);for(x=-1;++x<s;){
[](auto m,int&r){
 int s=r=m.size(),a,b,c
 F(a)
  auto A=m[a];               //shortcut for this row
  r*=s==A.size()&&A[a]==a;   //square and idempotet
  int u=0                    //bitset for uniqueness in col
  F(b)
   u|=1<<m[b][a];            //count this item
   r*=A[b]<s                 //closed
   F(c)
    r*=m[A[b]][c]==m[A[c]][m[b][c]];
   }
  }
  r*=!(u-(1<<s)+1);          //check right-divisibility
 }
}
;

int main(){
 int r;
 std::vector<std::vector<int>>
  A = {
   {0, 0, 1, 1},
   {1, 1, 0, 0},
   {3, 3, 2, 2},
   {2, 2, 3, 3},
  },
  B = {
   {0, 2, 3, 4, 1},
   {0, 1, 2, 3, 4},
   {3, 4, 2, 2, 2},
   {3, 3, 3, 3, 3},
   {4, 1, 1, 1, 4},
  };
 f(A,r);
 std::cout << r << "\n";
 f(B,r);
 std::cout << r << "\n";
}

```

---
Tags: code-golf, math, array, abstract-algebra
---


title: Permutation group operation

text:
# Question
Title: Permutation group operation
There is a well-known bijection between the permutations of \\$n\\$ elements and the numbers \\$0\\$ to \\$n!-1\\$ such that the lexicographic ordering of the permutations and the corresponding numbers is the same. For example, with \\$n=3\\$:

```
0 <-> (0, 1, 2)
1 <-> (0, 2, 1)
2 <-> (1, 0, 2)
3 <-> (1, 2, 0)
4 <-> (2, 0, 1)
5 <-> (2, 1, 0)

```

It is also well-known that the permutations of \\$n\\$ elements form a group (the symmetric group of order \\$n!\\$) - so, in particular, that one permutation of \\$n\\$ elements applied to a second permutation of \\$n\\$ elements yields a permutation of \\$n\\$ elements.

For example, \\$(1, 0, 2)\\$ applied to \\$(a, b, c)\\$ yields \\$(b, a, c)\\$, so \\$(1, 0, 2)\\$ applied to \\$(2, 1, 0)\\$ yields \\$(1, 2, 0)\\$.

Write a program which takes three integer arguments: \\$n\\$, \\$p\_1\\$, and \\$p\_2\\$; interprets \\$p\_1\\$ and \\$p\_2\\$ as permutations of \\$n\\$ elements via the bijection described above; applies the first to the second; and outputs the corresponding integer, reapplying the above bijection. For example:

```
$ ./perm.sh 3 2 5
3

```

This is so the shortest code in bytes wins

# Answer
## J, 30

I like the elegance of this:

```
[:A.[:{/]A.~/~i.@[

```

or this:

```
13 :'A.{/(i.x)(A.)~/y'

```

but they work like this:

```
3 f 2 5
3
12 f 8 9
17

```

So this is the valid entry:

```
([:A.[:{/i.@{.A.~/}.)".}.>ARGV

```

Some explanations:

* `3 A. 0 1 2`: gives the 3rd permutation of `0 1 2` (= `1 2 0`)
* `0 1 2 (A.)~ 3`: is the same but with arguments reversed
* `0 1 2 (A.)~/ 3 4 5 ...` "applies" `(A.)~` to `3 4 5 ...`, so it gives the 3rd, 4th, 5th, ... permutation of `0 1 2`.
* `A. 1 2 0`: gives the order of the permutation of `1 2 0` (= 3)
* `i. n`: gives the sequence `0 1 2 ... n-1`
* `1 2 0 { 0 2 1` arranges `0 2 1` by `1 2 0` (= `2 1 0`)
> 7 votes

# Answer
# Ruby - 77 chars

```
n,a,b=$*.map &:to_i
l=[*[*0...n].permutation]
p l.index(l[b].values_at *l[a])

```
> 4 votes

# Answer
## Python 2.6, 144 chars

```
import sys
from itertools import*
n,p,q=map(int,sys.argv[1:])
R=range(n)
P=list(permutations(R))
print P.index(tuple(P[q][P[p][i]] for i in R))

```
> 2 votes

# Answer
# Jelly, 8 bytes

```
œ?Ụị¥/Œ¿

```

Try it online!

Uses 1-indexing, Jelly's default (i.e. just increment every number in the challenge body). +2 bytes to use zero indexing. Takes \\$\[p\_1, p\_2\]\\$ on the left and \\$n\\$ on the right.

The text of the question is kinda confusing. "Applying" one permutation to another is essentially sorting the elements of the second by the values of the first, which is exactly what "grade up, then index into" does.

## How it works

```
œ?Ụị¥/Œ¿ - Main link. Takes [p1, p2] on the left and n on the right
œ?       - Generate the permutations of [1, 2, ..., n], then yield the p1'th and p2'th values
    ¥/   - Reduce those permutations by the following, with perm(p1) on the left and perm(p2) on the right:
  Ụ      -   Grade up perm(p1); This sorts the indices of perm(p1) by their corresponding values
   ị     -   Index into perm(p2) with these sorted indices
      Œ¿ - Sort the corresponding list, get all permutations and find it's index in them

```
> 2 votes

---
Tags: code-golf, math, combinatorics, permutations
---


title: Find the smallest file

text:
# Question
Title: Find the smallest file
## Goal:

Create a program to find the smallest file in the current folder.

* File size may be measured in bytes or characters.
* If multiple files have the same size, you can either choose one or display all of them.
* You can assume there will be at least one file in the folder, and no files will have a size of 0.
* Assume that all files in the folder can be loaded by the language you're using.
* ### Assume that there are no folders in the current directory.

### Input:

The program should not take any input from the user, unless:

* If your language doesn't have a "current folder", it may ask the user for a folder name/path.
* If your language cannot directly access files on your computer, it may allow the user to upload files. (JavaScript, for example)

### Output:

The name of the smallest file should be displayed.

* Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.
* (Printing a list of all the files is against the rules).

### Notes:

* Standard Loopholes are not allowed.
* You cannot modify/create/delete files in the folder to change the result.
* This is ; shortest answer (in bytes) wins.

# Answer
# Vim 12 bytes

```
!!ls -Sa
Gd{

```

Try it online!

## Explanation:

`!!` is the *filter* command. It pipes the contents of the current line to an arbitrary system command, and sends the output back into the buffer. It's useful for using external tools for things that bash is better at than vim, for example `!!rev` to reverse the current line, or `!Gxxd` to hexdump the buffer. In our case, the buffer is empty so it's equivalent to `:r!ls`, which just feeds the output of the command into the current line.

Now the cursor is on line 1, and we want to delete every line but the last one. The naïve approach is

```
G       " Go to the last line
 k      " Go up one line
  d     " Delete:
   gg   "   Everything up to the first line

```

But we can do better. Like I explained in this tip, the `{` can *usually* (but not always) be equivalent to `gg`. Here, it's even better. Because the motion is *character-based*, not *line-based* like `gg` is, we don't have to go up a line first, leaving us with

```
Gd{

```
> 8 votes

# Answer
# Bash + coreutils, 13 bytes

```
ls -Sar|sed q

```

Explanation:

```
ls -Sar|sed q
ls            # list files
   -S         # sorted, biggest first
     a        # show hidden files
      r       # reversed (smallest first)
       |sed q # q is quit at first line that matches given regex,
              # given regex is empty so guaranteed match.

```
> 16 votes

# Answer
# PowerShell, ~~30~~ ~~24~~ 21 bytes

```
(ls|sort le*)[0].Name

```

Try it online!

`ls` is an alias for `Get-ChildItem`. That's piped to `sort-object` with the `length` attribute, so the files are sorted by size. We index into that with the `(...)[0]` to get the first (i.e., smallest), and then take the `.Name` thereof. Output via implicit `Write-Output` happens at program completion.

*Saved 6 bytes since we're guaranteed that only files exist in the directory. Saved an additional 3 thanks to ConnorLSW.*
> 9 votes

# Answer
## Python ~~2~~ 3, ~~94~~ ~~76~~ ~~74~~ 54 bytes

-18 bytes thanks to @orlp
-2 bytes thanks to @Jonathan Allan
-20 bytes thanks to a change in challenge specs

```
from os import*
print(min(listdir(),key=path.getsize))

```
> 9 votes

# Answer
## Ruby, ~~61~~ ~~40~~ ~~38~~ 37 bytes

Thanks G B and Value Ink

```
p Dir[?*,".*"].min_by{|x|File.size x}

```
> 7 votes

# Answer
# Java 7, ~~149~~ 142 bytes

```
String f(){String n="";long s=-1>>>1,p;for(java.io.File f:new java.io.File(".").listFiles())if((p=f.length())<s){n=f.getName();s=p;}return n;}

```

Try it online!

-7 bytes thanks to CAD97
> 7 votes

# Answer
# Mathematica, 35 bytes

```
FileNames[]~MinimalBy~FileByteCount

```

`FileNames[]` produces a list of names of all the files (and directories) in the current directory; `~MinimalBy~FileByteCount` selects the name of the file whose byte count is smallest. `FileByteCount` throws a bunch of errors when it's applied to directories, but the errors don't derail the program.
> 6 votes

# Answer
## SH (Linux/Unix) ~~15~~ ~~14~~ ~~13~~ 14 bytes

```
ls -aS|tail -1

```

`-S` sorts by size (descending),

~~`-r`reverses~~ and `tail -1` outputs the last file in the list.

@ Dennis Thanks for saving 1 byte @Dani\_l Thanks for saving 1 byte.
> 6 votes

# Answer
# MATLAB / Octave, ~~52~~ 48 bytes

```
d=dir;[~,n]=min([d.bytes]./~[d.isdir]);d(n).name

```

**Explanation**

This gets a directory listing of all files and folders in the current directory using `dir`. The output of `dir` is a `struct` containing the filename, whether it's a directory or not, the size (in bytes), etc.

We can then take an array of the sizes of each in bytes `[d.bytes]` and perform element-wise division with a boolean indicating whether it's a directory or not `~[d.isdir]` which will yield `Inf` where it's a directory (division by zero) and the size in bytes otherwise (division by 1).

We find the index of the minimum of this array using the second output of `min` and use that to index into the initial struct and display the name with `d(n).name`
> 4 votes

# Answer
## Batch, ~~43~~ ~~39~~ 35 bytes

```
@dir/b/os|(set/pf=&call echo %%f%%)

```

Output includes a leading space for some reason, but fortunately that's allowed. Edit: Now assuming there are no directories to save 4 bytes.
> 4 votes

# Answer
# , ~~21~~ 20 bytes

```
>{.,(/:2&{"1)1!:0'*'

```

Saved a byte thanks to @Conor.

## Explanation

```
>{.,(/:2&{"1)1!:0'*'
                 '*' Glob all files in current directory
             1!:0    Table of file metadata in that directory
       2&{"1         Get the file size of each
     /:              Sort the files by that
   ,                 Flatten
 {.                  Get the first value
>                    Unbox

```
> 4 votes

# Answer
# Perl 6,  ~~33 32 31~~  16 bytes

```
'.'.IO.dir.grep(*.f).min(*.s).put

```

Try it

```
put '.'.IO.dir.min:{try .s//Inf}

```

Try it

```
put $*CWD.dir.min:{try .s//Inf}

```

Try it

```
put dir.min: *.s

```

Try it

## Expanded:

```
put        # print with trailing newline
dir        # the list of files in the current directory
.min:      # find the minimum by
  *.s      # calling the `s` method (size) in a Whatever lambda

```
> 4 votes

# Answer
**Scala, 52 bytes**

Old version, 79 bytes

```
new java.io.File(".").listFiles.map(a=>a.getName->a.length)sortBy(_._2)apply(0)

```

Adjusted according to jaxad0127's advice. It is only 52 bytes now.

```
new java.io.File(".").listFiles.sortBy(_.length)head

```
> 4 votes

# Answer
## BATCH File, ~~77~~ ~~72~~ ~~63~~ 60 bytes

```
@FOR /F tokens^=* %%G IN ('dir/o-s/b')DO @SET[=%%G
@ECHO %[%

```

There's no direct equivalent of `head` or `tail` in BATCH, at least to my knowledge, so here's a kludgy work-around. (with much assistance from @Neil - thanks!)

The `dir` command, with `/o-s` to sort in descending file size, and `/b` to output only the file names. We loop through those with `FOR /F`, setting the variable `[` to the file name each time. Finally, we output just the last one with `ECHO %[%`.

*Saved 9 more bytes thanks to Neil and thanks to guarantees that no directories are present.*
*Saved 3 bytes thanks to HackingAddict1337.*
> 3 votes

# Answer
## PHP, ~~84~~ 62 bytes

```
$t=array_map(filesize,$g=glob('*'));asort($t);echo$g[key($t)];

```

Since the question was updated with the assumption that there will be no folders in the current directory, I was able to remove the file check stuff and golf this down.

---

**Here is my old answer:**

```
$t=array_map(filesize,$g=array_filter(glob('*'),is_file));asort($t);echo$g[key($t)];

```

This is the best I could do. Maybe there is a better way I'm missing.

```
$t=array_map(              # visit each array element and...
    filesize,              # map each filename to its filesize...
    $g=array_filter(       # using an array of...
        glob('*'),         # all files and directories...
        is_file            # filtered by files...
    )                      #
);                         #
asort($t);                 # sort the array of filesizes, then...
echo$g[key($t)];           # print element from the array of files using the first key of the sorted array as an index

```
> 3 votes

# Answer
# SmileBASIC, 110 bytes

```
DIM F$[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
S=LEN(LOAD(F$[I],0))IF!Z||S<Z THEN Z=S:B=I
NEXT?F$[B]

```

Only looks at `TXT:` files, since `DAT:` files cannot be loaded unless you already know their size, making it impossible to load a random one.
> 2 votes

# Answer
# Tcl, 88 bytes

```
set s Inf
lmap f [glob -ty f *] {if [set m [file si $f]]<$s {set n $f
set s $m}}
puts $n

```

Try it online!
> 2 votes

# Answer
# Node.js (using `walk`), 114 bytes

Ignore newline:

```
require('walk').walk(__dirname).on('file',(r,s,n)=>
(m=s.size>m.size?m:s,n()),m=0).on('end',_=>console.log(m.name))

```

This invokes a walker that traverses through the current directory (`__dirname`) and for each file calls a function with its stat `s` and a function next `n()` that must be invoked to continue the traversal. Then at the `end`, it prints a filename with the minimum `size` in bytes found. `s.size>m.size` returns `false` when `m.size` is `undefined`, so after the first callback, `m` is equal to the first file found, and continues from there normally.
> 2 votes

# Answer
## R, 36 bytes

```
x=file.info(y<-dir())$s;y[x==min(x)]

```

**Explained**

`file.info()` returns a `data.frame` of "file information" when given a character or character vector of file/folder names which when used on the list of files/folders in the current directory (`dir()`), looks something like:

```
                                                               size isdir mode               mtime               ctime               atime exe
Polyspace_Workspace                                               0  TRUE  777 2014-11-28 17:29:25 2014-11-28 17:29:25 2014-11-28 17:29:25  no
Python Scripts                                                    0  TRUE  777 2016-03-21 23:59:41 2016-03-21 23:59:41 2016-03-21 23:59:41  no
R                                                                 0  TRUE  777 2015-12-23 20:11:02 2015-12-23 20:11:02 2015-12-23 20:11:02  no
Rockstar Games                                                    0  TRUE  777 2015-04-14 12:23:05 2015-04-14 12:23:03 2015-04-14 12:23:05  no
TrackmaniaTurbo                                                   0  TRUE  777 2016-03-24 17:15:05 2016-03-24 13:13:48 2016-03-24 17:15:05  no
ts3_clientui-win64-1394624943-2014-06-11 03_18_47.004772.dmp 314197 FALSE  666 2014-06-11 02:18:47 2014-06-11 02:18:47 2014-06-11 02:18:47  no

```

Subsequently we just have the find the name of the file for which the `size` column (abbreviated using `$s`) is the smallest. Consequently, if there are more than one file with the smallest size, all will be returned.

Bonus: if we also wanted to disregard folders in the current directory we could simply search for size when `isdir == FALSE`: `x=file.info(y<-dir());y[x$s==min(x$s[!x$i])]` which turns out to be 44 bytes.
> 2 votes

# Answer
# Groovy, 49 bytes

```
m={f->f.listFiles().sort{it.length()}[0].getName()}

```

Try it online!

Closure, usage: `m(new File("location"))`
> 1 votes

# Answer
# C#, 277 bytes

Not the shortest, but what would you expect from C#?

## Golfed

```
using System.Linq;using static System.IO.Directory;class P{static void Main(){var x=GetFiles(GetCurrentDirectory());var d=new long[]{}.ToList();foreach(var s in x){var b=new System.IO.FileInfo(s).Length;if(!d.Contains(b))d.Add(b);}System.Console.Write(x[d.IndexOf(d.Min())]);}}

```

## Ungolfed

```
//Linq using for List.Min()
using System.Linq;
//Static using to save bytes on GetCurrentDirectory() and GetFiles()
using static System.IO.Directory;

class P
{
    static void Main()
    {
        //String array containing file paths
        var x = GetFiles(GetCurrentDirectory());
        //Creating a Long array and converting it to a list, less bytes than "new System.Collections.Generic.List<long>()"
        var d = new long[] { }.ToList();
        foreach (var s in x) //Loop through all file paths
        {
            //Getting file size in bytes
            var b = new System.IO.FileInfo(s).Length;
            if (!d.Contains(b))
                //If there isn't already a file with this size in our List, add the file path to list
                d.Add(b);

        }
        //Get index of the smallest Long in our List, which is also the index of the file path to the smallest file, then write that path
        System.Console.Write(x[d.IndexOf(d.Min())]);
    }
}

```
> 1 votes

# Answer
# Röda, ~~32~~ 31 bytes

```
{ls""|sort key=fileLength|pull}

```

It's an anonymous function that sorts the files in the current directory by file length and selects then the first file with `pull`.

Use it like this: `main{ {ls""|sort key=fileLength|pull} }`
> 1 votes

# Answer
# Zsh `-C4`, 9 bytes

* `-C`: enables noclobber (Zsh will not redirect to files which already exist)
* `-4`: enables globdots (`*` matches files beginning with `.`.

> Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.

The following prints the file name, preceded by `$0:1: file exists:`  and followed by a newline, to stderr:

```
>*(oL[1])

```

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

* `(oL)` sorts by size
* `[1]` selects the first match

---

I used to have just `*(oL[1])` and rely on Zsh printing "command not found", but if the file matches the name of a builtin or executable, this would break. Additionally, the previous `echo` methods would break if the smallest file was `-e` or `-` or similar (interpreted as a flag to `echo`). This new method works for all file names and is still very short.
> 1 votes

# Answer
# SmileBASIC 3, 105 bytes (competing?)

Beats 12Me21's answer but still suffers from inability to load DAT files (which feels very cruel to be disqualifying considering the circumstances.)

```
DIM F$[0],T[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
PUSH T,LEN(LOAD(F$[I]))NEXT
SORT T,F$?F$[0]

```

The shorter version above is annoying and prompts you on every file to load, but it does work. For two bytes more you can suppress the prompt; change line 2 to this:

```
PUSH T,LEN(LOAD(F$[I],0))NEXT

```
> 0 votes

# Answer
## Batch File, 33 bytes

Batch files are moderately competitive this time, oddly enough.

```
@dir/os/b>..\q&set/pa=<..\q&"%a%.

```

**Output**

---

Find a way to stop the creation of `q` prior to `dir/os/b` being run and you'll save a maximum of 6 bytes by not needing to put the output file in a separate directory.

```
@dir/os/b>q&set/pa=<q&"%a%

```

Will always output `q` as the smallest file (unless tied for another 0 byte file) as it is created as an empty file before `dir/b/os` gathers a list of files.
> 0 votes

# Answer
# C++17 (gcc), 180 bytes

```
#include<filesystem>
using namespace std::filesystem;auto f(){std::error_code e;path r;size_t m=-1,s;for(auto&p:directory_iterator(".")){s=file_size(p,e);if(s<m)m=s,r=p;}return r;}

```

Try it online!

Requires a recent standard library that implements `std::filesystem`.
> 0 votes

# Answer
# PowerShell 6+ for Windows, 20 bytes

```
ls|sort l* -t 1|% n*

```

Try it online!

Unrolled:

```
ls|sort length -top 1|% Name

```

See also AdmBorkBork's answer.
> 0 votes

# Answer
# Red, 56 bytes

```
first sort/compare read %. func[a b][(size? a)< size? b]

```
> 0 votes

# Answer
# Pyth, 51 bytes

```
.ml$open(b,"rb").read()$$__import__("os").listdir()

```

I feel like Pyth might not be the best tool for the job here...

Try it online!
> 0 votes

---
Tags: code-golf, file-system
---


# Question
Title: 9/10 Geometers agree, Nepal has the coolest flag
Given no input, output the following:

```
 _
| ~-_
| o  ~-_
| ~     ~-_
|    ＼~~~~~~
|  *   ＼
|        ＼
|~~~~~~~~~~＼

```

Note the backslashes are actually , which is `U+FF3C`

Trailing whitespace is allowed, however leading whitespace is not.

This is so fewest bytes **in each language** wins!

# Answer
> 4 votes
# Python 2, ~~94~~ ~~92~~ 96 bytes

```
print(""" _
| ~-_
| o  ~-_
| ~     ~-_
|    ＼~~~~~~
|  *   ＼
|        ＼
|~~~~~~~~~~＼""")

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 50 bytes

```
•ζ1VS¹Tšã¦1d’sΩç!ÙT>_äтÿÀ†{ECZ{Ý•7ÝJ"_ -~|＼*o"‡8¡»

```

Try it online!

---

First I created a translation table as follows:

```
0   | "_"
1   | " "
2   | "-"
3   | "~"
4   | "|"
5   | "＼"
6   | "*"
7   | "o"
8   | "\n"

```

I then proceeded to replace each unique character in the flag with the number corresponding to the character at that specific position to get the number:

```
108413208417113208413111113208411115333333841161115841111111158433333333335

```

Here's the same pattern with the newlines (makes it more obvious):

```
10
41320
41711320
41311111320
411115333333
41161115
4111111115
433333333335

```

I then compressed the number into base-255 using 05AB1E (To compress a base-10 number to base 255 simply run 255B in 05AB1E).

Then, see the code explanation for how I rebuild it from the number.

---

```
•ζ1VS¹Tšã¦1d’sΩç!ÙT>_äтÿÀ†{ECZ{Ý• # Push the number we discussed.
7ÝJ                               # Push 01234567.
   "_ -~|＼*o"                    # Push "_ -~|＼*o".
              ‡                   # Replace 0-7 with the appropriate block.
               8¡»                # Split on 8's and print with newlines.

```

# Answer
> 1 votes
# Japt, ~~83 79~~ 78 bytes (UTF-8)

```
" _
| ~-_
| o  ~-_
| ~     ~-_
|    ＼~~~~~~
|  *   ＼
|{8ç}＼
|{Aç'~}＼

```

Hardcodes most of the string

Try it online!

# Answer
> 1 votes
# SOGL, 49 bytes

```
⁰∑J“ζ"Ω‰Θx(;╝φ╚○Δ§∆qσG⅛>K█׀IR'ΚΧqΞ⅞≥№█▼¡└+Β8‘# ~ŗ

```

If the flag used any other character than `~`, this would be 4 bytes shorter.

# Answer
> 1 votes
# 05AB1E, ~~76~~ ~~74~~ ~~72~~ 66 bytes

-6 bytes thanks to @carusocomputing

```
'~T×ð8×'~6×ð5×" _
| ~-_
| o  ~-_
| ~ÿ~-_
|    ＼ÿ
|  *   ＼
|ÿ＼
|ÿ＼"

```

String interpolation replaces the `ÿ`s. In order from first to last, it is: 5 spaces, 6 `~`s, 8 spaces, and then 10 `~`s

Try it online!

# Answer
> 0 votes
# C#, 89 bytes

```
_=>@" _
| ~-_
| o  ~-_
| ~     ~-_
|    ＼~~~~~~
|  *   ＼
|        ＼
|~~~~~~~~~~＼"

```

Any formatting options in C# for this require too many extra bytes that it is just cheaper to hard code the output as far as I can tell.

# Answer
> 0 votes
# Jelly, ~~51~~ 50 bytes

```
“ ½|~-o*_‘;65340Ọ“ßṆiṣ€|ʂwĊeḌ\<S@DƝbƘ×©ṗþ8¥Ḅ3Zȥ ’ṃ

```

Try it online!

# Answer
> 0 votes
# Java 8, 96 bytes

```
()->" _\n| ~-_\n| o  ~-_\n| ~     ~-_\n|    ＼~~~~~~\n|  *   ＼\n|        ＼\n|~~~~~~~~~~＼"

```

Boring, but it probably can't be shortened by using some fancy `.replace` or loops anyway in Java..

Try it here.

# Answer
> 0 votes
# Mathematica, 84 bytes

```
"_
| ~-_
| o  ~-_
| ~     ~-_
|    ＼~~~~~~
|  *   ＼
|        ＼
|~~~~~~~~~~＼"

```

# Answer
> 0 votes
# Bubblegum, 40

Not sure why no-one posted the bubblegum answer yet - Is bubblegum frowned upon these days?

xxd dump:

```
00000000: 5388 e7aa 51a8 d305 91f9 0a50 469d 0210  S...Q......PF...
00000010: 40d9 40f0 7ecf 9e3a 3000 71b5 2002 1019  @.@.~..:0.q. ...
00000020: 0518 a70e 0e80 5c00                      ......\.

```

Try it online.

# Answer
> 0 votes
# Retina, ~~60~~ 59 bytes

```

1_!1~-_!1o2~-_!1~5~-_!4＼""!2*3＼!8＼!"""~＼
"
~~~
!
¶|
\d
$*

```

Try it online!

# Answer
> 0 votes
# Charcoal, 37 bytes

```
←×~χ↑⁷ _Ｐ¶¶o¶~¶¶ *Ｆ³¶~-_↓←×~⁶Ｆ⁴«＼↘

```

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

```
←×~χ

```

Print the bottom `~`s.

```
↑⁷

```

Print the left `|`s.

```
 _Ｐ¶¶o¶~¶¶ *Ｆ³¶~-_

```

Print the upper right line and the interior decoration.

```
↓←×~⁶

```

Print the middle `~`s.

```
Ｆ⁴«＼↘

```

Print the lower right line.

# Answer
> 0 votes
# Deadfish~, 459 bytes

```
{iii}iic{iiiiii}iiic{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iiiic{{d}ii}dc{iiiii}c{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddc{{i}dd}dc{{d}ii}icc{{i}d}iiiic{{d}ii}dc{iiiii}c{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddc{{i}d}iiiic{{d}i}ddddccccc{{i}d}iiiic{{d}ii}dc{iiiii}c{{d}ii}dddddc{{i}}{i}iiiic{{d}i}ddcccc{iiiiii}c{iii}iiiicccccc{{d}}{d}ddddddc{{i}}{i}iiiic{{d}i}ddcc{i}c{d}ccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiic{{d}i}ddcccccccc{iiiiii}c{{d}ii}ddc{{i}}{i}iiiicii{c}{ddd}ddddc

```

Try it online!

Uses backslashes instead.

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---