title: Find the dimensions of a ragged list

text:
# Question
Title: Find the dimensions of a ragged list
For any ragged list its *dimensions* will be a list of non-negative integers defined as follows:

* Elements that are not a list will have dimensions \\$\textbf{\[}\\,\\,\textbf{\]}\\$.
* An empty list has dimensions \\$\[0\]\\$.
* An \\$n\\$ dimensional list \\$L\\$ of length \\$x\\$ has dimensions \\$x : k\\$ where \\$k\\$ is the element wise maximum of the dimensions of the elements of \\$L\\$ (treating missing elements as zero).

(Here, `:` is "cons", the list constructor, e.g. in Lisp or Haskell)

The intuitive idea is that this is the dimensions of the smallest box which can fit the list. But this is still a little bit daunting, so let's work through some examples.

To start with, for one dimensional lists, its dimensions are always just its length.

```
[ 1
, 2
, 3
]

```

There are 3 elements here so its dimensions are \\$3:k\\$. To determine \\$k\\$ we look at the dimensions of each element. They are all integers so they have dimensions \\$\textbf{\[}\\,\\,\textbf{\]}\\$, and the pairwise maximum is also \\$\textbf{\[}\\,\\,\textbf{\]}\\$. So the dimensions are \\$3:\textbf{\[}\\,\\,\textbf{\]}\\$ or just \\$\[3\]\\$.

Let's do an example that is actually ragged:

```
[ [ 1
  , 2
  , 9
  , 9
  ]
, 4
]

```

There are two elements, the first is one dimensional so it has dimensions \\$\[4\]\\$, the second is an integer so it has dimensions \\$\textbf{\[}\\,\\,\textbf{\]}\\$. Now we take the pairwise maximum. Since \\$\[4\]\\$ has more elements we treat the missing elements as zeros. The maximum is just \\$\[4\]\\$ then. The total list has length \\$2\\$ so the answer is \\$2:\[4\]\\$ or \\$\[2,4\]\\$.

Let's do another example:

```
[ [ 1
  , 2
  , 9
  , 9
  ]
, [ []
  , 2
  ]
]

```

The first element is the same, but the second one is different, so let's calculate its dimensions. It has two elements with dimensions \\$\[0\]\\$ and \\$\textbf{\[}\\,\\,\textbf{\]}\\$. The pairwise maximum is \\$\[0\]\\$ so this element has dimensions \\$\[2,0\]\\$. With this in mind now we take the pairwise maximum of \\$\[4\]\\$ and \\$\[2,0\]\\$ which gives \\$\[4,0\]\\$. Finally we add one the \\$2\\$ for the length of the top level and get the dimensions of \\$\[2,4,0\]\\$

# Task

Given an arbitrary ragged list of positive integer give a list of non-negative integers representing its dimensions. You may assume that the input is a *list*.

This is so the goal is to minimize the size of your source code as measured in bytes.

# Test cases

```
[]
=> [0]
[ 1, 2, 3]
=> [3]
[[1, 2, 9, 9], 4]
=> [2,4]
[[1, 2, 9, 9], [[], 2]]
=> [2,4,0]
[[[]],[]]
=> [2,1,0]
[[1,2,3],[[1,2,3],[[1,2,3],[[1,2,3],[1,2,3]]]]]
=> [2,3,3,3,3]

```

# Answer
# Python 2, 52 bytes

```
d=lambda l:d<l and[len(l)]+map(max,[],*map(d,l))or[]
```

Attempt This Online!

## Old Python 2, 53 bytes (@att)

```
d=lambda l:[1]*(d<l)and[len(l)]+map(max,[],*map(d,l))
```

Attempt This Online!

## Old Python 2, 65 bytes

```
d=lambda l:[1]*(d<l)and[len(l)]+map(lambda*a:max(a),[],*map(d,l))
```

Attempt This Online!

That's a cleanup of @Steffan's Python 2 answer. He made it a challenge, so I took the liberty of posting it as a separate answer.
> 4 votes

# Answer
# Whython, 95 bytes

```
from itertools import*
d=lambda l:[len(l),*(map(max,zip_longest(*map(d,l),fillvalue=0))?[])]?[]
```

Attempt This Online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
Max/@#~Position~_?AtomQ~Flatten~{2}&

```

Try it online!

-5 bytes thanks to @att.

---

## Wolfram Language (Mathematica), 41 bytes

```
Max/@Thread@PadRight@Position[#,_?AtomQ]&

```

Try it online!

### How?

In Mathematica, everything is an expression. An expression is a tree, where atoms are the leaves: symbols, numbers, strings, etc.

How many atoms are there in the expression `{1, 2, 3}`?

The answer is 4. In fact, `{1, 2, 3}` is just a syntactic sugar for `List[1, 2, 3]`, which has 4 atoms: `1`, `2`, `3` and `List`. `List` is the head of the expression, whose position is `0`.

Now takes the input `{1, {}, 2}` as an example. When desugared, it becomes `List[1, List[], 2]`, which has 4 atoms: `List`, `1`, `List`, `2`.

`Position[#,_?AtomQ]` finds the positions of all atoms in the input. In this case, it is `{{0}, {1}, {2, 0}, {3}}`.

`PadRight` pads the list with `0`s to make it a full (i.e., not ragged) array. So it becomes `{{0, 0}, {1, 0}, {2, 0}, {3, 0}}`.

`Thread` transposes the array. So it becomes `{{0, 1, 2, 3}, {0, 0, 0, 0}}`.

Finally, `Max/@` finds the maximum value in each row. So the result is `{3, 0}`.
> 2 votes

# Answer
# JavaScript, 65 bytes

```
f=(a,e=+(o=[]),L=0)=>!a.map?.(v=>f(v,e+1)*++L)|L<o[e]||(o[e]=L,o)

```

```
f=(a,e=+(o=[]),L=0)=>!a.map?.(v=>f(v,e+1)*++L)|L<o[e]||(o[e]=L,o)

t = `
[] => [0]
[ 1, 2, 3] => [3]
[[1, 2, 9, 9], 4] => [2,4]
[[1, 2, 9, 9], [[], 2]] => [2,4,0]
[[[]],[]] => [2,1,0]
[[1,2,3],[[1,2,3],[[1,2,3],[[1,2,3],[1,2,3]]]]] => [2,3,3,3,3]
`.trim().split('\n').map(l => l.split('=>').map(v => JSON.parse(v)));
t.forEach(([i, e]) => {
  console.log(f(i) + '' == e, JSON.stringify(f(i)));
});
```

```
f=(
  a,      // Input array
  e=+(    // Current level
  o=[]),  // Output array, initialized by []
  L=0     // length of input
)=>
  !a.map?.(v=>    // If Current level is an array not integer And
    f(v,e+1)*     //     Recursively call `f` for inner levels
    ++L)|         //     Count length of input array
  L<o[e]||        // If Current length is longer than we ever seen
  (o[e]=L,o)      // Update it, and remember to return the output array

```
> 2 votes

# Answer
# , ~~126~~ 119 bytes

```
d=function(l,`+`=sapply,r=length)c(r(l),if(any(m<-l+is.list))do.call(pmax,c(lapply(k<-l[m]+d,`[`,1:max(k+r)),na.rm=T)))

```

Try it online!

This was supposed to be just a simple recursive function using the elementwise-maximum (`emax`) to get the largest element at each position of a list of unequal-length vectors:

```
dimensions=
d=function(l,m=sapply(l,is.list))c(length(l),if(any(m))emax(lapply(l[m],d)))

```

Unfortunately, the `emax` function does not exist. This is because  **loves** element-recycling, and the similar-seeming parallel-maximum function - `pmax` \- helpfully recycles the elements of unequal-length vectors (so `pmax(10:11,1:3)` gives `10 11 10` instead of `10 11 3`): exactly what we *don't* want here!).
So this approach needs to implement `emax` by 'padding' all shorter vectors with `NA`s, before calling `pmax` and specifying `na.rm=T` to ignore them:

```
emax=
function(l)do.call(pmax,c(lapply(l,`[`,1:max(lengths(l))),na.rm=T))

```

Rolling these two functions together, we can golf out a few excess characters (and render the code near-unreadable as a by-product), but bearing in mind how awkward this overall approach is, I won't be surprised if there's a shorter one that doesn't require creating nonexistant functions to make it work...
> 2 votes

# Answer
# Python 2, 77 bytes

```
d=lambda l:l*0==[]and[len(l)]+('['in`l`[1:]and map(max,[],*map(d,l))or[])or[]
```

Attempt This Online!

Takes advantage of a bunch of Python 2 stuff:

* multiple lists passed to `map` pads with `None`
* `max` works with values other than integers (which includes `None`)
* can do ``l`` with Python 2's backticks instead of `str(l)`

# Python, 128 bytes

```
from itertools import*
d=lambda l:[len(l),*(map(max,zip_longest(*map(d,l),fillvalue=0))if'['in str(l)[1:]else[])]if[]==l*0else[]
```

Attempt This Online!
> 1 votes

# Answer
# Python 3, 73 bytes

```
f=lambda*a:a and[max(map(len,a)),*f(*[b for b in sum(a,[])if'A'<str(b)])]

```

Try it online!

And this is 70 bytes in Python 3 (Cython).
> 1 votes

# Answer
# Haskell \+ free, 73 bytes

```
(a:b)!(c:d)=max a c:b!d
[]!x=x
y!_=y
iter((:).length<*>foldr(!)[]).([]<$)

```

Try it online!

Here we represent ragged lists as free monads of lists.

We define `(!)` which takes the pairwise maximum of two lists. This is almost just `zipWith max`, but that takes the length of the shorter list, and we need the length of the longer one defaulting to zero when empty.

That makes up the majority of the code. The rest of the code is the point free function that implements the answer.

First we have `([]<$)` this replaces every terminal element with `[]` which is it's dimensions. This is the base case for our recursion. Then we have the recursive step which is `(:).length<*>foldr(!)[]`. Which is just point-free for `\x -> length x:foldr(!)[]x` or the length of the list `x` and the pairwise maximum of all its elements.

We combine the inductive step and the base case with `iter` from the free library to make it work. `iter` is just induction on free monads.
> 1 votes

# Answer
# Haskell + hgl, 21 bytes

```
shp[]$l*:*rF(zd' ma)i

```

## Explanation

* `zd' ma` takes the pairwise maximum of two lists. `zdm ma` would also work.
* `rF(zd' ma)i` folds the above across a list of lists. `lf(zd' ma)i` also works.
* `(l*:*)` takes the a function and a list and prepends the length of the list onto the result of the function.
* `l*:*rF(zd' ma)i` forms the inductive step of our algorithm. It takes a list of dimensions, calculates the pairwise maximum and then adds the length onto the front of that result.
* `shp[]` takes an inductive step and replaces everything with `[]` as a base case.

So altogether this implements a basic recursive algorithm.

## Reflection

There's a lot here that might be useful to combine.

* `frF i<zd'` could be useful, if I had a function `zzD=frF i<zd` the answer would be `shp[]$l*:*zzD ma` saving 5 bytes here. It might in general be useful to have versions of the zip functions that operate over a foldable rather than just combining two elements.
* `shp i` might be useful as a standalone it seems like the most common arguments for `shp` would be `[]` and `0`, which are both `i`.
* `(l*:*)` is something I think I've done in the past might be useful to give it a name.
> 1 votes

# Answer
# Python3, 202 bytes:

```
lambda x:(K:=lambda d,j={}:[max(j[i])for i in j]if[]==d else K(d[1:],{**j,d[0][0]:j.get(d[0][0],[])+[d[0][1]]}))(f(x))
f=lambda x,c=0:[[c,len(x)]]+[j for k in x for j in(f(k,c+1)if list==type(k)else[])]

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 30 bytes

```
"Ddi¯ëÐ˜Êi®δ.VDU0ζ€àXgšëg¸"©.V

```

Try it online or verify all test cases.

**Explanation:**

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

  i                # If
D                  # a copy of the current value
 d                 # is >= 0 (thus an integer):
   ¯               #  Push an empty list
ë   i              # Else-if
 Ð                 # a copy of the current value
   Ê               # is NOT equal to
 Ð˜                # a flattened copy of the current value (thus it's a ragged
                   # list):
      δ            #  Map over each inner list:
     ® .V          #   And do a recursive call by 05AB1E-executing string `®`
         DU        #  Store a copy of the result in variable `X`
            ζ      #  Zip/transpose; swapping rows/columns,
           0       #  with 0 as filler for unequal length lists
              à    #  Get the maximum
             €     #  of each inner list
                 š #  And then prepend to this list
                g  #  the length
               X   #  of variable `X`
ë                  # Else (thus it's a flattened list):
 g                 #  Push its length
  ¸                #  Wrap it into a list

```
> 0 votes

# Answer
# Jelly, 10 bytes

```
WẎƬṖḟFẈṀƲ€

```

A monadic Link that accepts a ragged list of integers and yields a list of non-negative integers giving the depth-wise dimensions as required.

**Try it online!**

### How?

```
WẎƬṖḟFẈṀƲ€ - Link: ragged list of integers, L
W          - wrap L in a list
  Ƭ        - (starting with that) collect up inputs while distinct applying:
 Ẏ         -   tighten (drop first level of the inner lists)
   Ṗ       -   pop (remove the final input)
         € - for each:
        Ʋ  -   last four links as a monad:
     F     -     flatten (to a list of integers)
    ḟ      -     filter these out (only filters out integers at depth 1)
      Ẉ    -     length of each
       Ṁ   -     maximum

```
> 0 votes

# Answer
# Charcoal, 34 bytes

```
⊞υＡＷυ«≔υθ≔⟦⟧υＦθＦΦκ⁼λ⁺⟦⟧λ⊞υλ⟦Ｉ⌈ＥθＬκ

```

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

```
⊞υＡ

```

Push the input list to the predefined empty list.

```
Ｗυ«

```

Repeat until the list of lists is empty.

```
≔υθ≔⟦⟧υ

```

Save it and start a new list.

```
ＦθＦΦκ⁼λ⁺⟦⟧λ⊞υλ

```

Push all of the elements of the lists that are themselves lists to the list.

```
⟦Ｉ⌈ＥθＬκ

```

Output the maximum length of all of the original lists on its own line.
> 0 votes

---
Tags: code-golf, ragged-list
---


title: Magic: the Gathering - Colour Sorting

text:
# Question
Title: Magic: the Gathering - Colour Sorting
Related: Deck Names Friends or Foes Paying for Spells

The Magic: the Gathering card game has five colours of magical mana: white (W), blue (U), black (B), red (R), and green (G). Cards can be any of the \\$2^5=32\\$ subsets of these colours. Hereafter 'colours' refer just to the initials `W`, `U`, `B`, `R`, `G`.

The order that these colours present themselves on cards follows a method using the colours arranged as a pentagon:

```
  W
G   U
 R B

```

The order seeks to minimise the gaps between colours when read clockwise around the pentagon, while making the gaps equal sizes. Ties are broken by starting with `W`. There are only eight arrangements with rotational symmetry;

* no colours: `C` or `''`
* one colour: `W`, `U`, `B`, `R`, `G`
* two adjacent colours: `WU`, `UB`, `BR`, `RG`, `GW`
* two opposite colours: `WB`, `UR`, `BG`, `RW`, `GU`
* three adjacent colours: `WUB`, `UBR`, `BRG`, `RGW`, `GWU`
* three opposite colours: `WBG`, `URW`, `BGU`, `RWB`, `GUR`
* four colours: `WUBR`, `UBRG`, `BRGW`, `RGWU`, `GWUB`
* all five colours, start from the top: `WUBRG`

## Challenge

You challenge is to create a function/program, which when given a set of colours, outputs their correct order.

This is code golf, so your solution should be as short as possible!

## Input

Input format is flexible. As long as it is not relying on the order given, anything is acceptable. Some examples:

* Binary number or bit string of length 5
* A string/array containing each colour, either a substring of 'WUBRG' or arbitrary order
* A set or dictionary for each colour

## Output

Output must follow standard output methods to output a string/array of the colours. For the case of no colours, an empty string/array or `C` (colourless) is allowed. Otherwise output must match an entry from the list below. Case doesn’t matter.

For your convenience, here is a list of all possible combinations

```
C
W
U
B
R
G
WU
UB
BR
RG
GW
WB
UR
BG
RW
GU
WUB
UBR
BRG
RGW
GWU
WBG
URW
BGU
RWB
GUR
WUBR
UBRG
BRGW
RGWU
GWUB
WUBRG

```

# Answer
# Vyxal, 11 bytes

```
sṖµ¯5%₍≈⌐;t

```

Try it Online!

I *think* this works? Takes a list of 0, 1, 2, 3, 4. Fixed for +1 byte thanks to @KevinCruijssen.

```
s           # Sort (annoying edgecase)
 Ṗµ      ;t # The maximal permutation by...
   ¯        # Differences
    5%      # Modulo 5
      ₍     # Sort primarily by...
       ≈    # All differences are the same
      ₍     # And secondarily by...
        ⌐   # 1 - the list = minimal value.

```
> 8 votes

# Answer
# JavaScript (ES10), 71 bytes

Expects a bitmask in `UWGRB` order (from most to least significant bit). Returns an array of characters.

```
n=>[...s="BRGWU"].flatMap(_=>n>>++k%5&1?s[k%5]:[],k=1950448093/n/n%5|0)

```

Try it online!

---

# JavaScript (ES10), 75 bytes

Expects a bitmask in `RBUWG` order (from most to least significant bit). Returns an array of characters.

```
n=>[...s="GWUBR"].flatMap(_=>n>>++k%5&1?s[k%5]:[],k=~~"204122031"[n%19%13])

```

Try it online!

### How?

We build the output by adding characters from the string `"GWUBR"` according to the bits that are set in the input, starting at a valid position, going from left to right and wrapping.

Fortunately, the starting position is quite flexible. For instance, for the expected output `"GW"`, we can start anywhere except at `W` because `U`, `B` and `R` are discarded anyway. This allows to increase the number of consistent collisions in the lookup table and make it a little more compact.

Below is a summary of all acceptable starting positions for each pattern, along with the position which is actually chosen.

```
  n | pattern | acceptable  | i=n%19%13 | ~~"204122031"[i]
----+---------+-------------+-----------+------------------
  0 | ""      | [0,1,2,3,4] |      0    |        2
  1 | "G"     | [0,1,2,3,4] |      1    |        0
  2 | "W"     | [0,1,2,3,4] |      2    |        4
  3 | "GW"    | [1,2,3,4]   |      3    |        1
  4 | "U"     | [0,1,2,3,4] |      4    |        2
  5 | "GU"    | [2,3,4]     |      5    |        2
  6 | "WU"    | [0,2,3,4]   |      6    |        0
  7 | "GWU"   | [2,3,4]     |      7    |        3
  8 | "B"     | [0,1,2,3,4] |      8    |        1
  9 | "BG"    | [0,1,2]     |      9    |        0
 10 | "WB"    | [0,3,4]     |     10    |        0
 11 | "WBG"   | [0]         |     11    |        0
 12 | "UB"    | [0,1,3,4]   |     12    |        0
 13 | "BGU"   | [2]         |      0    |        2
 14 | "WUB"   | [0,3,4]     |      1    |        0
 15 | "GWUB"  | [3,4]       |      2    |        4
 16 | "R"     | [0,1,2,3,4] |      3    |        1
 17 | "RG"    | [0,1,2,3]   |      4    |        2
 18 | "RW"    | [1,2,3]     |      5    |        2
 19 | "RGW"   | [1,2,3]     |      0    |        2
 20 | "UR"    | [0,1,4]     |      1    |        0
 21 | "GUR"   | [4]         |      2    |        4
 22 | "URW"   | [1]         |      3    |        1
 23 | "RGWU"  | [2,3]       |      4    |        2
 24 | "BR"    | [0,1,2,4]   |      5    |        2
 25 | "BRG"   | [0,1,2]     |      6    |        0
 26 | "RWB"   | [3]         |      7    |        3
 27 | "BRGW"  | [1,2]       |      8    |        1
 28 | "UBR"   | [0,1,4]     |      9    |        0
 29 | "UBRG"  | [0,1]       |     10    |        0
 30 | "WUBR"  | [0,4]       |     11    |        0
 31 | "WUBRG" | [0]         |     12    |        0

```
> 6 votes

# Answer
# JavaScript (Node.js), ~~258~~ 247 bytes

```
s=>(c="WUBRG",p=[0,1,2,3].map(i=>(t=>t.slice(i)+t.slice(0,i))(s.sort(m=(x,y)=>c.indexOf(x)-c.indexOf(y)).join``)).filter(x=>new Set([...x.slice(1)].map((z,k)=>(x=>(m(x,z)+5)%5)(x[k]))).size==1),({"WG":"GW","WR":"RW","UG":"GU"})[q=p+p?p[0]:s+p]||q)

```

Try it online!
> 4 votes

# Answer
# x86-64 machine code, 37 bytes

```
6B CE 21 B8 47 52 42 55 B2 57 BE FD F7 FD 55 D3 E6 45 18 C0 C1 C0 08 86 D0 D1 D9 78 ED 73 F3 AA 84 C0 75 EE C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string, and takes the input bitmask in ESI (W=1, U=2, B=4, R=8, G=16).

In assembly:

```
f: imul ecx, esi, 33

```

ECX := 33 * ESI. Transfer the bitmask from ESI to ECX while duplicating bits 0–4 into bits 5–9.

```
mov eax, ('U'<<24|'B'<<16|'R'<<8|'G')
mov dl, 'W'

```

Put the colour letters in these registers.

```
a: mov esi, 0b01010101111111011111011111111101
shl esi, cl

```

Place this value in ESI, then shift it left by the low 5 bits of ECX. The last bit shifted out goes into CF; a 0 indicates a correct arrangement.

```
.byte 0x45      # REX.RB
ws: sbb al, al

```

These combine to form `sbb r8l, r8l` (subtract R8L+CF from R8L). The value of R8L becomes -CF, and SF is set from its sign bit, equalling CF.

```
n: rol eax, 8
xchg al, dl

```

Together, these instructions rotate the five colour letters, while SF remains unchanged.

```
rcr ecx, 1

```

Rotate ECX (holding the bitmask) and CF together right by 1; the low bit of ECX goes into CF. Also, SF still remains unchanged.

```
js a

```

Jump back if SF=1.

```
w: jnc ws

```

At this point, the correct arrangement has been found, and it remains to produce the string from it. Jump if CF (which is the bit just taken off the bitmask) is 0.

```
stosb

```

(If it is 1) Add AL to the output string, advancing the pointer.

```
test al, al
jnz ws

```

Jump back if AL is nonzero.

```
ret

```

(If AL is zero) Return.

Both of the jumps within the output section lead to `ws: sbb al, al`, which sets AL to 0 (as CF will be zero, from the `rcr` or from the `test`), to end the string instead of repeating the letter when it comes back around.

---

Input 0 is a special case. `shl` by 0 does not change the flags, but CF will be 0 from the `imul` to indicate a correct arrangement. Nothing will be written for a while, and all the letters will be replaced with null bytes. Eventually, a 1 bit rotated into the top of ECX by `rcr ecx, 1` (from CF becoming 1 from the `rol eax, 8`) will make its way to the bottom and then back into CF, resulting in outputting a null byte and returning.
> 3 votes

# Answer
# Python, 171 bytes

```
lambda s,g="WUBRG":[min([[e,p]for p in permutations(s)if len(set(e:=[(g.find(p[i+1])-g.find(p[i]))%5 for i in range(len(s)-1)]))<2])[1],g][len(s)>4]
from itertools import*
```

Attempt This Online!

Works similarly to @emanresuA's answer, but derived independently. Takes a string as input, outputs a list
> 2 votes

# Answer
# Python, 106 bytes

```
f=lambda s,t=0:(2*"WUBRG")[x:x+len(y):1-t]if~(x:=(2*s).find(y:=(s.count("1")*"01"[~t:])[-t:]))else f(s,~t)
```

Attempt This Online!

Test harness shamelessly stolen from @jezza\_99. Expects a binary string indicating which of "WUBRG" are present.

How?

Counts "1"s in the input, for example 3 "1"s. Then checks for the patterns "111" and "10101" in 2\*input where the factor 2 is to simulate wrap around. Finally, finds the same index in 2\*"WUBRG" and cuts out the corresponding letters.
> 2 votes

# Answer
# , 84 bytes

```
\(i)chartr("0-4","WUBRG",Find(\(j)all(i%in%j),Map(\(j)seq(j%%5,,j%/%5,,i)%%5,5:24)))
```

Attempt This Online!

Takes input as a vector of numbers 0-4, outputs a vector of letters.
> 2 votes

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

```
{ÀœΣ¥5%(DËš}θ

```

Port of *@emanresuA*'s Vyxal answer, so make sure to upvote him/her as well!
+2 bytes to correct the output when all five values are input

Uses `1,2,3,4,5` for `W,U,B,R,G` respectively.

Try it online or verify all test cases.

**Explanation:**

```
           # Fix the output of the edge-case when all five values are input:
{          #  Sort the (implicit) input-list
 À         #  Rotate it once towards the left
œ          # Get all permutations of this list
 Σ         # Sort this list of lists by:
  ¥        #  Get the differences of the current list
   5%      #  Modulo-5 for the negative values
     (     #  Negate all of these values
      D    #  Duplicate it
       Ë   #  Check if all values in the copy are the same
        š  #  Prepend this 0 or 1 to the list of negative differences
 }θ        # After the sort_by: pop and push the last value
           # (the `Σ...}θ` basically acted as a max_by builtin)
           # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Charcoal, ~~26~~ 25 bytes

```
⊟ΦＥχ⭆θ§UBRGW⁺ι×μ⊕‹ι⁵⬤ι№θλ

```

Try it online! Link is to verbose version of code. Explanation: Generates all cyclic slices of `UBRGW` with step of either `2` or `1` having the length of the input and outputs the last that is a permutation of the input.

```
   χ                        Predefined variable `10`
  Ｅ                         Map over implicit range
     θ                      Input string
    ⭆                       Map over characters
       UBRGW                Literal string `UBRGW`
      §                     Cyclically indexed by
             ι              Outer value
            ⁺               Plus
               μ            Inner index
              ×             Times
                  ι         Outer value
                 ‹          Is less than
                   ⁵        Literal integer `5`
                ⊕           Incremented
 Φ                          Filtered where
                     ι      Current string
                    ⬤       All characters satisfy
                       θ    Input string
                      №     Contains
                        λ   Current character
⊟                           Take the last element (smallest delta)
                            Implicitly print

```

For input strings of lengths `1` to `5` the following strings are generated:

1. `U` `B` `R` `G` `W` `U` `B` `R` `G` `W`
2. `UR` `BG` `RW` `GU` `WB` `UB` `BR` `RG` `GW` `WU`
3. `URW` `BGU` `RWB` `GUR` `WBG` `UBR` `BRG` `RGW` `GWU` `WUB`
4. `URWB` `BGUR` `RWBG` `GURW` `WBGU` `UBRG` `BRGW` `RGWU` `GWUB` `WUBR`
5. `URWBG` `BGURW` `RWBGU` `GURWB` `WBGUR` `UBRGW` `BRGWU` `RGWUB` `GWUBR` `WUBRG`

In the case of strings of length `1` the same string is generated twice so it doesn't matter which is picked while in the case of strings of length `2` or `3` all `10` permutations are generated so there is only one matching the input but in the case of strings of length `4` or `5` there would be multiple matching strings; in the case of `4` the first five are invalid and in the case of `5` the first nine are invalid so that the last matching string is the correct output as desired.
> 0 votes

---
Tags: code-golf, sorting, card-games
---


title: What's the Missing Code? (Cops)

text:
# Question
Title: What's the Missing Code? (Cops)
# Cops' Challenge

Robbers' challenge here.

> It has now been four days since the challenge was posted so all new answers should be marked as **non-competing** in the title. These answers can still be cracked by robbers but will not go towards their total, and cannot win this challenge.

In this challenge, you (the cops) must write a program which prints out a certain string (to STDOUT) when run (and does not error or print to STDERR).
Then, **remove a string of consecutive characters** from the code so that it **still runs (without erroring or printing to STDERR)**, but does not give the correct output (or gives no output).

Robbers will try to find the correct characters to add back into the code so that it produces the right (case-sensitive) output (except that there may be an extra trailing newline).
The number of characters they find must be less than or equal to the number of characters removed, so if 4 characters were removed and they find a solution adding in only 3 characters, it is still valid.

In your answer, provide:

1. The language of the code
2. The code with characters removed (remember, the characters must be consecutive: you can't remove characters from several different places in the code)
3. How many characters have been removed
4. The string that the full program outputs (if there is a trailing newline, you may leave that out)

**Remember that your answer is still cracked even if the solution found by the robbers was not intended**. For this reason, make sure it is not possible for the robbers to simply put some code which says

```
Print out the string;
End the program.

```

(In order to stop this happening, try to minimise the number of characters removed while making sure the submission is still challenging. This will also improve your score.)

The score of an answer is equal to: $$ \operatorname{len}(\text{program with chars removed}) + 2 \times \operatorname{len}(\text{chars removed}) $$ or $$ \operatorname{len}(\text{program}) + \operatorname{len}(\text{chars removed}) $$ (They both equate to the same thing).

Make sure to edit your answer if it has been cracked, and link the robber's post. If the robber found an unintended solution, then you may keep the intended solution a secret so that people can still try to find it.

## Example submission

> # Python, score of 14
>
> Code: `print(5*"a")`
> Number of characters removed: 1
> Target output: `5 a` (currently outputs `aaaaa`)

This would be very easy to crack as the character `,` would just need to be added before the `*`, but it would be valid.

## Scoring

The following scoring criterion will be used in order (if #1 is a tie, then #2 is used to tiebreak, etc.):

1. The cop with the lowest-score uncracked answer after 1 week wins!
2. Out of the tied cops, the one whose lowest-scored uncracked answer has the most upvotes wins
3. Out of the tied cops, the one whose lowest-scored most-upvoted uncracked answer was posted first wins

After 4 days, answers posted to this question will be non-competing (but can still be posted), to stop people posting answers just before the week is over and not giving robbers enough time to crack them.

If it has been four days since this was posted (Saturday 2nd April 2022, after whatever time this was posted in your time zone), please mark your answers as "non-competing" in the title.

Robbers can still crack cops' answers for the remaining 3 days and have those count towards their total; however, cracking non-competing cops' answers does not count towards their total.

Good luck!

# Answer
# Vyxal, 2 + (2 * 4) = 10, safe!

```
kj

```

Try it Online!

One last one... Output should be `////\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\////\\///\\\//\\\////\\///\\\//\\\\///\\///\\\//\\\\///\\///\\\//\\\\`

> ```
> k/3(:j
> ```
> Try it Online!
> Explanation:
> ```
> k/      # "/\"
>    3(   # 3 times...
>      :j # Join by itself
> ```
> Spoilers = pain
> 5 votes

# Answer
# Python 3, score 24, cracked by xnor

```
print((99,15))

```
* 5 characters removed
* Target output: `(6, 9)`
* Current output: `(99, 15)`

There's a lot of ways to get 6 but (hopefully) only one to get 5.
> 16 votes

# Answer
# Java (OpenJDK 8), 547 + 10 = 557 Cracked by Kevin Cruijssen

```
import static java.util.stream.Collectors.joining;
import java.util.stream.IntStream;

class Program {
    public static void main(String[] args) {
        System.out.println(new Program());
    }

    String getName(int x) {
        return x + " " + Integer.toHexString(x);
    }

    public String toString() {
        return IntStream.of(130, 14, 8613, 8784, 150, 151).mapToObj(x -> {
            String[] s = getName(x).split(" ");
            int n = (x % 13) % 5;
            return s[n % s.length];
        }).collect(joining(" "));
    }
}

```

Try it online!

I've never done this before and I see my entry is way longer than others. If that's not appropriate let me know and I'll delete it. Of course, Java is infamously verbose. I could also give a hint about what part of my program the characters were deleted from.

* 10 characters removed
* Target output: `BREAK OUT FROM THE GUARDED AREA`
* Current output: `130 e 8613 8784 150 97`

So, can the robbers break out from the guarded area?
> 12 votes

# Answer
# Jelly, score = 19

A contiguous string of **seven bytes** was removed from **twelve**, leaving these **five**:

```
49“»V

```

Running this as a full program now outputs `0`, the output of the original program was:

```
Dyesters opposredoundse urosthenicupdrying@uniocular alkie Elgar ontic)0e eyednesses Kangarooed TPN harvestbug_| Enviability gilly ophiolaterDenebWorst horsRockierU Huey: Yelt aBA

```

**Try it online!**

I don't think this will be easy by any stretch of the imagination, but there are some clever people here who might just find one (of the ones?!) that work out of the \\$4.3 \times 10^{17}\\$ possible programs.

---

### Safe, so how did it work?

I guess this was just a little too much to crack, here's the original program:

> ```
>  49!’Æfj@⁾“»V - Link:
>  49           - fourty-nine        ->  49
>    !          - factorial              608281864034267560872252163321295376887552831379210240000000000
>     ’         - subtract one           608281864034267560872252163321295376887552831379210239999999999
>      Æf       - prime decomposition    [823,3739397,197653021455862028208110725148879567449727922627417829]
>          ⁾“»  - list of characters ->  ['“', '»']
>         @     - with swapped arguments:
>        j      -   join                 ['“',823,3739397,197653021455862028208110725148879567449727922627417829,'»']
>             V - evaluate “82337...829» as Jelly code
>                     (“...» is Jelly's dictionary-based compression)
>
> ```
> 9 votes

# Answer
# Perl 5, score 24, safe

```
print for a..z

```
* 5 characters removed
* Target output: `ABABABABABABABABABABABABAB`
* Current output: `abcdefghijklmnopqrstuvwxyz`

No interpreter flags or trickery involved, this is pure Perl.

## Solution

> ```
>
>  print<\3>^B for a..z
>
> ```

> The code works as is, but replace `\3` with a literal `\3` character to get the claimed score of 5 characters removed.
> 9 votes

# Answer
# , score 31, cracked by Dominic van Essen

```
el(6)

```

Try it online!

* `13` characters removed
* Target output: `"Infant.Mortality"`
* Current output: `6`

Probably too easy for those familiar with ...
> 7 votes

# Answer
# MATL, score 20. Cracked by Sanchises

```
'Hey My'

```

Try it online!

* 6 characters removed.
* Target output: `Hey Hey My My` (displayed with line feed at the end).
* Current output: `Hey My` (displayed with line feed at the end).
> 5 votes

# Answer
## PHP, cracked by dingledooper

* Score : **45**
* Removed 5 consecutive chars
* Current output is `38416064248`
* Expected output is `612510483624`

```
<?php for($i=7;$i-->2;)print$i<<$i;

```

**Edited** : *removed whitespaces and score was updated in consequence. Also assuming short\_open\_tag are disabled.*
> 5 votes

# Answer
# , score 10 + 2×8 = 26, cracked by Dominic van Essen

```
print("R")

```

Try it online!

* 8 characters removed
* Current output: `[1] "R"`
* Target output: `[1] R`

I haven't done this in a while; I hope I didn't miss an obvious solution!
> 4 votes

# Answer
# Python, score 36, cracked by dingledooper

```
"print("")"
print()
""
```

Attempt This Online!

Add 7 bytes, and output:

```
print()

```
> 4 votes

# Answer
# JavaScript (Node.js), 13+23\*2=59, Cracked

```
console.log()

```

Try it online!

* Removed 23 characters
* Should output `39iw027a2hnuqi2c1os255jmjsidafs3nx6496n8vl8dak0qc3r15xwheq4vxpb136up7rsmbm8v5slowjwf7mvj0s751b03gxif5`
> 3 votes

# Answer
# C (C99, clang), 34 bytes removed + 666 bytes total = 700 score

Try it online!

```
#include <stdio.h>
#include <string.h>
#define p1 2
#define p2 3
#define p3 (p1+p2)
#define p4 p3+p1
#define p5 p4+p1+p1
#define p6 (p5+p1)
#define p7 p6+p1+p1
#define p8 p7+p1
#define ONEHUNDREDTHIRTYONE (p6*p1*p3 + 1)
#define A (p1<<p6)
#define P0 625*p3
#define P P0*P0
#define P3 (P0*p3)*(p1<<p3)
#define B P/A + A/P
#define C(X,Y) X+X+Y*Y
#define D(W,V) C(W,V)*C(V,W)
#define E(M,N) M+N+1
#define F(X) E(X,p2*X)
#define G F(D(E(B,A),(A,B)))
int main()
{
long long a = p1*p1*p1*p1;
a<<=(p8);
a<<=(p8);
a<<=(p6);
a*=ONEHUNDREDTHIRTYONE;
int g = G;
a/=g;
for(int i = 1; i < (g/(P3)) && a!=0; i++)
{
printf("%llX",F(a));
a/=p1;
}
}

```

Currently outputs `270F665E11387B32F19C3D99794E1ECCBD270F665D1387B32D9C3D9954E1ECC9270F6651387B319C3D994E1ECD270F651387B19C3D94E1ED270F5138799C3D4E1D270D13859C14E12711399D4D251195`

Should output `8300000001418000000120C0000001106000000183000000141800000120C000001106000001830000014180000120C00001106000018300001418000120C0001106000183000141800120C001106001830014180120C01106018301418120C1106183141920D105`

A lot of preprocessor trickery was used to set up the challenge which sadly makes it a little less competetive lengthwise.

Hint:

> In the intended solution there is no character from either \[0-9\] or \[+,-\] sets
> 3 votes

# Answer
# Lexurgy, Cracked by Jonathan Allan

# \\$7 + 2\times 32=71\\$ score

```
a:
*=>w

```
* Characters removed: 32
* Target: `zwq`
* Current: `w`

Original code:

```
a:
*=>aaa
b:
a=>z/$ _
a=>q/_ $
a=>w

```
> 2 votes

# Answer
# Python 3, 55 bytes + 3 removed = 58 score CRACKED

```
print("".join(chr(i)for i in b'wZSSP\x1fhPMS[\x1e'))

```

Currently outputs `wZSSPhPMS[` (Plus two unprintables SE markup hates, check TIO link)

Should output `Hello World!`

Cracked by Sylvester Kruin
> 2 votes

# Answer
# Rust, \\$ 26 + (2 \times 12) = 50\\$

```
fn main(){print!("{}",81)}

```

Try it online!

* Characters removed: 12
* Expected output: `0.057987041728136374`
* Currently outputs: `81`

I'm putting the solution here, partly so that I don't forget later ;-), but even though the challenge is over, I encourage you to try to figure it out!

If you *really* want to know the solution, here it is:

> `fn main(){print!("{}",8f64.exp()%0.1)}`
> (added `f64.exp()%0.` between the `8` and the `1`)
> The `f64` converts the `8` to a float, and `.exp()` returns `e^(self)` (the exponential function).
> Then, the `%0.1` returns the remainder from dividing `8f64.exp()` by `0.1`. The resulting number is `0.057987041728136374`.
> Try it online!
> 2 votes

# Answer
# Python, 125 + 34 removed = 159 Cracked

```
import sys
S=sys.stdout
sys.stdout=type('',(),{'write':lambda x,y:'','flush':lambda z:1})()
```

Attempt This Online!

Not competitive compared to current Python answers, but I imagine people will find the answer *Pythonic*

Target output:

```
Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.

```

Current output: None
> 2 votes

# Answer
# Vyxal, 3 + (2 * 2) = 7, Cracked by Jonathan Allan.

```
kay

```

Try it Online!

Should output `acegikmoqsuwy]`. Bonus challenge: `cegikmoqsuwya`.
> 2 votes

# Answer
# Python 3, 23 chars with 4 chars removed = score 27 CRACKED

```
print(str()[14:18])

```

Currently outputs nothing, should output `Ctrl`

Try it online!
> 2 votes

# Answer
# , score 14 + 2×8 = 30, cracked by Dominic van Essen

```
`?`=print
?"R"

```

Try it online!

* 8 characters removed
* Current output: `[1] "R"`
* Target output: `[1] R`

This is my second attempt, after Dominic van Essen found an unintended crack to my first attempt. I hope this one is more robust!
> 2 votes

# Answer
# , score 24 + 2×8 = 40, cracked by Dominic van Essen

```
{assign("?",print)}
?"R"

```

Try it online!

* 8 characters removed
* Current output: `[1] "R"`
* Target output: `[1] R`

This is my third and probably last attempt, after Dominic van Essen found an unintended crack to my first attempt and then to my second attempt. I hope this one is more robust!
> 2 votes

# Answer
# MATL, 11 + 14 = 25 (safe)

```
'tacocat'0y

```

Try it online!

Current output:

```
tacocat
0
tacocat

```

Desired output, adding 7 bytes:

```
taataccocaccoaaat

```

---

## Intended solution

```
'tacocat'0y"@Yfh])

```

Try it online!

Forgot about this challenge for a while. Explanation:

```
'tacocat'          % Push the string 'tacocat'
          y"    ]  % Loop over copy of this string
            @Yf    % Calculate prime factors of each ASCII code point
         0     h   % Concatenate factors, with initial zero
                 ) % Index (modularly) into the original string. Implicit display.

```
> 2 votes

# Answer
# PHP all versions 64 bits, cracked by dingledooper

* Score : **50**
* Removed : 12 consecutive ascii chars
* Current all PHP versions (64 bits) output : `/* Nothing */`
* Expected all PHP versions (64 bits) output : `687755285922905`

```
<?php echo '';

```

**Info** : The solution may generate a deprecation notice and has possibly no digit.
> 2 votes

# Answer
# Vyxal, 3 + (11 * 2) = 25

```
`İy

```

Currently outputs `</li>y`, should output `d xdirf irrwst.mreo3//h.s-ksxdiry`.

A necessary spoiler: This works on MacOS and probably only there, on the offline Vyxal interpreter.
> 1 votes

# Answer
# Python 3, 20 bytes + 3 removed = 23, Cracked by des54321

```
print(str()[1:3]*50)

```

Try it online!

Currently prints an empty string. Should print 100 lowercase L's like so: `llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll`
> 1 votes

# Answer
# StackCell, 8 + (11 * 2) = 30 \[non-competing, safe\]

`"?":[;:]`

Current output: `?`
Correct output: `StackCell`

This should be pretty easy

Solution:

> **`"lleCkcatS` \[null\]** `"?":[;:]`

Explanation:

> The first `"` enters string mode.

> The bytes 108, 108, 101, 67, 107, 99, 97, 116, 83, and 0 are pushed, in turn (the string `\0Stackcell`, in reverse).

> The second `"` exits string mode.

> The `?` pops the top element (0) from the stack, and skips the next instruction (`"`)

> Then `:[;:]` prints the contents of the stack.
> `:` duplicates the top element of the stack to prevent the `[`/`]` from consuming the original, `[`/`]` form a loop as long as the stack contains a non-null item, and `;` pops and prints the top item of the stack as a character
> 1 votes

# Answer
# JavaScript (Node.js), 35+23\*2=81 bytes, safe

23 hidden chars

```
console.log([...Array(1e3).keys()])

```

Try it online!

Current output:

```
[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482,483,484,485,486,487,488,489,490,491,492,493,494,495,496,497,498,499,500,501,502,503,504,505,506,507,508,509,510,511,512,513,514,515,516,517,518,519,520,521,522,523,524,525,526,527,528,529,530,531,532,533,534,535,536,537,538,539,540,541,542,543,544,545,546,547,548,549,550,551,552,553,554,555,556,557,558,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,616,617,618,619,620,621,622,623,624,625,626,627,628,629,630,631,632,633,634,635,636,637,638,639,640,641,642,643,644,645,646,647,648,649,650,651,652,653,654,655,656,657,658,659,660,661,662,663,664,665,666,667,668,669,670,671,672,673,674,675,676,677,678,679,680,681,682,683,684,685,686,687,688,689,690,691,692,693,694,695,696,697,698,699,700,701,702,703,704,705,706,707,708,709,710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728,729,730,731,732,733,734,735,736,737,738,739,740,741,742,743,744,745,746,747,748,749,750,751,752,753,754,755,756,757,758,759,760,761,762,763,764,765,766,767,768,769,770,771,772,773,774,775,776,777,778,779,780,781,782,783,784,785,786,787,788,789,790,791,792,793,794,795,796,797,798,799,800,801,802,803,804,805,806,807,808,809,810,811,812,813,814,815,816,817,818,819,820,821,822,823,824,825,826,827,828,829,830,831,832,833,834,835,836,837,838,839,840,841,842,843,844,845,846,847,848,849,850,851,852,853,854,855,856,857,858,859,860,861,862,863,864,865,866,867,868,869,870,871,872,873,874,875,876,877,878,879,880,881,882,883,884,885,886,887,888,889,890,891,892,893,894,895,896,897,898,899,900,901,902,903,904,905,906,907,908,909,910,911,912,913,914,915,916,917,918,919,920,921,922,923,924,925,926,927,928,929,930,931,932,933,934,935,936,937,938,939,940,941,942,943,944,945,946,947,948,949,950,951,952,953,954,955,956,957,958,959,960,961,962,963,964,965,966,967,968,969,970,971,972,973,974,975,976,977,978,979,980,981,982,983,984,985,986,987,988,989,990,991,992,993,994,995,996,997,998,999]

```

Expected output:

```
[597,123,155,320,156,214,277,194,228,314,42,93,490,67,0,10,441,478,95,99,500,819,15,787,217,815,769,870,476,794,883,907,914,882,916,895,56,887,38,929,934,261,502,248,935,910,467,452,117,572,942,318,347,504,933,635,468,4,621,175,943,674,688,495,888,927,539,413,133,491,187,475,238,754,605,903,742,75,132,96,902,564,163,941,718,596,890,267,400,341,892,728,894,932,535,429,497,921,52,901,33,415,573,19,457,571,659,308,219,264,554,904,378,310,944,394,523,937,908,695,295,136,983,335,143,950,29,897,379,755,968,770,667,297,624,849,842,877,131,130,396,276,594,486,313,565,545,292,380,83,446,484,881,1,256,434,579,372,47,867,797,406,663,966,555,337,66,699,612,119,820,339,342,763,327,807,580,338,220,780,712,330,984,111,913,196,86,311,602,885,824,680,986,557,87,366,442,975,305,506,924,801,221,167,766,930,100,345,684,515,186,302,343,437,730,939,837,765,630,714,611,449,844,758,869,456,39,459,779,733,122,538,460,543,43,878,958,511,383,138,21,312,551,465,254,756,225,548,647,291,293,14,537,393,31,711,114,987,544,852,533,542,768,514,762,397,598,41,408,286,859,333,928,25,374,363,931,418,751,20,124,303,309,948,492,990,868,646,607,862,481,62,344,633,436,956,681,458,772,61,377,202,55,296,271,631,477,721,268,298,142,325,208,180,529,677,190,280,781,431,886,283,599,185,113,876,184,110,84,282,899,76,782,218,864,118,97,144,370,583,284,922,788,289,32,435,235,140,813,11,160,736,253,584,851,559,826,995,588,251,274,546,422,321,692,189,989,628,810,561,216,988,399,148,73,562,211,13,115,725,696,510,785,812,920,536,381,51,911,255,776,450,239,915,655,30,480,805,165,432,193,106,44,272,629,675,616,236,591,918,980,362,455,17,592,290,371,620,60,483,553,149,800,203,428,709,369,893,773,353,811,961,151,367,58,570,840,340,37,328,161,258,505,532,257,525,294,331,299,550,376,8,209,301,761,171,834,909,121,134,375,959,790,359,317,461,789,463,720,723,964,80,777,905,153,414,508,563,199,830,642,448,618,275,26,823,509,795,757,923,182,49,940,556,2,786,835,803,614,260,919,706,679,796,731,306,648,816,582,57,619,191,994,898,125,92,552,601,753,750,304,802,445,657,729,472,300,970,658,22,398,698,936,90,494,68,145,585,604,129,213,12,694,569,352,307,24,671,722,77,799,273,334,744,285,856,141,517,660,644,227,953,818,74,355,558,322,735,575,18,855,205,263,783,798,732,985,108,395,262,451,792,332,889,833,632,474,973,78,288,825,420,139,498,28,603,440,454,178,704,952,405,891,315,192,357,252,79,316,710,863,45,884,996,516,865,319,896,577,210,560,419,587,323,512,411,900,998,198,748,387,649,668,389,269,945,482,425,822,767,101,181,201,368,473,278,27,669,625,578,600,521,946,724,259,234,574,697,775,734,444,102,403,6,373,154,287,741,738,224,265,195,715,808,326,229,726,846,906,827,183,917,639,120,809,595,222,164,829,279,925,266,7,957,392,626,350,240,866,926,382,72,103,549,232,610,976,507,962,804,447,739,687,513,427,568,764,5,832,845,636,982,576,270,749,850,112,135,360,617,716,147,493,471,609,547,615,105,912,168,737,204,960,527,65,430,281,94,173,88,197,817,401,947,606,622,705,623,991,365,70,346,747,608,955,385,821,645,713,530,760,349,354,967,979,82,409,107,848,324,954,329,567,981,470,627,23,519,412,89,485,656,814,59,358,828,351,439,336,35,16,871,853,831,793,581,104,589,526,361,693,176,685,963,839,858,969,464,593,771,40,703,791,348,745,664,977,364,743,759,503,949,854,701,64,541,206,752,179,700,50,740,690,683,689,433,774,391,386,860,972,34,666,638,177,691,843,158,230,661,416,384,53,872,613,993,438,453,63,407,673,522,586,978,424,650,479,590,85,443,116,421,54,717,528,404,152,388,69,524,971,540,651,3,965,518,231,951,874,157,237,207,520,71,784,634,499,534,778,999,841,247,137,170,172,466,708,566,98,838,719,880,702,857,91,682,496,727,672,487,423,410,806,469,662,390,402,417,81,489,128,426,462,250,501,215,169,9,36,245,46,243,109,127,233,166,146,223,686,707,992,641,670,126,746,241,997,678,242,847,188,162,249,653,150,836,200,654,212,244,938,879,159,640,637,643,861,873,226,875,531,174,665,48,246,974,676,488,356,652]

```

> Notice that the output is an rearrangement and try `sort`, then there's not large space to test
> 0 votes

# Answer
# Behaviour, score = 16 + 2 = 18, cracked by Makonede

```
@(type:type)-0

```

just use a language that nobody knows amiright ;)

* 2 characters removed
* current output: `func`
* desired output: `fun`

hint:

> `type` is an embeded function that returns the type of a variable. Using `type` on `type` results in `"cfunc"`

The rest of the technics used are on the docs.

I could have made it smaller but the allure of having the output be `fun` was too great.
> 0 votes

# Answer
# C (gcc), 59 bytes + 17 removed = 76 score

```
n=999;main(){for(;printf("%d",n),n*=.9;);}

```

Currently outputs `99989980972865558953047742938634731228025222620318216314613111710594847567605448433834302724211816141210987654321`

Should output `997002512520100`
> 0 votes

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


title: Implement FBLint

text:
# Question
Title: Implement FBLint
(FB, or Functional-Basic, as found here Interpret Functional-Basic)

## Task

Implement a linting program for FB, similar to JSLint for JavaScript.

## Error types

### Invalid identifier

Identifiers can only have upper and lower case ASCII letters.

Locations:

* The identifier right after a `let` expression
* The identifier in a `for` loop

Examples:

```
for (? in b) <-- ? is invalid
let b_b8 = ... <-- b_b8 is invalid

```

### Undefined identifier

If you encounter an identifier that has not been defined in either a `let` expression or a `for` loop. Note that the identifier in a for loop *only* count in the expression following it.

Location:

* Anywhere an identifier is used

Example program:

```
let b = a <-- nope
for (x in a) x+1 <-- nope, still don't know what `a` is
print x <-- gotcha! `x` is out of scope here

```

### Unexpected EOL

End of line is the deliminator for statements in FB, so you can't have a statement span multiple lines (even if it's surrounded by parenthesis `()`). Use this if you expected more but encountered a EOL char.

Locations:

* Any line

Examples:

```
let b <-- missing the `= [statement]`
for ( <-- missing `x in y) [statement]`
print <-- print what?
print print sum <-- sum what?

```

### Unexpected token

This is best explained by examples.

Locations:

* Any line

Examples:

```
print * 2 <-- What is `*2` doing for me? I need a statement!
3**5      <-- `3*` expects a number, not a `*` symbol
for x in y <-- a little diffrent, but for
                     expects a pren `(`, not x

```

### Improper type

Used when a list is expected and a number was encountered, or when a number is needed and you get a list. Lists in FB are only allowed to have numbers or other lists as children, so errors can occur here as well. Note that if you find an identifier that is valid, you should perform this check based on the id's type.

Locations:

* Function application
* `for` loops
* The `+-*/^` operators
* List literal creation

Examples:

```
let y = [5]
let z = y + [[], [6]] <-- invalid, y is a list of numbers, right
                            hand side is a list of lists
print y + 1           <-- y is a list, not a number
sum 1                 <-- sum takes a list, not a number
[5] - [5]             <-- invalid, subtraction doesn't apply to lists
1 + []                <-- addition doesn't work with a list and a number
for (digit in 12) ... <-- `for` takes a list
let list = [00, 00]
let nlst = [list, 1]  <-- invalid
[1, []]               <-- invalid

```

### Multiple assignment

This is when a `for` loop or `let` statements identifiers overlap with a currently defined identifier.

Locations:

* In a `for` loop
* In a `let` statement

Examples:

```
let y = 8
let y = 5 <-- invalid, y is already defined
for (y in []) <-- invalid, y is already defined
for (x in []) ...
let x = 8 <-- valid since the `x` in the for loop is out of scope

```

### Nested for loop

Again, pretty self explanatory. FB doesn't allow nested for loops.

Locations:

* In `for` loops

Examples:

```
for (x in [[1, 5], [2, 8]]) for (y in x) x*y <-- just invalid

```

## Input format

If you are writing a function, you will receive one multi-line string. If you are writing a full program, you must take a multi-line input.

## Output format

Output format is simply the error title, followed by the line number the error occurs on. You must show all errors in the program.

Format:

```
[error title] on line [line number, 1-indexed]

```

## Example

This is one large example that should show all possible error types and outputs. Please let me know if I missed something.

### Input

```
let bb8 = 0
let bbEight = lst

for (x in
let x = 5*/5
let y = 4
let z = [5, 6] + y
let y = [[4]] + [y]
for (x in [[y, y+1], 5]) for (y in x)

```

### Output

```
Invalid identifier on line 1
Undefined identifier on line 2
Unexpected EOL on line 4
Unexpected token on line 5
Improper type on line 6
Improper type on line 7
Multiple assignment on line 7
Nested for loop on line 8
Multiple assignment on line 8
Multiple assignment on line 8
Improper type on line 8
Unexpected EOL on line 8

```

Note that thees checks may come in any order, and if the same error occurs multiple times on the same line, you must print the error multiple times as well.

I hope this isn't to difficult

## Edits

I have removed the `Empty line` error since it didn't make sense, and nobody is working on the problem (to my knowledge).

# Answer
# Python3, 2381 bytes:

```
import re
N=lambda x:next(x,0)
G={'sum':[[2,1],1],'product':[[2,1],1],'print':[-1,[2]]}
P={'+':[(1,1),(2,2)]}
def s(l):
 r=[]
 while l:r+=[j:=re.search('\w+|\(|\)|\=|\+|\-|\*|/|\^|\[|\]|,|\s+|\W+',l).group()];l=l[len(j):]
 return filter(lambda x:x.strip(),r)
M=['Invalid identifier','Undefined identifier','Unexpected EOL','Unexpected token','Improper type','Multiple assignment','Nested for loop']
B=lambda x:x if int==type(x)else x[0]
F=lambda I,n:M[I]+f' on line {n}'
def O(l,n,E,t=-1,c=2):
 if l==0:c=2
 if t==-2:c=c
 if (t==-1 and l)or l==t:return l
 E(F(c,n));raise Exception
def A(b,s,k,v):
 if v:b[s][k]=v
def X(l,n,s,b,E,C,L=0,W=0):
 v,U=0,0
 while 1:
  if(k:=N(l))==0 and v:break
  if O(k,n,E)not in[')',']']:
   if k in'+-*/^':
    if v==0:O(1,n,E,-2,3)
    V,l=X(l,n,s,b,E,C)
    if(B(v),B(V))not in P.get(k,[(1,1)])or v!=V:O(1,n,E,-2,4)
    v=V;U=1
   elif U and k!=',':O(0,n,E,-2,3)
   elif k==',':l=iter([k,*l])
   if'for'==k:
    if L:E(F(6,n))
    v=C(iter([k,*l]),n,s,b,E);U=1
   elif'('==k:
    v,l=X(l,n,s,b,E,C);O(N(l),n,E,')',2);U=1
   elif k.isalpha():
    if k in G:
     V,l=X(l,n,s,b,E,C,0,1)
     if V==0:O(0,n,E)
     if G[k][0]!=-1 and G[k][0]!=V:O(1,n,E,-2,4)
     v=G[k][1];U=1
    else:
     if k not in b[s]:O(1,n,E,-2,1)
     v=b[s][k]
    U=1
   elif k.isdigit():
    v=1;U=1
   elif'['==k:
    L=[]
    while 1:
     V,l=X(l,n,s,b,E,C)
     if V:
      L+=[V]
      if(k:=N(l))==']':v=L;break
      O(k,n,E,',',3)
     else:O(O(N(l),n,E),n,E,']',3);break
    if(_:=len(Y:=set(map(str,L))))==1:v=[2,eval([*Y][0])]
    else:
     if _>1:E(F(4,n))
     v=[2]+([]if[]==L else[-1])
    U=1
   else:break
   if U and W:break
  else:l=iter([k,*l]);break
 return v,l
def p(l,n,s,b,E):
 k=N(l)
 if'let'==k:
  if O(k:=N(l),n,E).isalpha()==0:E(F(0,n))
  else:
   if(I:=(k in b[s])):E(F(5,n))
   O(x:=N(l),n,E);O(x,n,E,'=',3);V,l=X(l,n,s,b,E,p)
   if not I:A(b,s,k,V)
 elif'for'==k:
  O(N(l),n,E,'(',3);O(x:=N(l),n,E);O(1,n,E,x.isalpha(),0);O(m:=N(l),n,E);O(m,n,E,'in',3)
  if x in b[s]:E(F(5,n))
  V,l=X(l,n,s,b,E,p)
  O(V,n,E);O(N(l),n,E,')',2)
  if type(V)==int:E(F(4,n))
  V,l=X(l,n,(0,n),{**b,(0,n):{x:V if type(V)==int else V[1]}},E,p,1);O(V,n,E);return[2,V]
  return[2]
 elif k in G:l=iter([k,*l]);V,l=X(l,n,s,b,E,p)
def D(l):
 b,E={(0,):{}},[]
 for i,a in enumerate(filter(None,l.split('\n')),1):
  try:p(s(a),i,(0,),b,E.append)
  except:1
 return E

```

Try it online!
> 5 votes

---
Tags: code-golf, parsing
---


title: Is it a good chord?

text:
# Question
Title: Is it a good chord?
# Is it a good chord?

### Definition of a `chord`:

We define a `chord` as three notes together.

### Definition of a `note`:

We define a `note` as a number between `1` and `7`, inclusive. As in music, we define `1` as `do`, `2` as `re`, `3` as `fa`, etc. However, the note names are not important. They will not be included in the question and likely not in a golfed solution. `1` is a note. `0` and `8` are not a note. As we will mention later, the input is a list of three notes, and invalid notes will **not appear** as an input. So even if you print the entire Never Gonna Give You Up lyrics when you encounter invalid inputs, I don't care. (However, I don't see how that's more golf-y.)

### Definition of a `good chord`:

We define a `good chord` as follows:

* If there are any two notes that are the same, disregard one of them.
* Sort the notes.
* Space the result on a piano. For instance, `135` will look like `X X X` and so will `246`, `357`, for instance.
* If any of the notes are adjacent, it is considered a `bad chord` and thus not a `good chord`. That is, a chord containing `1` and `2` is `bad`, so is a chord containing `1` and `7`.
* The only possibilities that are left are:

With three digits,

* 135
* 136
* 137
* 146
* 147
* 157
* 246
* 247
* 257
* 357

And with two digits,

* 13 which could have been 113 or 133
* 14 which could have been 114 or 144
* 15 which could have been 115 or 155
* 16 which could have been 116 or 166
* 24 which could have been 224 or 244
* 25 which could have been 225 or 255
* 26 which could have been 226 or 266
* 27 which could have been 227 or 277
* 35 which could have been 335 or 355
* 36 which could have been 336 or 366
* 37 which could have been 337 or 377
* 46 which could have been 446 or 466
* 47 which could have been 447 or 477
* 57 which could have been 557 or 577

And with one digit,

* 1 which means 111
* 2 which means 222
* 3 which means 333
* 4 which means 444
* 5 which means 555
* 6 which means 666
* 7 which means 777

Note that the above possibilities are already sorted, **while you should not expect your input to be sorted**. Also, the above possibilities are represented as a three digit number, **while your input will be a list of three numbers from `1` to `7` inclusive**.

I would not expect an answer that hard-codes the values above, but if you intend to, or for some reason it is more golf-y, you are **permitted** to do it.

### Your challenge:

Given an input, decide whether it is `good` or not. Return a true-y or false-y value, a true-y value such as `1` means that it is `good`, while a false-y value such as `0` means that it is `not good`. Do not use ambiguous values like  or `\n` (indicating a newline) or `[[]]` et cetera.

### Scoring:

This is `code-golf`.

# Answer
# x86-64 machine code, 19 bytes

```
31 D2 AD 0F AB C2 FF CF 75 F8 8D 04 12 85 D0 0F 94 C0 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length and address of an array of 32-bit integers in EDI and RSI, respectively, and returns a value in AL.

In assembly:

```
.global f
f:  xor edx, edx    # Set EDX to 0.
r:  lodsd           # Load a number from the array into EAX, advancing the pointer.
    bts edx, eax    # Set the bit in that position in EDX to 1.
    dec edi         # Subtract 1 from EDI, counting down from the length.
    jnz r           # Jump back if that is not zero.
    lea eax, [rdx+rdx]  # Set EAX to 2 times EDX -- the bits move up by 1.
    test eax, edx   # Set flags based on the bitwise AND of EAX and EDX.
                    # This checks for adjacent bits being 1.
    setz al         # Set AL based on whether the result was zero.
    ret             # Return.

```
> 1 votes

# Answer
# Python 3, 32 bytes

```
lambda l:not{*l}&{x+1for x in l}

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Bidirectional Quine Chain

text:
# Question
Title: Bidirectional Quine Chain
# PPCG hasn't had enough of quines already...

### Challenge:

Your task is to create a program "A0". When this program is run with no input, it outputs nothing. When this program is run with input, it outputs "A1". When "A1" is run with no input, it outputs "A0". When "A1" is run with input, it outputs "A2". Pretty much, "A(k)" will output "A(k-1)" when run with no input, and will output "A(k+1)" when run with input.

### Details

I believe this challenge is simple enough; there are no other rules really. Every program must contain at least 1 byte, by the way. You may assume that the input will consist of only ASCII characters, and you may ignore whitespace if you want, but you may not specify a specific input. Output may be to either STDOUT or STDERR, but all of your programs must output to the same one. The other one may also contain text (so you may output to STDOUT and then exit with an error). Thanks to @Dennis for pointing that out.

All programs must be in the same language, and each program must be unique from the rest of them.

The score is equal to the length of program "A0". As this is a code-golf challenge, the lowest score wins!

# Answer
# Pip, 28 bytes

```
V Y"I#qSti0+i?`V Y`.RPyRtiu"

```

Try it online!

### Explanation

This is a modified version of the shortest known Pip quine `V Y"`V Y`.RPy"`. That quine works by defining a string, yanking it into the `y` variable, and then evaluating it. When evaluated, the string takes the repr of `y` (thus wrapping the value of `y` in double quotes) and concatenates the pattern literal ``V Y`` to the front of it.

Our strategy is to put a `0` in the program, then replace `0` with `10` if there was input, or replace `10` with `0` if there was no input. (Thus, A(*k*) will contain a number consisting of *k* 1's followed by a 0.) `0` and `10` are convenient because there are built-in variables (`i` and `t`, respectively) with those values, so we can refer to them without using actual digits.

So instead of `RPy`, we want `RP yRit` if there was input and `RP yRti` if not. We can combine the two cases by swapping the values of `t` and `i` if there is input (`I#q Sti`), then doing `RP yRti`. (We have to test `#q`, the *length* of the input, because inputs like `0` are falsey.)

Now we just have to get a literal `0` in the code and handle the special case of A0 producing no output. Both can be solved by testing `0+i` and returning `u` if it is falsey:

* For any *k* \> 0, the number in A(*k*) will be nonzero and therefore truthy (e.g. `110+i`).
* For *k* = 0, the number in A(*k*) will be zero:
    + If there is input, `i` and `t` are swapped and `i` is 10. `0+i` is still truthy.
    + If there is no input, `i` is still 0 and `0+i` is falsey. Instead of the quine core, we output `u`, which is a built-in variable for nil. Printing nil produces no output.
> 1 votes

# Answer
# Python 2, 93 bytes

There is a trailing linefeed.

```
p=1+2*bool(input())-1;s='print"p=%r+2*bool(input())-1;s=%r*(p>0);exec s"%(p,s)'*(p>0);exec s

```

**Try it with input** | **Try it without input**

This is modified from my answer on a similar question.

If there is input, then it will increment `p`. So the resulting program will be `p=2+...`, `p=3+...`, etc.
> 1 votes

# Answer
# Vyxal, 21 bytes

```
1`I$u?[N]+p`I$u?[N]+p

```

Try it Online!

The number on front is `k`.

```
1                     # Push 1 (or k)
 `I$u?[N]+p`          # Push a string containing part of the program code
            I         # Quinify, unevaling and appending
             $        # Swap with k
              u?[N]   # Push 1 if input, else -1
                   +  # Add
                    p # Prepend to the string

```
> 1 votes

# Answer
# PARI/GP, 67 bytes

```
(f=(a)->(a+=(-1)^!readstr("/dev/stdin"))&&print("(f="f")("a")"))(1)
```

Attempt This Online!

PARI/GP doesn't have a built-in to read a string from stdin. The shortest workaround I can find is `readstr("/dev/stdin")`, which only works on unix-like systems.
> 0 votes

---
Tags: code-golf, quine
---


title: Any digital permutation

text:
# Question
Title: Any digital permutation
# Task

Your task is to output a single integer, with one restriction: its digits must be a permutation of \[1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6\].

For example, you could output 653443653152432, 413265345463352, or any of the other 15-digit integers whose digits are a permutation of the list.

# Rules

* Your code must terminate in a reasonable amount of time (do not just enumerate every integer until you get to 122333344455566).
* If your language doesn't support 15-digit integers, or if there is no meaningful distinction between strings and integers in your language, you may output a string.
* This is , shortest answer in bytes wins.

# Answer
> 12 votes
# JavaScript (ES7), ~~13~~ 12 bytes

```
let f =

_=>266**6+19

console.log(f())
```

This computes: **2666 \+ 19 = 354233654641216 + 19 = 354233654641235**

There are two triples **(a, b, c)** with **0 \< a \< 1000**, **0 \< b \< 10**, **0 \< c \< 100** and **ab \+ c** satisfying the condition.

The following snippet finds them almost instantly.

```
for(a = 1; a < 1000; a++) {
  for(b = 1; b < 10; b++) {
    for(c = 1; c < 100; c++) {
      if((r = a**b + c + '').match(/^[1-6]+$/) && [...r].sort().join`` == '122333344455566') {
        console.log(a + '**' + b + ' + ' + c + ' = ' + r);
      }
    }
  }
}
```

# Answer
> 5 votes
# Brain-Flak, 65 bytes

```
(((((((((((((((((((()()()){}){}){}){}())()))()))))())))())))()))

```

Try it online!

This is `64` bytes of source code and `+1` for the `-A` flag. This simply pushes the ASCII values of each digit in a row. For reference, pushing the number `122333344455566` would take 238 bytes:

```
(((((((((((((((((((((((((((((((((((((((((((((((((()()()){}){}){})()){}{}){({}[()])}{}){}){}())){}{})){}{}){}())){}{})()){}{})){}{}){}())){}{}){}())){}{}){}())()){}{})()){}{})){}{})()){}{})()){}{})){}{}){}())){}{}){}())){}{})){}{}){}()){})

```

Try it online!

# Answer
> 3 votes
# , ~~12~~, 10 bytes

```
2¬26¬35a13

```

Try it online!

This generates the range `[2, 6]` twice, then the range `[3, 5]`, and then appends `13`.

Outputs:

```
234562345634513

```

# Answer
> 2 votes
# Turing machine, ~~132~~ 122 bytes

...and ~~11~~ ~~10~~ ~~8~~ 7 states, including `halt`.

```
0 _ x r A
0 x y r A
0 y z r A
0 z _ r C
0 * * l 0
A _ 6 r B
A * * r A
B _ 2 r C
C * 3 r D
D _ 4 r E
D 2 1 l halt
E _ 5 l 0

```

Here is a Turing machine simulator that understands this syntax. You should paste the code, clear the "Initial input" field, press Reset, then press Run.

## How it works

Outputs `313456234562345` by looping to write `62345` three times and then writing `31` on top of the initial `62`.

---

*-10 bytes thanks to @Leo*

# Answer
> 1 votes
# Jelly, ~~9~~ 8 bytes

```
“|BS½GA’

```

Try it online!

Simply a base-250 compressed version of the number `122333344455566`

Saved 1 byte thanks to @Mr. Xcoder

# Answer
> 1 votes
# SOGL V0.12, 7 bytes

```
↓čvν□⅟“

```

Try it Here!
A simple compressed number.

Alternate 9 byte run-length version:

```
Ƨ≡+‰“7─◄H

```

Try it Here!

# Answer
> 1 votes
# brainfuck, 40 bytes

```
+++++++[>+++++++<-]>.+..+....+...+...+..

```

Try it online!

fairly boring solution

# Answer
> 1 votes
# 05AB1E, 7 bytes

```
•=["∊…Q

```

Try it online!

# Answer
> 1 votes
# Befunge-93, ~~16~~ 14 or 12 bytes

The only native integer literals supported by Befunge are the numbers 0 to 9, so coming up with an efficient representation for larger values is actually quite a common problem. In this case, though, it's not just a matter of finding the most efficient representation for a number, but also choosing a target number whose best representation is the shortest of all possible targets.

After trying thousands of different combinations, the best I've been able to do so far is 14 bytes (12 to calculate the number, and then two more bytes to output it).

```
m&"7*:*::**+.@

```

Try it online!

If we allow extended ASCII characters, though, we can improve on the above solution by two bytes with:

```
eûãÃ"**:*+.@

```

This is using the Latin-1 encoding, which we unfortunately can't demonstrate on TIO, since it doesn't support 8-byte encodings for the Befunge interpreters.

**Explanation**

In the first answer, we start with the string `"m&"`, which essentially pushes the values 109 and 38 onto the stack. Note that we save a byte by dropping the opening quote, since we can rely on Befunge's wrap-around playfield to have the one quote both open and close the string (this pushes a number of additional values onto the stack that we don't need, but we only care about the final two).

We then push an additional `7` onto the stack, and execute the sequence `*:*::**+`, which performs a set of arithmetic calculations with the stack values, essentially calculating the expression:

```
109+(38*7)^2^3 = 354233654641325

```

Finally we use the `.` instruction to output the result of the calculation, and then the `@` instruction ends the program.

In the second answer, we start with the string `"eûãÃ"`, which pushes the values 101, 251, 227 and 195. We then execute the sequence `**:*+`, which performs the required calculations on those values:

```
101+(251*227*195)^2 = 123443543565326

```

And again we finish with the instructions `.` and `@` to output the result and exit.

Note that in both cases you need to be using an interpreter which supports 64-bit integers. Also note that the string wrapping trick won't work on Befunge-98 interpreters, since it relies on the interpreter ignoring instructions it doesn't recognise, but in Befunge-98 an invalid instruction will reflect.

# Answer
> 1 votes
# Vyxal, 7 bytes

```
»Ċ¨?»²›

```

Try it Online!
Port of the second answer here
Explanation:

```
»Ċ¨?»   # Compressed integer 11972312
     ²  # Squared
      › # Increment

```

I was on my way to making a super short one but I had read the rules wrong :(

# Answer
> 0 votes
# Python 2, 21 bytes

```
print 122333344455566

```

Try it online!

# Answer
> 0 votes
# Jelly, 12 bytes

```
4967b5Ėẋ/€FḌ

```

Try it online!

could probably be shorter

# Answer
> 0 votes
# Pyth, 9 bytes

```
."16U<³

```

**Try it here!**

**Output:**

```
223133344455566

```

# Answer
> 0 votes
# Tcl, 89 bytes

```
proc f a\ b {expr rand()>.5}
puts [join [lsort -command f [split 122333344455566 ""]] ""]

```

Try it online!

# Answer
> 0 votes
# Tcl, 20 bytes

```
puts 122333344455566

```

Try it online!

# Answer
> 0 votes
# Befunge-98 (FBBI), 20 bytes

```
"ek,@122333344455566

```

Try it online!

Output is `665554443333221`.

# Answer
> 0 votes
# Groovy, 23 bytes

```
{"233456"*2+145}

```

Outputs: 233456233456145

# Answer
> 0 votes
# APL (Dyalog Unicode), 14 bytes

```
⎕pp←30
37+266*6

```

Try it online!

Used @Arnauld's snippet, so credit goes to them.

# Answer
> 0 votes
# C++, 24 bytes

```
[]{return(57LL<<41)-31;}

```

Try it online!

Returns 57×241−31 = 125344325566433.

# Answer
> 0 votes
# ARM T32 machine code, 8 bytes

```
20d5 f24e 6157 4770

```

Following the AAPCS, this is a function returning a 64-bit integer in r0 and r1. The number is 58967×232+213=253261336543445.

Disassembled:

```
20d5        movs    r0, #213
f24e 6157   movw    r1, #58967
4770        bx  lr

```

# Answer
> 0 votes
# A0A0, 16 bytes

```
O122333344455566

```

`O` outputs the number after it. The number after it is a valid integer.

I don't really think it's possible to save bytes by using some arithmetic expression. When multiplying two numbers of n and m digits, the resulting length of the multiplication will be at most n + m. Doing such a multiplication requires at least n + m + 2 (ignoring the operand) bytes, at which point you might as well just write the result directly. Addition is even worse in terms of length. Considering multiplication, addition and subtraction are the only built-in operators I find it hard to believe this can be shortened. I'd love to be proven wrong, though.

# Answer
> 0 votes
# x86 32-bit machine code, 9 bytes

```
6A 85 58 BA 4F C9 00 00 C3

```

Returns a 64-bit integer in EDX and EAX, as is standard. The value is 51536×232−123 = 221345434566533.

Try it online!

In assembly:

```
f:  push -123; pop eax
    mov edx, 51535
    ret

```

---

Some alternatives that also take 9 bytes:

---

```
B8 D8 AE B6 00 F7 E0 40 C3

```

Try it online!

```
f:  mov eax, 11972312
    mul eax
    inc eax
    ret

```

119723122+1 = 143336254625343

---

```
6A E1 58 0F B6 D4 B6 71 C3

```

Try it online!

```
f:  push -31; pop eax
    movzx edx, ah
    mov dh, 113
    ret

```

114×240−31 = 125344325566433

---
Tags: code-golf, kolmogorov-complexity, open-ended-function
---


title: Can a run ascending list be made?

text:
# Question
Title: Can a run ascending list be made?
A *run ascending list* is a list such that runs of consecutive equal elements are strictly increasing in length. For example `[1,1,2,2,1,1,1]` can be split into three runs `[[1,1],[2,2],[1,1,1]]` with lengths `[2,2,3]`, since two runs are the same length this is **not** a run ascending list. Similarly `[2,2,1,3,3,3]` is not run ascending since the second run (`[1]`) is shorter than the first (`[2,2]`). `[4,4,0,0,0,0,3,3,3,3,3]` is run ascending since the three runs strictly increase in length.

An interesting challenge is to figure out for a particular set of symbols whether they can be arranged into a run ascending list. Of course the values of the individual symbols don't matter. It just matters how many of each there are.

In this challenge you will be given a list of \\$n\\$ positive integers, \\$x\_i\\$, as input. Your task is to determine if a run ascending list can be made from the numbers \\$1\\$ to \\$n\\$ with each number \\$k\\$ appearing *exactly* \\$x\_k\\$ times.

For example if the input is `[4,4,7]` it means you must determine if a run ascending list can be made with four 1s, four 2s and seven 3s. The answer is yes:

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

```

If the input is `[9,9,1]` it means you must try to find a run ascending list made of nine 1s, nine 2s and one 3. This cannot be done. It must start with the single `3` since that run can only be 1 long. Then the 1s and 2s must alternate to the end, since each run must larger than the previous, there must be more of whichever number goes last.

## Rules

You should take as input a non-empty list of positive integers. You should output one of two distinct values. One if a run ascending list can be made the other if it cannot.

This is the goal is to minimize the size of your source code as measured in bytes.

## Testcases

Inputs that cannot make a run ascending list

```
[2,2]
[40,40]
[40,40,1]
[4,4,3]
[3,3,20]
[3,3,3,3]

```

Inputs that can make a run ascending list

```
[1]
[10]
[6,7]
[7,6]
[4,4,2]
[4,4,7]
[4,4,8]

```

# Answer
# Python 3, 106 bytes

```
def f(a,n=-1,x=0):a[n]-=x;return~-any(a)^any(f(1*a,i,j+1)for i,k in enumerate(a)for j in range(x,k)if i-n)

```

Try it online!

Brute force search. Recursively subtracts a strictly increasing value from every index in the input, as long as it is not equal to the prviously picked index. This continues until all values in the input are zero or the options to continue are exhausted.
> 8 votes

# Answer
# 05AB1E, 13 bytes

```
āsÅΓœεÅγü›P}à

```

Brute-force approach, so extremely slow.

Try it online or verify some of the smaller test cases.

**Explanation:**

```
ā           # Push a list in the range [1, (implicit) input-length]
 s          # Swap so the input-list is at the top
  ÅΓ        # Run-length decode using the two lists
    œ       # Get all permutations of this list
     ε      # Map over each permutation:
      Åγ    #  Run-length encode the list, pushing the values and counts as two
            #  separated lists to the stack
        ü›P #  Check if this counts-list is strictly increasing:
        ü   #   For each overlapping pair of the counts-list:
         ›  #    Check if the first is larger than the second
          P #   Product to check if all of them are truthy
            #   (or if the list is empty after the overlapping pairs builtin,
            #   which means the counts-list only contains a single value)
     }à     # After the map: max to check if any of them is truthy
            # (which is output implicitly as result)

```
> 6 votes

# Answer
# Brachylog, 15 bytes

```
{igᵗj₍}ᶠcpḅlᵐ<₁

```

Try it online!

Times out on most of the test cases. I believe the algorithm is something like \\$O(S!)\\$, where \\$S\\$ is the sum of the input list.

### Explanation

```
{igᵗj₍}ᶠcpḅlᵐ<₁
{     }ᶠ         Find all ways to satisfy this predicate:
 i                 [E, I] pair where E is an element of the input and I is its index
  gᵗ               Turn that into [E, [I]]
    j₍             Concatenate [I] to itself E times
                 Result: a list of lists like [[0, 0, 0, 0], [1, 1, 1, 1], [2, 2]]
        c        Concatenate those lists into one big list
         p       Consider some permutation of that list
          ḅ      Break it into blocks (i.e. runs of the same value)
           lᵐ    Take the length of each block
             <₁  Assert that the list of lengths is strictly increasing

```
> 4 votes

# Answer
# JavaScript (ES6), 84 bytes

Returns \\$0\\$ or \\$1\\$.

```
f=(a,i=0,p,g)=>a.some((v,j)=>v&&(g=_=>p!=j&v>i&&f(a,v,j,a[j]-=v)|g(a[j]+=v--))())|!g

```

Try it online!

### Commented

```
f = (             // f is a recursive function taking:
  a,              //   a[] = input array
  i = 0,          //   i = previous run length
  p,              //   p = previous index
  g               //   g = variable used to store a local
                  //       helper function and as a flag
) =>              //
a.some((v, j) =>  // for each value v at position j in a[]:
  v && (          //   abort if v = 0
  g = _ =>        //   g is a helper function which ignores its argument
  p != j &        //     if the index is not equal to the previous one
  v > i &&        //     and v is greater than the previous run length:
    f(            //       do a recursive call to f:
      a,          //         pass a[]
      v,          //         update i to v
      j,          //         update p to j
      a[j] -= v   //         subtract v from a[j]
    ) |           //       end of recursive call
    g(            //       do a recursive call to g:
      a[j] += v-- //         restore a[j] and decrement v
    )             //       end of recursive call
  )()             //   initial call to g
) |               // end of some()
!g                // success if some() is truthy or g = 0,
                  // which means that a[] is now filled with 0's

```
> 2 votes

# Answer
# Vyxal, 17 bytes

```
żZødṖƛĠvL2lvƒ>A;G

```

Try it Online!

Port of 05AB1E. ~~`vw` and `f` are only needed due to a bug, and `ƒ∴` is needed instead of `G` due to another bug.~~ Bugs fixed.

Could be 13 bytes, but, well, this challenge is what inspired me to create all those new builtins, so, I guess it doesn't count.
> 2 votes

# Answer
# Burlesque, 32 bytes

```
{+.bxj.*}wiFLr@{gw)-]qU_qsom&}ay

```

Try it online!

Drastically inefficient brute force

```
{    # Generate initial list, e.g. for [2,2] builds {1 1 2 2}
 +.  # Increment (indexed from zero)
 bx  # Box
 j.* # Product
}wi  # Zip with indices and map
FL   # Flatten (strictly builds {{{1}{1}}{{2}{2}}})
r@   # All possible permutations (even repeated ones)
{
 gw  # Group like with length (count)
 )-] # Get length (count)
 qU_ # Quoted Unique
 qso # Quoted sorted
 m&  # Make and (is sorted and unique)
}ay  # Any

```
> 1 votes

# Answer
# Charcoal, 59 bytes

```
⊞υ⟦±¹θ⁰⟧ＦυＦ…⊟ι⌈§ι¹ＦＬθＦ∧⁻λ§ι⁰›§§ι¹λκ⊞υ⟦λＥ§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧⬤υ⌈⊟ι

```

Try it online! Link is to verbose version of code. Outputs nothing if a run ascending list can be made, `-` if not. Explanation: Inspired by @Jitse's Python answer.

```
⊞υ⟦±¹θ⁰⟧Ｆυ

```

Start a search with a previous run of `0` `-1`s and the original input still to process.

```
Ｆ…⊟ι⌈§ι¹

```

Loop over potential next run lengths.

```
ＦＬθ

```

Loop over potential next run values.

```
Ｆ∧⁻λ§ι⁰›§§ι¹λκ

```

If this is a new run and there are enough of the value remaining, then...

```
⊞υ⟦λＥ§ι¹⁻ν∧⁼ξλ⊕κ⊕κ⟧

```

... add a new search entry of the run and updated array of counts.

```
⬤υ⌈⊟ι

```

See whether an array of all zeros was achieved.
> 1 votes

# Answer
# Husk, 12 bytes

```
¬ΛȯV≤mLgP`ṘN

```

Try it online!

Brute force approach, times out for even moderate inputs. TIO link includes a set of very short true & false inputs.

```
¬ΛȯV≤mLgP`ṘN
           N  # for each integer 1..N
         `Ṙ   # replicate it the number of times in the input array;
        P     # now get all permutations of this list
 Λȯ           # and output zero if none of these satisfy:
   V          #   there is at least one pair of adjacent elemnts
    ≤         #   for which the left is smaller or equal to the right,
     mL       #   for the lengths of each
       g      #   group of equal elements;
              # (at this point truthy (nonzero) means a run-ascending list cannot be made,
              # falsy (zero) means a run-ascending list can be made)
¬             # so NOT the result to get a consistent output
              # 1=can be made, 0=cannot be made

```

(Omit the final `¬` for falsy & truthy-but-non-consistent output)
> 0 votes

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


title: Maximal Substring Construction

text:
# Question
Title: Maximal Substring Construction
In this challenge, you are passed two things:

1. A string length, `N`
2. A list of strings, `L`, each with an assigned point value. Any string that is not passed in has a point value of 0

You need to construct a string of length `N` such that the sum of all substring points is as large as possible.

For example:

```
5 [("ABC", 3), ("DEF", 4), ("CDG", 2)]

```

should output

```
ABCDG

```

Because the two substrings with points (`ABC` and `CDG`) have a total of 5 points, and no other possible construction can give 5 or more points.

Substrings can be used multiple times in a string, and can overlap. You can assume that the points will always be positive, the substring lengths will be between 1 to `N` characters longs, and that `N > 0`. If multiple constructions are maximal, print any one of them.

Your program must run in a reasonable amount of time (no more than a minute for each of the examples):

```
1 [("A", 7), ("B", 4), ("C", 100)]     => C
2 [("A", 2), ("B", 3), ("AB", 2)]      => AB
2 [("A", 1), ("B", 2), ("CD", 3)]      => BB
2 [("AD", 1), ("B", 2), ("ZB", 3)]     => ZB
3 [("AB", 2), ("BC", 1), ("CA", 3)]    => CAB
3 [("ABC", 4), ("DEF", 4), ("E", 1)]   => DEF
4 [("A", 1), ("BAB", 2), ("ABCD", 3)]  => AAAA or ABAB or BABA or ABCD
5 [("A", 1), ("BAB", 2), ("ABCD", 3)]  => BABCD or BABAB
5 [("ABC", 3), ("DEF", 4), ("CDG", 2)] => ABCDG
5 [("AB", 10), ("BC", 2), ("CA", 2)]   => ABCAB
6 [("AB", 10), ("BC", 2), ("CA", 2)]   => ABABAB
8 [("AA", 3), ("BA", 5)]               => BAAAAAAA
10 [("ABCDE", 19), ("ACEBD",  18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]
=> ACEBDACEBD

```

This is a , so prepare your shortest answer in your favorite language!

# Answer
# Python3, 383 bytes:

```
lambda t,s,k={}:max(f(s,'',t,0,k),key=lambda x:x[1])[0]
C=lambda l,a:(l[:len(a)]==a)+(0if''==l else C(l[1:],a))
def U(l,a,k):
 if(l,a)in k:return k[(l,a)]
 k[(l,a)]=C(l,a);return k[(l,a)]
def f(s,l,t,p,k):
 if(T:=len(l))==t:yield(l,sum(b*U(l,a,k)for a,b in s));return
 for a,b in s:
  for i in range(len(a)):
   if l[T-i:]==a[:i]and T<len(L:=(l[:T-i]+a))<=t:yield from f(s,L,t,p+b,k)

```

Try it online!
> 2 votes

# Answer
# Python 2.7, 503 Bytes

This isn't particularly golfed, nor is it particularly efficient; it's just a relatively condensed enumeration of feasible strings that are brute-forced. I don't think it would be too hard to create an admissible heuristic to use with A\*, which would probably be a bit quicker. I didn't bother doing that, though, because this method solves all of the examples in about 47 seconds on my laptop.

```
import re
v=lambda l,s:sum([len([m.start() for m in re.finditer('(?=%s)'%u,s)])*v for u,v in l])
def m(n,l,e):
 if len(e)==n:
  yield e
 else:
  u=1
  for s,v in sorted(l,key=lambda j:j[1],reverse=True):
   for i in range(len(s)-1,0,-1):
    if len(e)+len(s)-i <= n and e.endswith(s[:i]):
     for r in m(n,l,e+s[i:]):
      u=0;yield r
   if len(e)+len(s)<=n:
    for r in m(n,l,e+s):
     u=0;yield r
  if u:
   yield e
def p(n,l):
 b,r=-1,0
 for s in m(n,l,''):
  a=v(l,s)
  if a>b:b,r=a,s
 return r

```

To test it:

```
if __name__ == "__main__":
    for n, l in [
            (1, [("A", 7), ("B", 4), ("C", 100)]),     # => C
            (2, [("A", 2), ("B", 3), ("AB", 2)]),      # => AB
            (2, [("A", 1), ("B", 2), ("CD", 3)]),      # => BB
            (2, [("AD", 1), ("B", 2), ("ZB", 3)]),     # => ZB
            (3, [("AB", 2), ("BC", 1), ("CA", 3)]),    # => CAB
            (3, [("ABC", 4), ("DEF", 4), ("E", 1)]),   # => DEF
            (4, [("A", 1), ("BAB", 2), ("ABCD", 3)]),  # => AAAA or ABAB or BABA or ABCD
            (5, [("A", 1), ("BAB", 2), ("ABCD", 3)]),  # => BABCD or BABAB
            (5, [("ABC", 3), ("DEF", 4), ("CDG", 2)]), # => ABCDG
            (5, [("AB", 10), ("BC", 2), ("CA", 2)]),   # => ABCAB
            (6, [("AB", 10), ("BC", 2), ("CA", 2)]),   # => ABABAB
            (8, [("AA", 3), ("BA", 5)]),               # => BAAAAAAA
            (10, [("ABCDE", 19), ("ACEBD",  18), ("ABEDC", 17), ("BCEDA", 16), ("EBDAC", 15), ("BACD", 14), ("CADB", 13), ("ABDC", 12), ("CABD", 11), ("EBDC", 10), ("ACE", 9), ("CBA", 8), ("AEC", 7), ("BE", 6), ("AE", 5), ("DC", 4), ("BA", 3), ("A", 2), ("D", 1)]) # => ACEBDACEBD
    ]:
        print p(n, l)

```

**Explanation**

The `v` function simply calculates the value of a given string by searching for all occurrences of the substrings in L. The `m` function enumerates all strings of length `n` with prefix `e` that can be generated from the substrings in `l`. `m` recursively calls itself; the first call should pass in `''` for `e`. For example:

```
>>> for s in m(4, [("A", 1), ("BAB", 2), ("ABCD", 3)], ''):print s
ABCD
BABA
ABCD
ABAB
AAAA

```

The `p` function simply loops through all possible strings (as enumerated by `m`) and returns the one with highest value (as determined by `v`).

Note that the `m` function actually prioritizes the enumeration by sorting based on substrings' values. This turns out to be unnecessary to ensure optimality, and it actually hinders efficiency a bit; I could save ~20 or so bytes by removing it.

Try it online!
> 1 votes

---
Tags: code-golf, string, sequence, subsequence, restricted-time
---