title: The Most Wanted Prime Numbers

text:
# Question
Title: The Most Wanted Prime Numbers
Output a sequence of all the primes that are of the following form: `123...91011...(n-1)n(n-1)..11109...321`. That is, ascending decimal numbers up to some `n`, followed by a descending tail, all concatenated.

## Background

Recently, Numberphile posted a video about primes that follow this pattern.

## Output

```
1 -> 12345678910987654321 (n=10)
2 -> 123...244524462445...321 (n=2446)

```

No more terms are known, but it's likely that there are infinitely many.

# Answer
> 12 votes
# 05AB1E, 7 bytes

```
∞η€ûJʒp

```

Try it online! Times out on TIO without printing a single number because the primality test is too slow. Takes 77 seconds locally for the first number and will never† get to the second number.

```
∞η       Prefixes of [1, 2, 3, ...]
  €û     Palindromize each prefix
    J    Join each into a number
     ʒp  Filter: keep primes

```

Local output:

```
05AB1E git:master ❯ ./osabie programs/mwp.abe
["12345678910987654321"

```

† in the lifetime of the universe, the test is \\$\mathcal{O(\sqrt{n} \log{}n})\\$.

# Answer
> 7 votes
# Jelly, 8 bytes

```
ŒḄV©ẒƊ#®

```

Try it online!

By default sequence I/O rules, this inputs a value `k` and outputs the prime corresponding to `k`.

This is a monadic link `f(k)` that returns the prime. It also outputs the `n` value for that prime as a side effect - this should be considered a function that returns the prime. I've included a 9 byte version that doesn't output anything extra below.

```
ŒḄV©ẒƊ#ṛ®

```

Try it online!

---

Both can handle \\$k = 1\\$ on TIO, can't handle \\$k = 2\\$ or above.

## How they work

```
ŒḄV©ẒƊ#® - Main link. Takes k on the left
     Ɗ#  - Find the first n such that the following is true:
ŒḄ       -   Bounced range of n; [1, 2, ..., n, ..., 2, 1]
  V      -   Evaluated as an integer: 12...n...21
   ©     -   Save this in the register
    Ẓ    -   Is this prime?
       ® - Print n and return the register

```

The second uses `ṛ®` instead of `®`. The  causes the program to discard the value of `n` rather than printing it, and then `®` returns the register.

# Answer
> 0 votes
# Python 3, 213 bytes

```
def A(n):return int(''.join(str(d)for d in range(1,n+1))+''.join(str(d)for d in range(n-1,0,-1)))
i=5
w=0
y=int(input())
while 1:
	p=n=1;exec("p*=n*n;n+=1;"*~-A(i))
	if p%n==1:w+=1
	if w==y:print(A(i));break
	i+=1

```

Try it online!

Probably should be correct. If you find bugs then comment the answer.

Upvote Lynn solution of prime checking!

# Answer
> 0 votes
Here I used the Miller-Rabin Primality Test to approximate if the number is in fact prime.

```
import math
import random

def miller_rabin(n, k):

    # Implementation uses the Miller-Rabin Primality Test
    # The optimal number of rounds for this test is 40
    # See http://stackoverflow.com/questions/6325576/how-many-iterations-of-rabin-miller-should-i-use-for-cryptographic-safe-primes
    # for justification

    # If number is even, it's a composite number

    if n == 2 or n == 3:
        return True

    if n % 2 == 0:
        return False

    r, s = 0, n - 1
    while s % 2 == 0:
        r += 1
        s //= 2
    for _ in range(k):
        a = random.randrange(2, n - 1)
        x = pow(a, s, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(r - 1):
            print(_)
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True

def constructNumber(n):
    numberArray = []
    for i in range(n):
        numberArray.append(str(i+1))
    for i in range(n-1):
        numberArray.append(str((n-1)-i))
    return int(''.join(numberArray))

if __name__ == "__main__":
    print(miller_rabin((constructNumber(10)),40))

```

Miller-Rabin Python Source

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


# Question
Title: AoCG2021 Day 21: Blinking through the forest
Part of **Advent of Code Golf 2021** event. See the linked meta post for details.

Related to AoC2020 Day 3.

---

On the way to vacation, you're traveling through a forest on an airplane. For some biological and geological reasons, the trees in this forest grow only at the exact integer coordinates on a grid, and the entire forest repeats itself infinitely to the right. For example, if the map (input) looks like this (`#` for trees and `.` for empty spaces):

```
..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#

```

the forest actually looks like this:

```
..##.........##.........##.........##.........##.........##.......  --->
#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..
.#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.
..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.
..#.##.......#.##.......#.##.......#.##.......#.##.......#.##.....  --->
.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........#.#........#.#........#.#........#.#........#
#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...
#...##....##...##....##...##....##...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#  --->

```

Starting at the top-left corner of this forest and moving at a rational slope (e.g. `3/2` represents two units to the right and 3 units down), how many trees will you encounter until you escape the forest through the bottom row? (You encounter a tree if your path goes through the exact integer coordinates of that tree.)

**Input:** A rectangular grid representing the map, and a rational number (non-zero, non-infinity) representing the slope of your movement. You can use any two distinct values (numbers/chars) to represent trees and empty spaces respectively. You can take two positive integers for the slope instead of a rational number, and the two numbers are guaranteed to be coprime.

**Output:** The number of trees you will encounter during the flight.

Standard rules apply. The shortest code in bytes wins.

## Test cases

```
Grid:
.##
#.#
##.
down/right -> trees
1/1 -> 0
99/1 -> 0
2/1 -> 1
2/3 -> 1
1/2 -> 2
1/3 -> 2
1/99 -> 2

Grid:
##.#
.###
##..
..##
down/right -> trees
1/1 -> 3
1/2 -> 4
1/3 -> 2
2/3 -> 1
3/4 -> 1

Grid: (the one shown at the top)
down/right -> trees
1/1 -> 2
1/3 -> 7
1/5 -> 3
1/7 -> 4
2/1 -> 2

```

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

```
(a,x,y)=>a.map((r,i)=>t+=r[i*x/y%r.length]|0,t=0)|t

```

Try it online!

Input an 2d 0/1 array where 1 means tree, and step x, y.

Use the fact that you can index an array with non-integer value without causing errors in JavaScript. You will get non-harmful `undefined` which may be convert to `0` safely by any bitwise operator. And as you are keeping moving south, you may only encounter at most 1 tree each row. So we just sum all tree encountered each row. And that's all we need to make it working.
> 7 votes

# Answer
# Whython, <sup>~~59~~</sup> 57 bytes

```
f=lambda F,a,b,x=0:F[a-1][x%len(F[0])]+f(F[a:],a,b,x+b)?0
```

Attempt This Online!

Inputs a 2D array of booleans, and 2 integers.

## Normal Python, 69 bytes

```
f=lambda F,a,b,x=0:F[a-1:]>[]and F[a-1][x%len(F[0])]+f(F[a:],a,b,x+b)
```

Attempt This Online!
> 4 votes

# Answer
# Haskell, 60 bytes

```
f g a b=sum[cycle(g!!(a*t))!!(b*t)|t<-[0..div(length g-1)a]]

```

Try it Online!

Takes input as a list of lists, followed by the down and right numbers. Trees are represented as 1s, blanks spaces are represented by 0s.
> 3 votes

# Answer
# Jelly,  ~~11~~  10 bytes

-1 thanks to Dominic van Essen (Avoid multi-link chaining by getting the m-slice result again when needed.)

```
mJ’×⁵‘ị"mS

```

A full program accepting a list of lists of `1`s (trees) and `0`s (clearings), the Down amount, and the Right amount that prints the result.

**Try it online!**

### How?

```
mJ’×⁵‘ị"mS - Main Link: Map, Down (Right is the third program argument)
m          - modular slice Map's rows using Down
              -> list of the rows on which we could hit trees
 J         - range of length -> [1, 2, 3, ..., length of slice result]
  ’        - decrement -> [0, 1, 2, ..., n-1]
    ⁵      - program's third argument, Right
   ×       - multiply -> [0, Right, 2×Right, ..., (n-1)×Right]
     ‘     - increment -> [1, Right+1, 2×Right+1, ..., (n-1)×Right+1
        m  - modular slice Map's rows using Down
       "   - zip with (f(value, row) for row in m-slice result):
      ị    -   index into that row
         S - sum

```
> 3 votes

# Answer
# JavaScript (ES6), 57 bytes

Expects `(grid, dy, dx)`, where `grid` is a binary matrix.

```
(G,v,h)=>(g=y=>(r=G[y])?r[x%r.length]+g(y+v,x+=h):0)(x=0)

```

Try it online!
> 2 votes

# Answer
# Pip, 29 bytes

```
g@>:2Wy<#g{i+:g@y@xy+:ax+:b}i

```

Full program; takes dy, dx, and each row of the grid as arguments. The grid should use `0` for no tree and `1` for tree. Try it online!

### Explanation

```
g@>:2Wy<#g{i+:g@y@xy+:ax+:b}i
                               For our purposes, y, x, & i can be considered to start at 0
g                              List of arguments
 @>:2                          Remove the first two
                               g is now just the grid
     Wy<#g{                }   While y coordinate is less than number of rows in g:
              g@y@x             Get the value (1 or 0) at coordinates (x,y) in g
                                (using cyclical indexing)
           i+:                  Add it to running total i
                   y+:a         Increment y by first program argument
                       x+:b     Increment x by second program argument
                            i  After the loop, autoprint the number of trees encountered

```
> 2 votes

# Answer
# Python, 57, 54 bytes (@GB)

```
lambda a,y,x,i=0:sum((r*(i:=i+x))[i-x]for r in a[::y])
```

Attempt This Online!

#### Old version

```
lambda a,y,x,i=0:sum(r[(i:=i%len(r)+x)-x]for r in a[::y])
```

Attempt This Online!

Expects a list of lists of 0s and 1s plus two integers.
> 2 votes

# Answer
# Pari/GP, 45 bytes

```
(a,b,c)->sum(i=0,(#a-1)/b,a[b*i+1,c*i%#a~+1])

```

Try it online!
> 2 votes

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

```
ιнε³N*è}O

```

-6 bytes, by using the exact same program as *@ovs*' used in the related challenge.. :/ (thanks for letting me know *@DominicVanEssen*)

Takes the inputs in the order \\$right\\$, \\$grid\\$, \\$down\\$, where \\$grid\\$ is a matrix of `0` for empty spots and `1` for trees.

Try it online or verify all test cases.

**Explanation:**

```
ι          # Uninterleave the second (implicit) input-matrix with the first (implicit)
           # input right-slope as step-size
 н         # Only leave the first inner matrix
  ε        # Map over each row:
   ³       #  Take the third input down-slope
    N*     #  Multiply it by the 0-based map-index
      è    #  Use it to 0-based modular index into the row
  }        # After the map:
   O       # Sum the list together to get the amount of trees encountered
           # (which is output implicitly as result)

```
> 2 votes

# Answer
# Ruby, ~~56 ...~~ 51 bytes

```
->v,y,x{z=0;v.each_slice(y).sum{|l,|(l*z+=x)[z-x]}}

```

Try it online!
> 2 votes

# Answer
# Rust, 80 bytes

```
|i:&[Vec<_>],a,b|i.iter().step_by(b).fold((0,0),|(x,t),v|(x+a,t+v[x%v.len()])).1

```

Try it online!

Takes input as a slice of vectors of ones and zeroes.
> 2 votes

# Answer
# TypeScript Types, 298 bytes

```
//@ts-ignore
type a<T,N=[]>=T extends N["length"]?N:a<T,[...N,{}]>;type b<T,N>=N extends[{},...infer M]?T extends[infer A,...infer U]?b<[...U,A],M>:0:T;type M<G,Y,X,N=[],>=G extends[]?N["length"]:M<{[K in keyof G]:b<G[K],a<X>>}extends[...a<Y>,...infer Rest]?Rest:[],Y,X,G[0][0]extends 1?[...N,0]:N>

```

Try It Online!

## Ungolfed / Explanation

```
// Convert a number literal to a tuple of {} of equal length
type NumToTopTuple<T,N=[]> = T extends N["length"] ? N : NumToTopTuple<T,[...N,{}]>

// Cycles a non-empty tuple T to the left N times
type CycleLeft<T, N> = N extends [{}, ...infer M] ? T extends [infer A, ...infer U] ? CycleLeft<[...U,A],M> : 0 : T

type Main<
  Grid,
  Y,
  X,
  Trees=[],
> =
  Grid extends []
    // If there are no more rows left, return Trees
    ? Trees["length"]
    // Otherwise, recurse:
    : Main<
      // Map over Grid and cycle its rows X times to the left. Then, remove the first Y rows
      {
        [K in keyof Grid]: CycleLeft<Grid[K], NumToTopTuple<X>>
      } extends [...NumToTopTuple<Y>, ...infer Rest] ? Rest : [],
      Y,
      X,
      // If there's a tree at (0,0), increment Trees
      Grid[0][0] extends 1 ? [...Trees, 0] : Trees
    >

```
> 1 votes

# Answer
# , 68 bytes

```
function(g,d,r,n=1:(nrow(g)/d)-1)sum(g[1+cbind(n*d,(n*r)%%ncol(g))])

```

Try it online!

**Ungolfed**

```
ntrees=function(g,d,r)  # ntrees = function with arguments
                        # g = grid, d = down, r = right
 n=1:(nrow(g)/d)-1      # first calculate n = 0 ... number of moves we'll make
                        # (number of moves is rounded-down to an integer)
 sum(                   # now calculate the sum of all trees
  g[                    # at positions of g given by
   1+                   # 1+ = R uses 1-based indexing
    cbind(              # cbind = combind 2 vectors, to use as 2d indices to a matrix
     n*d,               # x-coordinates are just d * n
     (n*r)%%ncol(g))])  # y-coordinates are r * n, modulo the number of columns in g

```
> 1 votes

# Answer
# Python3, 84 bytes:

```
f=lambda b,d,r,y=1,x=1:0if y-1>=len(b)else(b[y-1][(x-1)%len(b[0])]+f(b,d,r,d+y,r+x))

```

Try it online!
> 0 votes

# Answer
# Charcoal, 24 bytes

```
ＮθＮηＷＳ⊞υιＩ№Ｅ✂υ⁰Ｌυθ§ι×ηκ#

```

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

```
ＮθＮη

```

Input the slope as two positive integers `y` and `x`.

```
ＷＳ⊞υι

```

Input the grid.

```
Ｉ№Ｅ✂υ⁰Ｌυθ§ι×ηκ#

```

Take every `y`th element of the grid, and from those rows, take every `x`th element respectively. Count how many of them are `#`s.
> 0 votes

---
Tags: code-golf, grid
---


title: Hide a message in an image - Robbers

text:
# Question
Title: Hide a message in an image - Robbers
Choose a challenge from the Cops thread, determine the third hidden message, and describe how the system works.

Keep in mind limitations and possibilities available to Cops:

* You are not expected to guess any cryptographic secrets or additional information required to extract the hidden messages, as they should have already been included in their post.
* The hidden message will be in English
* The hidden message may be encoded as plain text, a text bitmap rendering, audio clip, or ascii art font. This encoding will be consistent across all hidden messages.
* No further processing will be required after obtaining the hidden message.
* Data is allowed to be hidden in metadata, but at least one bit of one pixel must have been used for something.

Score 1 point per cracked system.

# Answer
# CreaZyp154's

I don't know the first thing about image encodings, but it looks like in each of the three images every pixel is an index into a palette containing two identical colors. Messages are encoded as transposed images in the palette indices.

Thus, the third image says `STEGANOGRAPHY`:
> 7 votes

# Answer
# emanresu A's

Image 1, which encodes `HI`, can be decoded by turning it into a 32×32 square:

Same with Image 2, which encodes `BYE`:

And, with Image 3:

> The words `OI You!`

Since all the images are 1024×1, you just need to split it into segments 32 pixels wide, and stack them on top of one another.

Here's a tool I wrote to do this: https://gist.github.com/Radvylf/b5d1bc5f39903400b243abf2041feefe
> 3 votes

---
Tags: cops-and-robbers, steganography
---


title: AoCG2021 Day 22: Hyperbolic rescue

text:
# Question
Title: AoCG2021 Day 22: Hyperbolic rescue
Part of **Advent of Code Golf 2021** event. See the linked meta post for details.

The story continues from AoC2017 Day 11.

---

Crossing the bridge, you've barely reached the other side of the stream when you are overcome with a sense of deja-vu. "Haven't I done this already?" But before you can finish that thought, someone runs up to you, and cries "My child process has gotten lost in an infinite grid! Can you help me?"

Fortunately for them, you have plenty of experience with infinite grids, even hexagonal ones.

Unfortunately for you, this isn't your typical hex grid.

This is is an order-4 hexagonal tiling. In your typical hexagonal tiling three tiles meet at every vertex:

*Image by wikipedia user watchduck*

The order-4 hexagonal tiling has *4* tiles around every vertex. In terms of geometry this means it's embedded in hyperbolic space.

*Image by Anton Sherwood*

In order to traverse this hyperbolic space and rescue the child you receive a list of instructions. Each instruction consists a number from `0-5`, with `0` move to the next tile straight ahead and each successive number meaning to take move to the next tile clockwise from the last. So as an example `3` would be the tile right behind you.

Given this path you want to figure out how far the child is from your current position.

So your task in this challenge is to take a path of instructions as input and output the number of steps in the shortest path to the same

## Strategies

There are three ways to simplify paths we can use. The first is to remove backtracks. If you ever see a `3` that's just a step back to where you were the step before. So you can remove the `3` and that step. The one hitch is that when you get back you are facing the opposite direction so you need to flip the instruction after.

So if your sequence is:

```
..., y, 3, z, ...

```

It can be rewritten as:

```
..., y+3+z mod 6, ...

```

There's one special case if your sequence ends in a `3`:

```
..., x, 3] = ...]

```

The second method you to take alternative paths around corners. For example in the regular square grid these two paths are the same length:

```
  B--D      B  D
  |     ==     |
  A  C      A--C

```

Since both tilings are order 4 we can actually use a version of this rule.

```
..., x, 2, y ... = ..., x+1 mod 6, 4, y+1 mod 6, ...

```

And again there's an edge case when the `2` or `4` is the last step.

```
..., x, 2] = ..., x+1 mod 6, 4]

```

Note that these equivalences go both ways.

You can always find the shortest path by applying a combination of these two rules.

## Worked examples

### `[0,0,0,0]`

The second move can't be applied and the first one can only be applied backwards. This is the shortest possible path to the destination, so the answer is the number of steps `4`.

### `[2,2,2,2]`

We can apply the second rule right of the bat to get `[2+1,4,2+1,2] = [3,4,3,2]`. Now we can use the first rule with the `3` to get `[3,3]`, and the first rule again gives us `[]`. The answer here is `0` this is a loop.

### `[2,0,2,0,2,0,2,0]`

Ok this is just the last one except we take an extra step forward after each turn. This should just make a bigger version of the same thing right? Nope, hyperbolic space is tricky. We can apply rule `2` a bunch but it never really goes anywhere. This is actually the shortest path to the destination. The answer is `8`.

### `[2,1,2,1,2,1,2,1,2,1,2,1]`

This one forms a big hexagon.

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

```

It's a loop so the answer is `0`.

### `[0,2,1,2]`

This isn't a loop but it can be reduced.

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

```

There's nothing we can apply to `[1,5]` so the answer is `2`.

## Testcases

```
[0,0,0,0] -> 4
[2,2,2,2] -> 0
[2,0,2,0,2,0,2,0] -> 8
[4,0,4,0,4,0,4,0] -> 8
[2,1,2,1,2,1,2,1,2,1] -> 2
[4,5,4,5,4,5,4,5,4,5] -> 2
[2,1,2,1,2,1,2,1,2,1,2,1] -> 0
[4,5,4,5,4,5,4,5,4,5,4,5] -> 0
[0,2,1,2] -> 2

```

# Answer
> 10 votes
# Perl 5 `-p`, 82 bytes

```
s/./"bc"x($&+3)."ab"/ge;1while s/(.)\1//+s/(b|cac)a/a$1/+s/(cbcbca?)b/b$1/;$_=y;a;

```

Try it online!

### How it works

Draw right triangle \\$ABC\\$, where \\$A\\$ is the center of your initial tile, \\$B\\$ is the vertex of the edge behind you on your right, and \\$C\\$ is the center of the edge behind you. The group of symmetries of the tiling are generated by the reflections \\$a, b, c\\$ over the sides \\$BC\\$, \\$CA\\$, \\$AB\\$ of this triangle, which satisfy the equations

$$a^2 = b^2 = c^2 = (bc)^6 = (ca)^4 = (ab)^2 = ε.$$

We can translate our path to a symmetry by applying \\$(bc)^{n + 3}ab\\$ for each step \\$n\\$. Conversely, any symmetry written as an even-length string of \\$a, b, c\\$ can be translated to a path whose length is the number of \\$a\\$s.

With the Knuth–Bendix algorithm, we can transform the above equations to a rewriting system that produces a canonical representation for any symmetry:

\begin{align\*} aa &→ ε, \\ bb &→ ε, \\ cc &→ ε, \\ ba &→ ab, \\ caca &→ acac, \\ cbcbcb &→ bcbcbc, \\ cbcbcab &→ bcbcbca. \end{align\*}

Since these rules never increase the number of \\$a\\$s, we are guaranteed that the canonical representation has the minimal number of \\$a\\$s.

# Answer
> 3 votes
# Pari/GP, 160 bytes

```
a->for(i=1,2*#p=Mod(Polrev(a)+y*x^#a,6),p=-if([[t=p%x^l+(3-s)*x^l--+(p\x^j+3)*x^j-=2|j<-[i..#p],x^(k=j-i)+1+x^k++\(x-1)==s=p%x^j\x^l=i-1]|i<-[2..#p]],t,p));#p-1

```

Try it online!

Based on my Mathematica answer.

# Answer
> 3 votes
# Charcoal, 139 bytes

```
≔⟦Ｅ⁶⊕ι⟧η⊞υ⮌ηＦ⁶⊞ηω≔⁰ζ≔⁰εＦＡ«≔§§ηζ⁺ειδＦ¬§ηδ«≔⟦⟧κＷＥΦ§υ±¹№μ⌕ηω⌕ημ«Ｆ¬›⌈λ⊕⌊λ≔⮌λλ⊞λ⊖ＬηＦ⁻⁶Ｌλ⊞λ⊖Ｌ⊞Ｏηω§≔η⌕ηωλ⊞κλ»§≔§κ⁰¦¹⊖Ｌη⊞υκ»≔⁺³⌕§ηδζε≔δζ»Ｉ⌕Ｅυ№ι§ηζ¹

```

Try it online! Link is to verbose version of code. Explanation: Works by mapping out the grid. The starting point is `0`, then the six adjacent hexagons are numbered `1-6`, then the 24 hexagons at a distance of `2` are numbered `7-30`, then the 90 hexagons at a distance of `3` are numbered `31-120`, and so on.

```
≔⟦Ｅ⁶⊕ι⟧η

```

The edges of the starting hexagon take you to hexagons `1-6`.

```
⊞υ⮌η

```

Save a copy as the list of hexagons at a distance of `0`.

```
Ｆ⁶⊞ηω

```

Add six placeholders for the hexagons at a distance of `1`.

```
≔⁰ζ≔⁰ε

```

Start at the origin facing direction `0`.

```
ＦＡ«

```

Loop through the input steps.

```
≔§§ηζ⁺ειδ

```

Take a step in the appropriate direction.

```
Ｆ¬§ηδ«

```

If we have hit a placeholder, then...

```
≔⟦⟧κ

```

Start collecting the hexagons at the next distance.

```
ＷＥΦ§υ±¹№μ⌕ηω⌕ημ«

```

Until all of the placeholders at the next distance have been mapped, get the edge or edges of the next hexagon that step to a mapped hexagon.

```
Ｆ¬›⌈λ⊕⌊λ≔⮌λλ

```

Ensure that the edges are listed in clockwise order. This usually needs to be descending, except for the very last hexagon to be mapped, which steps to the first and last hexagon to be mapped in the previous pass. For example, hexagon `10` steps back to hexagons `2` and `1`, `20` steps back to hexagon `4` and `30` steps back to hexagons `1` and `6`, in that order.

```
⊞λ⊖Ｌη

```

The next edge from this hexagon goes to the same hexagon as the last edge from the previous hexagon.

```
Ｆ⁻⁶Ｌλ⊞λ⊖Ｌ⊞Ｏηω

```

The remaining edges go to new unmapped hexagons that are further away.

```
§≔η⌕ηωλ

```

Update the map with the edges of this hexagon.

```
⊞κλ

```

Collect this hexagon in the list of hexagons at this distance.

```
»§≔§κ⁰¦¹⊖Ｌη

```

Fix the second edge of the first hexagon, which needs to wrap around to the last unmapped hexagon.

```
⊞υκ

```

Collect this list of hexagons in the list of hexagons for each distance.

```
»≔⁺³⌕§ηδζε

```

Work out the direction we arrived at this hexagon from, and add 3 so that we're facing away from there.

```
≔δζ

```

Actually move to this hexagon.

```
»Ｉ⌕Ｅυ№ι§ηζ¹

```

Find out which list of hexagons we ended up in, which is our final distance.

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

-7 bytes thanks to @att.

```
Count[Table[t=b.c,#+3].a.b&/@#/.List->Dot//.{(n:a|b|c).n_:>Dot[],(n:b|c.a.c).a:>a.n,(n:c.t.t).b:>b.n},a]&

```

Try it online!

A port of Anders Kaseorg's Perl answer.

### A proof that the last rule in Anders Kaseorg's answer is not needed

As I said in the comment, the last rule is needed for minimizing the length of the word, but we only need to minimize the number of \\$a\\$s.

After applying the first 6 rules, there are only 6 possible cases between every two \\$a\\$s: \\$c\\$, \\$bc\\$, \\$cbc\\$, \\$bcbc\\$, \\$cbcbc\\$, \\$bcbcbc\\$. Since there is no \\$ba\\$ or \\$caca\\$, \\$aca\\$ can only appear at the beginning of the word.

Now let's apply the last rule \\$cbcbcab\Rightarrow bcbcbca\\$, and see what will happen before and after the \\$a\\$ in \\$cbcbcab\\$. Remember that the only way to decrease the number of \\$a\\$s is applying the first rule: \\$aa\Rightarrow \varepsilon\\$.

#### Before the \\$a\\$

If this is the first \\$a\\$ in the word, there isn't another \\$a\\$ for us to apply the first rule.

If it is not the first \\$a\\$, the only two possible cases between this \\$a\\$ and the previous \\$a\\$ are \\$cbcbc\\$ and \\$bcbcbc\\$, which will become \\$bcbcbc\\$ and \\$cbcbc\\$ respectively. So the number of \\$a\\$ will not decrease.

#### After the \\$a\\$

If this is the last \\$a\\$ in the word, there isn't another \\$a\\$ for us to apply the first rule.

If it is not the last \\$a\\$, there are 3 possible cases between this \\$a\\$ and the next \\$a\\$: \\$bc\\$, \\$bcbc\\$, \\$bcbcbc\\$, which will become \\$c\\$, \\$cbc\\$, \\$cbcbc\\$ respectively. In the last two cases, nothing else will change.

But the first case will produce a new \\$caca\\$: \\$cbcbcabca\Rightarrow bcbcbcaca\\$. Applying the rule \\$caca\Rightarrow acac\\$, this substring will become \\$bcbcbacac\\$, and further become \\$bcbcabcac\\$ (by applying \\$ba\Rightarrow ab\\$). Now the \\$c\\$ at the end of the substring might meet another \\$c\\$ and get eliminated. But there can't be another \\$ca\\$ right after the substring, so nothing else will change, and the number of \\$a\\$ won't decrease.

---

# Wolfram Language (Mathematica), 133 bytes

-10 bytes thanks to @att.

```
Length[##.E.E&@@#//.{a_ . 3 .b_/;a<6>b:>Mod[a+b+3,6],##&@@(a_ .#2.(o:#...).#2.b_/;a<6>b:>Dot@@Mod[-{-a-#,o,-b-#},6]&@@@1?2@*5?4)}]-2&

```

Try it online!

First appends two dummy variable `E`'s to the list, then repeatedly replaces:

* \\$a3b\Rightarrow\operatorname{mod}(a+b+3,6)\\$
* \\$a2\underbrace{1\cdots 1}\_{n\ge0}2b\Rightarrow\operatorname{mod}(a+1,6)\underbrace{5\cdots 5}\_{n}\operatorname{mod}(b+1,6)\\$
* \\$a4\underbrace{5\cdots 5}\_{n\ge0}4b\Rightarrow\operatorname{mod}(a-1,6)\underbrace{1\cdots 1}\_{n}\operatorname{mod}(b-1,6)\\$

And then takes the length of the result and minus 2.

# Answer
> 1 votes
# Retina 0.8.2, ~~55~~ 53 bytes

```
\d
$*____ab
_
bc
(.)\1

(b|cac)a
a$1
}`(cbcbc)b
b$1
a

```

Try it online! Link includes test cases. Explanation: Another port of @AndersKaseorg's Perl answer. Edit: Saved 2 bytes using @alephalpha's observation.

```
\d
$*____ab
_
bc

```

First expand each digit into `n+3` underscores followed by `ab`, then replace each underscore with `bc`.

```
(.)\1

(b|cac)a
a$1
(cbcbc)b
b$1

```

Perform the simplifications.

```
}`

```

Repeat until no more simplifications can be made.

```
a

```

Count the remaining number of `a`s.

# Answer
> 1 votes
# TypeScript Types, 568 bytes

```
//@ts-ignore
type a<N,P=[],A=[[0,1,2,3,4,5],[1,2,3,4,5,0],[2,3,4,5,0,1],[3,4,5,0,1,2],[4,5,0,1,2,3],[5,0,1,2,3,4]],I=A[1],D=A[5]>=N extends[infer X,infer Y,infer Z,...infer R]?Y extends 3?a<[A[3][A[X][Z]],...R],P>:|a<[Y,Z,...R],[...P,X]>|(Y extends 2?a<R,[...P,I[X],4,I[Z]]>:Y extends 4?a<R,[...P,D[X],2,D[Z]]>:never):N extends[infer X,infer Y]?Y extends 3?P:Y extends 2?[...P,I[X],4]|[...P,X,Y]:Y extends 4?[...P,D[X],2]|[...P,X,Y]:[...P,X,Y]:[...P,...N];type b<T,K=keyof T>=T extends T?keyof T extends K?T:never:0;type M<C,P=0>=[C]extends[P]?b<C>["length"]:M<a<C>,C>

```

Try It Online!

## Ungolfed / Explanation

```
// Iterate over an array, applying equivalence rules where possible
type ApplyRules<
  Next,
  Prev=[],
  // Modulo arithmetic addition table
  Add=[[0,1,2,3,4,5],[1,2,3,4,5,0],[2,3,4,5,0,1],[3,4,5,0,1,2],[4,5,0,1,2,3],[5,0,1,2,3,4]],
  Inc=Add[1],
  Dec=Add[5]
> =
  // Get the first three elements of Next
  Next extends [infer X, infer Y, infer Z, ...infer Rest]
    ? Y extends 3
      // Apply the rule for 3
      ? ApplyRules<[Add[3][Add[X][Z]], ...Rest], Prev>
      // Return a union of:
      :
        // Applying no rule and stepping forward one step
        | ApplyRules<[Y, Z, ...Rest], [...Prev, X]>
        // If Y is 2 or 4, applying the 2/4 rule
        | (
          Y extends 2
            ? ApplyRules<Rest, [...Prev, Inc[X], 4, Inc[Z]]>
            : Y extends 4
              ? ApplyRules<Rest, [...Prev, Dec[X], 2, Dec[Z]]>
              : never
        )
    // Next has fewer than 3 elements. If it has exactly 2, store them in X and Y:
    : Next extends [infer X, infer Y]
      ? Y extends 3
        // If Y is 3, remove both X and Y from the end of the array by returning Prev
        ? Prev
        // If Y is 2 or 4, return the union of the current state and the state after applying the end-2/4 rule
        : Y extends 2
          ? [...Prev, Inc[X], 4] | [...Prev, X, Y]
          : Y extends 4
            ? [...Prev, Dec[X], 2] | [...Prev, X, Y]
            // Otherwise, just return the full array array
            : [...Prev, X, Y]
      // Next has fewer than 2 elements; return the full array
      : [...Prev, ...Next]

// Filter a union of tuples for those with the shortest length
type Shortest<T, K=keyof T> = T extends T ? keyof T extends K ? T : never : 0

// Continually apply rules until nothing changes, then return the shortest length in Cur
type Main<Cur, Prev=0> = [Cur] extends [Prev] ? Shortest<Cur>["length"] : Main<ApplyRules<Cur>, Cur>

```

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


title: Create a pointer sequence

text:
# Question
Title: Create a pointer sequence
Lets define a pointer sequence to be any sequence such that **a(n) = a((n-1)-(a(n-1)))** forall **n** greater than some finite number. For example if our sequence begun with

```
3 2 1

```

Our next term would be `2`, because **a(n-1) = 1**, **(n-1)-1 = 1**, **a(1) = 2** (this example is zero index however it does not matter what index you use the calculation will always be the same.). If we repeat the process we get the infinite sequence

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

```

## Task

Given some initial array of positive integers output the pointer sequence starting with that array.

### Output types

Output is intended to be flexible, if you choose to write a function as your program it can return, either an infinite list of integers or a function that indexes the sequence. If you choose to write a full program you may output terms of the sequence indefinitely.

You may also choose to take two inputs, the starting array and an index. If you choose to do this you need only output the term of the sequence at that index.

---

You will never be given a sequence that requires indexing before the beginning of the sequence. For example `3` is not a valid input because you would need terms before the `3` to resolve the next term.

This is so your score will be the number of bytes in your program with a lower score being better.

## Test Cases

*test cases are truncated for simplicity*

```
2 1   -> 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 ...
2 3 1 -> 2 3 1 3 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 2 1 2 ...
3 3 1 -> 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 3 3 1 3 ...
4 3 1 -> 4 3 1 3 4 4 3 3 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 4 4 4 3 4 ...

```

# Answer
> 8 votes
# JavaScript (ES6), 25 bytes

```
a=>f=n=>a[n]||f(--n-f(n))

```

An anonymous function that, when called, creates a function `f` that gives the item at a given index in the sequence.

Please let me know if I misunderstood anything...

# Answer
> 8 votes
# Husk, ~~7~~ 6 bytes

```
¡S!o_→

```

Returns an infinite list. Try it online! Note that it takes a while for TIO to truncate and print the result.

## Explanation

The operator `¡` has several meanings. Here I'm using "construct infinite list by iterating a function that computes a new element from the list of existing ones". Given a list of length **N**, the new element will have 1-based index **N+1**. All we need to do is negate the last element of the list (which is the previous value) and index into the list using the result.

```
¡S!o_→  Implicit input.
¡       Construct infinite list by iterating this function on input:
 S!      Element at index
    →    last element
  o_     negated.

```

# Answer
> 4 votes
# Haskell, 36 bytes

*Takes a list and returns a function that indexes the sequence*

```
l!n|n<length l=l!!n|e<-n-1=l!(e-l!e)

```

Try it online!

## Explanation

Here we are defining a function `!` that takes a list `l` and a index `n`. If `n` is less than the length of `l` we index `l` by `n`, otherwise we return `l!((n-1)-l!(n-1))`. This follows the recursive definition of the function I gave in the question.

Here is the same program ungolfed.

```
a l n
 |n<length l = l!!n
 |otherwise = (a l) ((n-1) - (a l) (n-1))

```

I use `e<-n-1` instead of otherwise to save bytes while assigning `n-1` to `e` so it can be used later.

# Answer
> 4 votes
# MATL, ~~13~~ 9 bytes

```
:"tt0)_)h

```

Outputs the initial terms followed by *n* additional terms (allowed by the challenge), where *n* is a positive integer taken as input.

Try it online!

### Explanation

```
:"      % Implicitly input n. Do the following n times
  tt    %    Duplicate the sequence so far, twice. In the first iteration this
        %    implicitly inputs the array of initial terms
  0)    %    Get value of the last entry, say m
  _)    %    Get value of the entry which is m positions back from the last
  h     %    Append. This extends the array with the new entry
        % Implicit end. Implicitly display

```

# Answer
> 3 votes
# Mathematica, 63 bytes

takes two inputs

```
(Clear@a;(a@#2[[1]]=#)&~MapIndexed~#;a@n_:=a[n-1-a[n-1]];a@#2)&

```

Try it online!

-3 bytes from Martin Ender

# Answer
> 2 votes
# , 55 bytes

```
f=function(a,n)"if"(n<=sum(a|1),a[n],f(a,n-1-f(a,n-1)))

```

Try it online!

Takes two inputs.

# Answer
> 2 votes
# Standard ML (MLton), 58 bytes

```
fun a$n=if n<length$then List.nth($,n)else a$(n-1-a$(n-1))

```

Try it online! The function `a` takes the initial list and an index and returns the sequence element at that index. Example usage: `a [4,3,1] 5` yields `4`.

# Answer
> 2 votes
# Jelly, 6 bytes

```
NṪịṭµ¡

```

Takes a sequence **S** and an integer **k**, and adds **k** terms to **S**.

Try it online!

### How it works

```
NṪịṭµ¡  Main link. Left argument: S (sequence). Right argument: k (integer)

    µ¡  Combine the links to the left into a (variadic) chain and call it k times.
        The new chain started by µ is monadic, so the chain to the left will be
        called monadically.
N           Negate; multiply all elements in S by -1.
 Ṫ          Tail; retrieve the last element, i.e., -a(n-1).
  ị         At-index; retrieve the element of S at index -a(n-1).
            Since indexing is modular and the last element has indices n-1 and 0,
            this computes a( (n-1) - a(n-1) ).
   ṭ        Tack; append the result to S.

```

# Answer
> 2 votes
# Husk, 6 bytes

```
¡Ṡ!o_→

```

Try it online!

Figured this out after a lot of frustration with Jo King's help.

# Answer
> 1 votes
# Python 2, 48 bytes

```
a=lambda S,n:n<len(S)and S[n]or a(S,~a(S,~-n)+n)

```

Try it online!

# Answer
> 1 votes
# CJam, 10 bytes

```
{{(_j-j}j}

```

For CJam, this does very well (It even beats 05ab1e!).

This is an anonymous block that expects input in the form `i n` on the stack, where `i` is the index in the sequence and `n` is an array of starting numbers.

The reason this works so well is because of the `j` operator, which provides memoized recursion from a set of starting values.

## Explanation:

```
{    Function j(n) with [j(0), j(1), j(2)] = [4, 3, 1], return j(6):
 (    Decrement:    5
 _    Duplicate:    5 5
 j    j(5):
  (    Decrement:   5 4
  _    Duplicate:   5 4 4
  j    j(4):
   (    Decrement:  5 4 3
   _    Duplicate:  5 4 3 3
   j    j(3):
    (    Decrement: 5 4 3 2
    _    Duplicate: 5 4 3 2 2
    j    j(2) = 1:  5 4 3 2 1
    -    Subtract:  5 4 3 1
    j    j(1) = 3:  5 4 3 3
   -    Subtract:   5 4 0
   j    j(0) = 4:   5 4 4
  -    Subtract:    5 0
  j    j(0) = 4:    5 4
 -    Subtract:     1
 j    j(1) = 3:     3
}j   End:           3

```

# Answer
> 1 votes
# Java (8), 60 bytes

```
int a(int[]a,int n){return n<a.length?a[n]:a(a,--n-a(a,n));}

```

Takes two inputs (integer-array `a` and integer `n`), and outputs the `n`'th value of the sequence.

**Explanation:**

Try it here. (Might take a few seconds.)

```
int a(int[]a,int n){        // Method with int[] and int parameters and int return-type
  return n<a.length?        //  If input `n` is smaller than the length of the array:
          a[n]              //   Output the `n`'th item of the array
         :                  //  Else:
          a(a,--n-a(a,n));  //   Recursive call with `n-1-a(n-1)`
}                           // End of method

```

# Answer
> 1 votes
# 05AB1E, 5 bytes

```
λN<α₅

```

Outputs the infinite sequence.

Try it online. (No test suite with all test cases at once, because there is a bug when using the recursive environment within an iterator.)

Outputting the \\$n^{th}\\$ value or first \\$n\\$ values would cost an additional byte:
Output the (0-based) \\$a(n)\\$.
Output the first \\$n\\$ values.

**Explanation:**

```
λ      # Start a recursive environment
       # to output the infinite sequence
       # Using the (implicit) input-list I, start the sequence at a(0)=I[0], a(1)=I[1],
       # ..., a(n)=I[n],
       # For which we calculate the next a(n) value as follows:
       #  (implicitly push a(n-1))
 N<    #  Push n-1
   α   #  Calculate the absolute difference between the two: |a(n-1)-(n-1)|
    ₅  #  And use that as n'th value: a(|a(n-1)-(n-1)|)

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~34~~ ~~31~~ ~~30~~ 29 bytes

```
a_f@n_:=a[--t-a@t]&@@a[[t=n]]

```

Try it online!

Input `f[initial...][n]`, e.g. as `f[2, 1][3]`.

```
a_f@n_:=                        f[initial...][n], where a=f[initial...]
                     a[[t=n]]   attempt to take an index
        a[--t-a@t]&@@             if out of bounds, recurse

```

---

### Alternative input formats (also 29 bytes):

```
f=f[#,--t-#~f~t]&@@#[[t=#2]]&

```

Try it online!

Input `[initial, n]`, e.g. as `f[{2, 1}, 3]`.

```
h:f@a_=h[--t-h@t]&@@a[[t=#]]&

```

Try it online!

Input `[initial][n]`, e.g. as `f[{2, 1}][3]`.

# Answer
> 1 votes
# Japt, ~~8~~ 7 bytes

Outputs the `n`th term, 0-indexed. Change the second `g` to `h` to output the first `n` terms instead.

```
ÈgZw}gV

```

Try it

# Answer
> 1 votes
# Nibbles, 4 bytes

```
.~~_=`($

```

explanation

```
.~~      # append until null (aka always in this case)
   _     # first input int list
    =    # array subscript (aka haskell !!)
     `(  # uncons (returning head)
       $ # second value from uncons (the tail)

```

Note that the `$` can't also be implicit due to part of the uncons bin representation using part of its encoding after its arg :(

I say this is non competing because this problem influenced the idea to have the `.~~` operator, although something like this was definitely needed and its a standard op in Husk.

# Answer
> 0 votes
# Perl, 38 +3 (-anl) bytes

```
{print;push@F,$_=$F[$#F-$F[$#F]];redo}

```

Try It Online

# Answer
> 0 votes
# Java (OpenJDK 8), ~~95~~ ~~93~~ ~~91~~ 90 bytes

```
a->i->{int j=0,b[]=new int[++i];for(;j<i;j++)b[j]=j<a.length?a[j]:b[~-j-b[j-1]];return b;}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 20 bytes

```
#`r[=ˆŽ¼}[¯¾¯¾è-è=ˆ¼

```

Expects the input as a space-separated string, keeps outputting indefinitely; pretty straightforward implementation

Example run:

```
$ 05ab1e -e '#`r[=ˆŽ¼}[¯¾¯¾è-è=ˆ¼' <<< '3 2 1'
3
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2
2
1
2

```

# Answer
> 0 votes
# Perl 5, `-a` 30 bytes

```
#!/usr/bin/perl -a
use 5.10.0
say$F[@F]=$F[-1-$F[-1]]while 1

```

Try it online!

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


# Question
Title: Find all reflexicons using roman numerals
A reflexicon is a self-descriptive word list that describes its own letter counts. Take for example the one found by Ed Miller in 1985 in English:

> Sixteen e’s, six f’s, one g, three h’s, nine i’s, nine n’s, five o’s, five r’s, sixteen s’s, five t’s, three u’s, four v’s, one w, four x’s

This reflexicon contains exactly what it says it does as per the definition. These are pretty computationally intensive but your job is to find all the possible reflexicons using roman numerals; there are way fewer letters involved (`I V X L C D M`) which is why the search space is reduced. Notice the English reflexicon containing "one g" - we can call it "dummy text" and it is allowed. Our reduced alphabet only contains letters used in numerals. A reflexicon using roman numerals would be of the form:

> XII I, IV V, II X

The counts (12 I's, 4 V's, 2 X's) are not correct - this just illustrates the format (notice no plural `'s`). A letter is completely omitted if its count is 0 (there is no `L` in this case).

Here is a list of roman numerals \[1..40\] for convenience (doubtful you need any more than this):

```
I II III IV V VI VII VIII IX X
XI XII XIII XIV XV XVI XVII XVIII XIX XX
XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX
XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX XL

```

These are all valid reflexicons (but these are not all!):

> IV I, II V

> V I, I L, II V, I X

> V I, II V, I X, I L

Standard `code-golf` rules apply - find all reflexicons using roman numerals! One per line

# Answer
> 8 votes
# Charcoal, 84 bytes

```
≔⪪”{⊞‴ΣAº⧴θπ⪪λpＡz” θΦＥ×¹⁶φ⪫Φ⁺Ｅ⮌↨﹪κφχ∧λ⁺⁺§θλ §IVXμＥ⮌↨÷κφ²×λ⁺I §LCDMμλ, ∧κ⁼﹪κφＩ⭆XVI№ιλ

```

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

```
≔⪪”{⊞‴ΣAº⧴θπ⪪λpＡz” θ

```

Split the compressed string  `I II III IV V VI VII VIII IX` on spaces. Since there are only seven different Roman numerals, an description string can only have `22` of any one letter. However, this means that the letters `L`, `C`, `D` and `M` can only appear once, limiting the number to just `14` `I`s in the description string. I'm not convinced that you can actually get above `9` `I`s, and using base `10` makes the following loop somewhat golfier.

```
ΦＥ×¹⁶φ⪫Φ⁺Ｅ⮌↨﹪κφχ∧λ⁺⁺§θλ §IVXμＥ⮌↨÷κφ²×λ⁺I §LCDMμλ, ∧κ⁼﹪κφＩ⭆XVI№ιλ

```

Get the base `10` digits of the numbers up to `1000`, then use base `2` for the higher order bits, generate the description string represented by the number, count the number of times each Roman numeral appears, treat the digits as base `10`, and output those description strings where this equals the original number. Note that I don't have to count the number of occurrences of `L`, `D`, `C` and `M` since they will always appear the correct number of times and only exist to inflate the count of `I`s.

# Answer
> 7 votes
# 05AB1E, ~~47~~ ~~46~~ 44 bytes

-2 bytes thanks to Kevin Cruijssen!

Quite inefficient version that only finds the first reflexicon in 60 seconds.

```
₂ENÝ7ãDONQÏεŽ6ˆ.XRøʒ¬Ā}©.XDS{®ø`×S{Qiðý„, ý,

```

Try it online!

The builtin `.X` (*Convert from integer to roman numeral string*) does help quite a bit.

**Commented**:

```
₂E                 # for N in 1 .. 26:
  NÝ               #   range from 0 to N
    7ã             #   7th cartesian power - all 7-tuples with values in [0..N]
      DONQÏ        #   keep those that sum to N
  ε                #   map over the tuples                                       example: [4,2,0,0,0,0,0]
   Ž6ˆ             #     compressed integer 1666                                  [4,2,0,0,0,0,0], 1666
      .XR          #     convert to Roman numeral and reverse                     [4,2,0,0,0,0,0], "IVXLCDM"
         ø         #     zip this string with the current tuple                   [[4,"I"],[2,"V"],[0,"X"],[0,"L"],[0,"C"],[0,"D"],[0,"M"]]
          ʒ¬Ā}     #     keep only the pairs with a number larger than 0          [[4,"I"],[2,"V"]]
   ©               #     store the list in the register                           [[4,"I"],[2,"V"]]
    .X             #     convert all numbers in the list to Roman numerals        [["IV","I"],["II","V"]]
      f            #     make a copy of the resulting list ...                    [["IV","I"],["II","V"]], [["IV","I"],["II","V"]]
       S{          #     ... and flatten and sort it                              [["IV","I"],["II","V"]], ["I","I","I","I","V","V"]
         ®         #     get the list with the integers still in it               [["IV","I"],["II","V"]], ["I","I","I","I","V","V"], [[4,"I"],[2,"V"]]
          ø`×      #     and repeat Roman digit the corresponding number of times [["IV","I"],["II","V"]], ["I","I","I","I","V","V"], ["IIII","VV"]
              S{   #     flatten and sort this                                    [["IV","I"],["II","V"]], ["I","I","I","I","V","V"], ["I","I","I","I","V","V"]
                Q  #     are the two sorted lists of characters equal?            [["IV","I"],["II","V"]], 1
   i               #     if that is the case:
     ðý            #       join inner pairs with spaces                           ["IV I","II V"]
       „, ý        #       join by ", "                                           "IV I, II V"
           ,       #       and print

```

---

With some optimization we can find all of them reasonably fast:

```
16EN¸2Å2«4Å1«Ý.«â€˜DONQÏεŽ6ˆ.XRøʒ¬Ā}D.X©JJ{sε`×}J{Qi®ðý„, ý,

```

Try it online!

# Answer
> 2 votes
# Python3, 785 bytes:

```
import itertools as i
d={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8,'IX':9,'X':10,'XI':11,'XII':12,'XIII':13,'XIV':14,'XV':15,'XVI':16,'XVII':17,'XVIII':18,'XIX':19,'XX':20,'XXI':21,'XXII':22,'XXIII':23,'XXIV':24,'XXV':25,'XXVI':26,'XXVII':27,'XXVIII':28,'XXIX':29,'XXX':30,'XXXI':31,'XXXII':32,'XXXIII':33,'XXXIV':34,'XXXV':35,'XXXVI':36,'XXXVII':37,'XXXVIII':38,'XXXIX':39,'XL':40}
q=lambda p,s:all(d[a]==s.count(b)for a,b in p)and all(any(m==j for _,m in p)for b,_ in p for j in b)
def g(s):
 k=[1 if not(m:=max(h.count(i)for h in d))else sum([m]*len(s))for i in s]
 yield from i.product(*[[j for j in d if d[j]<=a]for a in k])
f=lambda s:{n for b in range(1,len(s)+1)for m in i.combinations(s,b)for j in g(m)if q(u:=[*zip(j,m)],(n:=','.join(a+' '+b for a, b in u)))}

```

Try it online!

Code is able to crunch the reflexicons in about 0.4 seconds. The crux of the logic is, for every character in the "base" Roman numeral input (i.e `IV`, `IVX`, `VXMC`, etc) is first to find the maximum number of times that character can occur (e.g `I` occurs a maximum of `3` times, while `M` does not occur), take the maximum (if the letter does not occur, set maximum to `1`), and then multiply the maximum by the length of the base input, thus producing an upper bound for the range of each Roman numeral, drastically reducing the total number of Cartesian Products that have to be produced.

I am sure this solution can be golfed further - the Roman numeral lookup table takes up an incredible amount of space.

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

The strict output format prompted me to try a approach. This is based on the output of Neil's answer.

This is obviously very fast, and I think it's rather competitive (size-wise) compared to some code that would actually compute the strings.

```
_=>`IV I, II V${"XLXCLCXDLDCDXMLMCMDM".replace(/../g,a=>[i=`
V`,0,0,0].map(n=>i+" I, II V0"+a[i+='I',0]+0+a[1]).join``)}
IX I0V, II X0L0C0D0M`.split`0`.join`, I `

```

Try it online!

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~136~~ 135 bytes

```
Pick[StringRiffle[s=Pick[{RomanNumeral@#,d=Characters@"IVXLCDM"},Sign@#,1],","," "],StringCount[""<>s,#]&/@d,#]&/@0~Range~9~Tuples~7

```

Searches \\$10^7\\$ possibilities, so quite slow. Does not finish in a reasonable time.
Check with better upper bounds on character occurences: Try it online!

Includes the empty string containing zero symbols.

Any single roman numeral contains at most one (each) `VLD`, and at most three (each) `IXCM`. Thus there are at most 8 (each) `VLD` (7\*1+1), and at most 22 (each) `IXCM` (7\*3+1). But the maximum possible number of any symbol is only 22, so `LCDM` can only occur at most once each, as "dummy text".

From here we can just run the program and see what the maximum encountered values of `IVX` are. Their maximum counts are 9, 2, and 2, respectively.

# Answer
> 1 votes
# Scala, 149 bytes

```
"IV I,II V\nIX I,I V,II X,I L,I C,I D,I M"+{for{i<-0 to 3;j<-"DMCMCDLMLDLCXMXDXCXL"grouped 2}yield s"\nV${"I"*i} I,II V"+j.flatMap(",I "+_)}.mkString

```

By the findings of others here, we know already that there are exactly 42 (sic!) valid reflexicons. So one solution strategy is to generate these 42 lines by as small as possible code. While doing so, I realized that my solution became very similar to Arnauld's answer. However, his trick of further saving some bytes by temporarily substituting the multiple occurences of `,I`  via `0` does not seem to save additional bytes in the Scala approach taken here.

Try it online!

---
Tags: code-golf, roman-numerals
---


# Question
Title: Concatenate characters' indexes in the alphabet in the given numeral system
1. Given a word, get the indexes of each letter in the alphabet.

For example: `uncopyrightable` becomes: `[21, 14, 3, 15, 16, 25, 18, 9, 7, 8, 20, 1, 2, 12, 5]`
2. Convert these indexes to the given numeral system.

For example, if the radix is `36`, then the array above would become:
`['l', 'e', '3', 'f', 'g', 'p', 'i', '9', '7', '8', 'k', '1', '2', 'c', '5']`
3. Joining those gives **`le3fgpi978k12c5`**.

Of course you don't have to use arrays.

More examples:

* `dermatoglyphics`, `36``45id1kf7cpg893j`
* `undiscoverability`, `8``25164112331726522121114112431`
* `superacknowledgement`, `16``13151051213bef17c5475d5e14`

---

* Your input will be a word (you decide if it'll be uppercase, lowercase or mixed) and a *valid* radix (2-36).
* You can receive input through any of the standard IO methods.
* This is , so shortest code in bytes wins!

(*very similar question here*)

# Answer
# 05AB1E, ~~13~~ 8 bytes

```
Ç96-IBlJ

```

-5 bytes thanks to *@ovs*.

With string and integer inputs; and string output. Could be 1 byte less if we can output in uppercase by removing the `l`.

Try it online or verify all test cases.

An alternative for `Ç96-` is `Ask>`, if we take the input as a character-list: Try it online or verify all test cases.

**Explanation:**

```
     # Step 1: Convert the (implicit) input to their 1-based alphabetical index:
Ç    #   Convert the (implicit) input-string to a list of codepoint integers
 96- #   Subtract 96 from each
     #  OR
A    #   Push the lowercase alphabet
 s   #   Swap so the (implicit) input-list is at the top of the stack
  k  #   Get the (0-based) index of each character in the alphabet
   > #   And increase each by 1 to make it a 1-based index

     # Step 2: Convert it to the base of the second input, and output:
IB   #  Convert it to the base of the second input
  l  #  Lowercase all letters, because `B` results in uppercase A-Z
   J #  And join the list together to a string
     #  (after which the result is output implicitly)

```
> 5 votes

# Answer
# Jelly, 9 bytes

```
ØaiⱮb‘ịØB

```

Try It Online!

-1 byte thanks to caird coinheringaahing
> 4 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
""<>LetterNumber@#~IntegerString~#2&

```

Try it online!

87-36 bytes from @att
> 4 votes

# Answer
# Charcoal, 9 bytes

```
⭆θ⍘⊕⌕βιＩη

```

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

```
 θ          First input
⭆           Map over characters and join
    ⌕       0-indexed index of
      ι     Current character
     β      In lowercase alphabet
   ⊕        Incremented i.e. 1-indexed
  ⍘         Convert to string base
        η   Second input
       Ｉ    Cast to integer

```

When given an integer base, the string base conversion uses the appropriate prefix of `0-9a-zA-z`.
> 4 votes

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

Expects `(string)(radix)`.

```
s=>r=>Buffer(s).map(c=>s+=(c%32).toString(r),s='')&&s

```

Try it online!
> 2 votes

# Answer
# Husk, 20 bytes

```
mȯc+48?+7I>9ṁȯB⁰%32c

```

Try it online!

No easy `0-9A-Z` built into Husk, so 12 bytes used to roll our own.

Main part: get the digit values in the given base

```
ṁȯ              # map and flatten across input string
       c        # get the character code
    %32         # modulo 32 (so A=1, B=2, ...)
  B⁰            # convert to digits in base given by input number

```

Helper function: convert digit values to 0,1,2,...9,A,B,C,...,Y,Z

```
mȯ              # map over all digit values
      ?   >9    # if it's bigger than 9
       +7       # add 7
         I      # otherwise leave unchanged;
   +48          # then add 48
  c             # and convert to corresponding ASCII character

```
> 2 votes

# Answer
# Java, 73 bytes

```
s->r->s.chars().mapToObj(c->r.toString(c%32,r)).reduce("",String::concat)

```

Try it online!
> 1 votes

# Answer
# , 89 bytes

```
\(x,y)Reduce(paste0,sapply(el(strsplit(x,"")),\(z)cwhmisc::int2B(grep(z,letters),y))[1,])

```

With `R < 4.1`, `\` needs to be replaced with `function` resulting in a total of 104 bytes.

-5 bytes thanks to @pajonk.

Try it online!
> 1 votes

# Answer
# Japt `-m`, ~~9~~ 8 bytes

```
#`nUc)sV

```

Try it
> 1 votes

# Answer
# Vyxal, 12 bytes

```
C96-kr⁰Ẏ$vτ∑

```

Try it Online!

A bit messy but it works.

```
C            #  Charcodes
 96-         # -96
    kr⁰Ẏ     # 0-9a-zA-Z sliced to input length
        $vτ  # Convert each to that base
           ∑ # Sum the result

```
> 0 votes

# Answer
# C (gcc), <sup>~~57~~</sup> 56 bytes

```
f(s,r)char*s;{for(;*s;*s+=*s<10?49:56,++s)*s-=65,*s%=r;}

```

Try it online!

*Saved a byte thanks to ceilingcat!!!*

Inputs an uppercase string.
Maps the string such that `A` -\> `1`, `B` -\> `2`, \\$\dots\\$, `J` -\> `A`, `K` -\> `B`, \\$\dots\\$ modulus radix \\$r\\$.
> 0 votes

---
Tags: code-golf, base-conversion, alphabet
---


title: 1 bit, 2 bits, 3 bits, …

text:
# Question
Title: 1 bit, 2 bits, 3 bits, …
Given a positive integer \\$n\\$, your task is to find out the number of partitions \\$a\_1+a\_2+\dots+a\_k=n\\$ where each \\$a\_j\\$ has exactly \\$j\\$ bits set.

For instance, there are \\$6\\$ such partitions for \\$n=14\\$:

$$\begin{align}&14 = 1\_2+110\_2+111\_2&(1+6+7)\\ &14 = 10\_2+101\_2+111\_2&(2+5+7)\\ &14 = 10\_2+1100\_2&(2+12)\\ &14 = 100\_2+11\_2+111\_2&(4+3+7)\\ &14 = 100\_2+1010\_2&(4+10)\\ &14 = 1000\_2+110\_2&(8+6)\end{align}$$

This is , so the shortest answer wins.

### Test cases

```
n  f(n)
-------
1  1
2  1
3  0
4  2
5  1
10 2
14 6
19 7
20 10
25 14
33 32
41 47
44 55
50 84
54 102
59 132

```

# Answer
# Jelly, 10 bytes

```
ŒṗB§Ṣ⁼JƲ€S

```

Try it online!

Brute force approach, we generate all partitions then count those that satisfy \\$\operatorname{bitsum}(a\_j) = j\\$. Times out for the \\$n = 59\\$ test case on TIO, and can handle a test suite going up to the \\$n = 50\\$ test cases

## How it works

```
ŒṗB§Ṣ⁼JƲ€S - Main link. Takes n on the left
Œṗ         - Integer partitions of n
  B        - Convert everything to binary
       Ʋ€S - Count for how many the following is true:
   §       -   Sum of bits for each
    Ṣ      -   Sorted
     ⁼J    -   Is equal to [1, 2, ..., n] for some n?

```
> 6 votes

# Answer
# Python 3, 74 bytes

```
f=lambda n,m=1:sum(f(n-i,m+1)for i in range(n+1)if i.bit_count()==m)+(n<1)

```

Attempt This Online!

-4 bytes suggested by loopy walt.

---

# Python 3, 78 bytes

```
f=lambda n,m=1:sum(f(n-i,m+1)for i in range(n+1)if bin(i).count('1')==m)+(n<1)

```

Try it online!
> 5 votes

# Answer
# Vyxal, 10 bytes

```
ṄƛbṠs:ż⁼;∑

```

Try it Online!

```
Ṅ          # Integer partitions
 ƛ      ;  # Map...
  bṠ       # Sums of binary
    s      # Sorted
       ⁼   # Equal to
     :ż    # 1..length?
         ∑ # Sum (count valid)

```
> 4 votes

# Answer
# Pari/GP, 56 bytes

```
f(n,m=1)=!n+sum(i=1,n,if(sumdigits(i,2)-m,0,f(n-i,m+1)))

```

Try it online!

A port of tsh's Python answer.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 99 bytes

```
(l=Length)@Select[Flatten[Permutations/@IntegerPartitions@#,1],Tr/@IntegerDigits[#,2]==Range@l@#&]&

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 11 bytes

```
Åœʒ2вO{āQ}g

```

Try it online or verify all test cases.

**Explanation:**

```
Åœ         # Get all lists of positive integers that sum to the (implicit) input
  ʒ        # Filter this list of lists by:
   2в      #  Convert it to a binary-list
     O     #  Sum each inner list together
      {    #  Sort it
       ā   #  Push a list in the range [1,length] (without popping)
        Q  #  Check if the two lists are the same
  }        # After the filter:
   g       # Pop and push the length to get the amount of remaining lists
           # (which is output implicitly as result)

```
> 3 votes

# Answer
# Charcoal, 48 bytes

```
Ｎθ≔⁰η⊞υ⁰ＦＬ↨θ²«≔υζ≔⟦⟧υＦΦ⊕θ⁼ι⊖Σ↨κ²Ｆζ⊞υ⁺κλ≧⁺№υθη»Ｉη

```

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

```
Ｎθ

```

Input `n`.

```
≔⁰η

```

Start with no partitions found.

```
⊞υ⁰

```

Start with `1` partition of `0` integers whose sum is therefore `0`.

```
ＦＬ↨θ²«

```

Loop over the potential lengths of the partitions.

```
≔υζ

```

Save the partitions found so far.

```
≔⟦⟧υ

```

Start collecting partitions of this length.

```
ＦΦ⊕θ⁼ι⊖Σ↨κ²

```

Loop over all integers up to `n` with the right number of bits set.

```
Ｆζ⊞υ⁺κλ

```

Add these integers to all of the previously found partitions.

```
≧⁺№υθη

```

Count how many equal `n`.

```
»Ｉη

```

Output the final total.
> 2 votes

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

```
f=(n,m,i=1,w)=>n<i?!n:!(w^m)*f(n-i,-~m)+f(n,m,i-~i,-~w)+f(n,m,i+i,w)

```

Try it online!

Very slow for `n>25`. Change `!(w^m)*f(...)` to `(w^m?0:f(...))` may be faster but cost +1 byte.
> 2 votes

# Answer
# Haskell, ~~77~~ 74 bytes

```
import Data.Bits
m!0=1
m!n=sum[(m+1)!(n-i)|i<-[1..n],popCount i==m]
g=(1!)

```

Try it Online!

-3 bytes thanks to Wheat Wizard

Port of tsh's Python answer.
> 2 votes

# Answer
# Python3, 156 bytes:

```
def f(n,i=1,c=0):
 if c==n:yield
 elif c<n:
  for k in range(1,n-c+1):
   if bin(k).count('1')==i and c+k<=n:yield from f(n,i+1,c+k)
g=lambda x:len([*f(x)])

```

Try it online!
> 1 votes

---
Tags: code-golf, binary, integer-partitions
---


# Question
Title: Nesting list with a value repeated `n` amount of times
Given the input of `n` and `value`. The code is supposed to nest the single element list with `value` repeated `n` times. The final output should be a multilevel nested list with single repeated values in all sublists.

This is , so the shortest code in bytes wins!

## Test cases:

```
n = 1, value = 'a': ['a']
n = 2, value = 'a': ['a', ['a']]
n = 3, value = 'a': ['a', ['a', ['a']]]
n = 4, value = 'a': ['a', ['a', ['a', ['a']]]]
n = 5, value = 'a': ['a', ['a', ['a', ['a', ['a']]]]]
n = 6, value = 'a': ['a', ['a', ['a', ['a', ['a', ['a']]]]]]

```

# Answer
# 05AB1E, 3 bytes

```
F‚Ù

```

Try it online.

**Explanation:**

```
F     # Loop the first input amount of times:
 ‚    #  Pair the (implicit) second input-value with the current list
  Ù   #  And uniquify it (which only does something in the first iteration,
      #  transforming the pair of values to a single wrapped value)
      # (after the loop, the result is output implicitly)

```
> 10 votes

# Answer
# Python 2, ~~33~~ 30 bytes

*-3 bytes thanks to @xnor*

```
lambda n,v:eval('[v,'*n+']'*n)

```

Try it online!
> 20 votes

# Answer
# Python, 34 bytes

```
f=lambda x,n:n and[x,f(x,n-1)][:n]
```

Attempt This Online!

Thanks to loopy walt for this one.

---

Old answers:

## Python, 36 bytes

```
f=lambda x,n:[x][n>1:]or[x,f(x,n-1)]
```

Attempt This Online!

## Python, ~~36~~ 35 bytes

```
f=lambda x,n:n*[1]and[[x]+f(x,n-1)]
```

Attempt This Online!

Outputs as a singleton list, but that feels like cheating here.

## Python, 39 bytes

```
f=lambda x,n:[x]+(~-n*[1]and[f(x,n-1)])
```

Attempt This Online!

## Python, 37 bytes

```
f=lambda x,n:x+(~-n*[1]and[f(x,n-1)])
```

Attempt This Online!

Inputs as a singleton list.
> 8 votes

# Answer
# Vyxal `r`, 4 bytes

```
(⁰"U

```

Try it Online!

The joys of golfing language :)

## Explained

```
(⁰"U
(     # n times:
 ⁰    #   push the value
  "U  #   pair and uniquify - a port of the 05ab1e answer

```
> 8 votes

# Answer
# Proton, 25 bytes

```
n=>v=>((a=>[v,a])*n)([v])

```

Try it online!

```
n=>v=>((a=>[v,a])*n)([v])    This language is stupid
n=>                          Given n
  v=>                        and v
       (a=>[v,a])            pair v with the current accumulator
                 *n          n times
      (            )([v])    and call that on [v]

```
> 7 votes

# Answer
# Wolfram Mathematica, ~~30~~ 21 bytes

```
Print[""@@#~Nest~##]&

```

-9 bytes from @att!

Try it online!

Sample I/O:

```
Print[""@@#~Nest~##]&@@{a,3}

```

> \[a\[a\[a\]\]\]

```
Print[""@@#~Nest~##]&@@{17,3}

```

> \[17\[17\[17\]\]\]

```
Print[""@@#~Nest~##]&@@{Pi,6}

```

> \\$\[\pi \[\pi \[\pi \[\pi \[\pi \[\pi \]\]\]\]\]\]\\$
> 6 votes

# Answer
# BQN, 9 bytes

```
∾⟜⋈´⥊⟜⋈⟜⋈

```

*Pins and bowties FTW*

Anonymous tacit function that takes two arguments and returns a nested list. This is why the list formatting looks weird. Run it online!

### Explanation

The left argument is the count; the right argument is the value. The example uses a left argument of `2` and a right argument of `0`.

```
∾⟜⋈´⥊⟜⋈⟜⋈
          ⟜⋈  Wrap the right argument in a list: ⟨ 0 ⟩, and then
       ⟜⋈     Wrap that list in a list: ⟨ ⟨ 0 ⟩ ⟩, and then
     ⥊        Reshape to a length equaling the left argument: ⟨ ⟨ 0 ⟩ ⟨ 0 ⟩ ⟩
    ´          Right-fold that list on this function:
 ⟜⋈             Wrap the right argument in a list: ⟨ ⟨ 0 ⟩ ⟩, and then
∾                Concatenate with the left argument: ⟨ 0 ⟩ ∾ ⟨ ⟨ 0 ⟩ ⟩ → ⟨ 0 ⟨ 0 ⟩ ⟩

```
> 6 votes

# Answer
# , 46 bytes

```
function(n,v)Reduce(list,rep(v,n-1),list(v),T)

```

Try it online!

Non-recursive approach. Pretty-printing and test harness taken from Dominic van Essen who insisted I post this as my own.
> 6 votes

# Answer
# Husk, 13 bytes

```
+J',R¹e'[²R']

```

Try it online!

Not an ideal challenge for a language that doesn't support ragged lists...

```
+              # join together:
    R¹         #  arg1 repeats of
      e        #   2-element list of
       '[      #    '[' and
         ²     #    arg2,
 J',           #  joined by commas,
               #  and
     R']       #  arg1 repeats of ']'

```
> 6 votes

# Answer
# Jelly, 5 bytes

```
W{Ɱṭ/

```

Try it online!

Value on left, \\$n\\$ on right

```
W        The value wrapped in a singleton list
 {Ɱ      for each 1..n.
   ṭ/    Reduce by Funky Reverse Append™.

```
> 5 votes

# Answer
# Ruby, ~~29~~ 23 bytes

```
->n,a{eval'[a,'*n+?]*n}

```

Try it online!

Stole the eval trick from dingledooper
> 5 votes

# Answer
# , 49 bytes

```
f=function(n,v)`if`(n-1,list(v,f(n-1,v)),list(v))

```

Try it online!
> 5 votes

# Answer
# Racket, 49 bytes

```
(define(f x n)(if(= n 1)`(,x)`(,x,(f x(- n 1)))))

```

Try it online!
> 5 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

```
t&@Do[t={#,t},Set@t;#2]&

```

Try it online!

Input `[n, value]`.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

0-indexed

```
Fold[List,{#},Table@##]&

```

Try it online!
> 4 votes

# Answer
# MathGolf, 5 bytes

```
a*Åαç

```

Outputs reversed (e.g. `[[["a"],"a"],"a"]` instead of `["a",["a",["a"]]]`), which is allowed based on the comments under the challenge.

Try it online.

**Explanation:**

```
a      # Wrap the (implicit) input-string into a list
       #  e.g. "abc" → ["abc"]
 *     # Repeat it the (implicit) input-integer amount of times
       #  e.g. 5 → ["abc","abc","abc","abc","abc"]
  Å    # For-each over these strings,
       # using the following 2 characters as inner code-block:
   α   #  Wrap the top two values into a list
       #  (which will wrap with the implicit loop-index 0 in the first iteration)
       #   e.g. [0,"abc"] in the first iteration
       #        [["abc"],"abc"] in the second iteration
       #        [[["abc"],"abc"],"abc"] in the third, etc.
    ç  #  Remove all 0s from the list with a falsey filter
       #  (only relevant for the first iteration: [0,"abc"] → ["abc"])
       # (after the loop, the entire stack is output implicitly as result)

```
> 4 votes

# Answer
# APL+WIN, 28 bytes

Prompts for n followed by value

```
(¯1↓∊n⍴⊂'[',⎕,','),(n←⎕)⍴']'

```

Try it online! Thanks to Dyalog Classic
> 4 votes

# Answer
# HBL, 11 bytes

```
1,(?(-.)(1('?(-.),)?)?

```

Try it!

### Explanation

A recursive function:

```
1,(?(-.)(1('?(-.),)?)?
1                       Cons
 ,                      the second argument with:
  (?(-.)                 If the first argument decremented is truthy (> 1):
        (1          )     Cons
          ('?     )        Recursive call with
             (-.)           First argument decremented
                 ,          Second argument unchanged
                   ?      with nil (empty list)
                         Else (the first argument is 1):
                     ?    Nil (empty list)

```

I.e., if the first argument is 1, we get `(cons arg2 nil)`, which simply creates a singleton list containing the second argument; and if the first argument is greater than 1, we get `(cons arg2 (cons [recursive-call] nil))`, which wraps the result of the recursive call in a singleton list and then prepends the second argument to it.
> 4 votes

# Answer
# PHP, ~~56~~ 55 bytes

```
function($n,$a){for($r=[$a];--$n;)$r=[$a,$r];return$r;}

```

Try it online!

Like often, PHP makes the worst score, akin only to C, but dirtier and with lots of $

EDIT: -1 byte, these dollars allow us some trickery with the parser after all
> 4 votes

# Answer
# PHP 50 bytes

```
function f($c,$n){return --$n?[$c,f($c,$n)]:[$c];}

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES6), 24 bytes

*-2 thanks to @tsh*

```
n=>g=x=>--x?[n,g(x)]:[n]

```
> 3 votes

# Answer
# PowerShell Core, 41 bytes

```
$n,$a=$args
1..$n|%{$r=$a,@($r)|?{$_}}
$r

```

Try it online!

Please note that this does not work for n = 1, for some reason PowerShell treats it as a string. Even when forcing to return an array.

Let me know if not OK and I'll withdraw this answer!
> 3 votes

# Answer
# Pari/GP, 29 bytes

```
f(a,n)=if(n--,[a,f(a,n)],[a])

```

Try it online!
> 3 votes

# Answer
# Charcoal, 15 bytes

```
ＦＮ≔⟦⁺⟦η⟧υ⟧υ⭆¹⊟υ

```

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

```
ＦＮ

```

Repeat `n` times...

```
≔⟦⁺⟦η⟧υ⟧υ

```

... prepend `value` to the initially predefined empty list, then wrap that in another list.

```
⭆¹⊟υ

```

Unwrap the very last wrapper list and pretty-print it.
> 3 votes

# Answer
# Pip `-p`, ~~14~~ 13 bytes

*-1 byte by porting Neil's Charcoal answer*

```
Lal:[lPEb]l@0

```

Try it online!

### Explanation

```
Lal:[lPEb]l@0
               l is empty list; a,b are command-line args
La             Loop a times:
        b       b
      PE        Prepended to
     l          Current list
    [    ]      Wrap that result in a singleton list
  l:            Assign back to l
          l    After the loop, l is our desired result wrapped in a singleton list
           @0  So get the first element
               and autoprint it, formatted as a list (-p flag)

```
> 3 votes

# Answer
# JavaScript (ES6), 27 bytes

```
f=(c,n)=>--n?[c,f(c,n)]:[c]

```

Try it out online.
> 3 votes

# Answer
# Lua, 50 bytes

```
n,v=...t={v}for i=2,n do t={v,t}n=n-1 end return t

```

Try it online!
> 2 votes

# Answer
# Retina, 31 bytes

```
L$`¶
$`*$([$', )$`*]
, (]+)$
$1

```

Try it online! Takes `n` and `value` on separate lines. Explanation:

```
L$`¶

```

Match the newline between `n` and `value`. This puts `n` in `$`` and `value` in `$'`.

```
$`*$([$', )$`*]

```

Wrap `value` in `n` lists.

```
, (]+)$
$1

```

Remove the trailing comma in the innermost list.
> 2 votes

# Answer
# C (clang), 56 bytes

```
i;f(*x,n){for(i=~n;++i<n;)printf(i<0?",[%s"-i/n:"]",x);}

```

Try it online!

Takes a string literal as *value* and *n* , prints to std out the result.

for(i=~n;++i<n;)      - iterate from -n to n

printf(i<0?  - select format string:
",[%s"-i/n..x)  * new nest, -i/n to skip comma at first stage
:"]"            * close nest
```
</code></pre>
> 2 votes

# Answer
# Python, 38 bytes:

```
f=lambda n,v:[v,f(n-1,v)]if n>1else[v]

```

Try It Online!
> 1 votes

# Answer
# , 53 bytes:

-7 bytes with `\` instead of `function`.

```
f=function(n,v)if(n>1){list(v,f(n-1,v))}else{list(v)}

```

Try it online!
> 1 votes

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


title: Verify Brainfuck program

text:
# Question
Title: Verify Brainfuck program
Yet another Brainfuck parsing problem, but this time... different.

> You are working in the Infinite Monkeys Incorporated, the company making Brainfuck programs, to solve various interesting problems (by accident, no less - after all, the company makes random programs). However, it appears that your fast Turing machines that only execute Brainfuck have a small and expensive problem with syntax errors - make one, and the computer explodes. It's probably a design flaw, but nobody had bothered to find why it happens.
>
> As Turing machines (especially fast ones) are expensive (after all, they have infinity RAM which costs), it would be better to make sure that the program doesn't have any syntax errors before executing the code. Your company is going to run lots of code, so manual verification won't work. Write a program that reads the STDIN for Brainfuck code, and exits with exit status set to anything other than 0 (error) if program has any syntax error (for example, `]` is a syntax error, because there is no matching `[`). Exit with exit status set to 0 if the program is completely fine.
>
> Make sure that your program correctly notices mistakes involving `[]`. You wouldn't want another computer to explode, would you? Oh, and make sure it's as short as possible - your boss pays for short programs (because he thinks they are fast, or something). Oh, and you don't have to code in Brainfuck (in fact, you cannot, because Brainfuck doesn't support exit codes) - your code will be ran on normal computer.

So, as you can see, your job is to check if Brainfuck program is "valid" (has paired `[]` symbols). Please note that Brainfuck programs can have other characters than `[]`, so don't refuse the program just because it has other commands. Smallest code wins, but probably you would care more about upvotes anyway.

# Answer
## GolfScript, 18 chars

```
.{[]`?)},~](`91?./

```

This code runs successfully with exit code 0 (and prints some garbage to stdout) if the square brackets in the input are balanced. If they are not, it fails with a non-zero exit code and prints an error message to stderr, e.g.:

```
(eval):2:in `/': divided by 0 (ZeroDivisionError)

```

or

```
(eval):1:in `initialize': undefined method `ginspect' for nil:NilClass (NoMethodError)

```

Since the challenge said nothing about output to stdout / stderr, I figure this qualifies. In any case, you can always redirect those to `/dev/null`.

### Explanation:

The code `{[]`?)},` strips everything but square brackets from the input, and the `~` evaluates the result as GolfScript code. The tricky part is that unbalanced brackets are perfectly legal in GolfScript (and, indeed, my code includes one!), so we need some other way to make the code crash.

The trick I'm using is to leave a copy of the input at the bottom of the stack, collect the entire stack into an array (using the unbalanced `]`) and shift the first element off. At this point, three things can happen:

* If the input ended in an unclosed `[`, trying to shift an element off an empty array will crash the interpreter (which, in this case, is exactly what we want!)
* If the brackets in the input were balanced, the shifted element will be the original input string.
* Otherwise (if the input had an unopened `]` or an unclosed `[`) it will be an array.

My original 14-char entry then compared the shifted value with a string, which would crash if it was a nested array. Unfortunately, it turns out that comparing a *flat* (or, in particular, empty) array with a string is also legal in GolfScript, so I had to switch tack.

My current submission, instead, uses a very brute-force method to tell arrays from strings: it un-evals them and tries to find the first occurrence of `[` (ASCII code 91), which will be zero if and only if the un-evaled variable was an array. If so, dividing the zero with itself triggers the desired crash.

Ps. Two other 18-char solutions are:

```
.{[]`?)},{.}%~](n<

```

and

```
.{[]`?)},~]([n]+n<

```

Alas, I haven't yet found a shorter way to solve the "empty array problem".
> 6 votes

# Answer
# Brainfuck 76 bytes

```
>>+[<+++++++++[->---------<]+>-[--[[-]<->]<[<[->-]>[<+]<]>]<[-<+>]+>,]<<[<+]

```

This goes out of it's bonds if square brackets are unbalanced turning the bf interpreter/compiler to fail runtime and some of them have exit codes to reflect that.

requires eof=0, wrapping values and finit number of cells

In Ubuntu you can use the interpreter `bf` (`sudo apt-get install bf`)

```
% echo '[[[]' | bf -n bf_matching.bf
Error: Out of range! Youwanted to '<' below the first cell.
To solve, add some '>'s at the beginning, for example.
an error occured
% echo $?
5
% bf -n bf_matching.bf < bf_matching.bf
% echo $?
0

```
> 19 votes

# Answer
# Befunge 98 - ~~26~~ ~~31~~ ~~20~~ 19 chars

```
~:']-!\'[-!-+:0`j#q

```

Got rid of some massive conditionals. Now the program works as follows:

```
~:   read an input char and duplicate it

']-! push a 1 if the char is the ] char, 0 otherwise

\    swap the comparison value for the duplicated input char

'[-! push a 1 if the char is the [ char, 0 otherwise

-    subtract the two comparison values. If the second one is 1, the first is 0,
     so the result is -1. Else if the second one is 0, the first is 1 and the result is
     1. Else, the first and the second are both 0 and the result is 0

+    Add the number to the counter (which is 0 if there is none already)

:0`  test if the counter is positive (that'd mean an invalid program). Pushes a 1 if
     positive, 0 otherwise.

j#q  if the counter is positive, then this jumps to the q. Otherwise, it skips the q
     and continues to the ~ at the beginning of the line. If there are no more chars in
     the input, then the IP will be sent back to the q.

```

`q` quits the program and pops the top value as an error value. The error value will be ~~-1~~ 1 if there are too many `]`'s, 0 if they are balanced, and ~~positive~~ negative if there are too many `[`'s. If the number is ~~positive~~ negative, then ~~that many~~ the absolute value of that number `]`'s are needed to balance the program.

**Edit:** Switched increment and decrement. `[` used to increment the counter and `]` used to decrement it. By switching it, I save 1 char, because for the exit condition, I only have to check if the counter is positive, rather than negative.

---

Old version

```
~:'[-!j;\1+\#;']-!j;1-#;:0\`j#q

```

This code works as follows:

```
~    read one char of input
:    duplicate it
'[-! push 1 if the character is [, 0 otherwise
j    jump that number of characters
;    skip until next ;
\1+\ increment counter

similarily for ].

#q when end of input is reached, ~ reflects the IP back. q ends the program with the error value on the stack.

```

**Edit:** realized that this accepted inputs like `][`, now it ends whenever the count gets negative, using

```
:0\`j

```
> 14 votes

# Answer
# ruby (64)

```
exit $<.read.tr('^[]','').tap{|x|0while x.gsub!('[]','')}.empty?

```

previously (68) it was:

```
exit ARGF.read.tr('^[]','').tap{|x| 0 while x.gsub!('[]','')}.empty?

```

Another equivalent solution uses

```
exit $<.read.tr('^[]','').tap{|x|0while x.gsub!('[]','')}.size>0

```

can't use `size` alone because it would give false negatives (!!!) when the total number of unbalanced brackets is multiple of 256
> 6 votes

# Answer
## J (~~38~~ 35)

```
exit({:+.<./)+/\+/1 _1*'[]'=/1!:1[3

```

Explanation:

* `1!:1[3`: read stdin
* `'[]'=/`: create a matrix where the first row is a bitmask of the `[`s in the input, and the second row is the `]`s.
* `1 _1*`: multiply the first row by 1 and the second row by -1.
* `+/`: sum the columns of the matrix together, giving delta-indentation per character
* `+/\`: create a running total of these, giving indentation level at each character
* `({:+.<./)`: return the GCD of the final element (`{:`) and the smallest element (`<./`). If all the braces match, both of these should be `0` so this will return `0`. If the braces do not match, it will return a nonzero value.
* `exit`: set the exit value to that and exit.
> 6 votes

# Answer
## Perl, 30 characters

Your basic Perl recursive regex to the rescue:

```
perl -0ne 'exit!/^(([^][]|\[(?1)\])*)$/'

```

For those unfamiliar with the command-line arguments used here: `-0` allows one to set the line-ending character for the purposes of file input; using `-0` with no argument sets the line-ending character to EOF. `-n` automatically reads the input (in this case, the entire file) into `$_` beforehand.

If the regex matches, it returns a true value, which is negated to 0 for the exit code. Otherwise, the false return value yields an exit code of 1.
> 5 votes

# Answer
## bash (tr + sed) - 42

```
[ -z `tr -Cd []|sed ":a;s/\[\]//g;t a"` ]

```

If you don't mind error messages then you can remove the last space between ``` and `]` to get length 41.
> 4 votes

# Answer
## Perl (56 chars)

```
$/=0;$r=qr/[^][]*(\[(??{$r})\])*[^][]*/;<>=~m/^$r$/||die

```

The obvious Perl solution: a recursive regex. Unfortunately it's a rather verbose construct.
> 3 votes

# Answer
# C, ~~73~~ 64 chars

Thanks to suggestions from breadbox (although this probably requires little-endian to work):

```
i;main(c){while(read(0,&c,1)*(i+1))i+=(c==91)-(c==93);return i;}

```

How it works:

* implicit int global `i` gets initialized to 0
* `c` becomes an implicit int which gets `argc` (initialized to 1 but we don't care, just as long as the higher bits aren't set)
* `read(0,&c,1)` reads a single character into the low byte of c (on little-endian architectures) and returns 0 at EOF; `i+1 != 0` unless the balanced bracket quote goes to -1; multiplying them together works as a (safe) boolean AND that takes one less char than `&&`
* `c==91` evaluates to 1 for `'['`, and `c==93` evaluates to 1 for `']'`. (There might be some fiddly bit-fiddling trick that would be smaller but I can't think of anything.)
* `return i` exits with status code 0 if it's balanced, non-zero if it isn't. Returning -1 technically violates POSIX but nobody actually cares about that.

Previous version:

```
main(i){char c;i=0;while(read(0,&c,1)*(i+1))i+=(c==91)-(c==93);return i;}

```
> 3 votes

# Answer
**Haskell (143)**

```
import System.Exit
f=exitFailure
v c []|c==0=exitSuccess|True=f
v c (s:t)|c<0=f|s=='['=v(c+1)t|s==']'=v(c-1)t|True=v c t
main=getContents>>=v 0

```

to jgon: Using 2 guards seems to be more dense than if-then-else. Also, I don't think yours checks that the brackets are in the right order ("\]\[" passes)
> 3 votes

# Answer
# Turing Machine Code, ~~286~~ 272 bytes

Again, I'm using the rule table syntax defined here.

```
0 * * l 1
1 _ ! r Q
5 _ _ r 5
5 * * * W
W [ ! l E
W ] ! l T
W _ _ l I
W * ! r *
E ! ! l *
E * * * R
R _ [ r O
R * * l *
T ! ! l *
T * * * Y
Y _ _ r U
Y * * l *
U [ _ r O
U ! ! * halt-r
I ! ! l *
I _ _ r halt
I * * l halt-r
O ! ! r Q
O _ _ l I
O * * r *
Q ! ! r *
Q * * * W

```

Terminates in state `halt` to accept the input and `halt-r` to reject it.
> 3 votes

# Answer
# Lua, 56

```
os.exit(("["..io.read"*a".."]"):match"^%b[]$"and 0 or 1)

```
> 2 votes

# Answer
# Ruby, ~~59~~ 58

Scans for opening and closing bracket, counting `[` as 1 and `]` as -1, and exits if the count drops below 0.

```
b=0
$<.read.scan(/\]|\[/){exit 1if(b+=92-$&.ord)<0}
exit b

```
> 1 votes

# Answer
## GTB, 55

```
0→O:0→X[`I@I="[":X+1→X@I="]":X-1→X@X<0:1→O@!!Ig;e]l;e~O

```

Misses `[]`

Use `0` to stop.
> 1 votes

# Answer
# Haskell (~~167~~,159)

Did this mostly for fun, if anyone's got any suggestions for how to make it shorter, I'd be glad to hear them tho :)

```
import System.Exit
p x y b|b=x|True=y
main=getContents>>=(return.all (>=0).scanl (\v->p (v-1) (v+1).(==']')) 0.filter (`elem`"[]"))>>=p exitSuccess exitFailure

```

**Edit:** Fixed an issue pointed out to me in the comments (added 11 bytes).

**Edit 2:** Created auxiliary function for testing predicates using guards inspired by user13350, removing 8 bytes.
> 1 votes

# Answer
## MATHEMATICA, 88 chars

```
s = "[ [ my crazy code ] [ don't explode please! [] [ :)Ahh) ]  [] []]]";

r=StringReplace;
StringLength@FixedPoint[r[#,"[]"-> ""]&,r[s,Except@Characters["[]"]-> ""]]

```
> 1 votes

# Answer
# Hassium, 104 Bytes

```
func main(){l=0;r=0;b=input();foreach (c in b){if(c=="[")l++;if(c=="]")r++;}if(!(r==l))exit(1);exit(0);}

```

Full expanded (note doesn't work in online interpreter as input() is disabled) here
> 1 votes

# Answer
# Stax, ~~14~~ 11 characters

```
╬Äτ↔EªÉs «Ü

```

Run and debug it

*Credit to @recursive for -3 bytes.*

ASCII equivalent:

```
.[]Y|&{yz|egp!

```

Remove all characters except `[]`, then remove `[]` until the string no longer changes. Return `1` if the final string is empty.
> 1 votes

# Answer
## Pyth, 25 bytes

```
Ilzv::z"[^[\]]"k"]\[""],[

```

Try it online!

Python 3 translation:
```
import re
z=input()
if len(z):
 print(eval(re.sub("]\[","],[",re.sub("[^[\]]","",z))))

```
> 1 votes

# Answer
# Vyxal, 10 bytes

```
‛[]↔øβ¬[°*

```

Try it Online!

The joys of having a balanced-bracket digraph.

## Explained

```
‛[]↔øβ¬[°*
‛[]↔       # remove all non "[]" from the input
    øβ¬    # are the brackets unbalanced?
       [°* # if so, multiply the input by the imaginary number `i`. Obviously you can't multiply a string by an imaginary number in python, so this errors.

```
> 0 votes

---
Tags: code-golf, decision-problem, balanced-string, brainfuck
---


title: Printing criss cross of two strings

text:
# Question
Title: Printing criss cross of two strings
Given a set of two strings guaranteed to be the same length, print their *criss cross*.

The *criss cross* of two strings is obtained as follows.

1. Yield the second character of the second string, then the first character of the first string.
2. Yield the first character of the second string, then the second character of the first string.
3. Discard the first character of each string.
4. If the strings have more than one character each, go back to step 1.

For example, if the two strings are

```
Truck
Tower

```

the *criss cross* is

```
oTTrwroueuwcrcek

```

as illustrated in the following diagram.

Each color represents a different iteration of criss-crossing. The numbers show the corresponding character's indices in the output.

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

```
żṚj@¥2\U

```

Try it online!

### How it works

```
żṚj@¥2\U  Main link. Arguments: s, t (strings)

          Arguments:    "Truck", Tower"
ż         Ziphwith; create all pairs of corresponding characters.
          Return value: ["TT", "ro", "uw", "ce", "kr"].
     2\   Reduce each pair of adjacent strings by the quicklink to the left.
    ¥       Combine the two links to the left into a dyadic chain.
 Ṛ            Reverse the left string.
  j@          Join the second string, using the previous result as separator.
          Map:          "TT", "ro" -> join("ro", "TT") -> "rTTo"
                        "ro", "uw" -> join("uw", "or") -> "uorw"
                        etc.
          Return value: ["rTTo", "uorw", "cwue", "kecr"]
       U  Upend; reverse each string.
          Return value: ["oTTr", "wrou", "euwc", "rcek"]
          (implicit) Flatten and print.

```
> 7 votes

# Answer
## JavaScript (ES6), 51 bytes

```
f=([G,...O],[L,...F])=>O[0]?F[0]+G+L+O[0]+f(O,F):''

```

```
f=([G,...O],[L,...F])=>O[0]?F[0]+G+L+O[0]+f(O,F):''

console.log(f("Truck", "Tower"))
```
> 8 votes

# Answer
## Haskell, ~~44~~ 38 bytes

*Crossed out 44 is still 44*

```
[_]#_=""
(a:b)#(x:y)=y!!0:a:x:b!!0:b#y

```

Slightly less golfed / maybe a little more readable:

```
[_]      # [_]      = ""
(a:b:bs) # (x:y:ys) = y:a:x:b:((b:bs) # (y:ys))

```
> 4 votes

# Answer
# Python 3, 56 bytes

```
f=lambda s,t:s[1:]and t[1]+s[0]+t[0]+s[1]+f(s[1:],t[1:])

```

Try it online!
> 4 votes

# Answer
# PowerShell, 71 bytes

```
param($a,$b)-join($a|% t*y|%{$b[+$i],$a[$i-1],$b[$i-1],$a[+$i]*!!$i++})

```

Try it online!

Less golfed:

```
param($a,$b)
-join(
    $a|foreach ToCharArray|foreach{  # transform each string from $a to an array and apply for each char...
        $CrissCross = $b[+$i],$a[$i-1],$b[$i-1],$a[+$i]
        $NotFirst   = !!$i++         # =0 if $i is 0; =1 if $i is not 0
        $CrissCross*$NotFirst        # repeat the $CrissCross array $NotFirst times
    }                                # and implicitly output
) # join all outputed chars to one string and implicitly output it as result

```
> 3 votes

# Answer
# PHP\>=7.1, 64 bytes

```
for([,$a,$b]=$argv;$c=$b[++$i];)echo$c,$a[$i-1],$b[$i-1],$a[$i];

```

PHP Sandbox Online
> 2 votes

# Answer
# PowerShell, 203 bytes

```
param($a,$b)$s=$k=@()
function q($x){$u=$x|% t*y;($u|%{$u[--$q]})-join''}
$a|% t*y|%{$s+=$_+$b[($i++)]}
$n=1;$s|%{$k+="$($s[$n][0])$(q($s[$n-1]))$($s[$n][1])";$n++}
($k[0..($k.length-2)]|%{q($_)})-join''

```

Try it online!

golfed, used negative indexing iteration for reversing array

# PowerShell, 210 bytes

```
param($a,$b)$s=$k=@()
function q($x){$u=$x|% t*y;[array]::reverse($u);$u-join''}
$a|% t*y|%{$s+=$_+$b[($i++)]}
$n=1;$s|%{$k+="$($s[$n][0])$(q($s[$n-1]))$($s[$n][1])";$n++}
($k[0..($k.length-2)]|%{q($_)})-join''

```

Try it online!

To Criss-Cross the string, I use the following algorithm:

* Take two strings: `Truck` and `Tower`
* Zip them and form a new array. Two zip them means to pair each character in the string with another, so it results an array with these 5 elements: `TT ro uw ce kr`
* Iterate the array in `0,1` `1,2` `2,3` pairs. So it results a new array in `TT ro` `ro uw` `uw ce` `ce kr` form.
* Iterate the array again and swap the elements in each iteration and reverse the new second element. So it results `ro TT` `uw or` `ce wu` `kr ec`
* Reverse each element in the array again and join them `oTTrwroueuwcrcek`!

**Code explanation**

* First take two parameters `$a` and `$b`, it is done using `param()` block
* Then define two empty arrays `$s` and `$k`, in Powershell Empty array is `@()`
* Then define a function `q` to reverse strings (I wonder why there is no string `.reverse()` method on .NET), First it takes a string `$x`, then defines `$u` as the character array of `$x` (`t*y` is the shorthand for `ToCharArray()` .NET string method, Powrshell can automatically expand it using `Foreach` loop), then reverse the `$u` array in-place using the `reverse()` static method of `[array]` type (`::` is used to invoke a static method), and at last, join the `$u` array with seperator `''` meaning nothing (`-join` is an operator which does that), which result in the reversed string
* Then again iterate over the character array of first string (`$a`, I have said in the previous step how character array works), and build a string with the each element of array (`$_` represents that, it is an automatic variable which contains the iterated element in an object supplied from pipeline) and `$i++`th index of `$b` string (You can see that I haven't defined `$i` anywhere, because it is not needed, in powershell non-declared variables are automatically assigned to 0, `++` operator increments a variable, and surrounding parentheses around this increments and then outputs the variable, no need to explicitly increment and use latter), and each builded string is added to the `$s` array through the assignment operator `+=` (Does the 2nd step in algorithm, no builtin Zip function in powershell)
* Then I declare another variable `$n` to value of 1 (a semicolon `;` is used to seperate statements and fit in a single line), iterate over the `$s` array, and build a string with the first character in `$n`th indexed element of the `$s` array, then `$n-1`th indexed element in the `$s` array and then the second (In fact the last, but negative indexing with `-1` would cost one more precious byte) character in `$n`th indexed element of the `$s` array and append to `$k` array using `+=` assignment operator, and increment `$n` variable using `++` operator at end (Does the 3rd and 4th step in algorithm, In python and some other languages it would be easier using enumeration and slicing)
* Then I iterate in the `$k` array with the last element removed (In powershell .NET `.RemoveAt()` method for removing array elements using index don't work for normal arrays), to do this I used indexing, first started index from 0 and ended 2 subtracted from array length, and `..` range operator is used to multiple index here, and I then apply `q()` function (reverse, that I built earlier), and parenthesise the whole expression to form an array, and then join it with `''` seperator using `-join` operator, and the string is implicitly outputted (Does the last step in algorithm, .NET has severe lack of builtins, at least it should have a map function!)
> 2 votes

# Answer
# , 14 bytes

```
[:,19&A.@,;._3

```

Try it online!

J's "Max cubes" verb `;._3` is made to order here. It works by creating a maximal "sliding window" and then using that to tile a matrix. So for example if we just box things to see how it works:

```
echo i.2 6

0 1 2 3  4  5
6 7 8 9 10 11

echo <;._3 i.2 6

┌───┬───┬───┬────┬─────┐
│0 1│1 2│2 3│3  4│ 4  5│
│6 7│7 8│8 9│9 10│10 11│
└───┴───┴───┴────┴─────┘

```

Now we just flatten each of those boxes `,`, apply the required permutation `19&A.`, and flatten the final result `[:,`.
> 2 votes

# Answer
# K (ngn/k), 17 bytes

```
,/{(|x),y}.'+2':'

```

Try it online!

Takes (implicit) input as a list of two strings, e.g. `f ("Tower"; "Truck")`.

* `+2':'` take 2-length sliding windows, transposing the results to obtain `(("To";"Tr");("ow";"ru");("we";"uc");("er";"ck"))`
* `{(|x),y}.'` apply the desired transformation to each pair of the above
* `,/` flatten the result
> 2 votes

# Answer
# C++14, ~~115~~ 112 bytes

As unnamed lambda, parameters should be like `std::string`:

```
#define P putchar(
[](auto A,auto B){for(int i=0;++i<A.size()&&i<B.size();P B[i]),P A[i-1]),P B[i-1]),P A[i]));}

```

Ungolfed and usage:

```
#include<iostream>
#include<string>

using namespace std;

#define P putchar(
auto f=
[](auto A,auto B){
 for(int i=0;
     ++i<A.size() && i<B.size();
     P B[i]),
     P A[i-1]),
     P B[i-1]),
     P A[i]));
}
;

int main(){
 string A="Truck",B="Tower";
 f(A,B);
}

```
> 1 votes

# Answer
# Factor, 101 bytes

```
2 clump [ reverse 1 group ] map concat swap 2 clump [ 1 group ] map concat swap [ write write ] 2each

```

Try it online!
> 1 votes

# Answer
# Vyxal `s`, 9 bytes

```
Z2lƛṠ÷$Ṙj

```

Try it Online!

```
Z         # Zip
 2l       # Slices of length 2
   ƛ      # Map...
    Ṡ     # Stringify
     ÷$Ṙj # Join second by first reversed

```
> 1 votes

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