title: Trap the hero in a maze

text:
# Question
Title: Trap the hero in a maze
You are an evil wizard, doing evil wizard business, when suddenly your crystal ball alerts you of a hero on their way to defeat you. To crush their hopes and dreams, you decide to trap the hero in a maze. You could just make a big maze but where would be the fun in that? Instead, you decide you want to make the maze as small as possible for a truly humiliating defeat. Thanks to your wizard skills, you know in advance how the hero will navigate the maze.

The hero's moves are represented by a list where each element can be one of "LR", "LS", "RL", "RS", "SL" or "SR". Inside the maze the hero moves forwards until they reach an intersection. Then the corresponding element in the list tells which direction the hero should continue. The hero first tries to move in the direction represented by the first letter, and next in the direction represented by the second letter. So for example, if the hero's moves are `["LS", "SR", "RS"]`, at the first intersection the hero will turn left. If that is not possible, they will go straight. Similarly in the second intersection, the hero will try to go straight, but if that's not possible, they will go right instead.

If the hero reaches a dead end or the beginning of the maze, they will just turn around. If there is a corner (the path just turns), then the hero will just follow the path. These interactions don't require any decisions, and therefore don't consume the decision list.

The hero gives up when they reach an intersection, but the decision list is consumed.

# Rules

You are given the hero's move list as input and you have to output the maze as output. The maze begins at the upper left corner and ends at the lower right corner. The maze must be possible to traverse. You can use different values for "LR", etc, but please don't encode any extra information in the values, such as code. Output the maze as ascii art like this:

```
█ ████████
█    █   █
██ █ █ ███
██ ███   █
█      █ █
████████ █

```

You can also use different (distinct) characters for the wall and air. You can also return a two dimensional or flattened two dimensional list with two distinct values for wall and air (if you use a flattened list, please also return at least one of the dimensions to remove ambiguity). Since the outer border of a maze is always the same, you can return just the inner portion (also applies to ascii art output).

The maze cannot contain any areas accessible to the hero where the hallway is wider than one block. So for example:

Not Ok:

```
█ ███
█   █
█   █
███ █

```

Ok:

```
█ █
█ ████
█    █
████ █

```

The size of a maze is the area of it's rectangle bounding box. For example, the preceding maze has size 24.

You must output the smallest maze, where the hero gives up. In case of ties, any minimal solution is fine.

The input list has at least one element.

# Test cases

```
["LR"]
->
█ ██
█  █
██ █
█  █
██ █
or
█ ██
█  █
█ ██
█  █
██ █
or
█ ███
█ █ █
█   █
███ █

["RL","RL","RS","LS","LR","RS","RS","SR","LR","RL"]
->
█ ███
█  ██
█ █ █
█   █
███ █

["LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS", "LS"]
->
█ █████
█    ██
█ █ █ █
█  █  █
█ █ █ █
█     █
█████ █

["LR","RL","LS","LR","LS","LR","SR","SR","LR","SL","RL","SL","RS","RL","SR","LS","RS","SR","LS","SL","RS","SL","SR","SR","RS","RS","RS","RS","RL","LS","RS","RL","RL","SR","RL","RS","SL","RS","LS","RS","SR","SR","SR","RL","RL","SL","LR","LR","RS","RL","SR","SL","SR","RS","SR","RS","RS","RL","RL","RS"]
->
█ █████
█   █ █
█ █   █
█   █ █
█ ██  █
█████ █

["LR","RS","LR","RS","SR","RS","RS","LR","RS","SR","SR","SL","RS","LS","SR","SR","RL","RS","LS","LR","RS","RL","RL","RL","SL","SL","RL","RS","RS","RS","SL","SL","SR","RS","RS","LR","RS","RL","LR","RL","RS","SL","LR","RL","LR","SR","RS","LR","LR","RL","RS","SR","SR","LR","SR","SR","SL","RL","RS","LR","RS","RS","RS","LS","LS","RL","RL","SL","LS","LS","SL","RS","LS","RS","SL","LS","LS","RS","LS","LS","SL","SR","LS","RL","SL","LR","RS","RS","RS","RS","SL","LR","RL","RL","RS","SL","SR","RS","LR","RS","RS","LS","RS","LR","RS","SL","RS","LS","RS","SR","RL","RL","RL","LS","RS","RS","RS","LS","LS","SR"]
->
█ ████
█    █
█ █ ██
█    █
██ ███
█    █
██ █ █
████ █

```

# Answer
# Python 3.8 (pre-release), ~~1206 1095 1052~~ 866 bytes

```
H=range
R=input().split()
s=0
while s:=s+1:
 B=[[*map(int,bin(2**s|k)[3:])]for k in H(2**s)]
 for a in H(2,s):
  for c in((b:=s//a)*a==s)*B:
   m=[[1,0,*[1]*a],*[[1,*c[a*n:a*-~n],1]for n in H(b)],[*[1]*a,0,1]];I=0;P=[0,1];D=[1,0]
   while[b,a]>=(P:=[P[0]+D[0],P[1]+D[1]])>[0for T in B if 1>T[-1]==T[0]and all(W or len([w for w in[i%a>a-2 or T[i+1],1>i%a or T[i-1],i+a>=len(T)or T[i+a],i<a or T[i-a]]if 1>w])==1+(len(T)-1>i>0)and 1>c[i]for i,W in enumerate(T))]>[1for c in H(a)for r in H(b)if 1>m[r+1][c+1]+m[r][c+1]+m[r][c]+m[r+1][c]]:
    A=[l for l in[[0,1],[1,0],[0,-1],[-1,0]]if 2+b>P[0]+l[0]>-1<P[1]+l[1]<a+2>1>m[P[0]+l[0]][P[1]+l[1]]!=[-l[0],-l[1]]!=D]
    if A[1:]:R[I:]or exit([print(*r,sep="")for r in m][0]);F,S=R[I];f=lambda Q:[D,[D[::-1],[-D[1],0]][D[1]],[[0,-D[0]],D[::-1]][D[1]]][ord(Q)%5%3];D=[f(S),Z:=f(F)][Z in A];I+=1
    else:D,*_=*A,[-D[0],-D[1]]

```

Try it online!

This version brute-forces every possible maze. The results don't match the test cases, but then again, the other answers don't match the test cases either.

Takes way too long to solve the third one, however.

## More explanation

The code creates a variable called `s` which holds the size of the inner maze. At each iteration, we generate all binary strings of length `s` (where a 1 is wall and a 0 is air) using a trick to avoid having to use lengthy padding methods, and ensuring that it doesn't start with a 1 in order not to have to check for impossible entry into the maze.

We go through each width from 2 to `s`. If this width does not divide `s`, dismiss it. Otherwise, we generate the mazes with the wall/air determined by the binary string, and the width/height determined by this divisor. We dismiss the maze if it is not traversable (a maze is traversable if, out of the binary strings, you can find one in which the zeroes form a linear path from the beginning of the maze to the exit) or if there is a 2x2 block of zeroes within the maze (disallowed by the OP).

Then, we run a simulation of the maze. We initialize the directions, decision number, and position, and update the position accordingly at each iteration. If the exit is reached, we break out of the current loop and move on to the next binary string. Otherwise, we calculate the number of possible directions to go at an intersection (excluding the way we came, of course), and:

* if there is no direction left (i.e. the hero hits a dead end), turn around, i.e. negate the direction;
* if there is one direction left, simply go that way;
* if there are two or more directions, we take the current decision. If there is no such decision, meaning we have consumed all decisions, that is victory and hence we break out of all loops. Otherwise, we try following the first choice of that decision, and if impossible, we follow the second choice (one or the other is guaranteed to work, as some simple mathematical reasoning will reveal). We then increment the decision number.

We increment the size of the maze once all factorizations and binary strings have been exhausted for that particular size.

Once we have found a good maze, we output it with a nice output format.

*I insist on the nice input/output format.*

## Acknowledgements

Thanks to @AnttiP, the OP of this challenge, for golfing off an astonishing 186 bytes.
> 5 votes

# Answer
# JavaScript (Node.js), 314 bytes

```
f=(x,n=8)=>(g=(s,i=n)=>s[n]?i>2?(h=x=>~n%i|M.some((_,b)=>(s[b+1]&s[b+i]&s[b-~i]|-~b%i<2|b<i^b>n-i^b==1^b==n-1)&s[b]|[...E.filter(j=>+s[j+P])[2]?x[R++]||[]:_].some(g=>+s[p=P+E[+g+W&3]]&&(P=p,W+=+g))&P>n-3,P=W=R=0,E=[1,i,-1,-i]))(M=[...(x+1).repeat(n)].fill('3012'))>h(x)?[s,i]:g(s,i-1):0:g(s+1)||g(s+0))``||f(x,n+1)

```

Try it online!

EDIT: Fixed a bug(not enough steps for `LS RS RS ... RS LS LS`), making it MORE slower

```
01000
01110
01010
01110
00010

```

Slow even for smallest input `[]`, returning (same as 1st case)

```
0100
0110
0100
0110
0010

```

For the 2nd case f(\['13','13','10','30','31','10','10','01','31','13'\]), output is

```
01000
01100
01010
01110
00010

```

not further tested

```
f=(x,n=8)=>(  // start from size=9, though startting from 10 also work
  g=(s,i=n)=> // recurse
    s[n]?     // otherwise g(s+1)||g(s+0)
      i>2?(   // width>=3
        h=(s,i,x)=>    // runable checker
          ~n%i|        // rectangle (n+1 is the size)
          [...s].some(
            (t,j)=>(   // no 2*2 road, border is correct. 1 if don't satisfy
              s[j+1]&s[j+i]&s[j-~i]|-~j%i<2|j<i^j>n-i^j==1^j==n-1
            )&t
          )||
          M.some(_=> // walk for enough time
              [...E.filter(j=>+s[j+P])[2]?x[R++]||[]:'0132'] // if branch then take instruction, otherwise try 3 forward then one back
              .some(g=>+s[p=P+E[+g+W&3]]&&(P=p,W+=+g))       // try walk
              &P>n-3,P=W=R=0,E=[1,i,-1,-i]                   // if at aim
          )          // it starts at (0,0) and go right, but can never go back to (0,0) since it's a wall
      )(s,i,M=[...s+s].fill('30')) // Using fact that '30'(LS)*inf always go for a possible maze to share code
      &&!h(s,i,x)?[s,i]:g(s,i-1)
  :0:g(s+1)||g(s+0))``||f(x,n+1)

```
> 4 votes

# Answer
# Python 3, 2̶9̶3̶1̶ 1765 bytes

It's long, it's ugly, but it works (and for an infinite maze size). Brute force method, and it takes quite a while to run all test cases (took me ~15 minutes). Big thanks to @ThisFieldIsRequired and @12944qwerty for helping me shave it down.

```
def f(a):
    from pathfinding.core.grid import Grid
    from pathfinding.finder.a_star import AStarFinder as A
    c=[]
    r=None
    x,y=4,4
    while 1:
        z=x-2
        v=y-2
        e=(x-2)*(y-2)
        if c and x*y>=r:pass
        else:
            for i in range(2**e, int(''.join([t for u in [['1']+['0']*(v-1) for t in range(z)] for t in u]),2),-1):
                o=list(a)
                p=list(map(int, format(i,'b').rjust(e,'0')))
                b=[p[(i*z-z):i*z] for i in range(1,v+1)]
                if 0 in [b[0][0],b[-1][-1]]:continue
                g=Grid(matrix=b)
                s=g.node(0,0)
                d=g.node(z-1,v-1)
                h=A(diagonal_movement=2)
                P,R=h.find_path(s,d,g)
                if len(P)==0:continue
                B=0
                for k in range(v-1):
                    for l in range(z-1):
                        q = [b[k][l],b[k+1][l],b[k][l+1],b[k+1][l+1]]
                        if 0 not in q:B=1;break
                    if B:break
                if B:continue
                b=[[0]+l+[0] for l in b]
                b.insert(0, [0 for f in range(x)])
                b.append([0 for f in range(x)])
                b[0][1],b[-1][-2]=1,1
                L=[[1,1],[0,1]]
                d=[y-1,z]
                o.reverse()
                while 1:
                    if [L[0][0], L[0][1]]==d:break
                    U=[L[0][0]-1,L[0][1]]
                    U.append(b[U[0]][U[1]])
                    D=[L[0][0]+1,L[0][1]]
                    D.append(b[D[0]][D[1]])
                    S=[L[0][0],L[0][1]-1]
                    S.append(b[S[0]][S[1]])
                    R=[L[0][0],L[0][1]+1]
                    R.append(b[R[0]][R[1]])
                    Q=[U, D, S, R]
                    O=sum([U[2],D[2],S[2],R[2]])
                    if O==1:L[0],L[1]=L[1],L[0];continue
                    elif O==2:
                        for C in Q:
                            if [C[0],C[1]] == L[1]:continue
                            elif C[2] == 1:L=[[C[0],C[1]],L[0]];break
                        continue
                    else:
                        try:
                            I=o.pop()
                        except IndexError:
                            c=b
                            r=x*y
                            B=1
                            break
                        Y=[q-w for q,w in zip(L[0],L[1])]
                        for m in I:
                            if m=="L":T=[-Y[1],Y[0]]
                            elif m=="R":T=[Y[1],-Y[0]]
                            else:T=Y
                            N=[[q+w for q,w in zip(L[0],T)],L[0]]
                            if b[N[0][0]][N[0][1]]:L=N;break
                if B:break
        if x!=y and x<y:x,y=y,x
        elif x!=y and x>y:x,y=y,x;continue
        if x==y:x+=1;y=4
        else:y+=1
        if c and r<=x*4:break
    return c

```

Try it online!

Outputs:

```
['LR']
->
█ ███
█ █ █
█   █
███ █
Score is: 20

['LR', 'RS', 'SR', 'LS', 'RL', 'SL', 'SL', 'RL', 'RL', 'LR', 'RL', 'RL', 'LS']
->
█ ██
█  █
█ ██
█  █
█ ██
█  █
██ █
Score is: 28

['LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS', 'LS']
->
█ █████
█    ██
█ █ █ █
█  █  █
█ █ █ █
█     █
█████ █
Score is: 49

['LR', 'RL', 'LS', 'LR', 'LS', 'LR', 'SR', 'SR', 'LR', 'SL', 'RL', 'SL', 'RS', 'RL', 'SR', 'LS', 'RS', 'SR', 'LS', 'SL', 'RS', 'SL', 'SR', 'SR', 'RS', 'RS', 'RS', 'RS', 'RL', 'LS', 'RS', 'RL', 'RL', 'SR', 'RL', 'RS', 'SL', 'RS', 'LS', 'RS', 'SR', 'SR', 'SR', 'RL', 'RL', 'SL', 'LR', 'LR', 'RS', 'RL', 'SR', 'SL', 'SR', 'RS', 'SR', 'RS', 'RS', 'RL', 'RL', 'RS']
->
█ █████
█   █ █
█ █   █
█   █ █
█ ██  █
█████ █
Score is: 42

['LR', 'RS', 'LR', 'RS', 'SR', 'RS', 'RS', 'LR', 'RS', 'SR', 'SR', 'SL', 'RS', 'LS', 'SR', 'SR', 'RL', 'RS', 'LS', 'LR', 'RS', 'RL', 'RL', 'RL', 'SL', 'SL', 'RL', 'RS', 'RS', 'RS', 'SL', 'SL', 'SR', 'RS', 'RS', 'LR', 'RS', 'RL', 'LR', 'RL', 'RS', 'SL', 'LR', 'RL', 'LR', 'SR', 'RS', 'LR', 'LR', 'RL', 'RS', 'SR', 'SR', 'LR', 'SR', 'SR', 'SL', 'RL', 'RS', 'LR', 'RS', 'RS', 'RS', 'LS', 'LS', 'RL', 'RL', 'SL', 'LS', 'LS', 'SL', 'RS', 'LS', 'RS', 'SL', 'LS', 'LS', 'RS', 'LS', 'LS', 'SL', 'SR', 'LS', 'RL', 'SL', 'LR', 'RS', 'RS', 'RS', 'RS', 'SL', 'LR', 'RL', 'RL', 'RS', 'SL', 'SR', 'RS', 'LR', 'RS', 'RS', 'LS', 'RS', 'LR', 'RS', 'SL', 'RS', 'LS', 'RS', 'SR', 'RL', 'RL', 'RL', 'LS', 'RS', 'RS', 'RS', 'LS', 'LS', 'SR']
->
█ ████
█    █
█ █ ██
█    █
██ ███
█    █
██ █ █
████ █
Score is: 48

```
> 3 votes

# Answer
# Python3, 1651 bytes:

```
import copy,time
M=[(0,1),(0,-1),(1,0),(-1,0)]
R=range
E=enumerate
def v(m,n):
 for j,k in M:
  if(q:=n[0]+j)<0 or(w:=n[1]+k)<0:return 0
  try:
   m[q][w]
  except:return 0
 for q,l in E(m):
  for w,s in E(l):
   if not s:
    try:
     if not any([s,m[q][w+1],m[q+1][w],m[q+1][w+1]]):return 0
    except:1
 return 1
class H:
 def __init__(self):self.s={}
 def g(self,m,e,s):
  if e in s:
   yield(m,s);return
  for x,y in s:
   for j,k in M:
    if 0<(q:=x+j)<len(m)and 0<(w:=y+k)<len(m[0])and m[q][w]:
     B=copy.deepcopy(m)
     B[q][w]=0
     if (q,w)==e or v(B,(q,w)):
      if (q,w)not in self.s.get(tuple(sorted(s)),[]):
       self.s[tuple(sorted(s))]=self.s.get(tuple(sorted(s)),[])+[(q,w)]
       yield from self.g(B,e,s+[(q,w)])
T={0:{'L':((0,1),1),'R':((0,-1),2),'S':((1,0),0)},1:{'L':((-1,0),3),'R':((1,0),0),'S':((0,1),1)},2:{'L':((1,0),0),'R':((-1,0),3),'S':((0,-1),2)},3:{'L':((0,-1),2),'R':((0,1),1),'S':((-1,0),3)}}
U={0:3,3:0,1:2,2:1}
def r(d,c,w,e,s):
 if c==(0,1):d=0
 if c==e:return 0
 if not(m:=[(a,(x,y),D)for a,(q,D)in T[d].items()if(x:=q[0]+c[0],y:=q[1]+c[1])in w]):return r(U[d],c,w,e,s)
 if len(m)==1:return r(m[0][-1],m[0][1],w,e,s)
 if not s:return 1
 W={a:(c,b)for a,b,c in m}
 return r(*W.get(s[0][0],W.get(s[0][1])),w,e,s[1:])
def S(s):
 L=set()
 P=max(4,len(set(s)))
 k=P+1
 while k:
  for i in R(P,k):
   for j in R(P,k):
    if (i,j)not in L:
      L.add((i,j))
      b=[[1 for _ in R(j)]for _ in R(i)]
      b[0][1]=0
      t=time.time()
      for G,W in H().g(b,(i-1,j-2),[(0,1)]):
       if time.time()-t>5:break
       yield(G,W,(i-1,j-2))
  k+=1
def f(s):
 for G,W,e in S(s):
  if r(0,(0,1),W,e,s):return G

```

Try it online!

Produces the correct mazes for all the test cases in under 60 seconds.
> 3 votes

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


# Question
Title: Animate finding the middle (hypercube edition)
1d version

Given a multidimensional array of positive integers where all dimensions are the same length, animate finding the centre of it.

Simply output the array, then remove the first and last items of every array within it and output it, until the length of each dimension is less than 3 and can't have the first and last removed.

For example, with this 2-dimensonal array:

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

```

You'd output the array, then remove the first and last of each to output this:

```
[ [4, 9, 9],
  [3, 1, 9],
  [1, 7, 6] ]

```

And finally output just this:

```
[ [ 1 ] ]

```

Output format can be as an array of multidimensional arrays, each array printed separately, etcetera.

You may output a trailing empty list, and you don't have to output the original array.

## Testcases

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

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

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

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

```

# Answer
# Wolfram Language (Mathematica), ~~47~~ 44 bytes

```
#//.l_:>(Print@l;#0/@#[[2;;-2]]~Check~#&@l)&

```

Try it online!

Prints the steps, one per line. Includes a final empty list if the input has even length

```
#                                           starting from input,
 //.                                        until a fixed point is reached:
    l_:>(Print@l;                         )   output current value
                 #0/@#[[2;;-2]]        &@l    recursively take its middle on every level
                               ~Check~#         or unchanged if length<2
                                                (this also handles recursion base case)

```

---

**43 bytes**, non-competing

```
{#}//.l_:>{#0/@#[[2;;-2]]~Check~#&@@l}⋃l&

```

Try it online!

Returns the lists in reverse order. I don't expect this is allowed, but it's an interesting variation.
> 8 votes

# Answer
# APL(Dyalog Unicode), 17 bytes SBCS

```
{h↓⍵↓⍨-h←×⍴⎕←⍵}⍣≡

```

Try it on APLgolf!

A dfn submission which prints each iteration. Input is a multidimensional array.

-14 from ovs.
> 6 votes

# Answer
# Pip `-xp`, ~~25~~ ~~24~~ 22 bytes

```
W@<P@ggM:{0*a?fM@<Saa}

```

Takes the input array as a command line argument; outputs each step on a separate line. Gives an empty list at the end for even-size test-cases, as permitted. Attempt This Online!

### Explanation

This is for a somewhat more straightforward 23-byte version. The 22-byte version works the same way, except that the main program manipulates `g` (the list of all command-line args--in our case, a singleton list) instead of `a` (the first command-line arg). This ends up saving a byte because Pip's function-call syntax is a bit verbose.

```
W@<Paa:({...}a)
                 ; a is 1st cmdline arg (evaluated, thanks to -x flag)
W                ; While...
    a            ;   Current array
   P             ;   Printed (in list format, thanks to -p flag)
 @<              ;   Minus its last element
                 ; ...is truthy (nonempty list), loop:
       (      )  ;   Call
        {...}    ;   This function (see below)
             a   ;   With argument a
     a:          ;   Assign the result back to a

{0*a?fM@<Saa}    ; Recursive function to strip one hypercube layer:
   a             ; The function argument
 0*              ; Times 0 (either 0 for integer a, or list of 0s for list a)
    ?            ; If truthy, the argument is a nonempty list:
         Sa      ;   Argument minus its first element
       @<        ;   Minus its last element
     fM          ;   Map this function recursively to each remaining element
                 ; Else, the argument is an integer:
           a     ;   Return it unchanged

```
> 5 votes

# Answer
# Ruby, 57 bytes

```
f=->x{x*0==0?x:x[1..-2].map(&f)}
g=->h{p h
h[2]&&g[f[h]]}

```

Try it online!
> 5 votes

# Answer
# APL (Dyalog Unicode), 18 bytes

Anonymous tacit prefix function.

```
{⍵(⊢↓↓⍨∘-)×⍴⎕←⍵}⍣≡

```

Try it online!

`{``}⍣≡` apply lambda until stable

`⎕←⍵` print the argument

get its shape

`×` signum of that (gives list with one 1 per dimension)

`⍵(``)` apply the following tacit function with the argument as left argument:

…`∘-` negate the right argument (the number of elements to drop, so they'll be dropped from the rear

`↓⍨` drop that many elements from the left argument

`⊢↓` drop right-argument elements from that
> 4 votes

# Answer
# Python + NumPy, 74 bytes --\> 64 bytes (@DLosc)

```
def x(a):
 if len(a):print(a);x(a[(slice(1,-1),)*len(a.shape)])

```

Try it online!

Thank's @DLosc for removing the return. Nice spot.
> 4 votes

# Answer
# Python 3, 75 bytes

```
f=lambda x:[x]+(x[2:]and f(q(x)))
q=lambda x:0!=x*0and[*map(q,x[1:-1])]or x

```

Try it online!

-7 bytes + fixed thanks to DLosc
> 3 votes

# Answer
# JavaScript, 53 bytes

```
f=a=>[a,...g(a)+''&&f(b)]
g=a=>b=a.map?.(g).slice(1,-1)??a

```

```
f=a=>[a,...g(a)+''&&f(b)]
g=a=>b=a.map?.(g).slice(1,-1)??a

console.log(JSON.stringify(f([[[4, 6, 7], [1, 6, 8], [3, 3, 4]], [[9, 2, 8], [4, 9, 4], [6, 3, 9]], [[3, 7, 8], [4, 3, 6], [2, 8, 2]]])))
console.log(JSON.stringify(f([[[6, 5, 9, 4], [8, 8, 5, 1], [9, 3, 1, 6], [1, 7, 7, 9]], [[8, 3, 7, 2], [6, 6, 9, 4], [5, 6, 8, 3], [2, 1, 9, 9]], [[4, 9, 6, 9], [6, 9, 3, 7], [3, 6, 8, 2], [7, 5, 8, 6]], [[8, 6, 2, 1], [3, 5, 9, 5], [2, 6, 1, 3], [3, 6, 3, 9]]])))
console.log(JSON.stringify(f([[[[[5, 1, 6], [8, 2, 9], [9, 2, 4]], [[7, 1, 8], [1, 1, 5], [6, 9, 4]], [[3, 6, 6], [9, 9, 9], [4, 2, 5]]], [[[9, 9, 8], [7, 2, 7], [1, 2, 6]], [[3, 1, 8], [1, 7, 9], [6, 9, 2]], [[6, 6, 1], [6, 8, 8], [2, 5, 6]]], [[[9, 5, 3], [3, 6, 9], [8, 8, 7]], [[4, 6, 4], [8, 7, 9], [8, 6, 7]], [[2, 4, 1], [4, 5, 2], [8, 7, 8]]]], [[[[8, 1, 6], [1, 4, 4], [7, 6, 6]], [[9, 9, 9], [8, 1, 7], [9, 2, 4]], [[9, 5, 7], [1, 4, 8], [3, 8, 1]]], [[[3, 8, 1], [8, 7, 6], [1, 5, 7]], [[8, 5, 1], [7, 2, 1], [7, 1, 3]], [[1, 2, 6], [4, 3, 7], [1, 1, 1]]], [[[8, 1, 1], [7, 5, 2], [9, 3, 6]], [[2, 1, 5], [1, 3, 3], [5, 5, 2]], [[7, 6, 2], [9, 5, 7], [3, 8, 1]]]], [[[[5, 8, 9], [7, 2, 5], [3, 9, 7]], [[7, 8, 7], [3, 4, 1], [4, 1, 3]], [[3, 8, 6], [7, 7, 9], [8, 4, 8]]], [[[7, 5, 4], [8, 1, 7], [9, 9, 1]], [[1, 1, 8], [2, 3, 7], [9, 5, 4]], [[2, 2, 6], [8, 8, 2], [1, 3, 6]]], [[[7, 2, 7], [1, 7, 3], [8, 3, 9]], [[6, 1, 4], [8, 3, 8], [8, 9, 5]], [[5, 7, 2], [9, 7, 6], [1, 3, 4]]]]])))
console.log(JSON.stringify(f([[[[1, 8, 1, 7, 8], [2, 6, 6, 2, 8], [9, 4, 2, 3, 3], [1, 9, 5, 8, 5], [6, 3, 9, 2, 2]], [[8, 2, 5, 5, 3], [3, 3, 8, 6, 6], [3, 3, 5, 6, 6], [4, 2, 5, 3, 6], [2, 2, 5, 5, 4]], [[4, 4, 1, 9, 7], [4, 3, 4, 3, 8], [3, 7, 1, 7, 7], [1, 2, 7, 5, 6], [5, 6, 5, 4, 6]], [[7, 8, 9, 7, 2], [9, 4, 9, 9, 2], [3, 1, 9, 2, 9], [3, 5, 8, 4, 7], [3, 3, 5, 9, 9]], [[5, 6, 2, 4, 3], [2, 9, 6, 6, 1], [6, 8, 2, 9, 7], [5, 2, 1, 8, 4], [7, 7, 9, 6, 1]]], [[[2, 2, 8, 1, 6], [3, 6, 9, 9, 9], [9, 7, 6, 8, 7], [9, 6, 3, 5, 6], [9, 1, 8, 5, 6]], [[2, 4, 2, 7, 3], [8, 9, 8, 7, 1], [1, 6, 1, 8, 4], [9, 9, 8, 8, 2], [5, 5, 7, 9, 5]], [[6, 4, 3, 1, 2], [6, 4, 4, 7, 6], [7, 7, 6, 1, 3], [8, 7, 1, 4, 7], [4, 7, 1, 1, 2]], [[1, 7, 7, 5, 3], [7, 8, 4, 1, 1], [8, 5, 7, 5, 3], [6, 9, 1, 9, 6], [5, 9, 7, 3, 1]], [[6, 3, 7, 1, 5], [1, 9, 4, 8, 2], [9, 6, 5, 9, 5], [2, 9, 4, 4, 6], [8, 3, 6, 7, 4]]], [[[2, 4, 7, 7, 8], [4, 2, 9, 4, 8], [5, 4, 2, 1, 3], [1, 6, 8, 1, 1], [4, 7, 4, 9, 5]], [[4, 9, 1, 3, 7], [3, 3, 7, 6, 4], [4, 6, 7, 4, 5], [7, 3, 2, 7, 6], [5, 5, 7, 9, 3]], [[7, 6, 7, 4, 1], [8, 3, 4, 7, 3], [1, 9, 9, 2, 4], [2, 7, 2, 8, 1], [5, 1, 4, 8, 8]], [[3, 5, 4, 8, 2], [1, 2, 7, 4, 5], [1, 7, 2, 2, 9], [8, 4, 2, 1, 4], [4, 9, 2, 3, 5]], [[1, 1, 9, 7, 8], [4, 8, 1, 7, 5], [3, 5, 2, 2, 7], [8, 6, 3, 2, 1], [6, 9, 9, 1, 3]]], [[[2, 8, 5, 5, 6], [6, 3, 4, 6, 4], [2, 3, 5, 7, 9], [2, 6, 1, 1, 2], [6, 4, 9, 8, 5]], [[8, 4, 7, 2, 1], [6, 5, 4, 8, 7], [7, 8, 3, 6, 8], [2, 2, 4, 7, 2], [2, 3, 6, 4, 4]], [[5, 2, 8, 4, 8], [6, 7, 2, 8, 7], [8, 2, 1, 9, 2], [2, 1, 1, 7, 2], [9, 6, 1, 5, 2]], [[3, 2, 9, 2, 2], [9, 4, 5, 1, 2], [9, 1, 6, 3, 7], [8, 8, 7, 1, 8], [3, 4, 8, 9, 6]], [[8, 6, 1, 6, 9], [1, 9, 6, 9, 4], [6, 6, 6, 9, 6], [2, 5, 3, 6, 5], [6, 6, 9, 5, 7]]], [[[2, 4, 3, 6, 1], [6, 8, 2, 8, 8], [5, 2, 9, 7, 7], [1, 3, 5, 6, 2], [5, 3, 5, 7, 9]], [[5, 3, 8, 8, 5], [2, 7, 5, 3, 7], [2, 5, 1, 6, 6], [5, 7, 1, 4, 2], [5, 1, 4, 5, 2]], [[1, 6, 2, 5, 3], [3, 8, 1, 9, 4], [3, 9, 6, 7, 1], [8, 5, 3, 7, 1], [3, 8, 8, 1, 4]], [[3, 1, 2, 1, 9], [5, 7, 1, 4, 2], [1, 8, 5, 7, 3], [2, 5, 8, 2, 1], [9, 9, 6, 9, 7]], [[4, 8, 3, 5, 6], [5, 6, 4, 2, 3], [2, 5, 3, 1, 6], [2, 9, 4, 9, 4], [4, 6, 8, 2, 2]]]])))
```
> 3 votes

# Answer
# Wolfram Language, ~~34~~ 32 bytes

```
#~ArrayPad~-1&~FixedPointList~#&

```

Try it online!

* `ArrayPad[array,-1]` negatively pad 1 element on every side regardless the dimension of `array`.
* `FixedPointList[f, x]` applies function `f` on `x` repeatedly, until a fixed-point of `f` is reached.

The result is collected in a `List`, extra code (`Grid[...]`) is needed for aesthetic view.

Example for Notebook environment:

```
{{7, 2, 3, 6, 4}, {2, 4, 9, 9, 8}, {7, 3, 1, 9, 8}, {9, 1, 7, 6, 9}, {4, 3, 4, 8, 5}} //
  #~ArrayPad~-1&~FixedPointList~#& //
 Grid[#,Dividers->{False,Center},Alignment->Left]&

```
> 3 votes

# Answer
# BQN, 20 bytesSBCS

```
×∘≠¨⊸/×∘≢⊸(-∘⊣↓↓)⍟⊒˜

```

Run online!

`...⍟⊒˜` Iterate 0 to length-1 times, collecting the results:
`×∘≢⊸(-∘⊣↓↓)` Drop the outer face.

`×∘≠¨⊸/` Remove empty arrays from the output.

Calculating the length of the output to avoid the last step is a byte longer:

```
×∘≢⊸(-∘⊣↓↓)⍟(↕·⌈2÷˜≠)

```

Run online!
> 2 votes

# Answer
# Brachylog, 12 bytes

```
ẉ&{ċbk↰ᵐ|ℕ}↰

```

Outputs one array per line. Includes an empty array for even-length inputs. Try it online!

### Explanation

```
ẉ&{ċbk↰ᵐ|ℕ}↰
ẉ             Write the input to stdout with a trailing newline
 &            And, with the input
  {       }   Apply this predicate to remove one hypercube layer:
   ċ            The input must be a list
    b           Remove the first element
     k          Remove the last element
      ↰ᵐ        Map the current predicate recursively to each remaining element
        |       Or, if that definition fails, try this one:
         ℕ      The input is a nonnegative integer (return it unchanged)
           ↰  After removing a layer, call the outer predicate recursively
              The recursion continues until the predicate fails

```
> 2 votes

# Answer
# 05AB1E, 20 bytes

```
Δ=DdΔ€`}\N>"ε¦¨"×¦.V

```

Will always output a single trailing empty list.

Try it online or verify all test cases.

**Explanation:**

```
Δ            # Continue looping until the result no longer changes:
 =           #  Print the current multi-dimensional matrix with trailing newline
             #  (without popping)
             #  (which will use the implicit input in the first iteration)
  DdΔ€`}\N>  #  Determine the depth of this multi-dimensional matrix:
  D          #   Duplicate it
   d         #   Transform each inner integer to a 1 (with a >=0 check)
    Δ        #   Inner loop until the result no longer changes:
     €`      #    Flatten one level down
       }\    #   After the inner loop: discard the result
         N>  #   Push the last 1-based index instead (0-based index + 1)
   "ε¦¨"×    #  Repeat "ε¦¨" that many times as string
         ¦   #  Remove the leading "ε"
          .V #  Evaluate and execute it as 05AB1E code:
    ε        #  Map over each inner list:
     ¦       #   Remove the first item
      ¨      #   As well as the last item

```

It'll always output an additional trailing empty list, because `Δ` will loop an additional time to determine if the list isn't changing anymore.

The determination of the depth of the multi-dimensional matrix (`DdΔ€`}\N>`) is taken from this answer of mine.

Minor note: `"ε¦¨"×` cannot be `…ε¦¨×` or `…ε¨¦×`, because the `¦¨`/`¨¦` will be interpret as dictionary words `"ink"`/`"keys"` respectively: try it online.
> 1 votes

# Answer
# Retina 0.8.2, 188 bytes

```
;{:G`
(\[)(\d+|\[((\[)|(?<-4>])|[^][])+(?(4)^)]),(?=(\d+|\[((\[)|(?<-7>])|[^][])+(?(7)^)]),)|(?<=,(\d+|(?(10)^)\[((])|(?<-10>\[)|[^][])+])),(\d+|\[((\[)|(?<-13>])|[^][])+(?(13)^)])(?=])
$1

```

Try it online! Link includes test cases. Explanation:

```
;{:G`

```

Output the contents of the buffer before every iteration, but don't double-output the last iteration.

```
(\[)(\d+|\[((\[)|(?<-4>])|[^][])+(?(4)^)]),(?=(\d+|\[((\[)|(?<-7>])|[^][])+(?(7)^)]),)|

```

Match the first element in the array or one of its inner subarrays, as long as that array has at least three elements. The leading `[` is captured as that's slightly golfier than a lookbehind. The first element is matched normally and the second element is matched with a lookahead as if it's a subarray then we'll want to match the first element in the subarray. .NET balancing groups are used to ensure that whole subarrays are matched. Alternatively:

```
(?<=,(\d+|(?(10)^)\[((])|(?<-10>\[)|[^][])+])),(\d+|\[((\[)|(?<-13>])|[^][])+(?(13)^)])(?=])

```

Match the last element in the array or one of its inner subarrays, as long as that array has at least three elements. The penultimate element is matched with a lookbehind which is subtly different as it matches from right to left so `]`s increase the balancing group depth and `[`s decrease it. Here a lookahead is slightly golfier than capturing the trailing `]`.

```
$1

```

Keep the leading `[` before the first element if that's what we matched.
> 1 votes

# Answer
# Charcoal, 66 bytes

```
Ｗ¬⁼θυ«≔∨υθθ⟦⭆¹θ⟧≔ＩＩθυ≔⟦υ⟧ηＦη«Ｆ‹²Ｌκ«≔⟦⟧ζＷκ⊞ζ⊟κＦ⮌✂ζ¹±¹⊞κμ»Ｆκ¿⁺⟦⟧λ⊞ηλ

```

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

```
Ｗ¬⁼θυ«

```

Repeat until the array stops changing.

```
≔∨υθθ

```

Except on the first run, use the new array in place of the original.

```
⟦⭆¹θ⟧

```

Pretty-print the array on its own line.

```
≔ＩＩθυ

```

Deep clone the array. (Unfortunately adding `0` or multiplying by `1` doesn't work because those operators only vectorise once.)

```
≔⟦υ⟧ηＦη«

```

Start processing the array and all of its subarrays.

```
Ｆ‹²Ｌκ«

```

If this array has at least three elements, then...

```
≔⟦⟧ζＷκ⊞ζ⊟κ

```

... remove the elements of the array into a temporary array, and...

```
Ｆ⮌✂ζ¹±¹⊞κμ

```

... push all of the elements of the temporary array except the first and last back to the array.

```
»Ｆκ¿⁺⟦⟧λ⊞ηλ

```

Push all subarrays of the current array to the list of arrays to be processed.
> 1 votes

# Answer
# Python 2, 68 bytes

```
def f(L):L>f<map(f,L)<L.pop(0)+L.pop()
L=input()
while[f(L)]:print L

```

Try it online!

A program taking input from STDIN and output to STDOUT. Doesn't output the initial array. Terminates with error.
> 0 votes

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


title: Fill the (possibly leaky) bowl

text:
# Question
Title: Fill the (possibly leaky) bowl
## Challenge:

Given an ASCII art of a (possibly leaky) bowl consisting of a random distinct non-whitespace and non-`~` character, fill it completely with `~` characters. If the bowl is leaky, fill the bottom row below the bowl and a stream of liquid emerging from that, with the intended amount of `~` if the bowl would not have been leaky.

For example:

*Regular bowl:*

| Input | Output |
| --- | --- |
| ``` #      #<br> #    # <br>  ####   ``` | ``` #~~~~~~#<br> #~~~~# <br>  ####   ``` |

*Leaky bowl:*

| Input | Output |
| --- | --- |
| ``` 00     00<br> 00   00 <br>  000 0   ``` | ``` 00     00<br> 00   00 <br>~~000~0~~<br>     ~   <br>     ~   <br>     ~    ``` |

If there wouldn't have been a leak, it could have contained eight `~`. Instead, the bottom row including leak position is now filled with five `~`, and the remaining three `~` are below the leak.
(Imagine the bowl standing on a table, so the five `~` at the bottom row of the bowl are on the table, and the `~` vertically below the leak are dripping off the table.)

## Challenge rules:

* The potential leak is guaranteed to be at the bottom row, and there will never be any gaps at the sides of a bowl.
* The potential leak is guaranteed to be a single character gap.
* The character used for the bowl can be any printable ASCII character, except for the `~` and whitespaces.
* The bowl can be in an irregular shape (see some of the test cases).
* The top ridges of the bowl are guaranteed to be on the same top row, and there will only be two top ridges.
* If the bottom row contains more space characters than inside the leaky bowl (see the third leaky bowl test case below), we still fill the entire bottom row of the output regardless, but there won't be any additional `~` below it.
* For the sake of this challenge, there won't be any smaller inner bowls (e.g. no doughnut-shaped bowls if we'd imagine it as 3D). So every space in the bowl will always flow towards the leak. (See the fourth leaky bowl test case below, which doesn't have `#~# #` as its second line.)
* There also won't be any enclosed blobs at the sides (or inside) of a bowl, not any 'stalagmites' nor 'stalactites'.
* The bottom of the bowl won't have a path traveling up and back down.
* I/O is flexible. Could be a multi-line string; a list of lines; a character matrix; etc.
    + You're allowed to pad the input with trailing spaces to make the input a rectangle.
    + You're allowed to have leading/trailing whitespaces and/or newlines in the output, as long as the expected result is somewhere on the screen.

**Here some examples of invalid bowls based on the rules.** Your program can have unspecified behavior for any of the invalid bowls. If you have a question about a certain bowl-shape, feel free to ask in the comments.

## General rules:

* This is , so the 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 (e.g. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases

*Regular bowls:*

| Inputs | Outputs |
| --- | --- |
| ``` #      #<br> #    # <br>  ####   ``` | ``` #~~~~~~#<br> #~~~~# <br>  ####   ``` |
| ``` !!!        !!<br>   !!      ! <br>     !!!   ! <br>        !!!!  ``` | ``` !!!~~~~~~~~!!<br>   !!~~~~~~! <br>     !!!~~~! <br>        !!!!  ``` |
| ``` 4   4<br>4 4 4<br>44444 ``` | ``` 4~~~4<br>4~4~4<br>44444 ``` |
| ```   B B  <br> B   B <br>B     B<br>B     B<br> B   B <br>  BBB   ``` | ```   B~B  <br> B~~~B <br>B~~~~~B<br>B~~~~~B<br> B~~~B <br>  BBB   ``` |
| ``` sss  sss<br>  s  s  <br>   s s  <br>ssssssssss ``` | ``` sss~~sss<br>  s~~s  <br>   s~s  <br>ssssssssss ``` |

*Leaky bowls:*

| Inputs | Outputs |
| --- | --- |
| ``` 00     00<br> 00   00 <br>  000 0   ``` | ``` 00     00<br> 00   00 <br>~~000~0~~<br>     ~   <br>     ~   <br>     ~    ``` |
| ``` ^^^        ^<br>   ^^      ^<br>     ^^^   ^<br>        ^ ^  ``` | ``` ^^^        ^<br>   ^^      ^<br>     ^^^   ^<br>~~~~~~~~^~^~<br>         ~  <br>         ~  <br>         ~  <br>         ~  <br>         ~  <br>         ~  <br>         ~   ``` |
| ``` @@@ @@@<br>  @ @   ``` | ``` @@@ @@@<br>~~@~@~~ ``` |
| ``` #   #<br># # #<br>### # ``` | ``` #   #<br># # #<br>###~#<br>   ~ <br>   ~ <br>   ~ <br>   ~  ``` |
| ``` xx xx<br>x   x<br>x   x<br> xx   ``` | ``` xx xx<br>x   x<br>x   x<br>~xx~~<br>   ~ <br>   ~ <br>   ~ <br>   ~  ``` |
| ``` 2 2<br>2 2 ``` | ``` 2 2<br>2~2 ``` |

# Answer
> 4 votes
# Charcoal, 76 bytes

```
ＷＳ⊞υι≔Ｅυ⭆ι⎇∧∧⁻…ιμ ⁻✂ιμＬι¹ ⁼ λ~λη¿⁼§η±¹⊟υη«υ≔⊟ηζ⟦⭆ζ⎇⁼ ι~ι⟧Ｅ⁻№⪫ηω~№ＫＡ~⭆ζ§ ~⁼~λ

```

Try it online! Link is to verbose version of code. Takes input as a rectangular list of newline-terminated strings. Explanation:

```
ＷＳ⊞υι≔

```

Input the bowl.

```
Ｅυ⭆ι⎇∧∧⁻…ιμ ⁻✂ιμＬι¹ ⁼ λ~λη

```

Try to fill the bowl with water.

```
¿⁼§η±¹⊟υη«

```

If the bowl isn't leaky, then output the filled bowl. Otherwise:

```
υ

```

Output all but the last row of the bowl.

```
≔⊟ηζ

```

Get the last row of the leaky bowl.

```
⟦⭆ζ⎇⁼ ι~ι⟧

```

Flood it and output the result.

```
Ｅ⁻№⪫ηω~№ＫＡ~⭆ζ§ ~⁼~λ

```

Count how much extra water there is and output just the hole of the last row of the leaky bowl for each extra line needed.

# Answer
> 5 votes
# APL(Dyalog Unicode), 145 bytes SBCS

A dfn taking a character matrix.

```
{h w←⍴m←' '=⍵
i←{∪⍵,(⌷∘(0@h⊢m)¨n)/n←⍵~⍨,(⌽q)(-q)q∘.+⍵}⍣≡⊂q+⊃⍸m⍷⍨q←0 1
b←h⌷m
×x←⊃⍸b∧i∊⍨(h-1),¨⍳w:'~'@((h,¨⍸b),x,⍨¨h+⍳d)⊢⍵↑⍨h+d←0⌈(≢i)-+/b
'~'@i⊢⍵}

```

Try it on APLgolf!

**Ungolfed:**

```
Fill ← {
  Height Width ← ⍴ Mask ← ' '=⍵
  Fixed   ← 0@Height⊢Mask
  ⍝ The initial interior piece is identified by the first occurence of <wall><no wall>
  Opening ← ⊂0 1+⊃⍸0 1⍷Mask
  ⍝ Iteratively expand the interior to the right, left and bottom
  Deltas  ← (1 0)(0 ¯1)(0 1)
  Volume  ← ≢ Interior ← {∪⍵,(⌷∘Fixed¨n)/n←⍵~⍨,Deltas∘.+⍵}⍣≡ Opening
  Bottom  ← Height⌷Mask
  ⍝ There is an hole when air on the bottom is below an interior point
  Hole    ← ⊃⍸Bottom∧Interior∊⍨(Height-1),¨⍳Width
  ⍝ If there is no hole, fill the interior
  0=Hole: '~'@Interior⊢⍵
  ⍝ Otherwise expand the matrix downwards and fill the column below the hole
  ⍝ and the spaces on the last row
  Drip    ← 0⌈Volume-+/Bottom
  '~'@((Height,¨⍸Bottom),Hole,⍨¨Height + ⍳Drip)⊢⍵↑⍨Height+Drip
}

```

Read it on APLgolf! Apparently this doesn't run with the comments on there, so if you want to have to run this version, you'll have to remove the comments.

# Answer
> 4 votes
# Python 3.8 (pre-release), ~~256 251~~ 223 bytes

```
lambda s:[[*map(F,s)],s+[(b:=s.pop()).replace(E,W)]+[E*(h:=F(''.join(map(max,zip(b,s[-1])))).find(W))+W]*(sum(F(x).count(W)for x in s)-b.count(E))][h>-1]
E,W=' ~'
F=lambda s:E*(len(s)-len(s.lstrip()))+s.strip().replace(E,W)

```

Try it online!

A function taking in a list of strings representing an empty bowl, and output a list of strings representing the filled bowl. The input must be padded with whitespaces so that each line is the same length.

# Explanation

`F` is a helper functions for filling a line with water between the walls. This is done by stripping all leading and trailing whitespaces, replace the remaining whitespaces with water, then add the leading whitespaces back.

`f` is the main function, and has the structure: `[answer_if_not_leak, answer_if_leak][has_leak]`

* `h:=F(''.join(map(max,zip(b,s[-1])))).find(W)` is the the index of the hole. This is done by first merging the walls of the bottom 2 lines (`b` and `s[-1]`), then fill the merged line with water. The only position that has water must be the hole:

```
L1     |  xxx        xx  |
L2     |    xxxx xxxx    |
Merged |  xxxxxx xxxxxx  |
Filled |  xxxxxx~xxxxxxx |

```
* If the bowl doesn't leak, there's no hole. So `h>-1` indicates that there's a leak.
* If no leak, simply applies `F` to each line
* If there is a leak, we returns a list consists of:
    + Every line except the bottom: `s` (note that we used `b:=s.pop()` so the bottom is already removed)
    + The bottom, with all whitespaces replaced with water: `[(b:=s.pop()).replace(E,W)]`
    + The rows representing leaking water stream: `[E*h+W]*number_of_water_in_the_stream`

# Answer
> 3 votes
# Python3, 522 bytes:

```
from re import*
r=range
g=lambda x:[i for i in r(len(x))if i and i<len(x)-1 and findall('^(?:[^\s]|\s)\s+$',''.join(x[i]))and any(d!=' ' for d in x[i-1][1:])and any(d!=' ' for d in x[i+1][1:])]
f=lambda x:'\n'.join(sub('(?<=[^\s])\s+(?=[^\s])',lambda x:'~'*len(x.group()),l)for l in k)if not(j:=g([*zip(*(k:=x.split('\n')))]))else'\n'.join(k[:-1]+[sub(' ','~',k[-1])]+[' '*j[0]+'~'+' '*(len(k[-1])-j[0]+1) for _ in r(sum(len(findall('(?<=[^\s])\s+(?=[^\s])',n)[0])for n in k[:-1])-k[-1].count(' ')+(k[-1].count(' ')==1))])

```

Try it online!

# Answer
> 3 votes
# ,(Version 903) 270 bytes

```
fb=:{{((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y}}
l=:{{'~' e. {."1 (]#~"1' '&~:) |."1|: fb y}}
flb=:{{
lr=.{:I.+./"1 '~'= fy=.fb y
lb=.(lr{(' '=y)} y,:'~') lr} y
r=.('~'=lr{fy){' ~'
c=.-/+/"1^:2 '~'=fy ,: lb
lb, ((c,#r)$r)
}}
cgb=:{{>(l y){(fb y);flb y}}

```

With comments:

```
NB. FillBowl
fb=:{{((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y}}

NB. LeakyBowl?
l=:{{'~' e. {."1 (]#~"1' '&~:) |."1|: fb y}}

NB. Fill Leaky Bowl
flb=:{{
lr=.{:I.+./"1 '~'= fy=.fb y NB. leak row
lb=.(lr{(' '=y)} y,:'~') lr} y
r=.('~'=lr{fy){' ~' NB. dripping row
c=.-/+/"1^:2 '~'=fy ,: lb NB. add c dripping rows
lb, ((c,#r)$r)
}}

cgb=:{{>(l y){(fb y);flb y}}  NB. Code Golf Bowl solution

```

# ,(Version 806) 320 bytes

tio.run currently only has an older version of j without the direct definition syntax:

```
fb=:3 : 0
((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y
)
l=:3 : 0
'~' e. {."1 (]#~"1' '&~:) |."1|: fb y
)
flb=:3 : 0
lr=.{:I.+./"1 '~'= fy=.fb y
lb=.(lr{(' '=y)} y,:'~') lr} y
r=.('~'=lr{fy){' ~'
c=.-/+/"1^:2 '~'=fy ,: lb
lb, ((c,#r)$r)
)
cgb=:3 : 0
>(l y){(fb y);flb y
)

echo b1 ; cgb b1
echo lb1 ; cgb lb1

```

Try it online!

## Explanation

I'm still relatively new to J and this solution could probably be made shorter again by someone with more experience golfing in J.

We define three helper verbs (J terminology for functions) `fb` "FillBowl", `l` "IsBowlLeaky?" and `flb` "FillLeakyBowl" and then finally a main verb `cgb` "CodeGolfBowl" to tie them all together.

All three verbs take a rectangular 2 dimensional array of characters as argument y.

### `fb` "FillBowl"

```
fb=:{{((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))}'~',:y}}

```

`fb` creates a boolean mask of not-spaces and spaces from the sides and then uses the mask to index into either water ('~' array) or the original argument. Eg:

```
   y
#      #
 #    #
  ####
   ((y~:' ')+.(*./\"1 &.|."1 y=' ')+.(*./\"1 y=' '))
1 0 0 0 0 0 0 1
1 1 0 0 0 0 1 1
1 1 1 1 1 1 1 1

```

### `l` "IsBowlLeaky?"

```
l=:{{'~' e. {."1 (]#~"1' '&~:) |."1|: fb y}}

```

`l` fills the bowl ignoring whether it leaks or not and then checks if the bottom non-whitespace row contains any water ('~' chars). If it does then the bowl is leaky. To check for the leak we transpose the array to the right, delete leading spaces and then check if any water '~' is in the first column. Eg:

```
   y
00     00
 00   00
  000 0
   fb y
00~~~~~00
 00~~~00
  000~0
   (]#~"1 ' '&~:) |."1 |: fb y
0
00
00~
0~~
0~~
~~~
00~
00
0

```

### `flb` "FillLeakyBowl"

```
flb=:{{
lr=.{:I.+./"1 '~'= fy=.fb y
lb=.(lr{(' '=y)} y,:'~') lr} y
r=.('~'=lr{fy){' ~'
c=.-/+/"1^:2 '~'=fy ,: lb
lb, ((c,#r)$r)
}}

```

`flb` proceeds with the following logic:

* Find the leaky row index `lr`
* Create the leakybowl array `lb` with the leaky row flooded
* Create the dripping row `r` with the drip in the correct location
* Count `c` how many water drops are missing
* Append `c` dripping rows `r` to the leakybowl array `lb`

### `cgb` "CodeGolfBowl"

```
cgb=:{{>(l y){(fb y);flb y}}

```

Finally our `cgb` verb combines everything together with the following logic:

* Create a boxed array of both the filledbowl and filledleakybowl solutions `(fb y);flb y`
* Check if the bowl is leaky `(l y)` and use the boolean 0 or 1 as the index into the previous boxed array

Eg:

```
   y
00     00
 00   00
  000 0
   (fb y);flb y
┌─────────┬─────────┐
│00~~~~~00│00     00│
│ 00~~~00 │ 00   00 │
│  000~0  │~~000~0~~│
│         │     ~   │
│         │     ~   │
│         │     ~   │
│         │     ~   │
└─────────┴─────────┘

```

For more information on this fascinating and fun language the J wiki has a huge amount of information and also links to quite a few free books:

# Answer
> 1 votes
# Python 3, 387 365 bytes

```
from re import*
def l(b):
    s=b[-1];r=search;l=len;m=r("^( *[^ ]+)(.*?)([^ ]+ *$)",b[-2])
    if r("^.{"+str(l(m.group(1)))+"}[^ ]{"+str(l(m.group(2)))+"}",s):b=[r("^ *(?=[^ ])",x).group(0)+x.strip().replace(" ","~")for x in b]
    else:b[-1]=s.replace(" ","~");b+=[" "*l(r("^( *[^ ]+)",s).group(0))+"~"]*(sum([x.strip().count(" ")for x in b[:-1]])-s.count(" "))
    return b

```

Try it online!

Takes input as a list of strings and returns a string representation of the bowl.

The first line sets up variables and then checks for bowl leaky-ness. The second line deals with non-leaky bowls, replacing spaces from the whitespace trimmed version of each line with `~`. The third line deals with leaky bowls, first filling the bottom row with water, then adding extra lines on the bottom as many times as is necessary.

Just out of interest, this answer, and I would guess most, are able to use bowls made of `~` characters, it is just confusing to look at.

# Answer
> 1 votes
# Python 3.8 (pre-release), 315 308 303 bytes

```
e=enumerate
def f(b):
 for y,l in e(b):
  s=0
  for x,c in e(l):
   if c==" ":
    if s and(L:=b[y])[x:].strip():
     if y<len(b)-1:b[y]=L[:x]+"~"+L[x+1:]
     else:return[n.replace("~"," ")for n in b[:y]]+[l.replace(" ","~")]+[" "*x+"~"]*max(0,"".join(b).count("~")-l.count(" "))
   else:s=1
 return b

```

Try it online!

Takes a list of strings (each representing a line) and outputs a modified version of that list. Input must be padded to a rectangle.

Not the smallest Python solution here, but I wanted to try a more standard iterative approach. If anyone has ideas on how to make it smaller it'd be much appreciated!

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

```
(r,l=r.pop(),w=t=>t.replace(/ /g,'~'),m=r.reduce((a,c)=>a+(s=t=>t.split` `.length-1)(c.trim()),0))=>((q=l.trim()).search` `>0|q.length<s([...r].pop().trim())?[r,w(l),[...Array((m-=s(l))<0?0:m)].map(_=>'~'.padStart(l.search`\\S `+2))]:[r.map(v=>v.trimEnd().replace(/( *\S)( +)/g,(_,x,y)=>x+w(y))),l]).flat().join`
`

```

Try it online!

Expects input as an array of strings, each representing a line. Outputs a string with the bowl.

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


title: From code to golf (Cops' thread)

text:
# Question
Title: From code to golf (Cops' thread)
*This is a challenge, the robbers' thread is here*

You can change the word `code` into `golf` by changing a letter at a time in four steps:

```
CODE
COLE
COLD
GOLD
GOLF

```

Today, we’ll be doing the same thing with programs.

Your challenge is to:

* choose a programming language
* write two programs / functions, one that outputs `code` and one that outputs `golf`
* Such that you can repeatedly change a single character and get a program that outputs an English word until you get to the `golf` program.
* Share the `code` program and the number of times you need to change a character, but not any of the intermediate programs or the `golf` program, which robbers will try to discover.
* No two programs can output the same word.

For example, if the program `abcde` outputs `code` in a certain language, and the program `abcdf` outputs `potato`, then changing that e to an f is a valid step.

And if the program `aqcdf` outputs `golf`, then `abcde` -\> `abcdf` -\> `aqcdf` is a valid chain in which you change a character twice.

You should only share the `code` program and the number of programs not counting the `code` program, the rest is for the robbers to guess.

Your solution is cracked when your entire chain of programs is found. It does not have to be your intended solution, only one with the same initial program and same or less length. (If someone finds a longer chain, it’s not a crack.)

If your answer is not cracked after a week, you may mark it as safe and reveal your solution.

Casing can be whatever you want - You can output `Code`, `CODE`, `coDe`, etc. Output may contain a trailing newline.

The dictionary used is `/dict/words`, which I've put in a gist for convenience.

## Scoring

Your score is the number of programs not counting the `code` or `golf` ones, multiplied by the length in bytes of your `code` program. The safe answer with the lowest score wins.

# Answer
> 7 votes
# JavaScript (ES6), 32 bytes, 4 changes, cracked by Dom Hastings

Should be easier to crack than it was to build. :-p

There are 4 intermediate steps, for a total of 6 programs.

```
_=>(0x63044+185886).toString(36)

```

Try it online!

# Answer
> 4 votes
# Pari/GP, 28 bytes, 1 step, cracked by M Virts

Let's start from an easy one.

```
go="co";lf="de";print(go,lf)

```

Try it online!

# Answer
> 4 votes
# Charcoal, 7 bytes * 9 steps = score 63, cracked by Dom Hastings

```
⍘⍘$zPγβ

```

Try it online! I had to use the full dictionary for this, because there is only one common word that is one source character away from the program for `golf` and that is `gold`, after which you would get stuck, however the words nearer the `code` end are less uncommon.

# Answer
> 4 votes
# Perl 5 \+ `-M5.10.0`, 43 bytes, 15 changes: score 645: SAFE

17 steps total, 15 excluding `code` and `golf`.

Yeah, I don't think this one's going to be a winner! Might be too easy anyway, as I'm pretty sure there's a shorter route than the one I ended up taking but I couldn't quite get it working!

```
$_=$!=35;/.(.)..(.). (.)(.)/;say$2.$1.$3.$4

```

Try it online!

## Solution

I noticed that I could have saved a byte on my solution too using:

```
$_=$!=35;/.(.)..(.). (.)(.)/;say"$2$1$3$4"; # code

```

but only after posting and didn't think it was fair to adjust, a whole 15 off my score!

```
$_=$!=35;/.(.)..(.). (.)(.)/;say$2.$1.$3.$4; # code
$_=$!=35;/.(.)..(.). (.)(.)/;say$3.$1.$3.$4; # dode
$_=$!=35;/.(.)..(.). (.)(.)/;say$3.$1.$3.$1; # dodo
$_=$!=95;/.(.)..(.). (.)(.)/;say$3.$1.$3.$1; # nana
$_=$!=95;/.(.)..(.). (.)(.)/;say$3.$2.$3.$1; # nona
$_=$!=95;/.(.)..(.). (.)(.)/;say$3.$2.$3.$2; # nono
$_=$!=75;/.(.)..(.). (.)(.)/;say$3.$2.$3.$2; # lolo
$_=$!=75;/.(.)..(.). (.)(.)/;say$3.$4.$3.$2; # lalo
$_=$!=75;/.(.)..(.). (.)(.)/;say$3.$4.$3.$3; # lall
$_=$!=75;/.(.)..(.). (.)(.)/;say$5.$4.$3.$3; # all
$_=$!=75;/ (.)..(.). (.)(.)/;say$5.$4.$3.$3; # off
$_=$!=75;/ (.)..(.). (.)(.)/;say$5.$4.$5.$3; # of
$_=$!=75;/ (.)..(.). (.)(.)/;say$5.$4.$5.$5; # o
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$5.$5; # go
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$4.$5; # goo
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$4.$3; # goof
$_=$!=75;/ (.)..(.). (.)(.)/;say$2.$4.$1.$3; # golf

```

Try it online!

I approached this by first printing out all the 2 digit error messages and looking for words that contained `g`, `o`, `l` and `f`. Once I had some target regexes I checked if any of them would match `code` and then refined to pick a regex that would have spaces in (at least some of) the right places. From there I worked manually (because I found it interesting!) to pick a route, although automation would have probably resulted in a better score.

# Answer
> 3 votes
# Vyxal, 4 bytes, 9 changes, crick craked by Aaroneous Miller

```
«ƛ↔ƒ

```

Try it Online!

This was kinda fun to create. I'll see what happens!

## Programs:

```
«ƛ↔ƒ outputs code
«ƛ↔ṙ outputs coal
«ƛ℅ṙ outputs fear
«ƛ℅ṫ outputs feat
«ƛFṫ outputs dent
«ƛF` outputs dell
«ƛ¾` outputs foci
`ƛ¾` outputs program
`ƛ₅` outputs then
`»₅` outputs golf

```

Try it Online! (last two characters of each line are to print)

Vyxal has two types of string compression. The first, delimited by `«`, takes the bytes within as a base-255 integer then converts that to base 27 and indexes it into a space plus the alphabet.

We switch through a bunch of these until we get to one where the last character is ```, allowing us to change the first character to ``` to get into a dictionary compressed regular string.

Vyxal's dictionary compression is fairly simple - it replaces pairs of non-ASCII characters with words from its dictionary, then remaining non-ASCII characters are replaced with words from a shorter dictionary.

This means that a string containing three characters shouldn't be able to return `golf`. But, I forgot that the short dictionary isn't complete (some slots aren't taken) and those just disappear, which Aaroneous's crack exploited.

Then, we iterate through a few words before getting to the 2-char compression code of `golf`.

# Answer
> 3 votes
# Pari/GP, 26 bytes, 3 changes, cracked by M Virts

Another easy one, using a similar trick.

```
g=c;f=e;l=d;print(g,o,l,f)

```

Try it online!

M Virts found a simple answer with only two changes that I didn't expect. Here is my intended solution:

> `g=c;f=e;l=d;print(g,o,l,f) /* code */`

> `g=c;f=e l=d;print(g,o,l,f) /* cold */`

> `g c;f=e l=d;print(g,o,l,f) /* gold */`

> `g c f=e l=d;print(g,o,l,f) /* golf */`

# Answer
> 1 votes
# !@#$%^&\*()\_+, 13 bytes * 4 steps = score 52, cracked by Dom Hastings

```
3130<202(^+@)

```

Try it online!

# Answer
> 1 votes
# Perl 5, 35 bytes, 5 steps: score 175: SAFE

7 steps total, 5 excluding `code` and `golf`.

```
$_=$!=56;/(.)(o)(.)/;say$1.$2.$3.$'

```

Try it online!

---

When attempting to crack my own previous post, I noticed another way to crack it (using `"$2$1$3$4"` would have prevented this and also saved a byte...). Changing the variable names (as per some of the other posts) is both efficient and relatively straightforward with the right set of words. The regex match against the error is purely a red herring in this instance.

```
$_=$!=56;/(.)(o)(.)/;say$1.$2.$3.$'; # code
$_=$!=56;/(.)(o)(.)/;say$1.$2.$3.$f; # cod
$_=$!=56;/(.)(o)(.)/;say$g.$2.$3.$f; # od
$_=$!=56;/(.)(o)(.)/;say g.$2.$3.$f; # god
$_=$!=56;/(.)(o)(.)/;say g.$2.$l.$f; # go
$_=$!=56;/(.)(o)(.)/;say g.$2. l.$f; # gol
$_=$!=56;/(.)(o)(.)/;say g.$2. l. f; # golf

```

Try it online!

# Answer
> 0 votes
# Python 2, 34 bytes * 2 steps = score 68, cracked by ThisFieldIsRequired

```
golf="code"
goof="cold"
print golf

```

Try it online!

Easier than you think

# Answer
> 0 votes
# Python 3, 55 bytes * 2 steps = 110 score, cracked by Aaron

```
golf="code"
try:exec("print( golf )")
except:print("a")

```

Try it online!

---
Tags: string, code-challenge, kolmogorov-complexity, source-layout, cops-and-robbers
---


title: Make an infinite chain

text:
# Question
Title: Make an infinite chain
Lets define a class of functions. These functions will map from the positive integers to the positive integers and must satisfy the following requirements:

* The function must be Bijective, meaning that every value maps to and is mapped to by exactly one value.
* You must be able to get from any positive integer to any other positive integer by repeated applications of the function or its inverse.

Now, write some code that will perform any one function in this class on its input.

This is a question so answers will be scored in bytes, with less bytes being better.

# Answer
> 10 votes
# Python 3, 24 bytes

```
lambda n:n-(-1)**n*2or 1

```

Try it online!

# Answer
> 7 votes
# Python, 22 bytes

```
lambda n:n+n%2*4-2or 1

```

The even numbers go down to the previous even number, odd numbers go up to the next odd number, and the mapping 2 -\> 1 connects those two.

# Answer
> 5 votes
## JavaScript (ES6), 20 bytes

```
n=>n>1?n%2?n-2:n+2:2

```

Maps `... -> 5 -> 3 -> 1 -> 2 -> 4 -> ...`, which I *think* is valid. Correct me if I'm wrong...

# Answer
> 5 votes
## Haskell, 20 bytes

```
f 1=2
f x=x+2*(-1)^x

```

The example function from the OP's comment in Haskell. Try it online!

# Answer
> 4 votes
# Jelly, 6 bytes

```
-*Ḥạo1

```

Try it online!

### How it works

```
-*Ḥạo1  Main link. Argument: n

-*      Compute (-1)**n, yielding 1 for even n and -1 for odd n.
  Ḥ     Unhalve; multipliy the result by 2.
   ạ    Compute the absolute difference of the result and n.
    o1  If the difference is 0, yield 1.

```

# Answer
> 2 votes
# Python 3, 43 bytes

```
lambda n,a=(1,3,-3,-1):n+a[n%4]if n-2else 1

```

Try it online!

And the inverse, also 43 bytes:

```
lambda n,a=(-3,-1,1,3):n+a[n%4]if n-1else 2

```

Try it online!

TIO links use Dennis's test footer code.

Since everyone is using one way of doing, I decided I'd be different, so I created by own (although I'm probably not the first person to discover it) function. This functions maps like `... 10 -> 7 -> 6 -> 3 -> 2 -> 1 -> 4 -> 5 -> 8 -> 9 -> ...`, I can show you the hand drawing I made to test this if you would like.

My golfed algorithm ~~may be~~ probably is golfable - tips would be appreciated.

Ungolfed versions: Try it online!

# Answer
> 2 votes
# x86 32-bit machine code, 10 bytes

```
48 83 F0 01 74 01 40 34 01 C3

```

Try it online!

Uses the regparm(1) calling convention – argument in EAX, result in EAX.

Assembly:

```
.global f
f:
    dec eax
    xor eax, 1
    jz skip
    inc eax
skip:
    xor al, 1
    ret

```

# Answer
> 1 votes
# 05AB1E, 8 bytes

```
®¹m·αD_+

```

Try it online!

Exactly what Dennis's stuff does.

```
É4*+ÍD_+

```

Try it online!

orlp's stuff.

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

```
r->r%2>0?r<2?2:r-2:r+2

```

Try it online!

I wish Java had a `**` exponentiation operator. Oh well!

# Answer
> 1 votes
# Vyxal `r`, 6 bytes

```
uedε1⟇

```

Try it Online!

@Dennis' answer, ported directly to Vyxal. Requires the `r` flag to reverse the arguments, e.g. `ab+` evaluates to `b+a` instead of `a+b`.

Explanation taken from Dennis:

```
        # Implicit input -> n

ue      # Compute (-1)**n, yielding 1 for even n and -1 for odd n.
  d     # Unhalve; multipliy the result by 2.
   ε    # Compute the absolute difference of the result and n.
    1⟇  # If the difference is 0, yield 1.

        # Implicit output

```

# Answer
> 0 votes
# Mathematica, 21 bytes

```
a@1=2;a@b_:=b+2(-1)^b

```

Move along, nothing to see here...

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


title: Find my other token (Robbers)

text:
# Question
Title: Find my other token (Robbers)
Cops thread

Robbers,

Write a program in the cop's language using the cop's P string and your own S string, and the amount of each of them specified in the cop's post. Your S string may not exceed the cop's S string in bytes.

### The program

Using only strings P and S, write a program which takes a list of 5 or more non-repeating positive integers, and returns them reordered such that the maximum of the list is in the center, the elements before it are in ascending order, and the elements after it are in descending order. You can output any list that meets these requirements. You may assume the list has an odd number of elements.

Examples (your outputs may differ):

```
input: [1,2,3,4,5]
output: [1,2,5,4,3]

input: [7,6,5,4,3,2,1]
output: [2,4,6,7,5,3,1]

input: [1,3,5,7,9,2,4,6,8]
output: [1,2,3,7,9,8,6,5,4]

```

For posterity, please specify your exact S string and its byte count in your answer, and link the cop which you are cracking.

### Scoring

Most cracks wins.

# Answer
# Crack, 39 bytes

```
;_=(x,y)=>x[y.toString(32)]((x,y)=>y-x)

```

Try it online!
> 4 votes

# Answer
# Python 3, 21 + 33(32) bytes

```
def f(i):m=len(i)//2;i.sort();return i[:m]+i[:m-1:-1]

```

Try it online!

Cracking this one. The S string is 32 bytes (1 shorter than expected)

```
i.sort();return i[:m]+i[:m-1:-1]

```
> 3 votes

# Answer
# JavaScript (Node.js), 63 bytes

```
x=>x.sort((a,b)=>a-b).map((e,i)=>i<L?e:x[L*3-i],L=x.length/2|0)

```

Try it online!

Cracks this one.

The S-string is 37 bytes long:

```
(e,i)=>i<L?e:x[L*3-i],L=x.length/2|0)

```

My function just keeps the first half (rounded down), and reverses the rest. For instance, given `[4,5,1,3,2]`, it first sorts `[1,2,3,4,5]` (part of l4m2's cop post), then it keeps the first half rounded down, which is the first 5/2 | 0 = 2 elements. It reverses the rest, giving `[1,2,5,4,3]` which indeed satisfies the question's requirements.

EDIT: @Arnauld has made me aware of a potential byte-saving, which I will not accept (nor will I accept other byte-savings) because I was deliberately aiming for a solution with a length exactly matching the expected one.
> 2 votes

# Answer
# JavaScript, 60 bytes

Crack of the 2nd version of l4m2's challenge.

```
x=>x.sort((a,b)=>a-b).map(e=>x[i+=2]?e:b.pop(),i=0,b=[...x])

```

Try it online!

The secret string is 33 bytes long (shorter than the expected solution of 36 bytes):

```
=>x[i+=2]?e:b.pop(),i=0,b=[...x])

```
> 2 votes

# Answer
# , 10 bytes, cracks Jonah's answer

```
(,|.)/@/:~

```

Try it online!

`/:~` sorts the list and `(,|.)/` reduces the sorted list by *reverse intermediate result*, *prepend new value*.
> 2 votes

# Answer
# Bash, 29 bytes

```
sort -n|sed '2~2p;G;1~2h;$!d'

```

Try it online!
> 2 votes

# Answer
# Pip, 19 bytes, cracks DLosc's answer

```
FiRSNalPBi&R:llR:ll
```

Attempt This Online!

The secret 4-byte 'S' string is `R:ll`. The full code works with either one or (as required here) two copies of 'S'.

The public 'P' string:

```
FiRSNalPBi&
Fi              # For each i in...
  R             # Reversed...
   SN           # Sorted by number...
     a          # 'a' (input);
       PBi      #    Push i to the Back of...
      l         #    'l'...
          &     #    ...and do something secret...

```

The secret 'S' string:

```
           R:ll
                #    ...the secret thing to do each step is:
           R:l  #    Reverse 'l'
              l # And finally output 'l'

```

If we use the 'S' string twice, we simply reverse '`l`' one more time at the end before outputting it.
> 2 votes

# Answer
# Pip, 15 bytes, cracks DLosc's 2nd answer

```
SN:a;R:a&@UWRFa
```

Attempt This Online!

The secret 7-byte 'S' string is `&@UWRFa`.

This was either very sneaky, or I haven't found the *intended* crack.

The task could be accomplished with an 11-byte \[Pip\] program - `SN:a;@UWRFa` \- which numerically sorts (`SN`) the input `a`, reflects it (`RF`; appending to itself), unweaves it (`UW`; splitting into two lists of odd & even indexed elements), and then takes the first list (`@`).
However, the 'P' string appears to reverse the sorted input in-place, which completely messes-up this approach (which would now put the smallest item in the centre instead of the largest).
But wait... there's no semicolon finishing this command... we can append to it...
So we append an `&` (logical AND) followed directly by our `@UWRFa` code: this appears to result in both expressions being evaluated independently, returning the result only of the second (our code).

So the reversing of the input is never actually used, and (I think) was just a decoy...
> 2 votes

# Answer
# Python 3, 42 bytes

```
def f(a):a.sort();return a[1::2]+a[-1::-2]

```

Try it online!

# 41 bytes

```
def f(a):a.sort();return a[::2]+a[-2::-2]

```

Try it online!

Trivial
> 1 votes

---
Tags: cops-and-robbers
---


title: Two interwoven chains

text:
# Question
Title: Two interwoven chains
In this question I defined a "chain" function as a function that:

* is a permutation, meaning that every value maps to and is mapped to by exactly one value.
* and allows any value can be obtained from any other value by repeated applications of the function or its inverse.

There are a lot of functions that do this and some of them are pretty simple (see the answers on that question). Now we are going to define a separate class of functions I am going to call "interwoven" functions. An interwoven function is a function on a set **A**, that has two infinite partitions **a0** and **a1** such that the function is a chain function on both **a0** and **a1**.

This means that no value in **a0** can map to a value in **a1** under the function or vice versa.

# Task

Your task is to write a code that performs or defines an interwoven function on the positive integers. Your function can be anything as long as it satisfies the criteria for being interwoven. You should include a explanation as to why your function is interwoven in the answer.

This is a question so answers will be scored in bytes, with less bytes being better.

# Answer
# Python, ~~46~~ ~~42~~ 37 bytes

*5 bytes saved thanks to @notjagan*

```
lambda x:1<x<4and x*2%5or x-(x&2)*4+4

```

Try it online!

Iterates the even and odd numbers with steps of 4 and links on 2 and 3:

```
=> 22 => 18 => 14 => 10 => 6 => 2 => 4 => 8 => 12 => 16 => 20 => 24 =>
=> 23 => 19 => 15 => 11 => 7 => 3 => 1 => 5 => 9 => 13 => 17 => 21 =>

```
> 2 votes

# Answer
# x86 32-bit machine code, 11 bytes

```
48 34 02 40 40 34 02 48 7E FA C3

```

Try it online!

Uses the regparm(1) calling convention – argument in EAX, result in EAX.

In assembly:

```
f:
    dec eax
    xor al, 2
    inc eax
repeat:
    inc eax
    xor al, 2
    dec eax
    jle repeat  # Jump back if pre-decrement value was ≤1
    ret

```
> 2 votes

# Answer
# JavaScript, ~~30~~ 24 bytes

```
a=>(a+=a&2?-4:4)<0?a*a:a

```

Sequences:

1. `... 19 15 11 7 3 1 5 9 13 17 21 ...`
2. `... 18 14 10 6 2 4 8 12 16 20 24 ...`

**Code snippet**

```
f=a=>(a+=a&2?-4:4)<0?a*a:a
console.log('23 19 15 11 7 3 1 5 9 13 17'.split` `.map(a=>f(a|0)).join` `);
console.log('22 18 14 10 6 2 4 8 12 16 20'.split` `.map(a=>f(a|0)).join` `);
```
> 1 votes

# Answer
# Dyalog APL, ~~24~~ 22 bytes

```
{x*1+0>x←4+⍵-8×2|⌊⍵÷2}

```

Try it online!

Same chains as my python answer.
> 0 votes

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


title: One pair or fewer

text:
# Question
Title: One pair or fewer
Given a list of positive integers, give the longest contiguous sublist which contains at most 1 pair of identical items. In the case of a tie return any of the solutions.

This is so the goal is to minimize your source code with answers being scored in bytes.

## Test cases

```
[] -> []
[1,2,3] -> [1,2,3]
[1,2,2,3] -> [1,2,2,3]
[2,2,3,2,4] -> [2,3,2,4]
[1,2,1,3,2] -> [2,1,3,2]
[1,2,3,1,4,1,2,3,4,5,1] -> [1,2,3,4,5,1]
[1,2,3,2] -> [1,2,3,2]

```

# Answer
> 8 votes
# Jelly, 10 bytes

```
Ẇœ-QḊƊÐḟṪȯ

```

**Try it online!**

### How?

```
Ẇœ-QḊƊÐḟṪȯ - Link: list, A
Ẇ          - substrings (well, non-empty ones) sorted by length then left to right
      Ðḟ   - filter discard those for which this is truthy:
     Ɗ     -   last three links as a monad:
   Q       -     distinct values
 œ-        -     multiset difference - remove one of each value from A
    Ḋ      -     dequeue - remove one from this list if there are any
                         - [] is falsey
        Ṫ  - tail - one of, or the, longest one
                  - unless A was [] in which case zero
         ȯ - logical OR with A - replace that zero with []

```

---

Alternatively, `Ẇœ-QLỊƲƇṪȯ`.

# Answer
> 6 votes
# Brachylog, ~~14~~ ~~12~~ 10 bytes

*-2 bytes thanks to xash*

```
⊇.ọtᵐ×≤2&s

```

Try it online!

### Explanation

We're looking for a sublist in which each element occurs only once, except that one element may occur twice.

Makes use of this very helpful tip from Unrelated String.

```
⊇.ọtᵐ×≤2&s
            The input
⊇           Sublist (not necessarily contiguous), trying longest first
 .          The result is the output
  ọ         Generate a list of [element, count] pairs
   tᵐ       Get the last element of each pair (list of counts)
     ×      Product
      ≤2    Is less than or equal to 2
        &s  Also, the output is a contiguous sublist of the input

```

# Answer
> 6 votes
# JavaScript (Node.js), 64 bytes

```
f=(a,...r)=>a[new Set(a).size+1]?f(...r,a.slice(1),a.pop()&&a):a

```

Try it online!

---

# Python 3, 58 bytes

```
f=lambda l,*r:len(l)>1+len({*l})and f(*r,l[1:],l[:-1])or l

```

Try it online!

Yet another question solved with same pattern?

# Answer
> 4 votes
# Jelly, 11 bytes

```
ẆµĠẈ’SỊµƇṪȯ

```

Try It Online!

-1 byte thanks to Jonathan Allan

```
ẆµĠẈ’SỊµƇṪȯ   Main Link
Ẇ             all sublists
 µ     µƇ     filter
  Ġ           - group indices of equal elements
   Ẉ          - length of each group
    ’         - subtract one from each length
     S        - sum of these (total number of duplicate elements)
      Ị       - is this insigificant? (between -1 and 1)
         Ṫ    take the last (longest) element
          ȯ   logical OR; if the output is 0 (only happens if input
              is []), return the input instead, which fixes [] being
              output as 0

```

# Answer
> 3 votes
# Japt `-h`, 14 bytes

Feel like I'm missing a trick here :\

```
ã fÈÊÉ¶Xâ ÊÃiU

```

Try it

# Answer
> 3 votes
# Python 3, 68 bytes

```
f=lambda l:len(l)>1+len({*l})and max(f(l[1:]),f(l[:-1]),key=len)or l

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~108~~ 83 bytes

```
f l@(u:q)|0:(0<$l)<[0|x<-l,y<-q,x==y]=f(init$l)!f q
f q=q
a!b|(a<$a)>(a<$b)=a|1>0=b

```

Try it online!

* Thanks to @Wheat Wizard for saving so many many bytes!

`g` : counts duplicates. -\> moved to list comprehension in *f* by Wheat Wizard , the tricky part is here and deserves an explanation

```
f(u:q)|
(0<$q)       list 0s for each element
<            compared to
[0|x<-q,y<-q,x==y] list of 0s for each equal pairs in the powerset

```

Note that we use tail so that one potential dupe is already counted and the lists must be the same, if not there is more than 1 dupe, in that case we search.. Else we skip this and f q=q match giving the result.

a`!`b : selects longer list.
`f`*list* : if *list* is not ok choose from head or tail else return it

# Answer
> 2 votes
# Retina 0.8.2, 78 bytes

```
M!&r`.*\d\b
.*\b(\d+)(?=.*,\1\b),(.*\b(\d+)\b.*,\3\b)
$2
O$^`((,)|\d)+
$#2
1G`

```

Try it online! Link includes test cases. Explanation:

```
M!&r`.*\d\b

```

Take all of the suffixes.

```
.*\b(\d+)(?=.*,\1\b),(.*\b(\d+)\b.*,\3\b)
$2

```

Truncate them at the second last duplicate. (Since we need this longish regex to check for two pairs/three of a kind, it turns out to be golfier to truncate the prefixes than to filter on all sublists.)

```
O$^`((,)|\d)+
$#2

```

Sort by descending number of elements.

```
1G`

```

Take the first.

# Answer
> 2 votes
# Charcoal, ~~40~~ 38 bytes

```
≔⟦⟧ηＦθ«⊞υιＷ‹¹ΣＥυ›μ⌕υλ≔Φυμυ¿›ＬυＬη≔Ｉυη»η

```

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

```
≔⟦⟧η

```

Start with no longest sublist.

```
Ｆθ«

```

Loop over the input terms.

```
⊞υι

```

Append the term to the predefined empty list.

```
Ｗ‹¹ΣＥυ›μ⌕υλ

```

While the current sublist contains more than one duplicate...

```
≔Φυμυ

```

... remove the first term from the sublist.

```
¿›ＬυＬη

```

If the sublist is longer than the longest sublist so far, then...

```
≔Ｉυη

```

... save a copy of the sublist (because we're going to push to the original, and we need to cast it to string anyway).

```
»η

```

Output the longest sublist (which we already cast to string above).

# Answer
> 2 votes
# Ruby, 63 bytes

```
f=->l,s=1{l[-s]&&f[l,s+1]||l.each_cons(s).find{|q|q.uniq[s-2]}}

```

Try it online!

# Answer
> 2 votes
# Burlesque, 28 bytes

```
su<-{f:)-]g_2<=j{1==}al&&}fe

```

Try it online!

```
su           # All substrings from shortest to longest
<-           # Reverse (longest first)
{
 f:          # Frequency list as (count, val) sorted by count
 )-]         # Map head (get counts)
 g_          # Split into head + tail
 2<=         # Head is 2 or 1
 j           # Swap
 {1==}al     # Tails all 1s
 &&          # Logical AND
}fe          # Find the first element for which

```

# Answer
> 2 votes
# , 162 bytes

Or **\>=4.1, 148 bytes** by replacing two `function` occurrences with `\`s.

```
function(v,a=apply(combn(rep(seq(v),2),2),2,function(x,t=table(k<-v[x[1]:x[2]]))if(x[1]<=x[2]&all(t%in%1:2)&sum(t==2)<2)k))"if"(sum(v),a[order(-lengths(a))[1]],v)

```

Try it online!

I was hoping for some ingenious answer from better  golfers here, but it looks like I have to post my boring straightforward one first for some motivation.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 47 bytes

```
f[s=___,Longest@a:s,s]/;Total[Counts@{a}-1]<2=a

```

Try it online!

Input and output a `Sequence` of values.

---

### Wolfram Language (Mathematica), 48 bytes

```
Last@*Select[Total[Counts@#-1]<2&]@*Subsequences

```

Try it online!

Input and output a list.

# Answer
> 2 votes
# Factor \+ `math.unicode`, 77 bytes

```
[ f suffix all-subseqs [ histogram values 1 v-n Σ 2 < ] find-last nip sift ]

```

Try it online!

## Explanation

* `f suffix ... sift` Work around the fact that `all-subseqs` blows up on an empty input. Add `f` to the input and remove it with `sift` at the end. (This doesn't change anything since we're only adding one.)
* `all-subseqs [ ... ] find-last nip` Find the last/largest subsequence of the input that returns true when the given quotation is called on it.

The quotation to `find-last` works by taking a histogram of the input, subtracting 1 from all the counts, taking the sum, and checking whether the sum is less than two. For instance:

```
             ! { 2 2 3 2 4 }
histogram    ! H{ { 2 3 } { 3 1 } { 4 1 } }
values       ! { 3 1 1 }
1 v-n        ! { 2 0 0 }
Σ            ! 2
2 <          ! f

```

# Answer
> 2 votes
# Husk, ~~10~~ 9 bytes

*Edit: -1 byte thanks to Razetime*

```
►LfoεṠ-uQ

```

Try it online!

```
►           # output the (first) element with maximum...
 L          # ...length...
            # ...from among:
         Q  # all contiguous sublists,
  fo        # filtered by:
      Ṡ-    # the difference between...
        u   # ...itself and unique elements of itself...
    ε       # ...has length 1.

```

# Answer
> 2 votes
# Haskell, 80 bytes

```
import Data.List
l=length
head.sortOn(\x->(l(x\\nub x)>1,-l x)).(tails=<<).inits

```

Try it online!

Get all infixes, sort by `(invalid, -length)`, return the first one.

# Answer
> 1 votes
# JavaScript (Node.js), ~~79~~ 75 bytes

```
f=(X,a)=>X[h=new Set([w,...x]=X).size+1]?(a=f(x),b=f(X,X.pop()),a[h]?a:b):X

```

Try it online!

AnttiP's idea, can't read golfing language so don't know if that's source

# JavaScript (Node.js), 89 bytes

```
f=(x,h,L=0,a=x.filter(y=x=>!(y[x]=h+=[y[x]])[20]&&++L),b=x[0]?f(x.slice(1)):[])=>b[L]?b:a

```

Try it online!

Is it usual to be 6-8x longer than golfing language or this is quite golfable?

# Answer
> 1 votes
# 05AB1E, 11 bytes

```
ŒʒgyÙg-!}éθ

```

Try it online or verify all test cases.

**Explanation:**

```
Œ        # Get all sublists of the (implicit) input-list
 ʒ       # Filter this list of sublists by:
  g      #  Get the length of the sublist
   y     #  Push the sublist again
    Ù    #  Uniquify its items
     g   #  Pop and push the length of this uniquified list as well
      -  #  Subtract the lengths from one another
       ! #  Check if this is either 0 or 1 by taking the faculty, which will
         #  result in [1,1,2,6,24,120,...] for [0,1,2,3,4,5,...] respectively,
         #  and only 1 is truthy in 05AB1E
 }é      # After the filter: sort the remaining sublists from shortest to longest
   θ     # Pop and keep just the last (longest)
         # (after which it is output implicitly as result)

```

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


title: Is there a stable way to stack these?

text:
# Question
Title: Is there a stable way to stack these?
If we have a binary matrix then we will say that a \\$1\\$ is stable if it is in the bottom row or it is directly adjacent to a \\$1\\$ which is stable.

In other words there must be a path to the bottom row consisting only of \\$1\\$s.

So in the following matrix the \\$1\\$s highlighted in red are not stable.

$$ 0110\color{red}{1}0\\ 0100\color{red}{11}\\ 110000\\ $$

A matrix is stable if every \\$1\\$ in it is stable.

Your task is to take a matrix or list of rows and determine if there is someway to rearrange the rows into a stable matrix.

The example above can be if we swap the top and bottom row:

$$ 110000\\ 011010\\ 010011\\ $$

But the following matrix cannot:

$$ 01010\\ 10101\\ 00000 $$

You may take input in any reasonable format. You may also assume that there is at least one row and that all rows are at least 1 element long. You should output one of two distinct values if it is possible to rearrange the rows into a stable matrix and the other if it is not.

This is so the goal is to minimize your source code with answers being scored in bytes.

## Test cases

```
000
000
000
-> True
1
-> True
011010
010011
110000
-> True
01010
10101
00000
-> False
01010
10101
01110
-> True
01010
01100
00011
10101
-> False
10
01
-> False

```

# Answer
> 3 votes
# MATL, ~~27~~ ~~26~~ 24 bytes

```
Zy:Y@!"2G@Y)tQ&v4&1ZImvA

```

Input is a binary matrix. Output is `0` if stable, `1` otherwise.

Try it at MATL online! Or verify all test cases.

### Explanation

```
Zy         % Input (implicit): binary matrixz. Size. Gives [r, c], where r and c
           % are the numbers of rows and of columns
:          % Range. Gives [1, 2, ... r] (c is ignored)
Y@         % All permutations of numbers 1, 2, ..., r. Gives an r-column matrix
           % where each row is a permutation
!"         % For each row
  2        %   Push 2
  G        %   Push input
  @Y)      %   Apply current permutation to the rows of the input
  tQ       %   Duplicate, add 1. Gives a matrix the same size as the input with
           %   all entries different from 0
  &v       %   Concatenate the two matrices vertically. This has the effect of
           %   adding a "bottom" of nonzeros to the permutation of the input
  4&1ZI    %   Connected components, using 4-neighbourhood (i.e. not diagonals)
           %   Each connected component of nonzeros is labelled 1, 2, ...
  m        %   Ismember: gives true if there is a connected component labelled
           %   with 2. This can only happen if some 1 in the input is not
           %   connected to the bottom, meaning that the current permutation
           %   is not stable
  vA       %   Concatenate vertically. All. This acts as a cumulative "and".
           %   The result is 1 if and only if all permutations so far were
           %   not stable
           % End (implicit). Display (implicit)

```

# Answer
> 3 votes
# , 60 bytes

```
1 e.i.@!@#(1*/@,@([:+./ .*^:_~1>:[:|@-/~$j./@#:I.@,)@,])@A.]

```

Try it online!

Feels like there's a trick I'm missing, but this takes a brute force approach as follows:

* For each permutation of rows...
* Prepend of row of all ones...
* Check if the "distance of 1" graph of the 1 positions is fully connected.
* If it is, we've found a solution.

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

```
lambda l:any(f(0,len(l[0]),*sum(p,[]))for p in permutations(l))
f=lambda p,a,x,*t:a>len(t)or-(p:=p+t[a-1])-len(t)%a*t[0]+x<f(x*p,a,*t)>0
from itertools import*

```

Try it online!

Takes input as a 2d list. `f` is a function that checks if a matrix is stable. Then we just try every permutation, until we find a matrix that works.

# Answer
> 1 votes
# Python3, 265 bytes:

```
lambda b:any(v(i)for i in permutations(b))
from itertools import*
E=enumerate
def p(b,c,d):
 if c==len(b)-1:return 1
 try:
  for x,y in[(0,1),(0,-1),(1,0)]:
   if(y:=d+y)*b[c+x][y]:return 1
 except:return 0
v=lambda b:all(p(b,x,y)for x,l in E(b)for y,s in E(l)if s)

```

Try it online!

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

```
f=(a,...b)=>a[0]?a.some(h=>f(a.filter(_=>_!=h),h,...b)):b[b=b.map(x=>[...x]),0].map(g=(y,x)=>(e=b[~y]||0)[x]&&++e[a=2,x]+[-1,1].map(i=>g(y+i,x)+g(y,x+i)))|!/1/.test(b)

```

Try it online!

Input `-1` for true and `0` for false

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

```
f=(a,p=1)=>a.some((r,j)=>r.every((c,i)=>c?(s|=p[i],l=1):!(l=s=l>s),l=s=0)&l<=s|p&&f(b=[...a],b.splice(j,1)[0]))||++a

```

Try it online!

Input 0/1 matrix. Output true vs NaN.

# Answer
> 1 votes
# 05AB1E, 53 bytes

```
œʒ¬!ªÐU˜!ƶsgäΔ0δ.ø¬0*šĆ2Fø€ü3}εεÅsyøÅs«à}}X*}˜0KÙg}gĀ

```

Try it online or verify all test cases.

**Explanation:**

In pseudo-code, I do the following steps (with the code-parts behind it - as you can see, the flood-fill takes up most of the bytes):

1. Get all permutations of rows of the input-matrix (`œ`)
2. Check if any permutation is truthy for the following steps (`ʒ...}gĀ`):
    1. Append a row of 1s to the matrix as new bottom (`¬!ª`)

    1. E.g. the permutation we want to check is:

        ```
         0,1,1,0,1,0
         0,1,0,0,1,1
         1,1,0,0,0,0

        ```
        2. Then it will become this with bottom row of 1s:

        ```
         0,1,1,0,1,0
         0,1,0,0,1,1
         1,1,0,0,0,0
         1,1,1,1,1,1

        ```
    2. Flood-fill the matrix, using only horizontal/vertical moves - done in a similar matter as @Jonah's J answer for the *To find islands of 1 and 0 in matrix* challenge (`ÐU˜!ƶsgäΔ0δ.ø¬0*šĆ2Fø€ü3}εεÅsyøÅs«à}}X*}`):

    1. We first create a matrix of the same size with unique positive integers:

        ```
          1, 2, 3, 4, 5, 6
          7, 8, 9,10,11,12
         13,14,15,16,17,18
         19,20,21,22,23,24

        ```
        2. Then for each cell we get the maximum among itself and its horizontal/vertical neighbors:

        ```
          7, 8, 9,10,11,12
         13,14,15,16,17,18
         19,20,21,22,23,24
         20,21,22,23,24,24

        ```
        3. Which we multiply by the matrix of 0s/1s we started with (the one from step 2.1.2):

        ```
          0, 8, 9, 0,11, 0
          0,14, 0, 0,17,18
         14,15, 0, 0, 0, 0
         20,21,22,23,24,24

        ```
        4. And we continue steps 2.2.2 and 2.2.3 until the result no longer changes:

        ```
          0,24,24, 0,18, 0
          0,24, 0, 0,18,18
         24,24, 0, 0, 0, 0
         24,24,24,24,24,24

        ```
    3. Check if there is just a single island after the flood-fill (`˜0KÙg`)

As for the actual code:

```
œ             # Get all permutations of rows of the (implicit) input-matrix
 ʒ            # Filter this list of matrices by:
  ¬!ª         #  Append a row of 1s:
  ¬           #   Push the first row (without popping the matrix)
   !          #   Convert all 0s/1s to 1s with the faculty
    ª         #   Append this row of 1s to the matrix
  Ð           #  Triplicate the matrix
   U          #  Pop and store a copy in variable `X`
   ˜!ƶsgä     #  Pop and push a matrix of the same size with values [1,length]
   ˜          #   Flatten the matrix
    !         #   Convert everything to 1s with the faculty
     ƶ        #   Multiply every 1 by its 1-based index
      s       #   Swap so the last copy is at the top
       g      #   Pop and push its amount of rows
        ä     #   Pop and split the list into that many equal-sized parts
   Δ          #  Loop until the result no longer changes
              #  (which will be used to flood-fill the matrix):
    0δ.ø¬0*šĆ #   Surround the matrix with a border of 0s:
     δ        #    Map over each row:
    0 .ø      #     Surround it with a leading/trailing 0
        ¬     #    Push the first row (without popping)
         0*   #    Convert all 0s/1s to 0s by multiplying by 0
           š  #    Prepend this row of 0s to the matrix
            Ć #    Enclose; append its own head
    2Fø€ü3}   #   Get all 3x3 blocks of this matrix:
    2F        #    Loop 2 times:
      ø       #     Zip/transpose; swapping rows/columns
       €      #     Map over each row:
        ü3    #      Get all overlapping triplets of this row
          }   #    Close the loop
              #   Looking at horizontal/vertical neighbors only, get the maximum
              #   of each 3x3 block:
    εε        #    Nested map over each 3x3 block:
      Ås      #     Push its middle row
      yøÅs    #     Push its middle column
          «   #     Merge the two triplets together
           à  #     Pop and push the maximum
    }}        #    Close the nested maps
    X*        #   Then multiply each maximum by matrix `X`,
              #   so all cells that contained 0s become 0 again
   }          #  Close the flood-fill loop
    ˜         #  Flatten the matrix to a list
     0K       #  Remove all 0s
       Ù      #  Uniquify the remaining values
        g     #  Pop and push the length (only 1 is truthy in 05AB1E)
}gĀ           # After the filter: check if any permutations remain (length>=1)
              # (which is output implicitly as result)

```

There are a bunch of 5-bytes alternatives for `˜0KÙg`, but I haven't been able to find a 4-byter.

# Answer
> 0 votes
# Charcoal, ~~129~~ 112 bytes

```
ＷＳ⊞υ⌕Ａι1≔⟦⟦⟧⟧θＦυ«≔⟦⟧ηＦθＦ⊕Ｌκ⊞η⁺⁺✂κ⁰λ¹⟦ι⟧✂κλＬκ≔ηθ»Ｆθ«≔⟦⟧ηＦＬιＦ§ικ⊞η⟦κλ⟧≔Ｅ⊟ι⟦Ｌικ⟧ιＷΦ⁻ηιΦ⁴№ιＥλ⁺π∧⁼ρ﹪ν²⊖⁻νρＦκ⊞ιλＰ↔¬⁻ηι

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings of `0`s and `1`s and outputs a Charcoal boolean i.e. `-` if a stable stack exists, nothing if not. Explanation:

```
ＷＳ⊞υ⌕Ａι1

```

Input the matrix and save the positions of the `1`s in each row.

```
≔⟦⟦⟧⟧θ

```

Start building up the permutations of the rows.

```
Ｆυ«

```

Loop through the rows.

```
≔⟦⟧η

```

Start building up the permutations that include this row.

```
Ｆθ

```

Loop through the permutations of the previous rows.

```
Ｆ⊕Ｌκ

```

Loop through the possible insertion points.

```
⊞η⁺⁺✂κ⁰λ¹⟦ι⟧✂κλＬκ

```

Insert this row at that point and save it to the list of permutations.

```
≔ηθ

```

Save the list of permutations.

```
»Ｆθ«

```

Loop through all of the permutations.

```
≔⟦⟧ηＦＬιＦ§ικ⊞η⟦κλ⟧

```

List the coordinates of all the `1`s.

```
≔Ｅ⊟ι⟦Ｌικ⟧ι

```

List the coordinates of the `1`s on the bottom row, which are stable by definition.

```
ＷΦ⁻ηιΦ⁴№ιＥλ⁺π∧⁼ρ﹪ν²⊖⁻νρ

```

While there are unknown coordinates adjacent to at least one stable coordinate, ...

```
Ｆκ⊞ιλ

```

... save all the newly discovered stable coordinates.

```
Ｐ↔¬⁻ηι

```

Overwrite the output with `-` if all the coordinates were stable.

---
Tags: code-golf, array, decision-problem
---