title: Convert from Spoken Binary

text:
# Question
Title: Convert from Spoken Binary
This is an exact inverse of the question Convert to Spoken Binary. This introduction is copied from there.

> # Introduction
>
> In the video the best way to count, binary is proposed as the best system of counting numbers. Along with this argument is a proposal on how to say numbers in this system. First, we give names to each "double power of two", \\$2^{2^n}\\$ for each \\$n\\$.
>
> ```
> number = symbol = spoken
> ============================
> 2^0    = 1      = "one"
> 2^1    = 2      = "two"
> 2^2    = 4      = "four"
> 2^4    = H      = "hex"
> 2^8    = B      = "byte"
> 2^16   = S      = "short"
> 2^32   = I      = "int"
> 2^64   = L      = "long"
> 2^128  = O      = "overlong"
> 2^256  = P      = "byteplex"
>
> ```
>
> Then, to get from a number to its spoken binary, we
>
> 1. Take its (big-endian) bit string and break off bits from the end equal to the number of zeros in the largest double power of two less than or equal to the number.
> 2. Use the name for the corresponding double power of two in the middle, and recursively name the left and right parts through the same procedure. If the left part is one, it is not spoken, and if the right part is zero, it is not spoken.
>
> This system is similar to how we normally read numbers: 2004 -\> 2 "thousand" 004 -\> "two thousand four".

You can find examples of this procedure in the linked question.

To parse a number in spoken binary, do the opposite of the above, i.e.

1. Find the largest double power of two in the spoken binary (it is unique).
2. Recursively parse the sections to the left and the right through the same procedure (assuming one on left and zero on right if either are empty), and compute left * middle + right.

This system is similar to how we normally parse numbers: "two thousand four" -\> 2 * 1000 + 4 -\> 2004.

As an example,

```
"2H214"
"2" * 16 + "214"
2 * 16 + "21" * 4 + 0
2 * 16 + (2 + 1) * 4 + 0
44

```

# Challenge

Your program must take a string of symbols for the spoken binary of a positive integer \\$n\\$ as input and output the integer it represents in decimal.

While numbers under \\$2^{512}\\$ are expressible in this system, you only need to handle integers **up to and including** \\$2^{32}\\$ = `I`, and as such, do not need to consider `L`, `O`, or `P`. You only need to consider valid spoken binary strings; you do not need to handle cases like `HH`, `1H`, `H44`, `4121S` etc.

Standard loopholes are forbidden. As this is , shortest program wins.

# Example Input and Output

```
1 -> 1
2 -> 2
21 -> 3
4 -> 4
41 -> 5
42 -> 6
421 -> 7
24 -> 8
241 -> 9
242 -> 10
2421 -> 11
214 -> 12
H241 -> 25
2H214 -> 44
42H4 -> 100
21B2142H24 -> 1000
21421H21421B21421H21421S21421H21421B21421H21421 -> 4294967295
I -> 4294967296

```

If you need any more test cases, the answers to the linked question can help. Here is one TIO (Credit to @Nick Kennedy).

# Answer
> 1 votes
# Jelly, 26 bytes

```
W“ISBH42”ṣȯ"JŻƊṫ-ʋ€Ẏ¥ƒFOḂḄ

```

A monadic link that is called as a monad with a spoken binary string argument and returns an integer.

The test suite takes a list of integers, uses my answer to the companion challenge to make spoken binary and then converts it back.

Inspired by @Neil’s Charcoal answer so please be sure to upvote that one too!

## Explanation

```
W“ISBH42”ṣȯ"JŻƊṫ-ʋ€Ẏ¥ƒFOḂḄ
W                           # Wrap in a list
 “ISBH42”           ¥ƒ      # Reduce using the wrapped spoken binary string as the starting argument and each of "ISBH42" in turn as the right argument using the following dyadic chain:
                 ʋ€         # - For each list in the list of lists:
         ṣ                  #   - Split with the current character (from ISBH42); will return a list of either one or two pieces, either of which may be empty
              Ɗ             #   - Following as a monad:
          ȯ"J               #     - Or with the list indices (will replace empty pieces in the first and second position with 1 and 2 respectively)
             Ż              #     - Prepend zero
               ṫ-           #   - Take the last two
                   Ẏ        # - Join outer lists
                      F     # Flatten
                       O    # Convert to Unicode code points (will convert "1" to 49 and leave the existing 1s and 2s alone)
                        Ḃ   # Mod 2
                         Ḅ  # Unitary (convert from base 2)

```

Created with the help of Luminespire.

## Original answer, Jelly, 41 bytes

```
>oḊ$k⁸ṣȯ"1,0Fæ.ʋċ¡€F
“24HBSI”iⱮ’2*2*ḞṢçƒ$

```

A pair of links that is called as a monad with a spoken binary string argument and returns an integer (wrapped in a length 1 list). When called as a full program will print the integer implicitly.

In brief this works like this:

1. Convert from spoken binary digits to the relevant powers of 2 (e.g. `B` -\> `256`)
2. Work up through each digit in ascending order; find sublists of between 1 and 3 adjacent integers which are not greater than the relevant digit (e.g. `3, 4, 1` if the current digit is `2`).
3. Within each sublist, multiply the current digit by the prefix if there is one (or by 1 if none) and add any suffix if there is one. So for the example above, `3, 4, 1` becomes 13.
4. Continue until all of the digits have been used (and so we have a single final integer result).

# Answer
> 3 votes
# Ruby, ~~91~~ 88 bytes

```
->(s){s.each_char.reduce(0){|x,a|v=2**(2**("124HBSI".index a)/2);x%v>0?x+x%v*(v-1):x+v}}

```

Try it online!

I'm only posting this one because I didn't see one remainder based approach. Basically, for each digit, we decide if we're adding it as it is, or using it as a multiplier. If we've seen something smaller than the current digit, then whatever is smaller should be multiplied, else we just add the digit.

Thanks @Neil for -3 bytes!

# Answer
> 2 votes
# JavaScript (Node.js), ~~78~~ 76 bytes

```
f=(x,i=6,z)=>i--?x.split('24HBSI'[i]).map(s=>z=(z|z<1)*2**2**i+f(s,i))&&z:+x

```

Try it online!

# Answer
> 2 votes
# Charcoal, 34 bytes

```
⊞υ⮌ＳＦISBH42≔ΣＥυ…⊞ＯＥ⪪κι∨μＩν0²υＩ⍘⮌υ²

```

Attempt This Online! Link is to verbose version of code. Will produce values up to `18446744073709551615`. Explanation:

```
⊞υ⮌Ｓ

```

Start with the reverse of the input in a single piece.

```
ＦISBH42

```

Work down from the highest double power of two to the lowest.

```
≔ΣＥυ…⊞ＯＥ⪪κι∨μＩν0²υ

```

Split each piece into two, defaulting the first piece to `0` and the second piece to `1`, but if the split only resulted in one piece then pad it with a `0` piece. Examples: `2` splits on `2` to give two empty strings, so the first becomes `0` and the second `1`, representing `10` in binary; `21` splits on `2` to give `1` and an empty string, the latter becoming `1`, representing `11` in binary; `1` splits on `2` to give `1`, which is padded with a `0`, representing `01` in binary.

```
Ｉ⍘⮌υ²

```

The reversed list is now a list of binary digits so convert it to decimal.

A port of @Pufe's Ruby answer is also 34 bytes:

```
≔⁰θＦＥＳＸ²÷Ｘ²⌕124HBSIι²≧⁺∨×﹪θι⊖ιιθＩθ

```

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

```
≔⁰θ

```

Start with zero.

```
ＦＥＳＸ²÷Ｘ²⌕124HBSIι²

```

Map the characters of the input string to the double powers of `2` and loop over the results.

```
≧⁺∨×﹪θι⊖ιιθ

```

Add on the current value modulo the current power multiplied by one less than the current power, unless that is `0`, in which case just add on the current value.

```
Ｉθ

```

Output the final result.

# Answer
> 1 votes
# APL(Dyalog Unicode), ~~57 55~~47 bytes SBCS

```
{⍵≡⍬:0⋄⍵(∇⍤↓+⌷×1⌈∘∇¯1↓↑)⍨⊃⍒⍵}2*∘⌊2*6-'ISBH42'∘⍳

```

Try it on APLgolf!

-8 bytes thanks to att.

## Explanation

```
{⍵≡⍬:0⋄⍵(∇⍤↓+⌷×1⌈∘∇¯1↓↑)⍨⊃⍒⍵}2*∘⌊2*6-'ISBH42'∘⍳
                                     'ISBH42'∘⍳  ⍝ indices of input in 'ISBH42'
                                   6-            ⍝ subtract from 6
                                 2*              ⍝ 2 to that power
                             2*∘⌊                ⍝ 2 to floor of that
                             2*∘⌊2*6-'ISBH42'∘⍳  ⍝ converts the symbols to numbers
 ⍵≡⍬:                                            ⍝ if passed empty vector:
     0                                           ⍝ return 0
      ⋄                                          ⍝ else:
                          ⍒⍵                     ⍝ indices to sort descending
                         ⊃                       ⍝ first
                         ⊃⍒⍵                     ⍝ index of maximum
       ⍵                                         ⍝ input vector
        (              )⍨                        ⍝ reverse the left and right arguments
                      ↑                          ⍝ take vector up to the max value
                   ¯1↓                           ⍝ drop the last element
                  ∇                              ⍝ apply this dfn
               1⌈∘                               ⍝ max with 1
             ⌷×                                  ⍝ times the max value (via indexing)
            +                                    ⍝ plus
           ↓                                     ⍝ drop vector up to and including max value
         ∇⍤                                      ⍝ apply this dfn

```

Created with the help of Luminespire

# Answer
> 1 votes
# Retina, ~~127~~ 125 bytes

```
21
3
(?<!\d)[4H]|(?<![\dH])B|^S
1$&
I
1SS
S
BB
(\d)4(\d?)
$.($1*4*_$2*
(\d+)H(\d*)
$.($1*16*_$2*
+`(\d+)B(\d*)
$.($1*256*_$2*

```

Try it online! Link is to test suite that converts the first number on each line. Explanation:

```
21
3

```

`2` always has an implicit `1` preceding it. If it also has a `1` following it, that's then `3`.

```
(?<!\d)[4H]|(?<![\dH])B|^S
1$&

```

Put in explicit `1`s in places that need them.

```
I
1SS

```

Special-case `I` as we only need to support a lone `I`. (Although this will actually work for numbers up to but not including `IS`.)

```
S
BB

```

Change `S` to `BB` as we can multiply by `256` twice without ambiguity. (See below.)

```
(\d)4(\d?)
$.($1*4*_$2*

```

For each `4`, multiply the digit before by `4` and add any digit after. Conveniently after this stage all the decimal digits are now part of the computation rather than the input.

```
(\d+)H(\d*)
$.($1*16*_$2*

```

For each `H`, multiply the number before by `16` and add any number after.

```
+`(\d+)B(\d*)
$.($1*256*_$2*

```

For each `B`, multiply the number before by `256` and add any number after. Examples for multiple `B`s:

* `S1``1BB1``256B1``65537`
* `SB1``1BB1B1``256B257``65793`
* `BSB1``1BBB1B1``256BB257``65536B257``16777473`
* `B1SB1``1B1BB1B1``257BB257``65792B257``16843009`.

---
Tags: code-golf, number, parsing, binary
---


title: Roguelike pathfinding

text:
# Question
Title: Roguelike pathfinding
# Roguelike pathfinding

Your task will be, given a two-dimensional array of the elements described below, which represents a dungeon, to output or return a single number representing the amount of gold pieces the rogue can collect without waking up any monsters.

The elements of the array are as follows:

1. Empty spaces are represented by either `.` or a space, your call;
2. Rogue's starting position is represented by, of course, `@`;
3. A gold piece is represented by `$`;
4. Walls are represented by `#`;
5. Monsters are represented by characters from the following regexp: `[a-zA-Z*&]`.

The array shall not contain any characters not listed above, so you can assume that anything that is not a wall, an empty space, the rogue or a gold piece is a monster.

The rules for pathfinding are:

1. The rogue can only walk through empty cells or cells containing gold;
2. It takes a turn to move to a adjacent or diagonally adjacent cell;
3. Picking up the gold is instant;
4. The rogue can't stay adjacent or diagonally adjacent to a monster for more than one turn without waking it up, which is forbidden;
5. The rogue can enter the awareness area of a monster any number of times, the monster will only wake up if the rogue spends two *consecutive* turns near it.

# Input and output rules

You can get the input in any reasonable format, including a two-dimensional array, a flat array, a string or whatever else. If it makes your life easier, you may also take the dimensions of the array as well.

It's guaranteed that the rogue will not be near a monster at the beginning.

A full program or a function is fine.

# Scoring

This is , the score is the bytes count of your submission with fewer being better.

# Test cases

I use dots for empty spaces here for readability purposes, if you so desire you may use spaces (see above). Also note that this is a pure coincidence that the rogue is always in the upper-left corner, your code should handle any other valid position as well.

```
1)
@..
.$.
...  -> 1

```

Just a sanity test.

```
2)
@....
...g$
.....  -> 0

```

Again, a sanity test.

```
3)
@....
...$g
.....  -> 1

```

The rogue can grab the gold by moving in from the left.

```
4)
@....g..
.......$
........
.....h..  -> 1

```

The rogue can zig-zag between the monsters, never staying for more than one turn near each.

```
5)
@....z..
.......$
.....b..  -> 0

```

The tactics from the previous test case don't work here - the monster sensitivity areas overlap.

```
6)
@$#.
###$
....  -> 1

```

Sanity test.

```
7)
@..#..
$.$g.$
...#..  -> 2

```

Ditto.

```
8)
@#.d#$
$...##
e.....
..$...
##..$b
.#..g$  -> 3

```

Of all the gold here, only three can be reached safely: the gold near the starting position can be got by moving down one and then back to the starting position. To escape from the top left corner the rogue has to move diagonally down-right twice. The gold in the middle poses no challenge. The outer gold guarded by `g` and `b` can be got by moving in diagonally from the place to the right of the middle gold and then back. The rest cannot be got: top-right gold is blocked by walls, and the bottom-right gold requires two turns in monster sensitivity areas.

The following test cases were generously donated by mbomb007.

```
9)
  12345678
a @....g.D
b .......$
c ......#.
d .....h..  -> 1

```

This one is tricky. A path is `b4-b5-c6-b7-c8-b8(grab)`.

```
10)
  12345678
a @....g.D
b .......$
c .......#
d .....h..  -> 1

```

A path is `[bc]4-c5-b6-c7-b8(grab)`.

```
11)
  12345678
a @....g.D
b ......#$
c .......#
d .....h..  -> 1

```

The extra wall doesn't actually change anything, `[bc]4-c5-b6-c7-b8(grab)` is still a solution.

# Answer
previous solutions (part of them) can be found in the footer container in the tio link (those are probably more readable)

# JavaScript (Node.js),883 436 411 360,345 311 bytes

```
g=>g.map((r,y)=>[...r].map((c,x)=>A+=c=="$"&&P(g,x,y)),A=0)|A
P=(g,x,y,m={},p={},I=i=9,M={})=>{if(/[.$]/.test(c=(g[y]||0)[x])){for(;i--;)if(/^[^.@$#]$/.test(C=(g[y+~-(i/3)]||0)[x+i%3-1])){if(m[C])return
M[C]=1}for(;I--;)if(!p[(X=x+~-(I/3))+","+(Y=y+I%3-1)]&&P(g,X,Y,M,{...p,[x+","+y]:1}))return 1}return c=="@"}

```

Try it online!

# Explantion -

instead of going from the player to the cash i went from the case to the @. i think i should be faster because i know when to stop looking (reach the @) , and when you look for cash you need to always keep moving until you covered all of the spots (and the ways to get to them). so the algo is pretty simple that way - the main function `g.map((r,y)=>[...r].map((c,x)=>A+=c=="$"&&P(g,x,y)),A=0)|A`: find cash -\> if you found it -\> start looking for the player -\> if you found him -\> increment A now lets got to the path finder aka P `if(/[.$]/.test(c=(g[y]||[])[x]))` just check if the current cell is "special" -\> if so we want to return if its a player. special cases : @#(monster)

`for(;i--;)
if(/^[a-zA-Z*&]$/.test(C=(g[y+~-(i/3)]||0)[x+i%3-1])) -> if my neighbor is a monster
{if(m[C])return false -> and it already was in the previous turn - this path is not value
M[C]=1} -> if not just add it to the neighbors monsters` `for(;I--;)
if(!p[(X=x+~-(I / 3))+","+(Y=y+I%3-1)]&&P(g,X,Y,M,{...p,[x+","+y]:1}))return true` iterate neighbors again - if i wasn't already there (p is the path taken) continue path (call P)
> 5 votes

# Answer
# Python3, 710 bytes

```
E=enumerate
def F(s,c,C,O,e,M,x,y,U):
 r=[]
 for X,Y in s:e[(x,y)]=e.get((x,y),[])+[((X,Y),c)];r+=[(O+[(x,y)],X,Y,c+C*((X,Y)not in U),M,U+[(X,Y)]*C)]
 return r
def f(b):
 d,D={4:[]},[]
 for x,r in E(b):
  for y,v in E(r):d[K]=d.get(K:=[[[[4,3][v=='$'],2][v=='#'],1][v=='.'],0]['@'==v],[])+[(x,y)];D+=[(x,y)]
 C,e=[],{}
 q=[([],*d[0][0],0,set(),[])]
 while q:
  O,x,y,c,M,U=q.pop(0)
  if c==len(d[3]):return c
  o={a:[(x+X,y+Y)for X,Y in[(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]if(P:=(x+X,y+Y))in b and[]==[1 for(J,K),w in e.get((x,y),[])if(J,K)==P and w>=c]]for a,b in d.items()}
  if not M&{*o[4]}:C+=[c];q=F(o[3],c,1,*(P:=[O,e,{*o[4]},x,y,U]))+q+F(o[1],c,0,*P)+F(o[0],c,0,*P)
 return max(C+[0])

```

Try it online!
> 1 votes

---
Tags: code-golf, grid, path-finding
---


# Question
Title: Inscribe a maximal regular polygon into a square image
You want to draw a regular polygon but you have limited space! In this challenge, you should draw a polygon with n sides which is as big as possible for a given square container image.

I found surprisingly little information on the Internet about inscribing a polygon into a square. To save you the hassle, I verified that in almost all cases one of the vertices is on the diagonal of the square. The diagram below marks the center of the polygon and some important segments. One exception is when n in divisible by 8: then the maximal polygon has 4 sides parallel to the sides of the square.

If you want to skip the math, here are the lengths of the blue and magenta segments:

> where ⌊x⌉ means x rounded to nearest integer

These formulas are only correct for n not divisible by 8; when it's divisible by 8, the math is much easier (an exercise for the reader).

Input: a number n in the range 3...16 inclusive.

Output: a square image with a maximal regular n-gon

* Draw just the boundary of the polygon or fill it - whatever is easier
* The dimensions of the output image should be the same for all n
* Width of the image should be exactly equal to height; alternatively, make a rectangular image, but then also draw the containing square
* The regular polygon must be the biggest one that can fit in the image or in containing square
* Any orientation
* If you make a raster image, the dimensions of the containing square must be at least 200 pixels

Examples (using different styles but you should pick one):

3:

7:  (with bounding rectangle)

12:  (with bounding rectangle of same colour)

16:  (filled)

# Answer
# , 124 bytes

```
\(n)plot(rbind(p<-cbind(cos(t<-(1:n/n+1/8+(!n%%8)/2/n)*2*pi),sin(t)),p[1,]),t="l",ann=F,xaxt="n",yaxt="n",xaxs="i",yaxs="i")

```

Attempt This Online! \- no graphical output

A function taking a single argument \\$n\\$ and plotting a polygon with \\$n\\$ sides circumscribed by a square. If \\$n \bmod 8 ≠ 0\\$ then one of the polygon’s points will be at 45°; otherwise one of them will be at 360/2n°. The points are then calculated using sin and cos. R’s plot function will plot the bounding square and maximise the polygon to that square. The rest of the code is just ensuring there’s nothing additional plotted like axes titles and ticks.

*Thanks to @pajonk for saving a byte!*
> 3 votes

# Answer
# JavaScript (ES2019), 216 bytes

```
f=
n=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${[l=(M=Math).min(...b=(a=[...Array(n)].map((_,i)=>[M.sin(w=((i*2+!(n%8))/n+.25)*M.PI),M.cos(w)])).flat()),l,l=M.max(...b)-l,l]}"><path d="M${a.join`L`}Z"/></svg>`
```

```
html{height:100%;display:flex;}body{display:flex;flex-direction:column;align-items:start;}img{flex:1;}
```

```
<input type=number min=3 max=16 oninput=o.src="data:image/svg+xml,"+f(+this.value)><img id=o>
```

The function, here assigned to `f` for convenience of the test snippet, outputs an SVG of the polygon filled in black, which the test snippet converts to a `data:` URL so that it can set it as the source of the image.
> 2 votes

# Answer
# LOGO, ~~195~~ 192 bytes

```
TO p :n
make "u 0make "v .1 pu
for[i 0 32][make "a(:i*2+not :n%8)*180/:n+45make "x cos(:a)if :x<:u[make "u :x]if :x-:u>:v [make "v :x-:u]if :i>15[pd]setxy (:x-:u)*99/:v ((sin :a)-:u)*99/:v]END

```

Run at https://www.calormen.com/jslogo/

Call the procedure like this: `p 16`

Recommended to do `cs p 4` to clear the screen and draw a bounding box. `ht` and `st` hide and show the turtle.

The loop starts with a `pu` to lift the pen up and always iterates 32 times. This ensures the correct minumum and maximum values of `x = cos a` are contained in `u` and `v`. After 16 iterations the pen is put down with `pd` and the polygon is drawn at the correct scale.
> 0 votes

---
Tags: code-golf, math, graphical-output
---


title: How many points this side of the line

text:
# Question
Title: How many points this side of the line
# Input

An integer n and a pair of distinct integer valued (x, y) coordinates on the boundary of the grid. The coordinates are indexed from 1. For example, n=10 and (1,2), (10, 7).

The points will always be on different sides of the grid and neither of them will be \\$(1, 1)\\$.

# Output

The number of integer points in an n by n grid that are on the same side of the line as the coordinate (1,1). Points that are exactly on the line should be counted as well.

# Examples

For n=10 and (1,2), (10, 7),

The output should be 41.

For n=8 and (8, 3), (3, 8),

The output should be 49.

For n=8 and (7, 1), (8, 2),

The output should be 63.

For n=8 and (1, 2), (2, 1),

The output should be 3.

# Answer
# APL+WIN, ~~32~~ 40 bytes

Plus 8 bytes to comply with the question as it is now written. Works for all four examples given.

Prompts for x coordinates followed by y coordinates and then grid size

```
+/,0≤(↑n)×n←×n∘.-⌊(⊃1,¨n←⍳⎕)+.×⎕⌹⎕∘.*0 1

```

Try it online! Thanks to Dyalog Classic
> 3 votes

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

```
(n,a,b,c,d,g=(x,y)=>(~y+b)*(c-a)-(~x+a)*(d-b))=>[...Array(s=i=n*n)].map(_=>s-=g(--i%n,i/n)*g()<0)|s

```

Try it online!

1-index
> 2 votes

# Answer
# Charcoal, 35 bytes

```
≔…·¹ＮθＮηＮζ≔×⁻θζ⁻ＮηεＩΣ⭆×⁻θη⁻Ｎζ⭆ε¬‹ιλ

```

Try it online! Link is to verbose version of code. Takes five inputs starting with `n`. Explanation:

```
≔…·¹Ｎθ

```

Create a range from `1` to `n`.

```
ＮηＮζ

```

Input the first point.

```
≔×⁻θζ⁻Ｎηε

```

Input the x-coordinate of the second point and subtract the x-coordinate of the first point from it, then for each integer from `1` to `n` multiply that by the y-coordinate subtracted from that integer.

```
ＩΣ⭆×⁻θη⁻Ｎζ⭆ε¬‹ιλ

```

Input the y-coordinate of the second point and subtract the y-coordinate of the first point from it, then for each integer from `1` to `n` multiply that by the x-coordinate subtracted from that integer. Pair the elements of this array with those of the previous array and count the number of parings where the element of this array does not exceed the element of the previous array.

Note: The output depends on the input points being entered in the correct order. The inputs for the other test cases are as follows:

* `8 3 8 8 3`
* `8 8 2 7 1`
* `8 1 2 2 1`
> 2 votes

# Answer
# Python 3.8, 109 bytes

```
lambda n,x,y,X,Y:sum(((a:=(Y-y)/(d:=x*Y-X*y))*-~(K%n)+(b:=(x-X)/d)*-~(K//n)-1)*(a+b-1)>=0for K in range(n*n))

```

Try it online!

(Even) Econ majors will know that a line can be described by the equation \\$ax+by=1\\$. So this solution just computes \\$ax+by\\$ for each point on the grid and compares it to \\$1\\$.
> 2 votes

# Answer
# Jelly, 15 bytes

```
_þḢU×_/}Z>þ/¬SS

```

Try it online!

A dyadic link taking \\$n\\$ as the left argument and the points as the right argument as a list of two lists of integers.

This is loosely a Jelly translation of @Neil’s Charcoal answer so please upvote that one too!

## Explanation

```
_þ              | Outer using subtract (will implicitly turn n into 1..n)
  Ḣ             | Head
   U            | Reverse order of innermost lists
    ×_/}        | Multiply by the difference between the two points
        Z       | Transpose
         >þ/    | Outer using greater than
            ¬   | Not
             SS | Sum and then sum again

```
> 1 votes

# Answer
# Haskell, 86 bytes

```
n#(a,b,c,d)|(%)<-(\x y->(c-a)*(y-b)-(d-b)*(x-a))=sum[1|i<-[1..n],j<-[1..n],i%j*1%1>=0]

```

Try it online!
> 1 votes

---
Tags: code-golf
---


# Question
Title: golf a range with modulus and subtraction
if you have a range of numbers with values missing, eg `l=[1,2,9,10,99]`, you can always use modulus and subtraction to make all the numbers in the list cover a smaller range, for example: `l%99%6=[1,2,3,4,0]`. your task is to take in a list of numbers and output an equation which will map them to unique numbers in the range `0..len(list)`. a sample method for determining such an equation for any range is below, but there are likely easier ways to do this as it's just something I came up with right now.

the sample list will be `l=[2,1,5,3,99,7,6]`

1. to get it into a format we can work with, sort the list and subtract the minimum value from each number:
    * `sorted(l)-1=[0,1,2,4,5,6,98]`
2. to find the first break, subtract the index of each number:
    * `tmp=[0,0,0,1,1,1,92]`
3. subtract the number which came after the break:
    * `sorted(l)-1-4=[-4,-3,-2,0,1,2,94]`
4. mod your whole list by `highest-lowest+1`: `(94)-(-4)+(1)`
    * `(sorted(l)-1-4)%99=[95,96,97,0,1,2,94]`

```
repeat

```
1. `sorted((sorted(l)-1-4)%99)-0=[0,1,2,94,95,96,97]`
2. `tmp=[0,0,0,90,91,92,93]`
3. `sorted((sorted(l)-1-4)%99)-0-94=[-94,-93,-92,0,1,2,3]`
4. `(sorted((sorted(l)-1-4)%99)-0-94)%98=[4,5,6,0,1,2,3]`

now that we have a 0-6 range, we can output our equation: `((l-5)%99-94)%98` (which gives us `[2,1,4,3,0,6,5]` on the original input)

by the nature of the way this method works you'll never need to loop more than `len(list)` times, looping extra times will not affect the values in the list, and you can stop as soon as you get a `tmp` with all 0 values.

so shortest code in bytes wins. to be considered valid, a solution must be able to take input representing a unique, non-negative list of numbers and give back something representing an equation which will make the list of numbers have unique, non-negative values between 0 and one less than the length of the list.

you may assume that each value of the initial list will be unique, but you may **not** assume they will be in order, and they do **not** need to end up in the same order. (eg your equation may transform a list \[8,0,2,3,5\] to anything like \[4,1,2,3,0\] or \[3,1,4,2,0\] or \[2,3,4,0,1\] etc). you do not need to worry about parenthesis if you don't want to, you can just output a series of subtraction and modulus operations in order (just say in your answer what format your output takes).

# Answer
> 1 votes
# Charcoal, 53 bytes

```
≔lηＷΦθ⁻…⌊θκθ«≔⊕⁻⌈θ⌊θζ≔⪫⟦(η-⌊ι)%ζ⟧ωη≧⁻⌊ιθ≧﹪ζθ»η¿⌊θ⁺-⌊θ

```

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

```
≔lη

```

Start with just the name of the list.

```
ＷΦθ⁻…⌊θκθ«

```

Repeat while there is a break in the list.

```
≔⊕⁻⌈θ⌊θζ

```

Calculate the span of the list.

```
≔⪫⟦(η-⌊ι)%ζ⟧ωη

```

Update the equation for the break and span.

```
≧⁻⌊ιθ≧﹪ζθ

```

Update the list for the break and span.

```
»η

```

Output the equation.

```
¿⌊θ⁺-⌊θ

```

Handle the case where there was no break in the list.

# Answer
> 1 votes
# Jelly, 7 bytes

```
ṢṚ+J-;Ɱ

```

A monadic link which is called as a monad with a single argument, an unsorted list of non-negative integers, and returns a list structured as `[[s1, m1], [s2, m2], …]` where there are pairs of subtraction (`- sn`) and modulo (`% mn`) steps.

The test suite has three fixed examples followed by a randomly generated fourth example. It also proves that the supplied result works; the header encodes a dyadic link that takes the result as detailed above as its left argument and the original list of integers as the right; it returns the list of integers from 0..(len(n) - 1) that results from applying the specified transformations.

## Explanation

```
Ṣ       | Sort
 Ṛ      | Reverse
  +J    | Add 1-indexed indices
    -;Ɱ | Prepend each with -1

```

Extends @l4m2’s observation that a series of plus ones can be used to simplify the task.

## Original answer, Jelly, 25 bytes

```
’¹ƇŻÄạ
ṢI’k$§$żçɗṀ_Ṃ‘ƲṖṭṂ

```

A pair of links which is called as a monad with a single argument, an unsorted list of non-negative integers, and returns a list structured as `[s0, [[s1, m1], [s2, m2]]]` where `s0` is an initial subtraction step and then there are zero or more pairs of subtraction (`- sn`) and modulo (`% mn`) steps.

The test suite has three fixed examples followed by a randomly generated fourth example. It also proves that the supplied result works; the header encodes a dyadic link that takes the result as detailed above as its left argument and the original list of integers as the right; it returns the list of integers from 0..(len(n) - 1) that results from applying the specified transformations.

## Explanation

```
’¹ƇŻÄạ
ṢI’k$§$żçɗṀ_Ṃ‘ƲṖṭṂ

’¹ƇŻÄạ              # Helper link: takes a list of increments as its left argument and the range + 1 of the original list as its right and returns the modulos needed (with a redundant final one)
’                   # Subtract 1
 ¹Ƈ                 # Keep only those which are non-zero
   Ż                # Prepend a zero
    Ä               # Cumulative sum
     ạ              # Absolute difference (from the range + 1)

ṢI’k$§$żçɗṀ_Ṃ‘ƲṖṭṂ  # Main link
Ṣ                   # Sort
 I                  # Increments
         ɗṀ_Ṃ‘Ʋ     # Following as a dyad, with the increments as the left argument and (max - min + 1) of the original list as the right
      $             # - Following as a monad:
  ’k$               #   - Split the list of increments after any which are >1
     §              #   - Sum inner lists
       żçɗ          # - Zip with the results of calling the helper link with the increments as the left argument and the range + 1 as the right
               Ṗ    # Remove the last member of the list
                ṭṂ  # Tag onto the minimum of the original list

```

Created with the help of Luminespire.

In brief, this works by separately constructing the right hand arguments needed for subtraction and the modulo separately. The arguments for subtraction are the increments, except where there are consecutive numbers (i.e. increments of 1), these are collapsed into the next non-consecutive one. The arguments for modulo start with the range + 1 and decrease each time by the non-consecutive gaps - 1.

# Answer
> 1 votes
# Python 3.8 (pre-release), 56 bytes by Nick Kennedy

```
lambda x:[[-1,z+i]for(i,z)in enumerate(sorted(x)[::-1])]

```

Try it online!

Each pair to subtract then modulo

# Python 3.8 (pre-release), 93 bytes

```
lambda x:['-',p:=min(x)]+g(sorted(x),p)
g=lambda x,p:x and['+',1,'%',x[-1]+1-p]+g(x[:-1],p-1)

```

Try it online!

That's why I need `+`

# Answer
> 0 votes
# Google Sheets, 87 bytes

```
=let(a,transpose(split(A1,",")),index(a-sort(mod(sequence(count(a)),count(a)),a,1)))

```

Put a string like `2,1,5,3,99,7` in cell `A1` and the formula in cell `B1`.

> *something representing an equation which will make the list of numbers have unique, non-negative values between 0 and one less than the length of the list*

The output is returned as a vertical array with values like `0,0,1,0,99,1,1`. It is a list of numbers to subtract from each value in `A1` in turn, using an equation like \\$r\\$\\$i\\$ = \\$a\\$\\$i\\$ \- \\$o\\$\\$i\\$ where \\$i\\$ ∈ (0, length of list\].

---
Tags: code-golf
---


# Question
Title: Output an infinitely proportional sequence
In this challenge, an *infinitely proportional sequence* is defined as a infinite sequence of positive integers such that:

* All positive integers are contained infinitely many times within the sequence.
* As more and more terms are added to the sequence, for all positive integers \\$n\\$, the ratio of the number of \\$n\\$s to the number of \\$n+1\\$s in the sequence must grow arbitrarily large.

An example of such a sequence is the following function taking an index and returning a value:

$$ S(n)=\begin{cases}S(\sqrt{n})+1 & n \text{ is perfect square \> 1} \\ 1 & \text{otherwise} \end{cases} $$

This results in a sequence `[1, 1, 1, 2, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 3 ...`, and it's fairly easy to see why this list satisfies the given properties. The first 4 occurs at index \\$2^8 = 256\\$, the first 5 at index \\$2^{16} = 65536\\$, and so on, with each positive integer occuring infinitely many more times than the previous.

An example of an invalid sequence is this:

$$ S(n)=\begin{cases}S(\frac{n}{2})+1 & n \text{ is even} \\ 1 & \text{otherwise} \end{cases} $$

This sequence goes `[1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1, 5, ...]`, and while it does contain every positive integer infinitely many times, and contains each positive integer more than the previous, it does not contain each integer infinitely many more than the previous. In the limiting case, the sequence contains twice as many 1s as 2s, twice as many 2s as 3s, and so on.

Your challenge is to output any infinitely proportional sequence. Standard rules apply - you may output as a function that takes \\$n\\$ and outputs the \\$n\\$th or first \\$n\\$ terms, or output an infinite sequence in some form. You may use 0-indexing, 1-indexing or 2-indexing (taking the first term as f(2))

This is , shortest wins!

# Answer
# 05AB1E, 2 bytes

```
Óθ

```

Attempt This Online!

Returns the exponent of the largest prime factor of \\$n\\$.

## Proof of correctness

Let's look at the ratio between the number of values which return \\$k\\$ and the number which return \\$k + 1\\$. For each number which gives \\$k+1\\$, with greater prime factor \\$p\_m\\$, we can create \\$m-1\\$ new numbers, by dividing by \\$p\_m\\$ and multiplying by \\$p\_i\\$ for \\$i \< m\\$. However, some numbers are generated multiple times, but it's bounded by their number of distinct prime divisors. If we look at numbers up to \\$n\\$, that's bounded by \\$O(\frac{\log(n)}{\log\log(n)})\\$. Therefore we have \\$\sum\_{p\_m} \frac{(m-1)\log\log(n)}{\log(n)} \Psi(\frac n{p\_m^{k+1}}, p\_m-1) \leq \sum\_{p\_m} \Psi(\frac n{p\_m^k}, p\_m-1)\\$. We want to show that for every \\$N\\$, for large enough \\$n\\$, we have \\$ N \sum\_{p\_m} \Psi(\frac n{p\_m^{k+1}}, p\_m-1) \leq \sum\_{p\_m} \frac{(m-1)\log\log(n)}{\log(n)} \Psi(\frac n{p\_m^{k+1}}, p\_m-1)\\$. We'll split it at \\$m = 2N \log(n)\\$. From theorem 1.4 in Integers without large prime factors, we have \\$\Psi(n, p\_m) = n^{O\_N(\frac 1{\log\log n})}\\$. The inequality is trivial for \\$m \> 2N \log(n)\\$, and because \\$\sum\_{p\_m} \Psi(\frac n{p\_m^{k+1}}, p\_m-1) = \Omega(\frac{n^{k+1}}{\log(n)})\\$ grows faster than \\$n^{O\_N(\frac 1{\log\log n})}\\$ the fact that we used \\$2N\\$ balances the terms we split out.

# 05AB1E, 2 bytes, thanks to @GregMartin

```
Ó¿

```

Attempt This Online!

Returns the gcd of the prime exponents, which is the largest \\$k\\$ such that \\$n\\$ is a \\$k\\$-th power.
> 15 votes

# Answer
# Haskell \+ hgl, 10 bytes

```
nM l<gr<bi

```

Attempt This Online!

## Explanation

* `bi` convert the input to binary
* `gr` group equal elements
* `nM l` length of the shortest group

This finds the shortest run of equal elements in the binary expansion of the input.

## Proof

I will provide a proof that the proportion of 1s approaches 1. That is \\$P(f(x)=1)=1\\$ This argument can be repurposed to show that for any number the proportion relative to numbers greater than or equal to it approaches 1. That is \\$P(f(x)=n\mid f(x)\geq n)=1\\$.

Let's consider the two least significant bits of a number \\$x\\$. If they are `10` or `01` then \\$f(x)=1\\$.

The two other options `11` and `00` may be any value. This means that at least half of all numbers give 1.

Now in the general case, let us treat the case where the least significant \\$2n\\$ bits do not rule out values other than 1. Considering the least significant \\$2n+2\\$ bits. A fourth of all cases of begin with `010` or `101` and thus \\$f(x)=1\\$. So 3/4 of all cases have the *possibility* of being something other than 1.

We can use recursion to then derive the following formula:

\\$ P(f(x)\neq 1) \leq \frac{1}{2}\left(\frac34\right)^n \\$

We can take the limit:

\\$ \displaystyle P(f(x)\neq 1)\leq\frac{1}{2}\lim\_{n\rightarrow\infty} \left(\frac{3}{4}\right)^n=0 \\$

So the probability of getting a 1 converges to 1.

## Reflection

There are a couple of things that would be nice here.

* There is `sss` which gives the shortest continuous substring satisfying a predicate, and `sSn` which gives the *maximal* substrings satisfying a predicate. Here it would have been useful to have a function which gives the shortest maximal substring satisfying a predicate.
* It might be nice to have a version of `gr` which just gives the lengths of the groups. It's not uncommon to care only about group lengths and not their contents.
> 7 votes

# Answer
# Python, 36 bytes

*-6 bytes thanks to l4m2, Command Master and xnor*

```
f=lambda n:-n&n<n or-~f(len(bin(n)))

```

Attempt This Online!

**39 bytes if using `True` as `1` is not allowed:**

```
f=lambda n:n&n-1and 1or-~f(len(bin(n)))

```

Similar to example but with logarithm base 2 instead of square root.

*I known that `len(bin(n))` is not exactly the logarithm, but it does not make a difference for the purpose of this challenge*

---

# Python, 36 bytes

*suggested by Wheat Wizard*

```
lambda n:len(min(bin(n).split("1")))

```

Attempt This Online!
> 5 votes

# Answer
# Charcoal, 35 bytes

```
Ｎθ⊞υ¹Ｗ›θΣυ«≧⁻Συθ⊞υ×⌈υＬυ»Ｉ⊕ΣＥυ›θΣ✂υκ

```

Try it online! Link is to verbose version of code. Outputs the `n`th term. Explanation:

```
Ｎθ

```

Input `n`.

```
⊞υ¹

```

Start with `1` `1` as the first term of the sequence.

```
Ｗ›θΣυ«

```

While more terms are needed, ...

```
≧⁻Συθ

```

... account for previous terms, and...

```
⊞υ×⌈υＬυ

```

generate a new set of terms.

```
»Ｉ⊕ΣＥυ›θΣ✂υκ

```

Calculate the resulting term.

The result is the following sequence:

```
1
1 2
1 1 2 3
1 1 1 1 1 1 2 2 3 4
1 (24 times) 2 2 2 2 2 2 3 3 4 5
1 (120 times) 2 (24 times) 3 3 3 3 3 3 4 4 5 6
1 (720 times) 2 (120 times) ...

```

Within each group, the number of times `m-1` appears more than `m` is more than the number of times `m-1` appeared more than `n` in the previous group.
> 3 votes

# Answer
# , 32 bytes

```
f=\(n,i=n^.5)`if`(i%%1,1,f(i)+1)

```

Uses the sequence from the question (2-indexed).

Attempt This Online!
> 3 votes

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

```
S=n=>++n**.5%1?1:S(n**.5)+1

```

Try it online!
> 2 votes

# Answer
# C (gcc), 39 bytes

```
i;f(n){i=sqrt(n);n=i*i-n||1/n?:f(i)+1;}

```

Try it online!
> 2 votes

# Answer
# Scala 3, ~~64~~ 63 bytes

A port of @pajonk's R answer in Scala.

Saved 1 byte(s) thanks to the comment of @pajonk

---

```
def f(n:Double):Int={val i=math.sqrt(n);if(i%1>0)1 else f(i)+1}

```

Attempt This Online!
> 2 votes

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

```
{⍵≠⌊⍵:0⋄1+∇⍵*.5}

```

Try it on APLgolf!

-1 byte thanks to att.

A tacit function which takes an integer \\$n\geq 2\\$ on the right and outputs the \\$n\\$th term in the sequence in the question.

```
{⍵≠⌊⍵:0⋄1+∇⍵*.5}
   ⌊⍵             ⍝ floor input
 0≠               ⍝ not input
 ⍵≠⌊⍵:            ⍝ If input is non-integer:
      0           ⍝     return 0
       ⋄          ⍝ Else:
           ⍵*.5   ⍝ sqrt input
          ∇       ⍝ apply this dfn
        1+        ⍝ add 1

```

Created with the help of Luminespire.
> 0 votes

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


# Question
Title: Can their first appearance happen together?
Given two non-empty 01 strings, check if there is string containing both given strings, and their first appearance end at same position.

Test cases:

```
01, 1 => true (01)
0, 00 => false (0 would at least come 1 character earlier)
01, 11 => false (can't meet on same position)
01, 0 => false (can't meet on same position)
11, 11 => true (11)
0101, 1 => false

```

The input can be encoded in whichever way you like.

As a , the output (true/false) can also be encoded using any 2 distinct, fixed values, or using your languages (optionally swapped) convention

Shortest code wins.

# Note:

This is the promise checker of https://codegolf.meta.stackexchange.com/a/26193/

# Answer
# Jelly, 8 bytes

```
LÞṫw¥@Ƒ/

```

Try it online!

Ran through a lot of 10-12 byters, but eventually lucked out into this. Takes monadic input as a pair of values. (`ṫw¥@Ƒ` for 5 bytes dyadic if the shorter input can be assumed to be on the left.)

```
LÞ          Sort by length.
       /    With the shorter string on the left and the longer on the right:
      Ƒ     Is the left equal to
  ṫ  @      the right without the characters before
   w¥       the first occurrence of the left in it?

```
> 4 votes

# Answer
# Uiua, 10 bytes

```
↥∩/<⌕⊃:⌕∩⇌

```

Try it!

Given two strings `a` and `b`, reverse them, evaluate "find" (a boolean array containing 1 at the starting points of appearance of `b` in `a`), and test if it is in the form of a 1 followed by a bunch of zeros (so the original strings match only at the end). Repeat it with arguments swapped and return the OR of the two results.

```
↥∩/<⌕⊃:⌕∩⇌    input: two strings a, b
         ∩⇌    reverse both a and b
     ⊃:⌕       reuse arguments:
       :          top: push b, a
        ⌕         below: push find(a, b)
    ⌕           take b, a from top and push find(b, a)
 ∩/<            test if each array is in the form of [1 0 0 ... 0] (APL trick)
↥               return the OR of the two

```
> 3 votes

# Answer
# Haskell \+ hgl, 28 bytes

```
eq[0]<<on(ap<fa<<mNl*^maL)rv

```

Attempt This Online!

## Explanation

* `on ... rv` reverse both arguments
* `fa` get the indexes of all occurrences of ...
    + `mNl` the shorter string
    ... in ..
    + `maL` the longer string
* `eq[0]` check if it is equal to `[0]`

## Tuple version, 29 bytes

```
eq[0]<(fa<U mNl*^U maL)<jB rv

```

## Reflection

Argument routing is really expensive in this answer, so improvements here are mostly about argument rerouting.

* A lot of the other answers here use a "try this or the arguments swapped" method and solve the problem with an assumed argument order. A function that does this could be useful.
* It would be good to have some functions which parallelize mins and maxes. i.e. take two arguments and spit out a tuple placing them in order. This would make a massive difference, with a function `xNl` which sorts two arguments by length, the whole thing would be 21 bytes:
```
eq[0]<<fa<<%(nXl.*rv)

```
* Two tuple related functions:
```
ot.*U :: (a -> b -> c) -> (a -> b -> c) -> (a, b) -> (c, c)

```
and
```
Cu<<(ot.*U) :: (a -> b -> c) -> (a -> b -> c) -> a -> b -> (c, c)

```
would both allow you to parallelize the mins and maxes properly. They'd be generally useful for this sort of thing and without the above bullet point implemented they'd save bytes here.
* A shortcut for `U x<y` exists but not one for `x<U y`. While the missing one not as philosophically motivated as the other both should probably exist.
* Similarly a shortcut for `jB x<y` exists but not one for `x<jB y`. No harm in both.
> 3 votes

# Answer
# AWK, 36 bytes

```
$1~$2a&&$1!~$2"."||$2~$1a&&$2!~$1"."

```

Attempt This Online!

This is a pattern that takes two strings on a line separated by a space and evaluates to a boolean. As a full program, it accepts multiple lines and prints only the lines that pass the test.

* `string ~ pattern` and `string !~ pattern` are "match" and "not match" respectively, i.e. regex `pattern` is found/not found in the `string`. `$1~$2a&&$1!~$2"."` tests if `$1` contains `$2` but only as a suffix (`$1` does not contain a pattern that is `$2` followed by any extra char).
    + `x y` is string concatenation. If `$2` is `"0110"`, `$2"."` is `"0110."`, which becomes `/0110./` in regex context. Since the input is numeric, `$2` needs to be explicitly coerced to a string (fortunately, Awk keeps numeric inputs in its original form as a string, so this works). `$2a` concats `$2` with `a` (an uninitialized variable, which evaluates to `""`).
* The code is repeated twice with `$1` and `$2` swapped so that the test is done in both directions.
> 3 votes

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

```
A⍨∨A←</∘⌽⍷⍥⌽

```

Try it on APLgolf!

A tacit function which takes strings on the left and right and determines whether one is a substring of the other only at the end.

## Explanation

```
A⍨∨A←</∘⌽⍷⍥⌽
          ⍥⌽  ⍝ reverse both strings
         ⍷    ⍝ find positions subsequences of right equal to left
        ⌽     ⍝ reverse
     </       ⍝ less than reduce
     </∘⌽     ⍝ checks if a Boolean vector is 1 0 0 ... 0
   A←         ⍝ assign this tacit function to A
  ∨           ⍝ OR
 ⍨            ⍝ swapped arguments of
A             ⍝ function A

```

Created with the help of Luminespire.
> 2 votes

# Answer
# Nekomata \+ `-e`, 10 bytes

```
ᶜ$ᵗ{iq=}s=

```

Attempt This Online!

```
ᶜ$ᵗ{iq=}s=
ᶜ$          Optionally swap the two inputs
  ᵗ{   }    Check that the following is not true:
    iq          a substring of the first input with the last character removed
      =         is equal to the second input
        s=  Check that the second input is a suffix of the first

```
> 2 votes

# Answer
# APL (dzaima/APL), 10 bytes

```
A⍨∨A←</⍷⍢⌽

```

Try it online!

Same as my Dyalog APL answer, but we can take advantage of the Under operator  to reverse before and after the .
> 1 votes

# Answer
# Charcoal, ~~18~~ 17 bytes

```
⁼⁰⌈⌈⟦⌕Ａ⮌θ⮌η⌕Ａ⮌η⮌θ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:

```
     ⌕Ａ             Find all matches of
          η         Second input
         ⮌          Reversed
        θ           In first input
       ⮌            Reversed
           ⌕Ａ       Find all matches of
                θ   First input
               ⮌    Reversed
              η     In second input
             ⮌      Reversed
   ⌈⟦               Take the maximum
  ⌈                 Take the maximum
⁼                   Is equal to
 ⁰                  Literal integer `0`
                    Implicitly print

```

There are three cases:

* Neither string is a substring of the other. In that case, both calls to `FindAll` return the empty list, so the maximum of the maximum is `None`. This therefore results in a false output.
* Both strings are equal. In that case, both calls to `FindAll` return the list `[0]`, so the maximum of the maximum is `0`. This therefore results in a true output.
* One string is a substring of the other. In that case, one `FindAll` will return the empty list, while the other will return a list of indices. In that case, the maximum of the maximum is the number of the characters after the end of first match, which we want to be `0` for a true output.
> 1 votes

# Answer
# Retina 0.8.2, 24 bytes

```
O#$`
$.&
^(.+)¶.*?\1

^$

```

Try it online! Takes input on separate lines but link is to test suite that splits on non-digits for convenience. Explanation:

```
O#$`
$.&

```

Sort in order of length.

```
^(.+)¶.*?\1

```

Delete the shorter string and up to the end of the first match of the shorter string in the longer string, if any.

```
^$

```

Check whether this actually removed the entire longer string.
> 1 votes

# Answer
# Python 3, ~~101~~ ~~78~~ ~~77~~ 53 bytes

```
lambda x,y:['']==y.split(x)[1:]or['']==x.split(y)[1:]

```

Try it online!

-23 bytes by using a different approach

-1 byte by changing from `==2` to `<3`

-24 bytes thanks by @l4m2 by combining `len(x.split(y))` and `x.split(y)[-1]` into one, then slightly changing the code.
> 1 votes

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

```
a=>b=>(g=c=>/^\d*,$/.test(c.split(b)))(a)|g(b,b=a)

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-pl`, 44 bytes

```
$_=($b=<>)=~/$_$/*$b!~/$_.+$/+/$b$/*!/$b.+$/

```

Try it online!
> 0 votes

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


title: Magnanimous numbers

text:
# Question
Title: Magnanimous numbers
Given an positive integer as input determine if it is a magnanimous number.

A magnanimous number is a number such that any insertion of a `+` sign between any two digits in base 10 results in an expression of a prime integer.

For example 40427 is magnanimous because

```
4+0427  = 431  is prime
40+427  = 467  is prime
404+27  = 431  is prime
4042+7  = 4049 is prime

```

## Output

You should output two distinct values, one when the input is magnanimous and one when the input is not.

## Scoring

The goal of this contest will be to make the size of the source code written to solve this task, given in bytes, as small as possible.

## Test Cases

```
1       -> True
2       -> True
4       -> True
10      -> False
98      -> True
101     -> True
109     -> False
819     -> False
4063    -> True
40427   -> True
2000221 -> True

```

**OEIS 253996**

# Answer
> 8 votes
# 05AB1E, 10 bytes

### Code

```
η¨¹.s¨R+pP

```

Uses the **05AB1E** encoding. Try it online! or Verify all test cases!

### Explanation

```
η¨             # Take the prefixes of the input and remove the last element
  ¹.s¨         # Take the suffixes of the input and remove the last element
      R        # Reverse the array of suffixes
       +       # Vectorized addition
        p      # Check if each element is prime
         P     # Product of the array

```

# Answer
> 7 votes
# C (gcc), 83 ~~84~~ ~~85~~ ~~83~~ ~~84~~ ~~86~~ ~~75~~ ~~111~~ bytes

All optimizations turned off and only on GCC 32-bit.

-1 byte thanks to @ceilingcat

+some bytes for `1` case.

+some bytes for reusable functions.

```
i,j,r,s;f(a){for(i=10,r=1;a/i;i*=10)for(s=a%i+a/i,r*=s-1,j=2;j<s;)r*=s%j++>0;a=!r;}

```

Takes input as an integer. **Return 1 for false cases, 0 for true cases.**

Try it online!

See my another answer for Mathematica code (55 bytes).

# Answer
> 6 votes
## Retina, 38 bytes

```
\B
$`$*_$'$*_
S`\d
G`^_$|^(__+)\1+$
^$

```

Try it online!

Prints `1` for magnanimous numbers and `0` otherwise.

### Explanation

```
\B
$`$*_$'$*_

```

We start by matching each position between two digits (positions that aren't word boundaries) and inserting both the prefix and the suffix of that match in unary, using `_` as the unary digit. So instead of inserting `+`s, we directly insert the unary result of the sum there.

```
S`\d

```

Now we split the string around digits, so that each sum goes on its own line and we get rid of those digits (there'll be an empty leading and trailing line as well, but that's not important).

```
G`^_$|^(__+)\1+$

```

This is the standard regex to match non-prime numbers in unary. Using a `G`rep stage here means that we simply keep all lines that contain positive non-primes (discarding the empty lines).

```
^$

```

Finally we check whether the string is empty. If the input was magnanimous, the previous stage will have discarded all lines (because they were all primes), and this gives us `1`. Otherwise, if any line wasn't a prime, it will remain in the string and the regex fails, giving `0`.

# Answer
> 4 votes
# Python 2, ~~82~~ ~~79~~ 78 bytes

```
f=lambda n,d=10:n<d or d/n<all((n/d+n%d)%k*f(n,10*d)for k in range(2,n/d+n%d))

```

This is *slow* and can only cope with the test cases with memoization.

Try it online!

### Alternate version, 79 bytes

```
f=lambda n,d=10:n<d or f(n,10*d)>d/n<all((n/d+n%d)%k for k in range(2,n/d+n%d))

```

Sped up at the cost of one byte.

Try it online!

# Answer
> 3 votes
# Jelly, 12 bytes

```
DJ⁵*⁸dṖS€ÆPẠ

```

Try it online!

Verify all test cases.

# Answer
> 3 votes
# Java 8, ~~175~~ ~~171~~ ~~94~~ 88 bytes

```
n->{long d=10,r=0,i,t;for(;d<=n;d*=10,r|=t-i)for(t=n/d+n%d,i=1;t%++i%t>0;);return r==0;}

```

-77 thanks to *@PeterTaylor* by using an arithmetic (instead of String with `.substring`) and getting rid of the separate method to check if the integer is a prime.
-6 bytes using *@SaraJ*'s prime-checking method, so make sure to upvote her!

Try it here.

**Explanation:**

```
n->{                  // Method with long as both parameter and return-type
  long d=10,r=0,i,t;  //  Some temp longs
  for(;d<=n           //  Loop as long as `d` is below or equal to input `n`
                      //  (inclusive instead of exclusive due to special case 10)
      ;               //    After every iteration:
       d*=10,         //     Multiple `d` by 10
       r|=t-i)        //     and Bitwise-OR `r` with `t-i`
    for(t=n/d+n%d,    //   Set `t` to `n` integer-divided by `d` plus `n` modulo-`d`
        i=1;          //   Set `i` to 1
        t%++i%t>0;);  //   Inner oop as long as `t` modulo `i+1` modulo `t` is not 0 yet
                      //   (after we've first increased `i` by 1 with `++i`)
                      //   (if `t` equals `i` afterwards, it means `t` is a prime)
  return r==0;}       //  Return if `r` is still 0

```

# Answer
> 2 votes
# Japt, 23 bytes

Takes input as a string.

Dang it; beaten to the punch on a much shorter alternative I was working on.

```
¬£i+YÃÅe@OxXr"%+0+"'+)j

```

Test it

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

* Thanks to @Wheat Wizard for 2 bytes: made `i` completely anonymous since it is called only once.
* Thanks to @Hyperneutrino for 4 bytes: smarter way of obtaining the numbers from the main number instead of slicing
* @Hyperneutrino saved another 2 bytes: `x-1` to just `x` for the prime checking rarnge.
* Fixed failure for case `x=10`,thus adding 7 Bytes, thanks to @Dennis and @Wheat Wizard for spotting it: my earlier version was considering 1 a prime

```
lambda x:all((lambda x:x>1and all(x%j for j in range(2,x)))(x/10**j+x%10**j)for j in range(1,len(`x`)))

```

Try it online!

# Answer
> 2 votes
# CJam, 22 bytes

```
r:L,({)_L<i\L>i+mp!},!

```

Try it online!

Prints positive integer for truthy, zero for falsy.

-1 thanks to a clever trick by Peter Taylor.
-3 thanks to another tip by Peter Taylor.

# Answer
> 2 votes
# Pyth, 14 bytes

```
.AmP_ssMcQ]dtU

```

Try it online! Will display `True` if the number is magnanimous, `False` otherwise. Takes the number as a string.

**Explanations**

```
.AmP_ssMcQ]dtU

              Q    # Implicit input Q
            tU     # Generate the range [1, 2, ..., len(Q)-1]
  m                # For each index d in the above range...
        cQ]d       # Split Q at index d
      sM           # Convert the two parts to integers
     s             # Sum
   P_              # Check it is a prime
.A                 # ...end for. Check all elements are True

```

# Answer
> 2 votes
# Japt, ~~24~~ 16 bytes

This was pretty much a collaboration between @Shaggy, @ETHproduction, and myself.

```
¬£[YîU UtY]xÃÅej

```

Try it online!

Takes input as a string.

# Answer
> 2 votes
# Pip, ~~25~~ 24 bytes

```
$&0N_%,_=1M$+(a^@_)M1,#a

```

Try it online!

### Explanation

`a` is the first command-line argument. `1,#a` generates a Range containing numbers `1` through `len(a)-1`. To this, we map a lambda function:

```
$+(a^@_)
   a^@_   Split a at this index
$+(    )  Fold the resulting 2-element list on +

```

Next, we map another lambda function, `0N_%,_=1`, that tests for primality. I took it from this answer; you can read the explanation there. Finally, we fold the list on logical AND (`$&`). The result is `1` iff all the sums were prime, `0` if any of them weren't.

Example, with input of `4063`:

```
                    1,#a   [1; 2; 3]
           $+(a^@_)M       [67; 103; 409]
  0N_%,_=1M                [1; 1; 1]
$&                         1

```

# Answer
> 2 votes
# Plain English ~~4,204~~ ~~341~~ ~~315~~ ~~251~~ ~~241~~ 240 bytes

(Re-)incorporated primality testing into Plain English's library, by moving 3,863 bytes into Plain English's library. Deleted 26 bytes of white space. Saved 64 bytes by abbreviating local variables. Saved 10 bytes by abbreviating the interface. Per RosLuP's suggestion, saved 1 byte by changing how m is initialized and incremented.

```
To decide if a n number is g:
Put 1 in a m number.
Loop.
Multiply the m by 10.
If the m is greater than the n, say yes.
Divide the n by the m giving a q quotient and a r remainder.
Add the q to the r.
If the r is not prime, say no.
Repeat.

```

Ungolfed version of final code:

```
To decide if a number is magnanimous:
  Put 1 in another number.
  Loop.
    Multiply the other number by 10.
    If the other number is greater than the number, say yes.
    Divide the number by the other number giving a quotient and a remainder.
    Add the quotient to the remainder.
    If the remainder is not prime, say no.
  Repeat.

```

Notes: The Plain English IDE is available at github.com/Folds/english. The IDE runs on Windows. It compiles to 32-bit x86 code.

The Osmosian Order's dynamic fork of Plain English already had primality testing in version 4700, but it used a very inefficient algorithm (as of January through June 2017). Versions 4001-4011 of the GitHub site's dynamic fork omitted primality testing. Version 4013 of the GitHub site's dynamic fork includes primality testing. The code to perform the primality testing was developed as part of previous revisions of this answer.

# Answer
> 2 votes
## Mathematica, 75 bytes

```
And@@Table[PrimeQ@ToExpression@StringInsert[#,"+",n],{n,2,StringLength@#}]&

```

`Function` which expects a `String`. `PrimeQ@ToExpression@StringInsert[#,"+",n]` returns whether inserting a `+` after the `n`th digit gives a prime number. `Table[...,{n,2,StringLength@#}]` gives the list of these values as `n` ranges from `2` to the length of the string. We then take `And` of each of the elements of that list. Conveniently, if `StringLength@#<2`, then `Table[...]` is the empty list, for which `And@@{}==True`

# Answer
> 2 votes
# Mathematica, 55 ~~50~~ ~~45~~ ~~49~~ ~~50~~ ~~54~~ ~~62~~ bytes

It seems I should post it separately.

+6 bytes for code length remeasured.

+5 bytes thanks to ngenisis.

```
And@@(qPrimeQ[#~Mod~q+⌊#/q⌋])@Rest@PowerRange@#&

```

Takes input as an integer and return regular `True` and `False`. The  in-between is unicode 0xF4A1, short for `Function[,]`. Code length is measured on file size (UTF-8 without BOM), comment if it is not correct.

`PowerRange[x]` returns 1, 10, 100... no greater than `x`, which is introduced in Mathematica 10.

# Answer
> 1 votes
# Perl 6, 58 bytes

```
{?(10,10* *...^*>$_).map({$_ div$^a+$_%$^a}).all.is-prime}

```

Try it online!

`10, 10 * * ...^ * > $_` is the geometric sequence of multiples of ten, taken until one before the element that exceeds the input parameter `$_`. Then we just check that for each power of ten, the sum of the input parameter taken div and mod that power is prime.

# Answer
> 1 votes
# Haskell, ~~114~~ 110 bytes

```
p x=[x]==[i|i<-[2..x],x`mod`i<1]
i!x|i<1=0<1|0<1=p(uncurry(+)$divMod x$10^i)&&(i-1)!x
f x=(length(show x)-1)!x

```

Ungolfed with explanation:

```
-- Check if x is a prime number
p x = [x] == [i | i<-[2..x], x`mod`i < 1]
-- Checks all pairs of numbers a '+' can be put in between
i ! x | i<1 = 0<1                                -- Single-digit numbers are always truthy
      | 0<1 = p (uncurry (+) $ divMod x $ 10^i)  -- Does x split at i digits from right sum up to a prime?
           && (i-1) ! x                          -- If so, check next pair
-- Start (!) with the number of digits in x minus one
f x = (length (show x)-1) ! x

```

# Answer
> 1 votes
# Axiom, 88 bytes

```
f(n:PI):Boolean==(i:=10;repeat(q:=n quo i;q=0 or ~prime?(q+n rem i)=>break;i:=i*10);q=0)

```

test and results

```
(10) -> [[i,f(i)]  for i in [1,2,4,10,98,101,109,819,4063,40427,2000221,999999999999999999999999999999999999999999999]]
   (10)
   [[1,true], [2,true], [4,true], [10,false], [98,true], [101,true],
    [109,false], [819,false], [4063,true], [40427,true], [2000221,true],
    [999999999999999999999999999999999999999999999 ,false]]

```

# Answer
> 1 votes
# Brachylog, 11 bytes

```
{~cĊℕᵐ+}ᶠṗᵐ

```

Try it online!

```
{      }ᶠ      Find every
      +        sum of
   Ċ           two
    ℕᵐ         whole numbers
 ~c            which concatenate to the input,
          ᵐ    and assert that all of them
         ṗ     are prime.

```

# Answer
> 1 votes
# Perl 6, 35 bytes

```
{m:ex/^(.+)(.+)$/.all.sum.is-prime}

```

Try it online!

### Explanation:

```
{                                 }     # Anonymous code block that
 m:ex/^        $/                         # Match all
       (.+)(.+)                           # Splits of the input number
                 .all                     # Are all of them
                     .sum                   # When summed
                         .is-prime          # Prime?

```

# Answer
> 1 votes
# Husk, 13 bytes

```
Λȯṗṁd§e↑↓d¹ḣL

```

Try it online!

-1 byte from user.

# Answer
> 1 votes
# Risky, 44 bytes

```
*0!?+0-_1+0___?+0+_1+0___?{?}_*+0+__?[?}_*+0_!\?+0+1111:!111111111+111111111111111111111

```

Try it online!

Takes input as an array of digits (which is allowed by default). Outputs `1` for true and `0` for false.

# Answer
> 1 votes
# Vyxal 3 `g`, 10 bytes

```
ṗΩL2=]“⌊ṠṄ

```

Try it Online!

# Answer
> 0 votes
# Stacked, 51 bytes

```
[tostr:#'1-~>splitat tr['+',' '#`#~prime]map 1,all]

```

Try it online!

This is a function. It works by converting its argument to a string (`tostr`), duplicating it and obtaining its length (`:#'`), subtracting 1 (`1-`), making a range from 1 to that number (`~>`). The stack looks something like this, for input `40427`:

```
('40427' (1 2 3 4))

```

We perform vectorized `splitat`, resulting in the following array to be at the top of the stack:

```
(('4' '40' '404' '4042') ('0427' '427' '27' '7'))

```

Transposing this with `tr`, we get:

```
(('4' '0427') ('40' '427') ('404' '27') ('4042' '7'))

```

Then, we map the function `['+',' '#`#~prime\]`(with`map\`). This function does:

```
['+',' '#`#~prime]
 '+',                concatenate a plus sign (string)    `('4' '0427' '+')
     ' '#`           join by spaces                      `'4 0427 +'`
          #~         evaluate                            `431`
            prime    check primality                     `1`

```

Then, after the map, we concatenate `1`. This is since `all` returns `undef` for an empty list.

# Answer
> 0 votes
## JavaScript (ES6), 70 bytes

```
P=(n,x=2)=>n%x?P(n,x+1):n==x
f=(n,i=10)=>i>n||P((n/i|0)+n%i)&f(n,i*10)

```

Fails on the last case in my browser due to a "too much recursion" error while calculating `P(200023)`. Hopefully this doesn't invalidate it.

# Answer
> 0 votes
# QBIC, 38 bytes

```
_L;|[a-1|q=q*µ!_sA,b|!+!_sA,b+1,a|!}?q

```

## Explanation

```
_L |     Create a variable a and set it to the length of
  ;      the input string (A$)
[a-1|    FOR b = 1 to a-1
q=q*     multiply q by
 µ       -1 if prime, 0 if not, of
  !        a cast of
   _s       a substring of
     A,       A$
     b        from index 1 to index b (only one index is given, so that is assumed to be the req. length from 1)
      |!   to number
 +         plus
 !         a cast of
  _s         a substring of
    A,         A$
    b+1        from index b+1
    ,a         for the length of a (does not error if it exceeds the end of the string)
      |!   to number
 }       NEXT
 ?q      PRINT q, which is eitrher -1 or 1 for all-prime sums, or 0 otherwise

```

# Answer
> 0 votes
# Pyth, ~~15~~ 14 bytes

```
.AmP_svcz]dtUz

```

Test suite

Saved a byte using Pyth's newest change.

# Answer
> 0 votes
## CJam (21 bytes)

```
r:R,({RiA@)#md+mp!},!

```

Online demo, online test suite

### Dissection

```
r:R       e# Take a token of input and assign it to R
,(        e# Take the length of R minus one
{         e# Filter i = 0 to (length of R minus two)
  Ri      e#   Push R as an integer value
  A@)#    e#   Push 10 to the power of (i + 1)
  md      e#   divmod
  +mp!    e#   Add, primality test, negate result
},        e# The result of the filter is a list of splits which give a non-prime
!         e# Negate result, giving 0 for false and 1 for true

```

# Answer
> 0 votes
# APL(NARS), chars 35, bytes 70

```
{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}

```

test:

```
  f←{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}
  f¨1 2 4 10 98 101 109 819 4063 40427 2000221
1 1 1 0 1 1 0 0 1 1 1

```

This would be the translation in APL from Axiom post algo here...

```
{0≥k←¯1+≢⍕⍵:1⋄∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k}
 0≥k←¯1+≢⍕⍵:1⋄  assign to k the length as array of argument return 1 if that is <=0
 ∧/0π(m∣⍵)+⌊⍵÷m←10*⍳k
              m←10*⍳k  m is the array pow(10,1..k)
           ⌊⍵÷m       the array of quotient of argumet with m
          +           sum
     (m∣⍵)            with array of remander
   0π                 build the binary array of "are prime each"
 ∧/                   and that array

```

# Answer
> 0 votes
# PHP, 100 bytes

```
for(;++$k<strlen($a=$argn);$x+=$i==1)for($i=$n=substr($a,$k)+$b.=$a[$k-1];--$i&&$n%$i;);echo$x+2>$k;

```

prints `1` if input is magnanimous, empty output if not. Run as pipe with `-nR` or try it online.

# Answer
> 0 votes
# Perl 5 `-p`, 42 bytes

```
$\=1;s//map$\&&=($`+$')%$_,2..$`+$'-1/ge}{

```

Try it online!

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


title: Possible Tetris sequences

text:
# Question
Title: Possible Tetris sequences
Write code to figure out whether a run of Tetris pieces could be generated by the official Tetris algorithm. Fewest bytes wins.

---

Official Tetris games generate the sequence of falling pieces in a special way. The seven pieces `IJLOSTZ` are dropped in a random order, then another random permutation is dropped, and so on.

```
JTLOISZ STJOLIZ LISJOTZ ...

```

This example contains the contiguous run of pieces

```
SZSTJOLIZLIS

```

Note that it cuts across the boundaries of a group of 7. But, the run of pieces

```
SZOTLZSOJSIT

```

cannot be a substring of any Tetris sequence, so it can never be seen in an official Tetris game.

---

**Input:** A non-empty string of letters `IJLOSTZ`.

**Output:** A Truthy or Falsey value for whether the input is a substring of a sequence that can be generated by the official Tetris Random Generator, i.e. of a concatenation of permutations of the seven letters.

**Test cases:**

True:

```
T
JJ                        (unique breakdown: J J)
JTJ                     (possible breakdown: JT J)
LTOZIJS
SZSTJOLIZLIS            (possible breakdown: SZ STJOLIZ LIS)
JTLOISZSTJOLIZLISJOTZ   (possible breakdown: JTLOISZ STJOLIZ LISJOTZ)
LIJZTSLIJZTS              (unique breakdown: LIJZTS LIJZTS)

```

False:

```
SZOTLZSOJSIT
ZZZ
ZIZJLJ
ZJLJLZITSOTLISOJT
JTLOISZSTJOLIZLISJOTZLJTSZLI
IOJZSITOJZST
LIJZTSLIJZTSL

```

**Leaderboard**

Courtesy of Martin Büttner.

```
function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/55689/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```

# Answer
> 6 votes
# CJam, ~~23~~ ~~20~~ 16 bytes

```
q7{\+_7/_Lf|=},&

```

*Credits to Sp3000 for shaving off 4 bytes!*

It prints a bunch of digits as a truthy value or nothing as a falsy value (before printing these are actually a non-empty or empty list, which are indeed truthy and falsy in CJam).

Test it here.

## Explanation

This just checks all 7 possible partitions of the input into chunks.

```
q      e# Read the input
7{     e# Select the numbers from 0 to 6 for which the following block is true.
  \+   e#   Prepend the number to the input. This shifts the string by one cell
       e#   without adding non-unique elements.
  _7/  e#   Make a copy and split into chunks of 7.
  _Lf| e#   Remove duplicates from each chunk.
  =    e#   Check if the last operation was a no-op, i.e. that there were no duplicates.
},
&      e# The stack now contains the input with [6 5 ... 1 0] prepended as well as a list
       e# of all possible splittings. We want to get rid of the former. To do this in one
       e# byte we take the set intersection of the two: since we've prepended all the
       e# integers to the list, this will always yield the list of splittings.

```

# Answer
> 6 votes
# Pyth, 16 15 bytes

```
sm*F.{Mc+>Gdz7T

```

Prints 0 for false, a positive integer for true.

# Answer
> 4 votes
# Retina, ~~61~~ 55 bytes

```
^((.)(?<!\2.+))*((){7}((?<-4>)(.)(?!(?<-4>.)*\4\6))*)*$

```

Since this is just a single regex, Retina will run in Match mode and report the number of matches it found, which will be `1` for valid sequences and `0` otherwise. This isn't competitive compared with the golfing languages, but I'm quite happy with it, seeing I started out with a monster of 260 bytes.

## Explanation

```
^((.)(?<!\2.+))*

```

This bit consumes a prefix of unique letters of variable length, i.e. it matches the potentially incomplete leading chunk. The lookbehind ensures that any character matched in this bit has not appeared in the string before.

Now for the rest of the input, we want to match chunks of 7 without repeating characters. We could match such a chunk like this:

```
(.)(?!.{0,5}\1)(.)(?!.{0,4}\2)(.)(?!.{0,3}\3)...(.)(?!.?\5).

```

I.e. we match a character that doesn't appear for another 6 characters, then one which doesn't appear for another 5 characters and so on. But this requires fairly horrible code repetition, and we'd have to match a trailing (potentially incomplete) chunk separately.

Balancing groups to the rescue! A different way to match

```
(.)(?!.{0,5}\1)

```

is to push 5 empty matches onto a capture stack and try emptying it:

```
(){5}(.)(?!(?<-1>.)*\2)

```

The `*` allows a minimum of zero repetitions, just like `{0,5}`, and because we've pushed five captures, it won't be able to pop more than 5 times either. This is longer for a single instance of this pattern, but this is much more reusable. Since we're doing the popping in a *negative* lookahead, this doesn't affect the actual stack once the lookahead has completed. So after the lookahead, we've still got 5 elements on the stack, no matter what happened inside. Furthermore, we can simply pop one element from the stack before each lookahead, and run the code in a loop, to automatically decrement the lookahead width from 5 down to 0. So that really long bit up there can actually be shortened to

```
(){7}((?<-1>)(.)(?!(?<-1>.)*\1\3))*

```

(You may notice two differences: we're pushing 7 instead of 5. One additional capture is because we pop *before* each iteration, not after it. The other is actually necessary so that we can pop from the stack 7 times (since we want the loop to run 7 times), we can fix that off-by-one error inside the lookahead by ensuring with the `\1` that there is still at least one element left on the stack.)

The beauty of this is that it can also match the trailing incomplete chunk, because we never required it to repeat 7 times (that's just the necessary maximum, because we can't pop from the stack more often than that). So all we need to do is wrap this in another loop and ensure we've reached the end of the string to get

```
^((.)(?<!\2.+))*((){7}((?<-4>)(.)(?!(?<-4>.)*\4\6))*)*$

```

# Answer
> 0 votes
# JavaScript (Node.js), 75 bytes

```
f=(n,i=7)=>(n+{}).match(/.{7}/g).some(x=>/(.).*\1/.test(x))?i&&f(i+n,i-1):1

```

Try it online!

Try `1234567<input>[object Object]` so that

* digits are inserted one by one, so starting anywhere is tested
* Tested length is large enough, `match` never return `null`
* connected string doesn't break the property

---
Tags: code-golf, string, game, permutations, tetris
---


title: Base Neutral Numbering System

text:
# Question
Title: Base Neutral Numbering System
It frustrates me that when you say "base 16", the 16 is in base 10. We need a base neutral way of writing down numbers when favoring a specific base would be inappropriate.

## How it works

We define `<n>` to be the nth prime. So `<1>=2`, `<2>=3`, `<3>=5`. Note that every positive integer can be uniquely represented by the product of some number of `<>` expressions. For example `6` can be written as `<1>*<2>`.

However, in this form we still have numbers that need to be represented in some base. So we must recurse on each term. Until we reach the number 1, which has the same value almost in any base.

Your challenge is to print positive integer in this base neutral format.

I hope the examples will make things more clear:

## Test cases

| base 10 | base neutral | Explanation |
| --- | --- | --- |
| `1` | `1` | 1 can't be factored |
| `2` | `<1>` | 2 is the first prime |
| `3` | `<<1>>` | 3 is the second prime, 2 is the first prime |
| `4` | `<1> * <1>` | 2 times 2 |
| `5` | `<<<1>>>` | 5 is the third prime |
| `6` | `<1> * <<1>>` | 2 times 3 |
| `10` | `<1> * <<<1>>>` |  |
| `13` | `<<1> * <<1>>>` | 6th prime |
| `255` | `<<1>> * <<<1>>> * <<<1> * <1>>>` | `3 * 5 * 17`, 17 is the 7th prime, 7 is the 4th prime |

You may replace `*` with any symbol of you prefer. You may replace `<>` with `{}`,`[]` or `()` if you prefer, as long as you don't use the symbol replacing `*`. The `1` must stay a `1` though. You may also add spaces or line breaks anywhere. The spaces in the examples are just for clarity and you may omit them.

For example, a valid output would be `[[1], [1]]` or `{{1 }%{1 }}` for the number 7.

This is code golf. Shortest answer in each language wins.

# Answer
# Vyxal, 13 bytes

```
λǐÞpvḟ›vx1w$∨

```

Try it Online! Output is an array, so there is an extra pair of brackets on the outside. `1w$∨` can be removed if we can omit the `1`s.

```
λǐÞpvḟ›vx1w$∨
λ               # Open a lambda for recursion
 ǐ              # Get the prime factors
  Þpvḟ›         # Find the one-indexed index of each in an infinite list of primes
       vx       # Recurse over each
         1w$∨   # Logical OR with [1] (replace empty lists with [1])

```
> 8 votes

# Answer
# JavaScript (ES6), 92 bytes

Borrowing an optimization from Jakque's answer, as suggested by @Mukundan314.

```
f=(n,k=2,p=1)=>n<2?1:n%k?f(n,k+1,p+(P=d=>k%--d?P(d):d<2)(k)):`<${f(p)}>`+(n>k?'*'+f(n/k):'')

```

Try it online!

---

# JavaScript (ES6), 96 bytes

*-4 thanks to @Mukundan314*

```
f=(n,m,k=2,p=1)=>n>1?n%k?f(n,m,k+1,p+(P=d=>k%--d?P(d):d<2)(k)):[m]+`<${f(p)}>`+f(n/k,'*'):m?'':1

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  n,              //   n = input
  m,              //   m = either undefined or '*'
  k = 2,          //   k = current divisor
  p = 1           //   p = 1-based index of the smallest prime >= k
) =>              //
n > 1 ?           // if n is greater than 1:
  n % k ?         //   if k is not a divisor of n:
    f(            //     do a recursive call:
      n,          //       leave n unchanged
      m,          //       leave m unchanged
      k + 1,      //       increment k
      p + (       //       pass either p or p + 1
        P = d =>  //       according to the result of P(k)
        k % --d ? //       where P is a recursive helper function
          P(d)    //       testing whether k is prime
        :         //
          d < 2   //
      )(k)        //
    )             //     end of recursive call
  :               //   else:
    [m] +         //     append m (force an empty string if undefined)
    `<${f(p)}>` + //     append '<', followed by f(p), followed by '>'
    f(            //     append the result of a recursive call:
      n / k,      //       divide n by k
      '*'         //       enable the multiply sign
    )             //     end of recursive call
:                 // else:
  m ? '' : 1      //   stop the recursion; append '1' if m is undefined

```
> 7 votes

# Answer
# Jelly, 9 bytes

```
ÆfÆCß€;¹?

```

**Try it online!**

A monadic Link that accepts a positive integer and yields a ragged list of ones - that is, a list of `1`s where inner nesting is the prime counting and adjacency is multiplication.

---

A full program that prints that without the outer `[]` is \\$15\\$ bytes:

```
ÆfÆCß€;¹?
ÇŒṘṖḊ

```

**Try it online!**

### How?

```
ÆfÆCß€;¹? - Helper Link: positive integer, I
Æf        - prime factors
  ÆC      - number of primes up to (vectorises across that)
        ? - if...
       ¹  - ...condition: no-op
    ß€    - ...then: call this Link for each
      ;   - ...else: concatenate (I) - N.B. Only 1 has no prime factors, so concatenate 1.

ÇŒṘṖḊ - Main Link: positive integer, I
Ç     - call the Helper Link (with I)
 ŒṘ   - get the Python representation (of that)
   Ṗ  - pop
    Ḋ - dequeue
      - implicit print

```
> 7 votes

# Answer
# Python 3, ~~90~~ 89 bytes

```
f=lambda n,i=2,p=1:1//n or n%i and f(n,i+1,p+(f(i)>"."))or(n>i)*f" {f(n/i)}*"+f"<{f(p)}>"

```

Try it online!

> "You may also add spaces or line breaks anywhere"

Wait a minute, I can totally (ab)use that!

## Explanation :

```
f=lambda n,i=2,p=1:
# f: recursive function
## n: input
## i: increment to have a prime that divide n
## p: prime index of i

1//n          # if n == 1: return 1
or              # else
n%i and f(      # if i is not a divisor of n recurse
  n,              # with same input
  i+1,            # increment i
  p+(f(i)>"."))   # increment p if i is prime (no leading space)
or              # then (assuming that i is prime and divide n and p the index of i)
(n>i)*          # if n//i > 1
  f" {f(n/i)}*"   # recurse adding a space before and a "*" after
+f"<{f(p)}>"    # add to the representation of i

```

-1 byte thanks to @Dominic van Essen

# Python 3, ~~99 83~~ 77 bytes, cheaty (but totally legit) version

This version abuse of list representation and the fact that `<...> * 1` is "equal" to `<...>` to produce non canonic expressions. But the author authorised it so ¯\\\_(ツ)\_/¯

`<...> * <...>` representation is `[...], [...]` with total result enclosed with `[]`

```
f=lambda n,i=2,p=1:1//n*[1]or n%i and f(n,i+1,p+2//len(f(i)))or[f(p)]+f(n//i)

```

Try it online!

the process is the same but we check the length of `f(i)` do detect if it is prime.
> 7 votes

# Answer
# Python 3, 108 bytes

```
f=lambda n,k=2,p=1,m=1:n>1and(n%k and f(n,k+1,p+all(k%i for i in range(2,k)),m)or[f(p)]+f(n/k,k,p,0))or[1]*m

```

Try it online!

Suggested by Mukundan314. Outputs nested lists.

# Python 3, ~~140 139 136~~ 135 bytes

```
f=lambda n,k=2,p=1,m='':(f(n,k+1,p+all(k%i for i in range(2,k)),m)if n%k else m+f'<{f(p)}>'+f(n/k,k,p,'*'))if n>1 else'1'if m==''else''

```

Try it online!

* -1 thanks to Arnauld
* -3 thanks to Seb

Port of Arnauld's JavaScript answer. Outputs the string shown in the test cases.
> 4 votes

# Answer
# Retina 0.8.2, 70 bytes

```
.+
$*
{+`\b(11+)(\1)+\b
$1*1$#2$*
\b1(1((?<!\b\3+(11+)))?)+\b
<$#2$*1>

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
{`

```

Repeat until no more numbers can be decomposed.

```
+`\b(11+)(\1)+\b
$1*1$#2$*

```

Decompose numbers into their prime factors. (Note that this outputs the factors in descending order as that's golfier.)

```
\b1(1((?<!\b\3+(11+)))?)+\b
<$#3$*1>

```

Decompose primes into their index.
> 4 votes

# Answer
# Charcoal, 50 bytes

```
≔⟦⟧θＦ²⊞υ1ＦＥ…·²ＮΦ…²ι¬﹪ιλ⊞υ⎇ι⁺⁺§υ⌊ι*§υ⌈ι⪫<>§υＬ⊞Ｏθω⊟υ

```

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

```
≔⟦⟧θ

```

Start with no prime numbers discovered.

```
Ｆ²⊞υ1

```

Start with a dummy entry for `0` and an entry of `1` for `1`.

```
ＦＥ…·²Ｎ

```

Loop from `2` to the input...

```
Φ…²ι¬﹪ιλ

```

... finding the factors of each number, ...

```
⊞υ⎇ι

```

... if the number has nontrivial proper factors, then push...

```
⁺⁺§υ⌊ι*§υ⌈ι

```

... the concatenation of the representations for the lowest and highest factor with an intermediate `*`, otherwise push...

```
⪫<>§υＬ⊞Ｏθω

```

... the representation of the incremented count of primes found so far, wrapped in `<>`.

```
⊟υ

```

Output the final value.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
#0/@(Join@@Table@@@FactorInteger@#/.#->PrimePi@#/.{0}->1)&

```

Try it online!

Uses `{ }` to represent both operations, depending on the number of elements. Test output converts lists with \>1 element into `NonCommutativeMultiply` (`**`) for clarity.

```
    Join@@Table@@@FactorInteger@#                       prime factorize
#0/@                                                    recurse on factors
                                 /.#->PrimePi@#         prime input: recurse on #prime instead
                                               /.{0}->1 1=input: return 1

```
> 4 votes

# Answer
# sclin, 43 bytes

```
P/"*`"mapf"$P rev.= find:1+ @"map""Q1.,, |#

```

Try it here! Outputs as `[[[1]] [[[1]]] [[[1] [1]]]]` where each space replaces `*`.

For testing purposes:

```
[1 2 3 4 5 6 10 13 255] ( ; f>o ) map
P/"*`"mapf"$P rev.= find:1+ @"map""Q1.,, |#

```

## Explanation

Prettified code:

```
P/ \*` mapf ( $P rev.= find: 1+ @ ) map dup 1.,, |#

```
* `P/ \*` mapf` prime factors converted from frequency map to list
* `(...) map` for each prime factor...
    + `$P rev.= find: 1+` get its index (1-indexed)
    + `@` execute this line (i.e. recurse)
    + since 1's list of prime factor is empty, `map` doesn't trigger recursion on 1s
* `dup 1.,, |#` replace empty list with `[1]`
    + boolean check works here because empty lists are falsy in sclin
> 3 votes

# Answer
# 05AB1E, 17 bytes

```
"Di¸ëÒεÅPg®.V"©.V

```

Recursion isn't exactly 05AB1E's strong suit.. As in, I have to use strings and `eval`s to mimic recursive behavior.

Outputs just like some of the other answers as a nested list, including additional wrapped list around the entire output (e.g. `[[[1],[1]]]` for \\$n=7\\$).

Try it online or verify all test cases.

**Explanation:**

```
"..."      # Push the recursive string explained below
     ©     # Store it in variable `®` (without popping)
      .V   # Evaluate and execute it as 05AB1E code,
           # using the (implicit) input-integer as argument
           # (after which the result is output implicitly)

D          # Duplicate the current integer
 i         # If it's exactly 1:
  ¸        #  Wrap this 1 inside a list: [1]
 ë         # Else:
  Ò        #  Get the prime factors (including duplicates) of the integer
   ε       #  Map over each prime factor:
    ÅP     #   Convert it to a list of primes <= this prime factor
      g    #   Pop and push the length to get the amount of primes in this list
       ®.V #   Do a recursive call by evaluating and executing string `®`

```
> 3 votes

# Answer
# C++, 156 bytes

(+40 bytes of header includes) Try it online!

Header:

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

```

My attempt at code. I find this exercise horrible, yet fascinating :)

```
void F(int v,std::string&o){if(v<2)o+=49;int c=1,i=1,p,j;for(;++i<=v;){p=j=1;for(;++j<i;)p&=i%j;while(v%i==0){v/=i;o+=60;F(c,o);o+=62;if(v!=1)o+=42;}c+=p;}}

```

Footer (calling the function):

```
int main() {
    auto numbers = { 1,2,3,4,5,6,10,13,255 };
    for (int number : numbers) {
        std::string result;
        F(number, result);
        std::cout << "base 10: " << number << "\tbase neutral: " << result << "\n";
    }
}

```

Output:

```
base 10: 1   base neutral: 1
base 10: 2   base neutral: <1>
base 10: 3   base neutral: <<1>>
base 10: 4   base neutral: <1>*<1>
base 10: 5   base neutral: <<<1>>>
base 10: 6   base neutral: <1>*<<1>>
base 10: 10  base neutral: <1>*<<<1>>>
base 10: 13  base neutral: <<<1>>>
base 10: 255 base neutral: <<1>>*<<<1>>>*<<<1>>>

```
> 3 votes

# Answer
# , ~~94~~ 92 bytes

*Edit: -2 bytes thanks to pajonk*

```
f=\(n,i=2,p=1)`if`(n<2,1,`if`(n%%i,f(n,i+1,p+(sum(!i%%2:i)<2)),paste(f(n/i),"*<",f(p),">")))

```

Attempt This Online!Outputs non-minimal base-neutral representations, as allowed, including quite a lot of `1*`s, but all expressions should evaluate correctly.

Based initially on Jakque's Python answer (upvote it) and golfed from there.
> 2 votes

# Answer
# Python 3, 483 bytes

```
f=lambda n,p=2:[]if n==1 else [p]+f(n//p,p=p)if n%p==0 else f(n,p=list(filter(lambda x:all(x%i!=0for i in range(2,(x//2)+1,2)),range(p+1,2*p)))[0])
g=lambda p,t=2,c=1:c if p in list(filter(lambda x:all(x%i!=0 for i in range(2,x)),range(2,t+1)))else g(p,t=list(filter(lambda x:all(x%i!=0 for i in range(2,x)),range(t+1,2*t)))[0],c=c+1)
r=lambda n:[[i]if i==1 else r(i)for i in[g(i)for i in f(n)]]
s=lambda n:str((lambda n:[[i]if i==1 else r(i)for i in [g(i)for i in f(n)]])(n))[1:-1]

```

Try online!

More cleaner version:

```
f = lambda n, p=2: [] if n==1 else [p] + f(n//p, p=p) if n%p == 0 else f(n, p=list(filter(lambda x: all(x%i != 0 for i in range(2, (x//2)+1, 2)), range(p+1, 2*p)))[0])
g = lambda p, t=2, c=1: c if p in list(filter(lambda x: all(x%i != 0 for i in range(2, x)), range(2, t+1))) else g(p, t=list(filter(lambda x: all(x%i != 0 for i in range(2, x)), range(t+1, 2*t)))[0], c=c+1)
r = lambda n: [[i] if i == 1 else r(i) for i in [g(i) for i in f(n)]]
s = lambda n: str((lambda n: [[i] if i == 1 else r(i) for i in [g(i) for i in f(n)]])(n))[1:-1]

```

## Explanation:

`f` will factor the input numbers and return the factorization result in a list.

```
>>> f(12)
[2, 2, 3]

```

`g`'s input is a prime and return the index of that prime. In other words `n = g(p)` means that `p` is the `n`th prime number.

```
>>> g(2)
1
>>> g(3)
2
>>> g(13)
6

```
> 1 votes

# Answer
# JavaScript(ES2021)

## Nested list output version, ~~86~~ 80 bytes

```
f=(n,a=[1,[1]],m=1)=>a[n]??=n%++m?f(n,a,m,f(m,a)):[f(n>m?a[0]:a[0]++),...f(n/m)]

```

Attempt This Online!

## String output version, ~~89~~ ~~85~~ 82 bytes

```
f=(n,a=[1,1],m=1)=>a[n]??=n%++m?f(n,a,m,f(m,a)):'<'+f(n>m?a[0]:a[0]++)+'>*'+f(n/m)

```

Attempt This Online!

---

The output contains extraneous `*1`s.

This "string version" actually returns a number for input `1` and a string for other input numbers. This can be changed for +2 bytes.

---

## Explanation

### Algorithm

The gist of the algorithm is to find the smallest factor `m`≥2 of `n` by brute-force trial division. Note that such an `m` must exist because `n` itself fits the criteria. Also note that `m` must be prime. Let `m` be the `k`th prime

During each iteration of the brute-force loop, we call `f` on the current divisor and cache the results in an array `a`. This ensures each prime \< `m` is processed exactly once before we find `m`.

That way, we can use a simple counter to determine `k`, by making `f(x)` increment the counter if and only if `x` is prime. Since `0` is not valid input, we can just use `a[0]` as the counter.

Once `m` is found, we recurse using the fact `n = m * (n/m) = <k> * (n/m)`. I.e.

```
f(n) =  '<' + f(k) + '>*' + f(n/m)

```

with the base case being `f(1) = '1'`.

### Ungolfed code

Changed the brute-force division from recursion to loop. Also changed the initial loop variable to make the code more idiomatic.

```
function f(n, a = [1,[1]]) {
    if (a[n] !== undefined) {
        return a[n];
    }

    for (let m = 2;; m++) {
        if (n % m !== 0) {
            // This increments a[0] exactly once if m is prime
            f(m, a);
        } else {
            // Found a factor m, which is the a[0]-th prime

            // Increment the counter if m==n (i.e. n is prime)
            const k = n > m ? a[0] : a[0]++;

            // Recurse (discard cache to save keystrokes)
            return a[n] = '<' + f(k) + '>*' + f(n/m)
        }
    }
}

```
> 1 votes

# Answer
# Retina, 61 bytes

```
{+`\b(11+)(\1)+\b
1$#2*1,$.1*1
11+
<$&>
(?=(11+)\1+\b|\b11)1

```

Attempt This Online!

Input is in unary. Output is same as OP except using `,` instead of `*`

## Explanation

```
+`\b(11+)(\1)+\b
1$#2*1,$.1*1

```

Completely factorize each composite number, using a loop that extract one factor per iteration.

So, we are left with only ones and primes in the working string

---

```
11+
<$&>

```

Wrap each prime in `<>`

---

```
(?=(11+)\1+\b|\b11)1

```

Now we need to convert each prime into its "prime index". We do so by removing `1`s:

* whose position from the end of the number is composite, or
* that is the first `1` in the number and is follow by at least another `1`

For example, take 5 as an example

```
1 1 1 1 1
↑ ↑ ↑ ↑ ↑
| | └-┴-┴------- Keep these
| └------------- Remove, because it is 4th 1 from the right, and 4 is composite
└--------------- Remove, because it is the first 1 and is followed by another 1

```

---

Finally, we loop all of the above (`{`) until fixpoint
> 1 votes

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