title: Compare shapeless lists

text:
# Question
Title: Compare shapeless lists
Let's have a ragged list containing no *values*, only more lists. For example:

```
[[[],[[]],[],[]],[],[[],[],[]],[]]

```

And the list will be finite, meaning that eventually every path terminates in an empty list `[]`.

It's simple enough to determine if two of these are structurally equal. Check each element in order for equality and recurse. However what if we don't care about the order of the lists for equality? What if we only care that they have the same elements?

We can define this shapeless equality like so:

> Two lists \\$A\\$, and \\$B\\$ are shapeless equal if for every element in \\$A\\$ there are as many elements in \\$A\\$ shapeless equal to it as there are in \\$B\\$, and vice-versa for the elements of \\$B\\$.

Your task will be to take two ragged lists and determine if they are "shapeless equal" to each other. If they are you should output some consistent value, if they are not you should output some distinct consistent value.

This is so answers will be scored in bytes with fewer bytes being the goal.

## Testcases

```
[] [] -> 1
[[],[[]]] [[[]],[]] -> 1
[[],[[],[[]]]] [[],[[[]],[]]] -> 1
[[],[[],[[]]]] [[[[]],[]],[]] -> 1
[[]] [] -> 0
[[],[]] [[[]]] -> 0
[[],[]] [[]] -> 0
[[[],[],[]],[[]]] [[[],[]],[[],[]]] -> 0
[[],[],[[]]] [[],[[]],[[]]] -> 0

```

# Answer
> 15 votes
# Brachylog, 3 bytes

```
p↰ᵐ

```

Try it online!

### Explanation

This takes the first list as the input variable, and the second list as the output variable. The interpreter then prints `true.` if it is possible to satisfy this predicate with these variables, and `false.` otherwise.

```
p     The output is a permutation of the input
 ↰ᵐ   Recursively call this predicate on each element of the input

```

# Answer
> 11 votes
# Python 3, 49 bytes

```
lambda x,y:g(x)==g(y)
g=lambda a:sorted(map(g,a))

```

Try it online!

# Answer
> 6 votes
# JavaScript (ES6), 41 bytes

Expects `(a)(b)`. Returns a Boolean value.

```
a=>b=>(g=a=>1+a.map(g).sort()+0)(a)==g(b)

```

Try it online!

### How?

We can't compare nested arrays in JS by simply coercing them to strings because everything is flatten and empty arrays are turned into empty strings. (Basically, only commas would remain with the arrays we're dealing with in this challenge.)

We could use `JSON.stringify`:

```
a=>JSON.stringify(a.map(g).sort())

```

but this is a bit lengthy.

Instead, we do a custom conversion to a string by prepending a `1` at the beginning of each call and appending a `0` at the end.

For an already sorted array, this effectively replaces opening brackets with 0's and closing brackets with 1's, while leaving commas unchanged.

For instance:

```
 [[],[[],[[]]]]
"110,110,110000"

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
ß€Ṣ
Ç€E

```

A monadic Link accepting a list of the two ragged lists that yields `1` if they are "shapeless equal".

**Try it online!**

### How?

Recursively sort the containers of any nested lists and compare the results for equality.

```
ß€Ṣ - Helper Link, recursively sort container lists and their content: List, X
 €  - for each element in X:
ß   -   call this Link
  Ṣ - sort

Ç€E - Link, the main function: List, A
 €  - for each of the two lists in A:
Ç   -   call the Helper Link
  E - all equal?

```

# Answer
> 4 votes
# Ruby, 38 bytes

```
->l,m{g=->a{a.sort.map &g};g[l]==g[m]}

```

Try it online!

(Stolen from hyper neutrino's python answer)

# Answer
> 4 votes
# Wolfram Language (Mathematica), 16 bytes

```
SameQ@@Sort//@#&

```

Try it online!

Input `[{A, B}]`.

# Answer
> 2 votes
# 05AB1E, 11 bytes

```
"®δ.V{"©.VË

```

Port of *@JonathanAllan*'s Jelly answer, but without having access to recursive functions.

Input as a pair of nested lists.

Try it online or verify all test cases.

**Explanation:**

```
"..."      # Push the 'recursive' string explained below
     ©     # Store it in variable `®` (without popping)
      .V   # Execute it as 05AB1E code
           # (using the implicit input-pair in the first call)
        Ë  # Check if both lists in the pair are now equal
           # (after which the result is output implicitly)

 δ         # Map over each inner list:
® .V       #  Do a recursive call by executing string `®` as 05AB1E code
    {      # Then sort each inner list

```

# Answer
> 1 votes
# Stax, 14 bytes

```
ü╙ûÆ╙X○Γfó¡↓↓▄

```

Run and debug it

Sort arrays till the lowest depth and compare for equality. ~~`G` might be usable here, but a reusable recursive function *feels* shorter (recursive will probably prove me wrong).~~ (I proved myself wrong. -1)

# Answer
> 1 votes
# Python3, 78 bytes:

```
s=sorted
l=len
f=lambda a,b:l(a)==l(b)and all(f(j,k)for j,k in zip(s(a),s(b)))

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 56 bytes

```
f(a,b)=s=vecsort;#a==#b&&prod(i=1,#a,f(s(a)[i],s(b)[i]))

```

Try it online!

# Answer
> 1 votes
# Charcoal, 47 bytes

```
⊞υθ⊞υηＦυＦι⊞υκＷυ«≔⊟υι≔⟦⟧ζＷι⊞ζ⊟ιＷ⁻ζιＦ№ζ⌊κ⊞ι⌊κ»⁼θη

```

Try it online! Link is to verbose version of code. Not easy due to lack of recursion or sorting primitives. Explanation:

```
⊞υθ⊞υηＦυＦι⊞υκ

```

Get all of the lists and sublists from the input.

```
Ｗυ«≔⊟υι

```

Process them in reverse order.

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

```

Move the elements of this (sub)list into a temporary list.

```
Ｗ⁻ζιＦ№ζ⌊κ⊞ι⌊κ

```

Put them back but in sorted order.

```
»⁼θη

```

Now that the input lists have been sorted in-place, we can just compare them directly.

# Answer
> 1 votes
# Retina 0.8.2, 116 bytes

```
+`(?=(((\[)|(?<-3>])|,)+(?(3)^)),(?!\1)(((\[)|(?<-6>])|,)+(?(6)^))(.*))(.*)\[.*(?=\4\7$)\8].*(?=\7$)
$4,$1
^(.+) \1$

```

Try it online! Link includes test cases. Explanation:

```
+`

```

Repeat until no more lists need exchanging.

```
(?=(((\[)|(?<-3>])|,)+(?(3)^)),(?!\1)(((\[)|(?<-6>])|,)+(?(6)^))(.*))

```

Look ahead to capture two balanced lists and the tail of the string.

```
(.*)\[.*(?=\4\7$)\8].*(?=\7$)

```

Check whether the second list should precede the first list. The lookaheads ensure that we only compare the two lists captured above. Note that this could inefficiently swap two lists back and forth before it's finished sorting their sublists, but once all of the sublists are sorted the lists will eventually sort stably.

```
$4,$1

```

If so then exchange the two lists.

```
^(.+) \1$

```

Now that the input lists have been sorted, just compare them directly.

# Answer
> 0 votes
# Perl 5, 59 bytes

```
sub f{@_>1?f(pop)eq f(pop):"(@{[sort map{f($_)}@{pop()}]}"}

```

Try it online!

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


title: Magnetic pull in an array

text:
# Question
Title: Magnetic pull in an array
## Background

I have a row of powerful magnets and a bunch of metal objects between them. Where will the magnets pull them?

## Input

Your input is an array of non-negative integers, which will contain at least one `1`. You can use any reasonable format.

The `0`s of the array represent empty space, and the `1`s represent fixed magnets. All other numbers are metal objects, which are pulled by the magnets. Every object gets pulled towards the nearest magnet (if there's a tie, the object is pulled to the right), and it travels in that direction until it hits the magnet or another object. In the end, all the objects have clustered around the magnets. The order of the objects is preserved.

## Output

Your output is the array where every object has been pulled as close to the nearest magnet as possible. It should have the same format as the input.

## Example

Consider the array

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

```

The leftmost `2` gets pulled towards the first pair of magnets, as does the second `2`. The `3` has a magnet four steps away in both directions, so it gets pulled to the right. The `5` also gets pulled to the right, and it goes between the `3` and the magnet. The correct output is

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

```

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

```
[0,1,0] -> [0,1,0]
[1,0,2,0,0,1,0] -> [1,2,0,0,0,1,0]
[7,0,5,0,0,1,0] -> [0,0,0,7,5,1,0]
[1,0,3,0,1,0,3,0,1] -> [1,0,0,3,1,0,0,3,1]
[1,0,0,0,0,0,0,7,3] -> [1,7,3,0,0,0,0,0,0]
[1,2,3,4,5,6,7,8,9,10,11,0,0,0,1] -> [1,2,3,4,5,6,7,0,0,0,8,9,10,11,1]
[12,3,0,0,1,0,1,3,0,0,6,12,0,0,0,1] -> [0,0,12,3,1,0,1,3,6,0,0,0,0,0,12,1]

```

# Answer
# Pyth, ~~28~~ 20

```
o@.e?bhaDk_x1QkQ~hZQ

```

Thanks @ThomasKwa for golfing 6 bytes!

This abuses stable sorting by assigning to all the values 1 or greater in the list the index of the nearest 1 (ties broken to the rightmost 1) and then sorting the list by these values. Zeroes are given their own index as their sort value.

Test Suite

Verification Suite

### Explanation:

```
o@.e?bhaDk_x1QkQ~hZQ  ##  implicit: Q = eval(input())
o                  Q  ##  Sort Q using the values of the lambda below
 @              ~hZ   ##  select the value from the matching index of the enumerate
  .e           Q      ##  enumerate with b = value, k = index
    ?b                ##  ternary on b
      haDk_x1Q        ##  if true, this thing
              k       ##  otherwise use the index as the sort weight
          _x1Q        ##  the indices of 1 in Q, given in reverse order
                      ##  (the reverse makes it sort to the right because of stable sorts)
       aDk            ##  sort those indices by |index - k|
      h               ##  take the first value

```

### Example:

Take the test case `[1,0,3,0,1,0,3,0,1]`, for example. When we apply the enumeration, the zeros will all get their own index as a sort value, so I'll skip those, and do a one and a three.

For the first one, we get the indices of ones: `[0, 4, 8]`. Then reverse it, and sort by the absolute value of the indices minus the index of the one, which happens to be zero here. So we get `[0, 4, 8]` back again. The first value is `0` so we use that.

For the three, we get the reversed indices and do the same sorting but using two as the index of the three, so both the `0` and the `4` give the same value for the absolute difference, so we get: `[4, 0, 8]` and we take the `4`.

Then the final "sorting values" array will be `[0, 1, 4, 3, 4, 5, 8, 7, 8]`. Thanks to the stable sort, the ties are broken by the order that the values originally appeared, so we get the final array we want.
> 8 votes

# Answer
## Retina, ~~97~~ 72 bytes

```
+`(?<=\b1(,1*)*?)(\B,(11+)|,(11+))\b(?!(?<-1>,1*)*,1\b)|(11+),\B
$3,$4$5

```

Input is expected to be a comma-separated list of unary integers (leading and trailing delimiters like `[...]` work just fine).

Run all test cases here. (For convenience, this takes care of the conversion from and to decimal automatically.)

Here is a completely different idea that avoids the expensive balancing groups by using multiple stage. It's currently 6 bytes longer, but might be more golfable:

```
,1\b
>1
\b1,
1<
(T`,`<`<1*,
)T`,`>`,1*>
+`(1+>)>
>$1
+`<(<1+\b)(?!>)
$1<
<|>
,

```
> 5 votes

# Answer
# JavaScript (ES6), 108 bytes

```
a=>a.map(_=>a.map((x,i)=>x>1?a[j=(n=a.indexOf(1,i))<0|n-i>i-p?i-1:i+1]?0:a[a[i]=0,j]=x:x<1?0:p=i,p=-1/0))&&a

```

## Explanation

Iterates over each cell and if it contains metal, checks if the next cell in the direction of the closest magnet is empty, and if it is, moves it there. This process is repeated many times until all metal has moved as far as it can go.

```
var solution =

a=>
  a.map(_=>                  // loop a.length times to ensure completeness
    a.map((x,i)=>            // for each cell item x at index i
      x>1?                   // if the cell contains metal
        a[j=                 // j = index of cell to move to
          (n=a.indexOf(1,i)) // n = index of next magnet
          <0|n-i>i-p?i-1:i+1 // set j to previous or next cell based on closest magnet
        ]?0:                 // if cell j is empty
          a[a[i]=0,j]=x      // set it to x and set cell i to 0
      :x<1?0:                // else if the cell contains a magnet
        p=i,                 // set p to the index of this magnet
      p=-1/0                 // p = index of previous magnet, initialise to -Infinity
    )
  )
  &&a                        // return a
```

```
<input type="text" id="input" value="1,2,3,4,5,6,7,8,9,10,11,0,0,0,1" />
<button onclick="result.textContent=solution(input.value.split(',').map(n=>+n))">Go</button>
<pre id="result"></pre>
```
> 4 votes

# Answer
# PHP, 337 chars

```
<?$i=explode(",",$argv[1]);$m=$n=[];foreach($i as$k=>$v)if($v>0)eval("array_push(\$".($v<2?"m":"n").",$k);");for($p=0;$p<count($i);$p++)foreach($i as$k=>$v)if($v>1){$i[$k]=0;$r=-1;foreach($m as$_)if($r<0||abs($k-$r)>abs($_-$k))$r=$_;while($i[$r]>0)$r+=($r<$k?1:-1);$i[$r]=$v;}$s="";foreach($i as$v)$s.=$v.",";echo substr($s,0,-1)."\n";?>

```

Yes this is very long, because PHP is not really a language for golfing, but it works and I had FUN making it so it's fine to me. Of course I'm open to possible shortings.

Also there is a little bug feature which thinks, so for example here:

```
root@raspberrypi:~/stack# php magnet.php 12,3,0,0,1,0,1,3,0,0,6,12,0,0,0,1
0,0,3,12,1,0,1,3,6,0,0,0,0,0,12,1

```

it looks like the 12 magicly got in front of the 3, but that's not true!

The 3 respects the bigger number and lets it go closer to the maget!
> 3 votes

# Answer
# Haskell, 127 bytes

```
(a:b)!(c:d)=c/=1&&a==1||b!d
_!_=1<0
infix 4#
x@(a:b)#0:i@(c:d)|i!x=a:0:b#i|x!i=c:x#0:d
x#a:b=a:x#b
x#[]=x
l=([]#)
l.l.l.reverse

```

Try it online!

Instead of moving the objects towards the magnets we move the empty space away from the magnets.

A big frustration for me was that the default was to the right. Defaulting to the left could have saved me 10 bytes. To default to the left we do `l.l` to default to the right we need `l.l.l.reverse`.

When we run `l` it naturally reverses the list, however this is actually pretty convenient since we need to run it on the list going both ways, so the output is ready to go for the second run. Unfortunately though since to default to the right this means we need to reverse it manually first, then run it twice, we end up needing an additional `l` to get it back to the correct order.
> 1 votes

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


# Question
Title: Indices of square numbers that are also pentagonal
First 15 numbers of the A046173:

```
1, 99, 9701, 950599, 93149001, 9127651499, 894416697901, 87643708742799, 8588189040096401, 841554882220704499, 82463790268588944501, 8080609891439495856599, 791817305570802005002201, 77590015336047156994359099, 7603029685627050583442189501

```

Your task is simple, output the first 20 numbers of this sequence on separate lines.

A simple explanation to this sequence, (you can also refer to the link above), is
As n increases, this sequence is approximately geometric with common ratio \\$ r = \lim\_{n\to\infty} \frac{a(n)}{a(n-1)} = (\sqrt2 + \sqrt3)^4 = 49 + 20 \times \sqrt6 \\$

This is code-golf, so shortest code wins!

# Answer
> 1 votes
# 05AB1E, 15 bytes

With strict I/O as defined in the challenge description: the first 20 items newline delimited:

```
21®1‚λ£98*s-}¦»

```

Try it online.

With default I/O rules: outputs the 1-based \\$n^{th}\\$ term (**10 bytes**):

```
®1‚λè98*s-

```

Try it online.

**Explanation:**

Uses the formula: \\$a(n)=98\times a(n-1)-a(n-2)\\$ with offset \\$-1,1\\$, the first formula defined on the oeis-page.

```
     λ       # Start a recursive environment,
21    £      # to get the first 21 terms
  ®1‚        # Starting with a(0)=-1 and a(1)=1
             # With every following a(n) defined as:
       98*   #  Multiply the implicit a(n-1) by 98
          s- #  Subtract the implicit a(n-2) from it
     }¦      # After the recursive environment: remove the first -1 term
       »     # Join the 20 terms by newlines
             # (after which it is output implicitly as result)

   λ         # Start a recursive environment,
    è        # to output the (implicit) input'th term
®1‚          # Starting with a(0)=-1 and a(1)=1
             # With every following a(n) defined as:
     98*s-   #  Same as above: 98*a(n-1)-a(n-2)
             # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Vyxal `j`, 22 bytes

```
λ²`(3ṙ-x)/2`∆qt:⌊=;20ȯ

```

Try it Online!

Finally a good use for symbolic algebra in a golfing language. Good luck porting this to Jelly lol.

## Explained

```
λ²`...`∆qt:⌊=;20ȯ
λ                 # Create a lambda, that takes a single argument n and:
 ²                #   squares n
 `...`            #   pushes the string "(3x^2-x)/2" (this is the formula for pentagonal numbers - I found it on Wikipedia)
      ∆q          #   and solves that for x (as in, it uses Sympy to solve it as if it were an equation) - this will give a list of up to 2 solutions - a negative and positive solution in that order
        t         #   Push that positive solution because that's what we're interested in checking
         :⌊=      #   Does the floor of that solution equal that solution? This checks to see if it's an integer solution, as only integer solutions are plugged into the original formula anyway
            ;     # Close the lambda
             20ȯ  # and push the first 20 numbers where that lambda is truthy - this times out online, but it works given infinite time and resources
# The j flag joins that list on newlines - I think it's okay here because the main focus of the challenge is generating the numbers

```

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

A full program.

```
for(v=q=1n;~v%39n;v=q-98n*(q=-v))console.log(v+'')

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 44 bytes

```
for(i=0,19,print(([-1,1]*[0,-1;1,98]^i)[2]))

```

Try it online!

Using the formula \\$a(n)=98\ a(n-1)-a(n-2)\\$.

---
Tags: code-golf, math, number, sequence
---


title: Reverse an N-Dimensional array

text:
# Question
Title: Reverse an N-Dimensional array
## Details

Write a function or program that, given an array (or list), containing only integers, returns or output an array with all sub-elements reversed. That is, reverse all elements of the deepest array, then the second deepest, etc. The dimensions need not be specified, but the function or program must work for jagged arrays in your programming language's native format.

---

## Examples

**This:**

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

```

**Would become this:**

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

```

---

**This:**

```
[[[ 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]]]

```

**Would become this:**

```
[[[54,53,52], [51,50,49], [48,47,46]],
 [[45,44,43], [42,41,40], [39,38,37]],
 [[36,35,34], [33,32,31], [30,29,28]],
 [[27,26,25], [24,23,22], [21,20,19]],
 [[18,17,16], [15,14,13], [12,11,10]],
 [[ 9, 8, 7], [ 6, 5, 4], [ 3, 2, 1]]]

```

---

**This:**

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

```

**Would become this:**

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

```

---

## Bonus

This will *hopefully* encourage answers in some object-oriented programming languages...

**-50% Bytecount** If your program can take as input an array (or list) with its member's of various types (these can be in the form of objects) and successfully reverse all arrays.

**This:**

```
[["Foo",["Bar",1]],
  2,
 ["Baz"],
 [[["Qux"],3],3.14]]

```

**Would become this:**

```
[[3.14,[3,["Qux"]]],
 ["Baz"],
  2,
 [[1,"Bar"],"Foo"]]

```

# Answer
# Pyth, 11 - 50% = 5.5 bytes

```
L?+IbY_yMbb

```

Try it online: Demonstration or Test Suite.

This defines a function `y`. The additional 3 bytes `<newline>yQ` simply call the function with the input list and therefore doesn't need to be counted towards the bytes total.

### Explanation:

```
L?+IbY_yMbb
L             define a function y(b), that returns:
 ?+IbY           if b + [] == b (test if b is a list):
      _yMb           recursively call y on all elements in b, then reverse the list
          b      else: b

```
> 10 votes

# Answer
# Dyalog APL, 14 - 50% = 7 bytes

```
{∇¨⍣(×|≡⍵)⌽⍵}

```

`⌽⍵` reverse argument
`⍣(×|≡⍵)` if the argument is not an atom (sign of the \[absolute\] depth)...
`∇¨` ... apply the function to each element (of the reversed argument).

If `⎕ML←3` (IBM style), which is the case on systems that migrated from APL2, one byte can be saved by removing `|`.

Try APL online.

For curiosity, the proposed int and float reversing:

```
{∇¨⍣(×≡⍵){0::⌽⍵⋄⍎⌽⍕⍵}⍵}

```

The inner function:

`0::⌽⍵` if any error occurs, just return the revesed argument
`⍎⌽⍕` make into string, reverse, make into number
> 7 votes

# Answer
# Prolog, 40 - 50% = 20 bytes

```
a(X,Y):-reverse(X,Z),maplist(a,Z,Y);X=Y.

```

This recursively calls predicate `a/2` with `maplist/3`, for each member of the list, until `reverse/2` fails (i.e. last element wasn't a list).
> 5 votes

# Answer
# Python 2, 40 - 50% = 20

```
f=lambda x:map(f,x)[::-1]if"">x>[]else x

```

Only some minor modifications needed from the basic way to do it are needed to get the bonus. Uses the fact that all lists are less than the empty string, and all numbers are less than the empty list.

All test cases
> 5 votes

# Answer
## Emacs Lisp, 46 bytes * 0.5 = 23

```
(defun g(x)(if(atom x)x(mapcar'g(reverse x))))

```

Usage example: `(g '((1 2) 3 (four 5)))` -\> `((5 four) 3 (2 1))`

Classic recursive approach: if the argument isn't a list, take it unchanged, if it's a list, map the function over the reverse of the list.
> 3 votes

# Answer
# Mathematica, 34/2=17 bytes

```
Quiet[Reverse//@#]/.Reverse->(#&)&

```

Or just `Reverse//@#&` if you want a ton of errors and `Reverse`s everywhere.
> 2 votes

# Answer
# Clojure 43/2=21.5 bytes

```
(defn f[x](if(coll? x)(reverse(map f x))x))

```
> 2 votes

# Answer
# Brachylog, 5 - 50% = 2.5 bytes

```
ċ↔↰ᵐ|

```

Try it online!

```
         The input
ċ        which is a list
 ↔       reversed
   ᵐ     with each element
  ↰      passed through this same predicate
    |    is the output. If the input isn't a list,
         it is the output.

```

Since  can also reverse strings and integers, we have to explicitly fail non-lists with `ċ`.
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~23~~ ~~22~~ 21 bytes

-50% bonus

```
#0/@Reverse@*List@@#&

```

Try it online!

Only works on nested `List`s of atoms. Reverse a list, then reverse its elements. `@@` and `/@` are no-ops on atoms.
> 2 votes

# Answer
# JavaScript ES6, 42 - 50% = 21 bytes

My score is perfect in so many ways. Implements a function `r` which recursively applies itself to the members of its input.

```
r=a=>Array.isArray(a)?a.reverse().map(r):a

```

If we assume no object has the property `pop`, then this becomes (31 - 50% = 15.5), thanks to dev-null:

```
r=a=>a.pop?a.reverse().map(r):a

```

Or, if we assume the object has a sane `reverse` property, we could do that as well (35 - 50% = 17.5):

```
r=a=>a[R="reverse"]?a[R]().map(r):a

```
> 1 votes

# Answer
# Lua, ~~111~~ 99 * .5 = ~~55.5~~ 49.5 bytes

```
function r(a)local t={}for i,v in next,a do t[#a+1-i]=type(v)=="table"and r(v)or v end return t end

```

Good bit of recursion
> 1 votes

# Answer
## CJam, 20 bytes * 50% = 10

```
{_`0='[={W%{F}%}&}:F

```

Defines the named block `F` which can be applied to an array on top of the stack (or anything else, in which case it's a no-op).

Test it here.
> 1 votes

# Answer
## Clojure, 38 bytes

**(and a bonus I guess, but Clojure is a dynamic language so it comes for free)**

```
(fn f[x](if(seq? x)(map f(into()x))x))

```

This is a good start but didn't employ these optimizations:

* Define an anonymous function with `fn` instead of a named one with `defn`. But we still need a "scoped" name `f` for recursion
* Take input as a list instead of vector, then we can use `seq?` instead of `coll?`
* Use `(into () ...)` instead of `reverse`
* Reverse `x` before mapping, we don't need as many spaces then
> 1 votes

# Answer
# Clojure, ~~40~~ 38 -50% = 19 bytes

```
(fn r[s](if(coll? s)(map r(rseq s))s))

```

Try it online!

A translation of the JavaScript answer. Matched the score with the best Clojure answer ;)
> 1 votes

# Answer
# Haskell \+ free, 8.5 bytes (17 bytes -50% bonus)

In order to represent a ragged list in Haskell we use a free monad of lists. We use the free library to get these free monads.

```
hoistFree reverse

```

Try it online!

## Explanation

`hoistFree` takes a natural transformation from some functor \\$F\\$ to another functor \\$G\\$ and makes a natural transformation from \\$\mathrm{Free}(F)\\$ to \\$\mathrm{Free}(G)\\$. Here the natural transformation is reverse, from lists to lists.

Because `hoistFree` must work with any natural transformation we know it must apply `reverse` exactly once to every sublist. For example imagine we had a natural transformation:

```
newtype Reversed f a
  = Reversed (f a)

reverse' :: [a] -> Reversed [] a
reverse' =
  Reversed . reverse

```

This is functionally identical to `reverse` but the types prove it must be applied exactly once to every list.
> 1 votes

# Answer
# Ruby, 32 - 50% = 16 bytes

Recursive function. Using `rescue` to catch the `NoMethodError` that triggers when trying to `reverse` a number or `map` a string turns out to be 2 bytes shorter than checking if the input is an array via `a==[*a]`.

```
f=->a{a.reverse.map(&f)rescue a}

```

Try it online!
> 0 votes

# Answer
# Julia 1.0, 27 -50% = 13.5

```
!x=x
!x::Array=reverse(.!x)

```

Try it online!
> 0 votes

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


# Question
Title: Reconstruct a recursively prime-encoded integer
**Recursively prime-encoded integers**

Consider \\$11681169775023850 = 2 \times 5 \times 5 \times 42239 \times 5530987843\\$. This isn't a nice prime factorisation, as \\$42239\\$ and \\$5530987843\\$ make it difficult to store this factorisation in a small manner. Being primes, we can't then factorise them, but we can factorise \\$p - 1\\$, which is guaranteed to not be prime (ignoring \\$p = 3\\$). by doing this we get:

* \\$42239 \to 42238 = 2 \times 7 \times 7 \times 431\\$
* \\$5530987843 \to 5530987842 = 2 \times 3 \times 17 \times 54225371\\$

This helps, but \\$431\\$ and \\$54225371\\$ are still pesky, so we run the same procedure (prime factorising their decrement). Just to be safe, we'll also do it with \\$17\\$ so that we can only have single digit primes (\\$2,3,5,7\\$) in the final result. This eventually results in:

```
[2, 5, 5, [2, 7, 7, [2, 5, [2, 3, 7]]], [2, 3, [2, 2, 2, 2], [2, 5, [2, 2, 2, 5], [2, 2, 2, 2, 2, [2, 2, [2, 2, 2, 3, [2, 3, 7]]]]]]]

```

representing \\$11681169775023850\\$. This is a program that shows the steps of decomposition of the input, and this is a program which decomposes a given integer.

The representations for the integers from 2 to 25 are:

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

```

For example, for `[2, [2, 5]]`, we first multiply the inner list and increment to get `[2, 11]`. From here, we just multiply, resulting in the final output of `22`

---

You are to take the representation of a recursively prime-encoded integer and output the original integer.

The input will be a jagged list, where each element is either a single digit prime (\\$2,3,5,7\\$) or a list where the same rule applies. The input will never contain empty lists, and will never be empty.

This is , so the shortest code in bytes wins

## Test cases

```
[2, 2, 2, 5] -> 40
[[2, 2, 3]] -> 13
[[2, 3, 5]] -> 31
[3] -> 3
[2, 3, 3, 5] -> 90
[2, [2, [2, 5]]] -> 46
[[2, 5]] -> 11
[[2, 2, 7, [2, 2, 2, 2, 3, 7]]] -> 9437
[2, 2, 2, 2, 2, 3, 5] -> 480
[2, 2, 2, 7, [2, 2, 2, 2]] -> 952
[2, [2, 2, 3, 7, [2, 3, 3]]] -> 3194
[2, 3, 3, [2, 2, 2, 2, 2, 2, 7]] -> 8082
[5, [2, 2, 7], [2, [2, [2, 5]]]] -> 6815
[5, [2, [2, 2, [2, 2, 2, 5], [2, [2, 5, 5, 5]]]]] -> 824935
[3, 3, [2, 2, 3, 3], [2, 7, [2, [2, 2, 2, 5]]]] -> 387279
[7, [2, 2, 5, 5], [2, 3, 5, [2, 3, 7]]] -> 912737
[[2, [2, [2, 5, [2, 2, 3]], [2, 2, 2, 2, 3, 3, 7]]]] -> 528719
[2, 2, 2, 2, 7, [2, 5], [2, 2, [2, 2, 2, 2, 2, 2, 3]]] -> 952336
[2, 3, 3, [2, 3, 5], [2, 5, 5, [2, 2, 7]]] -> 809658
[[2, 2, 2, 3, [2, 2, [2, 3, 7]]], [2, 2, 2, 2, 2, 2, 3, [2, 2, 3], [2, 2, 7, [2, 3, 3, 7]], [2, 5, [2, 2, 2, [2, 5]], [2, [2, 2, [2, 2, 3]]]]]] -> 3511306351619449
[5, 7, 7, [2, 3, [2, 5], [2, [2, 2, 2, 5]]], [2, 2, 2, 7, [2, [2, [2, 2, 2, [2, 5]]]], [2, 2, 2, 2, 2, 3, 3, [2, 5, [2, 3, [2, 2, 2, 2]]]]]] -> 8013135306533035
[2, 3, 3, [2, 2, 2, 3, 3], [2, 3, [2, [2, 5]]], [2, 3, [2, 2, 3, [2, 2, 2, 2, 2, 3], [2, [2, 5, 7, 7]], [2, 2, [2, 5], [2, 2, [2, 2, 3]]]]]] -> 2925382459116618

```

# Answer
> 11 votes
# Python 2, 42 bytes

*Thanks to @tsh for suggesting a 2-byte improvement*

```
f=lambda x=1,*a:x<2or-(x*-1or~f(*x))*f(*a)

```

Try it online!

`-(x*-1or~f(*x))` computes for a given element, its decoded value. If `x` is an integer, the `or` will short circuit, resulting in `x` as the value. If it is a list, `x*-1` will return an empty list, and the result becomes a recursive call on `x`: `-~f(*x)`.

This result is then multiplied by the rest of the elements through recursion: `f(*a)`. Finally, the default `x=1` argument assists in the terminating condition of `x<2`.

# Answer
> 8 votes
# yuno, 5 bytes

```
ᴘ’)υ‘

```

Try it online!

```
(ᴘ’)υ‘    Main Link
(  )υ     Deep Recurse; on each sub-list and recursively, call
 ᴘ        - Product
  ’       - Increment
     ‘   Decrement

```

I've had the idea for `υ` from ever since I first started drafting yuno, but this adverb was implemented after this challenge.

**Old version**

# yuno, 7 bytes

```
ɫ’)ᴅ?Ͼᴘ

```

Try it online!

Expect this to get shorter later once I implement more adverbs.

For now, this is the same approach as my Jelly solution.

```
(ɫ’)ᴅ?Ͼᴘ    Main Link
      Ͼ     For each item
     ?      - If
    ᴅ         - It has depth (it is a list and not just a single number)
(ɫ’)        - Monadic function:
 ɫ            - Call this link as a monad
  ’           - And increment
       ᴘ    Take the product

```

# Answer
> 8 votes
# APL (Dyalog Extended), 13 bytes

```
¯1+(≡+×/)⍥1⍣≡

```

Try it online!

Takes a nested APL array (which can be obtained from JSON-converting the test cases) and returns the original number.

### How it works

This uses the Depth operator `f⍥n`, which hasn't made into mainstream yet. A depth-1 value in a mixed array can be a vector or a scalar (if one of its siblings is nested). `≡+×/` is an expression that keeps scalar intact (product is itself and its depth  is 0), and evaluates product + 1 for vectors. Now, we can simply repeat this at depth 1 until the entire value becomes a single number, and subtract 1 at the end (to negate the +1 applied at the very last layer).

# Answer
> 6 votes
# Wolfram Language (Mathematica), ~~22~~ 17 bytes

```
1+1##&@@#&//@#-1&

```

Try it online!

```
1+1##&@@#&//@#      expressions become the product of their arguments plus 1
              -1&   subtract 1 (outermost list doesn't increment)

```

# Answer
> 6 votes
# JavaScript (ES6), 35 bytes

```
f=a=>a.map(n=>p*=+n||f(n)+1,p=1)&&p

```

Try it online!

# Answer
> 4 votes
# Perl 5 (`-p`), 30 bytes

```
y/,]/*)/;s/\[/(1+/g;$_=-1+eval

```

replacing `[` , `,`, `]` with `(1+`, `*`, `)` resp., and evaluating.

Try it online!

# Perl 5, 42 bytes

```
sub f{my$r=1;map$r*=@$_?1+f(@$_):$_,@_;$r}

```

with a recursive function

Try it online!

# Answer
> 3 votes
# , 46 45 bytes

```
[:(*>:)/[:;L:1^:_[:*/L:0;~&1^:((1=#)*1<L.)L:2

```

Try it online!

I thought this was going to be like 10 chars...

# Answer
> 2 votes
# Jelly, 9 bytes

```
ß‘µ¹ŒḊ?€P

```

Try it online!

```
ß‘µPŒḊ?€P      Main Link
       €       For each element:
      ?        - If
    ŒḊ           - It has depth (isn't a number)
ß‘µ            - Call this link on the sub-list, take the product, and increment it
   P           - Otherwise, take the product (or first element, or sum, w/e)
        P      Take the product

```

# Answer
> 2 votes
# MMIX, 56 bytes (14 instrs)

```
typedef union _rpe {
    struct {
        uint64_t flag : 1; // must be 1
        uint64_t val : 63;
    };
    union _rpe *list;
} rpe;

uint64_t __mmixware rpd(rpe encoded);

```

Lists terminate on a `union _rpe` that isn't a list (`flag` is on) whose `val` is 0. (MMIX pointers must be positive for user programs, or a trap occurs.)

```
00000000: 48000003 ec008000 f8010000 fe010004  H¡¡¤ġ¡⁰¡ẏ¢¡¡“¢¡¥
00000010: e3020001 8f040000 e7000008 f303fff9  ẉ£¡¢Ɓ¥¡¡ḃ¡¡®ṙ¤”ż
00000020: 42030003 1a020203 f1fffffb f6040001  B¤¡¤ȷ££¤ȯ””»ẇ¥¡¢
00000030: 23000201 f8010000                    #¡£¢ẏ¢¡¡

```

```
rpd     BNN   $0,0F     // if(encoded.flag)
        ANDNH $0,#8000
        POP   1,0       // return encoded.val;
0H      GET   $1,rJ
        SET   $2,1      // uint64_t i = 1;
0H      LDOU  $4,$0     // loop: rpe n = *encoded.list;
        INCL  $0,8      // encoded++;
        PUSHJ $3,rpd    // uint64_t j = rpd(n);
        BZ    $3,0F     // if(!j) goto end;
        MULU  $2,$2,$3  // i *= j;
        JMP   0B        // goto loop;
0H      PUT   rJ,$1
        ADDU  $0,$2,1
        POP   1,0       // return i + 1;

```

# Answer
> 2 votes
# Stax, 13 bytes

```
â╥¡░Ω↕¬∟oqFµ+

```

Run and debug it

recursion's a bit clunky here, but thankfully it works.

# Answer
> 2 votes
# Ruby, 41 bytes

```
f=->n{n.map{|x|x*0==0?x:f[x]+1}.reduce:*}

```

Try it online!

# Answer
> 2 votes
# Retina, 34 bytes

```
~(`,
$*
^.
.+¶$$.(
\[
$$.(_
]
$*)

```

Try it online! Link includes test cases. Explanation:

```
,
$*

```

Change all separators into multiplication operators.

```
^.
.+¶$$.(

```

Change the opening `[` into code to replace the input with the product of the values.

```
\[
$$.(_

```

Change the remaining `[`s into code to increment the product of the values.

```
]
$*)

```

Change the `]`s into code to terminate the product expressions.

```
~(`

```

Evaluate the resulting program on the original input.

For example, the input `[2, 2, 2, 7, [2, 2, 2, 2]]` is transformed into the following Retina program:

```
.+
$.(2*2*2*7*$.(_2*2*2*2*))

```

The `2*2*2*2*` evaluates to `________________`, so the `$.(_)` results in `17`, and the outer multiplication then produces the final result of 952.

# Answer
> 2 votes
# Japt, 9 bytes

```
ËÉªßD)ÄÃ×

```

Try it or test 2-25 or run all test cases

Takes advantage of the fact that the sub-arrays are never singletons.

```
ËÉªßD)ÄÃ×     :Implicit input of array
Ë             :Map each D
 É            :  Subtract 1 (resulting in NaN if it's an array)
  ª           :  Logical OR with
   ßD         :  A recursive call with argument D
     )        :  Group that together
      Ä       :  Add 1 to the result
       Ã      :End map
        ×     :Reduce by multiplication

```

# Answer
> 2 votes
# , ~~65~~ 57 bytes

```
r=function(l,z=0)`if`(is.list(l),prod(sapply(l,r,1))+z,l)

```

Try it online!

Recursively adds 1 to the product of all list elements.

This would end-up one-too-many, so we skip adding 1 for the outermost loop.

# Answer
> 1 votes
# Charcoal, 33 bytes

```
ＦＳ≡ι[⊞υ¹]¿⊖Ｌυ⊞υ×⊕⊟υ⊟υＩυ¿Σι⊞υ×⊟υΣι

```

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

```
ＦＳ≡ι

```

Loop over and switch on the input characters.

```
[⊞υ¹

```

For `[` push a `1` to the predefined empty list.

```
]¿⊖Ｌυ

```

For `]` if the list has more than one element, then...

```
⊞υ×⊕⊟υ⊟υ

```

... increment the top element and multiply the second element by it, otherwise...

```
Ｉυ

```

... print the result.

```
¿Σι⊞υ×⊟υΣι

```

Otherwise for digits multiply the top element by the value of the digits.

# Answer
> 1 votes
# Gaia, ~~14~~ 12 bytes

Defines a function which takes a nested list and returns an integer.

```
⟨::C⟨←)⟩¿⟩¦Π

```

Try it online!

```
⟨        ⟩¦     # map over each element in the input
 ::             # two copies of the TOS
   C            # compare for two ints (0), count occurences for two lists (1)
    ⟨  ⟩¿       # if the TOS is truthy:
     ←)         #   recursively call the function and add 1
           Π    # after the map: take the product

```

# Answer
> 1 votes
# Pari/GP, 37 bytes

```
f(a)=vecprod([if(#b',f(b)+1,b)|b<-a])

```

Try it online!

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


title: Slater-Velez permutation

text:
# Question
Title: Slater-Velez permutation
Let's build a sequence of positive integers. The rule will be that the next number will be the smallest number which:

* It hasn't already appeared in the sequence
* Its absolute difference from the number preceding it wouldn't be equal to any previous absolute difference between consecutive elements.

## Task

Your task is to implement this sequence. You may use defaults, found in the tag wiki.

This is so answers will be scored in bytes with fewer bytes being better.

## Example

As an example let's construct the first couple of terms. The first term is `1` since it's the smallest positive integer. After that comes `2`.

```
Sequence: 1, 2
Diffs:     1

```

`3` is the next smallest number, but it's difference from `2` is the same as the difference between `1` and `2`, so `4` is the next term.

```
Sequence: 1, 2, 4
Diffs:     1, 2

```

Now `3` *still* can't be added because it's difference from `4` is `1`, `5` and `6` also can't be added because their diffs are `1` and `2`. So the smallest number is `7`.

```
Sequence: 1, 2, 4, 7
Diffs:     1, 2, 3

```

Now `3` can be added, since it's difference from `7` is `4` which we haven't seen before.

```
Sequence: 1, 2, 4, 7, 3
Diffs:     1, 2, 3, 4

```

Since the diffs count up to `4` we know the next one is *at least* `5`, so the next number is at least `8`. `8` hasn't appeared so we can add it.

```
Sequence: 1, 2, 4, 7, 3, 8
Diffs:     1, 2, 3, 4, 5

```

## Test cases

This sequence is OEIS A081145. Here are the first few terms taken from OEIS:

```
1, 2, 4, 7, 3, 8, 14, 5, 12, 20, 6, 16, 27, 9, 21, 34, 10, 25, 41, 11, 28, 47, 13, 33, 54, 15, 37, 60, 17, 42, 68, 18, 45, 73, 19, 48, 79, 22, 55, 23, 58, 94, 24, 61, 99, 26, 66, 107, 29, 71, 115, 30, 75, 121, 31, 78, 126, 32, 81, 132, 35, 87, 140, 36, 91, 147, 38, 96, 155, 39

```

# Answer
# Python, 70 bytes

```
a={0,p:=1}
while[print(d:=p)]:
 while(s:={p-d,-d*d})&a:d-=1
 a|=s;p-=d
```

Attempt This Online!

-1 each thanks to @xnor and @ovs.

Prints the sequence infinitely. Avoids the need for two storage lists by using the negative absolute difference.
> 8 votes

# Answer
# Brachylog, 16 bytes

```
~l.ℕ₁ᵐ≠s₂ᵇ-ᵐȧᵐ≠∧

```

Try it online!

Returns a list of the `n` first elements of the sequence.

### Explanation

We basically describe the properties of the sequence: a list of positive integers, that are all different, and where each 2-element substring difference is unique.

```
~l.                Output is a list of length <Input>
  .ℕ₁ᵐ             Output contains strictly positive integers
  .   ≠            All elements in the output are different
  .    s₂ᵇ         Find all sublists of 2 consecutive elements in the Output
          -ᵐ       Map subtraction
            ȧᵐ     Map absolute value
              ≠    All results must be different
               ∧   Implicit labelling of elements in the output to match these constraints

```
> 6 votes

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

```
λλû¥+λ«∞sKн

```

-4 bytes thanks to @ovs.

Outputs the infinite sequence.

Try it online.

**Explanation:**

```
λ           # Start a recursive environment
            # to output the infinite sequence
            # Implicitly starting with a(0)=1
            # Where every following a(n) is calculated as follows:
            #  (implicitly push a(n-1))
 λ          #  Push a list of all previous terms: [a(0),a(1),...,a(n-1)]
  û         #  Palindromize this list: [a(0),a(1),...,a(n-1),...,a(1),a(0)]
   ¥        #  Pop and push its forward differences
    +       #  Add the implicit a(n-1) to each
     λ«     #  Merge the list of previous terms to this list
       ∞    #  Push an infinite positive list: [1,2,3,...]
        s   #  Swap so our earlier created list is at the top again
         K  #  Remove all those values from the infinite positive list
          н #  Pop and leave just the first value
            # (after which the infinite list is output implicitly as result)

```
> 5 votes

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

```
{x,{y+(1<#?:\#'!'1_-':x,y)|/x=y}[x]/1}/[;1]

```

Try it online!

Takes the number of terms to generate (0-indexed, so passing `0` generates the sequence up to position 0, `4` generates the sequence up to position 4, etc etc.)

* `{...}/[;1]` set up a do-reduce, run for the inputted number of times, seeded with `1` (the first term of the sequence)
    + `{...{...}[x]/1}` set up a converge-reduce, fixing `x` (the sequence generated so far) and seeded with `1`
        - `(1<#?:\#'!'1_-':x,y)` determine if the current value has a different absolute difference than the rest of the terms in the sequence so far
            * `x,y` append the value being tested to the sequence so far
            * `1_-':` take the differences between successive items
            * `#'!'` take the absolute value of these differences
            * `1<#?:\` determine if the differences are all distinct (i.e. none are repeated)
        - `(...)|/x=y` set up a max-reduce (i.e. any), seeded with the check described above and run over the sequence compared to the value being tested (for equality)
        - `y+` add this result to the current value being tested; if the value meets both checks, it will be unchanged and end the converge-reduce
    + `{x,...}` append the next term in the sequence and feed it to the next iteration of the do-reduce
> 5 votes

# Answer
# Haskell, 107 bytes

```
e l=[last l+x*v|v<-zipWith((abs.).(-))l$1:l,x<-[-1,1]]++l
f n=head$filter(flip notElem$e$f<$>[0..n-1])[1..]

```

Try it Online!

-3 bytes thanks to AZTECCO
> 4 votes

# Answer
# Haskell, 97 bytes

```
(#)=notElem
g=(iterate(\l->l++[[x|x<-[1..],x#l,abs(x-last l)#zipWith((abs.).(-))l(1:l)]!!0])[]!!)

```

Try it online!

* returns first *n* elements.
> 4 votes

# Answer
# JavaScript (V8), 84 bytes

A full program printing the sequence forever.

```
for(a=[];i=1;print(p=i),a.push(i))while(a.some(q=v=>v==i|(i-p)**2==(q-(q=v))**2))i++

```

Try it online!

---

# JavaScript (V8),  ~~66~~  65 bytes

Using pxeger's nice idea.

```
for(s=p={};i=1;print(s[q]=s[i]=p=i))while(s[q=i-p,q*=-q]|s[i])i++

```

Try it online!
> 3 votes

# Answer
# Vyxal, 20 bytes

```
(λ¾₌‡¯ȧtnεc¾nc∨¬;ṅ…⅛

```

Try it Online!

I'm probably going to take the L to better algorithms, but that's okay with me. Prints the first n numbers.

## Explained

```
(λ¾₌‡¯ȧtnεc¾nc∨¬;ṅ…⅛
(                     # input times:
 λ..............;ṅ    #   find the first number N where:
   ₌                  #     the
  ¾ ‡¯ȧ               #     absolute values of the deltas of the global array
          c           #     contains
  ¾    tnε            #     the absolute difference of the last item of the global array and N
              ∨¬      #     nor
           ¾nc        #     does the global array contain N
                  …⅛  #   print N and add to the global array

```
> 3 votes

# Answer
# Perl 5 List::Util, 64 bytes

```
$l=@a=0..1e3;$a[$l]=0,say$l while$l=first{$_&&!$d{abs$_-$l}++}@a

```

Try it online!
> 3 votes

# Answer
# , 76 bytes

```
while(k<-1){p=print(+T[1])
while((p-k)^2%in%diff(T)^2|k%in%T)k=k+1
T=c(k,T)}

```

Try it online!

Prints the sequence infinitely.
> 3 votes

# Answer
# , ~~74~~ ~~71~~ 70 bytes

```
repeat T=c((u=1:(T*5))[!u%in%T&!(u-print(+T[1]))^2%in%diff(T)^2][1],T)

```

Try it online!

Outputs the sequence indefinitely.

Note (from OEIS A081145) that "*The points appear to lie on three straight lines of slopes roughly 0.56, 1.40, 2.24 (click "graph")*".
If true, then `a(n)` should always be less than or equal to `a(n-1)` multiplied by about `2.24/0.56`, or `4`. So here we only search in the range from `1` up to `a(n-1)` times `5` (to be on the safe side).
> 3 votes

# Answer
# APL (Dyalog Unicode), 32 bytes

Prints the sequence without end.

```
{∇⍵,⍨⊃k~⍨⍳+/k←⍵,(⎕←⊃⍵)+2-/⍵,⌽⍵}1

```

Try it online!

```
{∇⍵,⍨⊃k~⍨⍳+/k←⍵,(⎕←⊃⍵)+2-/⍵,⌽⍵}1 ⍝ full program that prints the sequence indefinitely
{                             }  ⍝ recursive function taking the previous numbers as right argument ⍵
                       2-/⍵,⌽⍵   ⍝ forward and backward differences of consecutive numbers in ⍵
                 ⎕←⊃⍵            ⍝ print (and return) the previous value
                      +          ⍝ add this to all the differences
                                 ⍝ all these results are not allowed because of the absolute difference rule
              ⍵,                 ⍝ prepend the previous sequence values
            k←                   ⍝ store this list in k
          +/                     ⍝ take the sum of k (this is always larger than the maximum value)
      k~⍨⍳                       ⍝ [1 .. sum(k)] without the values in k
     ⊃                           ⍝ take the first (lowest) value
  ⍵,⍨                            ⍝ prepend to the sequence values
 ∇                               ⍝ recursive function call with updated list
                               1 ⍝ call above function with value 1

```
> 3 votes

# Answer
# Haskell, ~~81~~ 77 bytes

*4 bytes saved by xnor*

```
(?)=notElem
q@(a:b)!x=a:[(z:q)!(d:x)|z<-[1..],d<-[abs$a-z],z?q,d?x]!!0
[1]![]

```

Try it online!

I gave it a day so I thought I'd give this a spin in Haskell myself. `[1]![]` gives an infinite list of the results.
> 3 votes

# Answer
# Charcoal, 40 bytes

```
≔¹ηＦＮ«≔¹ζＷ∨№υζ№υ±↔⁻ζη≦⊕ζ⊞υζ⊞υ±↔⁻ζη≔ζη⟦Ｉζ

```

Try it online! Link is to verbose version of code. Outputs the first `n` terms. Explanation: Uses @pxeger's trick to avoid keeping track of two sets.

```
≔¹η

```

Start with the previous term being `1`. This gives a zero difference for the first term, which doesn't conflict with anything else.

```
ＦＮ«

```

Process `n` terms.

```
≔¹ζ

```

Start looking for the next term with `1`.

```
Ｗ∨№υζ№υ±↔⁻ζη

```

While the term, or its negated absolute difference with the previous term, already exists in the predefined empty list, ...

```
≦⊕ζ

```

... increment the potential next term.

```
⊞υζ

```

Save the term to the predefined empty list.

```
⊞υ±↔⁻ζη

```

Save the negated absolute difference to the predefined empty list.

```
≔ζη

```

Save the term as the previous term.

```
⟦Ｉζ

```

Output the term on its own line.
> 2 votes

# Answer
# Ruby, ~~59~~ 56 bytes

```
a=0,p=1;loop{d=p p;d-=1while[]!=a&s=[p-d,-d*d];p,=a=s|a}

```

Try it online!

Stolen from pxeger Python answer, and then thanks pxeger again for -2 bytes.

# (previously) Ruby, 76 bytes

```
a,*r=1;loop{r<<a-a=p(1.step.find{|b|q=1;r.all?{|c|[b]&[q-=c,a-c,c+a]==[]}})}

```

Try it online!
> 2 votes

# Answer
# C++ (clang), <sup>~~149~~ \\$\cdots\\$ ~~132~~</sup> 131 bytes

```
#import<set>
void f(int&n){std::set<int>s;int i,p=n,x;for(n=1;p--;s.insert({n=i,-x*x}))for(i=0;s.count(++i)|s.count(-(x=n-i)*x););}

```

Try it online!

*Uses pxeger's idea from his Python answer so only one `std::set` is needed.*

Inputs an integer \\$n\\$.
Returns (through re-assignment of the input value) the \\$1\\$-indexed \\$n^{\text{th}}\\$ term of the Slater-Valez sequence.
> 2 votes

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


title: Let's start with a brainy quote

text:
# Question
Title: Let's start with a brainy quote
The challenge today is to write a program that outputs a known proverb, `Where there is a will, there is a way.`, that means if someone is determined to do something, he will find a way to accomplish it regardless of obstacles.

## Output

It has to be exactly the same, including the space bar and punctuation and excluding the newline at the end.

```
Where there is a will, there is a way.

```

You may not use `Where` `there` `is` `a` `will` or `way` anywhere in the source.

This is , shortest answer per language wins.

# Answer
# 05AB1E, 23 bytes

-2 thanks to @Kevin Cruijssen

```
…€Ç€ˆ€…“‚Ã ÿ€§, ÿƒƒ.“.ª

```

Try it online!

## Older version, 24 bytes

```
“‚Ã€Ç€ˆ€…€§,€Ç€ˆ€…ƒƒ.“.ª

```

-1 thanks to @petStorm

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 50 bytes

```
_=>`W\here${s=' t\here i\s \x61 w'}ill,${s}\x61y.`

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 38 bytes

```

Wht8ll,t0y.
t
 th 8s 0 w
h
here
T`d`l

```

Try it online! Explanation:

```

Wht8ll,t0y.

```

Insert `Wht1ll,t0y.`.

```
t
 th 8s 0 w

```

Expand to `Wh th 8s 0 w8ll, th 8s 0 w0y.`.

```
h
here

```

Expand to `Where there 8s 0 w8ll, there 8s 0 w0y.`.

```
T`d`l

```

Transliterate the digits to letters, so as to avoid having the words `is` or `a` in the code.
> 4 votes

# Answer
# C (gcc), ~~87 78 75 ...~~ 59 bytes

*-9 bytes thanks to @my pronoun is monicareinstate!*

*-3 bytes thanks to @Arnauld!*

*+1 byte for forgetting the period*

*-3 bytes thanks to @petStorm!*

*-3 bytes thanks to @ceilingcat!*

```
f(){printf("W\here%sill,%1$s\x61y."," t\here i\s \x61 w");}

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), 102 bytes

```
x←⎕UCS 97
⎕←('⎕'⎕R'')'Wher⎕e ther⎕e i⎕s ',x,' w⎕ill, t⎕here i⎕s ',x,' w⎕ay.'

```

Try it online!

# Explanation:

```
x←⎕UCS 97

```

Define x and store ASCII (⎕UCS) 97

```
⎕←

```

Print (not be confused with define ⎕)

```
('⎕'⎕R'')

```

⎕Replace '⎕' to empty string

```
'Wher⎕e ther⎕e i⎕s ',x,' w⎕ill, t⎕here i⎕s ',x,' w⎕ay.'

```

will be

```
'Where there is ',x,' will, there is ',x,' way.'

```

And

```
...',x,'...

```

Means Followed by "a" followed by other string

Or if you want everything in one code then

```
x←⎕UCS 97     x = "a"
⎕←('⎕'⎕R'')'Wher⎕e ther⎕e i⎕s ',x,' w⎕ill, t⎕here i⎕s ',x,' w⎕ay.'
⎕←                                                                        Print
                                                                 ' w⎕ay.' The string 'w⎕ay.'
                                                                ,          Join
                                                               x           "a"
                                                              ,            Join
                                      ' w⎕ill, t⎕here i⎕s '              The string ' w⎕ill, t⎕here i⎕s '
                                   ,x,                                     Join, "a", Join
            'Wher⎕e ther⎕e i⎕s '                                         The string 'Wher⎕e ther⎕e i⎕s '
  ('⎕'⎕R'')                                                               Replace '⎕' to Empty String

```
> 3 votes

# Answer
# Bash \+ Core utilities, ~~54~~ ~~52~~ ~~51~~ 50 bytes

```
echo WHERE "THERE IS A w"{ILL\,,Ay}|tr ?-V\\n _-v.

```

Try it online!

---

---

If we're allowed to print a newline at the end, as several other entries appear to be doing, then:

# Bash \+ Core utilities, 47 bytes

```
echo WHERE "THERE IS A w"{ILL\,,Ay.}|tr ?-V _-v

```

Try it online!
> 2 votes

# Answer
# Brain-Flak, 1170 bytes (by hand)

I wrote this one by averaging the ascii value of every character in the saying. I then pushed the value (87) to the stack. Then on stack 2 I pushed the ascii value of the next character - 87 then added 87. The numbers were all coded by this program

```
((((((()()()){}()){}){}())){}{})<>([(((()()()()()){}){}){}()])((((()()()()){}){}()){}<>({})<>)((()()()()()){}<>({})<>)((((()()()()){}){}){}<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)((()()()()()){}<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)((((()()()){}()){}){}<>({})<>)((((()()()){})){}{}<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)(((()()()){}()){}<>({})<>)(((((()()())){}{})){}{}<>({})<>)(((()()()){}()){}<>({})<>)(((()()()()){}){}()<>({})<>)((((()()()){}()){}){}()<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)([((((()()()){}()){})){}{}()]<>({})<>)((((()()()){}())){}{}<>({})<>)((((()()()){}())){}{}<>({})<>)((((()()()){})){}{}<>({})<>)((((()()()()){}){}){}<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)((()()()()()){}<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)((((()()()){}()){}){}<>({})<>)((((()()()){})){}{}<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)(((()()()){}()){}<>({})<>)(((((()()())){}{})){}{}<>({})<>)(((()()()){}()){}<>({})<>)(((()()()()){}){}()<>({})<>)((((()()()){}()){}){}()<>({})<>)([((()()()()()){}){({}[()])}{}]<>({})<>)((((()()()){}())()){}{}<>({})<>)(((()()()){}()){}<>({})<>)(((()()()()){}){}()<>({})<>)(<>{}<>)

```

Try it online!

# Brain-Flak, 640 bytes (using text generator found here)

This was produced using an answer to a challenge I maded a while back.

```
(((((<(((<(<((<<((((<(<((((((((<(<(((((()(()(()()()()()){}){}){})(()(((()()[]){}){}){})({}){})[(((()[]){}){}){}])(()(()()[]){}){})>(((([]){}){}){})()((()([])({}){}){}){})>(((()()[]){}){})()(()((()()()[]){}){}){})[()()[]])[()((([]){}){}){}])(()(()[]){})({}){})()()[])[()[]])()()())((()()()){}){})>((()[]){})((()()()){}){})>(((()[])({}){}){}))[()()()])(()(()()()){}){})[()(()([]){}){}])>(()((()()[]){}){})>(()()()()()()()()()[])()()(()()()[])({}){})[(()()()()()){}])>(()()()()()()[])()(()()()()()()()[]){})>((()([]){}){})[()((()()()){}){}])()()())((()()()){}){})>([])()(()[]){})()((()()()){}){})[()((()()()){}){}])()()())[()((()()()()){}){}])

```

Try it online!
> 2 votes

# Answer
# Erlang (escript), 65 bytes

```
z()->"W\here"++[" t\here i\x73 \x61 w"++X||X<-["ill,","\x61y."]].

```

Try it online!

# Erlang (escript), 65 bytes

This simply employs the almighty hard-coding.

```
z()->"W\here t\here i\x73 \x61 w\ill, t\here i\x73 \x61 w\x61y.".

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~95~~ ~~60~~ 59 bytes

```
exit("W""here%sill,%s\x61y."%((" t""here i""s \x61 w",)*2))

```

Try it online!

-35 bytes thanks to newbie and petStorm. -1 byte thanks to newbie and petStorm.

I completely forgot that % did string formatting.
> 1 votes

# Answer
# brainfuck, 241 bytes

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

```

Try it online!

Could use some golfing but it's getting late.
> 1 votes

# Answer
# V (vim), 44 bytes

```
iWh t wi²l, t w97y.Ót/&h i115 97
Óh/here

```

Try it online!

Hexdump:

```
00000000: 6957 6820 7420 7769 b26c 2c20 7420 7716  iWh t wi.l, t w.
00000010: 3937 792e 1bd3 742f 2668 2069 1631 3135  97y...t/&h i.115
00000020: 2016 3937 0dd3 682f 6865 7265             .97..h/here

```

I suspect this can be shorter, but I'm a bit rusty with V.

---

Yes it can be shorter!

# V (vim), 42 bytes

```
i.yaw 97 si ereht ,lliw 97 si e erehWæ

```

Try it online!

Hexdump:

```
00000000: 692e 7961 7720 1639 3720 7369 2065 7265  i.yaw .97 si ere
00000010: 6874 202c 6c6c 6977 2016 3937 2073 6920  ht ,lliw .97 si
00000020: 650e 2065 7265 6857 1be6                 e. erehW..

```

---

# V or vim, either one, 38 bytes

```
iwHERE THERES A WILL, THERES A WAY.V~

```

Try it online!
> 1 votes

# Answer
# Deadfish~, 341 bytes

```
{{i}d}dddc{i}{i}dddcdddc{i}iiic{d}dddc{{d}iii}ic{{i}dd}iiiic{d}ddcdddc{i}iiic{d}dddc{{d}iii}ic{{i}ddd}iiic{i}c{{d}ii}dddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}d}dddc{d}ddddciiicc{{d}iiii}ddddc{d}ddc{{i}dd}iiiic{d}ddcdddc{i}iiic{d}dddc{{d}iii}ic{{i}ddd}iiic{i}c{{d}ii}dddc{{i}dddd}iiiiic{{d}iiii}dddddc{{i}d}dddc{d}{d}ddc{i}{i}iiiic{{d}iii}dddddc

```

Try it online!

Not as bad as usual!
> 1 votes

# Answer
# Japt `-S`, 26 bytes

```
`ï,ÀnØi,ÌÀÎsn°y.`qn

```

Test it
> 1 votes

# Answer
# Jelly, 25 bytes

```
“ḅṫ!Ḃḃ0ʋŀɼYẆḊỵ2Ƭqɦ⁷-&Y£z»

```

Try it online!
> 0 votes

# Answer
# Stax, 13 bytes

```
üx♦r i0c@9lc¡

```

Run and debug it
> 0 votes

---
Tags: code-golf, kolmogorov-complexity, restricted-source
---


# Question
Title: Lowest integer with no common digits between given bases
## Challenge

Given a list of bases for positional numeral systems as input, output the lowest positive integer that when represented in those bases they have no common digits. The input list can be assumed to have two or more unique positive integers \>= 2.

## Example

For the input list of bases 2, 8, 10, 16 (binary, octal, decimal and hexadecimal) the lowest number is 58 (a printed result should be in decimal) since 58 is *111010*, *72*, *58* and *3A* which, as you can see, have no common digits between them. And no positive integer less than 58 have that property. Whereas 57 is *111001*, *71*, *57* and *39* for the same bases and here the digit 1 appears in more than one base, in base 2 and base 8, so 57 cannot be the result for 2,8,10,16. (Also digit 7 appears in two of them).

## Tests

```
2 8 10 16          → 58
2 8 10             → 27
2 8 16             → 43
16 17 18           → 160
16 17 18 19        → 224
16 17 18 19 21     → 225
34 35 36           → 646
4 44 444 4444      → 512
3 33 333 3333 4444 → 16702
555 777 999        → 1665
111 222 333        → 555

```

Some valid inputs have no solution, as pointed out by @Nitrodon, or none that can be found within reasonable time (one minute at TIO/Try It Online). I'll leave it up to each contributor to chose *if* or *how* they want to handle such inputs.

# Answer
# , 96 bytes

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

```
function(b){while(any(table(unlist(Map(function(y)unique(T%/%y^(0:log(T,y))%%y),b)))>1))T=T+1
T}

```

Try it online!

Similar approach to @Giuseppe's, but independently developed (and shorter).
> 6 votes

# Answer
# Husk, ~~12~~ 11 bytes

```
ḟȯS=uṁuMB⁰N

```

Try it online!

```
ḟ         N  # get ḟirst Natural number that satisfies:
       M ⁰   #  Map over the input:
        B    #   get lists of digits in these Bases;
     ṁ       #  now ṁap over each list & flatten result:
      u      #   get unique digits;
  S=         #  is this list equal to
    u        #   the unique elements of itSelf?

```

(Or alternative 11 byte program: `VS=umṁuṪ`BN`:)

```
       Ṫ`    # make a Ṫable of:
         B   #  the digits in the bases of the input
          N  #  for each of the infinite list of Natural numbers;
   m         # now map over each list of lists of digits
    ṁ        #  and ṁap over each list of digits, flattening the result,
     u       #   getting just the unique digits;
V            # finally, return the index of the first list that satisfies:
 S=          #  it's equal to
   u         #   the unique elements of itself?

```
> 4 votes

# Answer
# Pyth, 10 bytes

```
f{Is{MjLTQ

```

Test suite

##### Explanation:

```
f{Is{MjLTQ | Full code
-----------+-----------------------------------------------------------------------
f          | Find the first integer T (starting with 1) such that
      jLTQ |  the list of T converted to each base in the input as a list of digits
    {M     |  with each sublist deduplicated
   s       |  flattened
 {I        |  is invariant over deduplication

```
> 4 votes

# Answer
# Jelly, 10 bytes

```
1bQ€FQƑʋ1#

```

Try it online!

## How it works

```
1bQ€FQƑʋ1# - Main link. Takes a list of integers L on the left
       ʋ   - Group the previous 4 links into a dyad f(k, L):
 b         -   Convert k into each base in L
  Q€       -   For each list of digits, remove duplicates
    F      -   Flatten
     QƑ    -   Are all elements in this list unique?
1       1# - Count up from n = 1, 2, ... until the first n is found such that f(n, L) is truthy

```
> 3 votes

# Answer
# , 105 bytes

```
function(b){while(anyDuplicated(unlist(lapply(b,function(B,x)unique(x%/%B^(0:log(x,B))%%B),F<-F+1))))0
F}

```

Try it online!

~~Ugly and appears altogether too long.~~ Outgolfed by pajonk.
> 3 votes

# Answer
# Ruby, 54 bytes

```
->a{(1..).find{|i|!a.flat_map{i.digits(_1)|[]}.uniq!}}

```

Try it online! (with modifications to work on older versions)
> 3 votes

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

Expects a list of BigInts.

```
f=(a,n=2n)=>a.some(c=>a.some(b=>c-b&&(g=k=>k&&1n<<k%b|g(k/b))(n)&g(n,b=c)))?f(a,-~n):n

```

Try it online!

## How?

The helper function \\$g\\$ is used to build a bitmask of all digits appearing in the representation of \\$k\\$ in base \\$b\\$ :

```
g = k => k && 1n << k % b | g(k / b)

```

The main function \\$f\\$ recursively looks for the smallest \\$n\ge2\\$ for which there's no pair \\$(b,c)\\$ from the input array such that \\$b\neq c\\$ and the bitmaks generated by \\$g(n)\\$ in base \\$b\\$ and \\$c\\$ have at least one bit in common.

```
f = (a, n = 2n) =>
a.some(c =>
  a.some(b =>
    c - b &&
    g(n) & g(n, b = c)
  )
) ?
  f(a, -~n)
:
  n

```
> 2 votes

# Answer
# Charcoal, 28 bytes

```
≔²ηＷ⊙Ｅθ↨ηκ⊙θ∧⁻λν⁻κ⁻κ↨ημ≦⊕ηＩη

```

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

```
≔²η

```

Start searching at `2` since `1` will have the same digit in all bases.

```
Ｗ⊙Ｅθ↨ηκ⊙θ∧⁻λν⁻κ⁻κ↨ημ

```

Convert the search value to all bases, then perform set intersection between all of the sets, and repeat until they are all empty (except for self-intersection of course). (Strictly speaking each set intersection repeats one of the base conversions but that's code golf for you.)

```
≦⊕η

```

Increment the search value.

```
Ｉη

```

Output the final search value.
> 2 votes

# Answer
# Burlesque, 25 bytes

```
{bcqdgZ])NB\[U_}j1iar1jfe

```

Try it online!

```
{
 bc  # Box and cycle infinitely
 qdg # boxed Digits
 Z]  # Zip and evaluate (get list of digits of N in bases Input)
 )NB # Map Nub (remove duplicates within each set of digits)
 \[  # Concatenate all digits
 U_  # Digits are unique
}
j    # Reorder stack
1ia  # Insert bases at position 1 (as the second argument of zip)
r1   # Range [1..inf)
j    # Reorder stack
fe   # Find the first element (in infinite range) which fulfils requirements

```

A shorter variant would be where `bcqdgZ]` is simply replaced with the convert base function `B!`

# Burlesque, 19 bytes

```
{B!)NB\[U_}j+]r1jfe

```

Try it online!

Unfortunately, this fails for larger bases due to limitations on rendering the digits as strings
> 2 votes

# Answer
# Julia 1.0, 67 bytes

```
x\b=digits(x;base=b)
<(l,x=1)=((a=x.\l).∩a'.>[[]])l>l ? l<x+1 : x

```

Try it online!

#### Explanation:

* `digits` gives the digits of a number in a certain base, eg `digits(9,base=8) == [1,1]`
* we rename `digits` to `\` to allow broadcasting over the base: `10 .\ [3,4] == [[1,0,1], [2,2]]`
* `a .∩ a'` is the `intersect` function: every list of digits is compared to all the others, the output is a matrix of lists
* `(...) .> [[]]` checks which elements of the matrix are empty, the output is a bitmatrix, where `0` means the list is empty (no common digits). The diagonal will always have `1`s
* `(...)*l > l` will be true is there is any `1` outside of the diagonal
* `l<x+1` iterates recursively to the next number
> 2 votes

# Answer
**Apl 37 bytes**

```
a←⎕
1∘+⍣{{⍬≡∊⍵/⍨⍤1≠/¨⍳⍴⍵}∘.∩⍨⍺⊥⍣¯1⍨¨a}0

```

`1∘+⍣{...}0` adds 1 until the function returns true

`⍺⊥⍣¯1⍨¨a` converts ⍺ to bases of a(input array)

`∘.∩⍨` returns a matrix checking if numbers present in one base are present in another base

`⍵/⍨⍤1≠/¨⍳⍴⍵` removes the diagonal (as it is compared to itself)

`⍬≡∊` checks if every argument is empty
> 1 votes

# Answer
# Ruby, 80 bytes

```
f=->l,n=1{a=l.map(&g=->b,x=n{x<1?[]:[x%b]|g[b,x/b]}).flatten
a|a==a ?n:f[l,n+1]}

```

Try it online!

```
f=->l,n=1{..}    recursive lambda taking a list and trying next number until a solution is found
a=l.map          map bases to:
&g=->b,x=n{        recursive base digits(as array of integer numbers)
..%b]|g[b..        we use | to add only new digits
.flatten         finally we flatten to get all digits found
a|a==a           if by removing duplicates the array doesn't change we return the number

```
> 1 votes

# Answer
# 05AB1E, 11 bytes

```
∞.Δsв€Ù˜DÙQ

```

Try it online or verify all test cases.

**Explanation:**

```
∞.Δ          # Find the first positive integer which is truthy for:
   Iв        #  Convert it to each of the input-bases as list of lists
     €Ù      #  Uniquify each inner list
       ˜     #  Flatten it
        DÙQ  #  Check if all values are unique:
        D    #   Duplicate the list
         Ù   #   Uniquify the copy
          Q  #   Check if the two lists are still the same
             # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Python 3, 139 bytes

```
def e(n,b):
 while n:
  yield n%b;n//=b
def f(a):
 n=1
 while 1:
  if all(sum(q in e(n,b)for b in a)<2 for q in range(n+1)):return n
  n+=1

```

Try it online!

It's annoying for it not to be a single expression, but those seemed to end up longer.
> 1 votes

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


title: Expand a Rubik's Cube Commutator

text:
# Question
Title: Expand a Rubik's Cube Commutator
## Background

We will be using a 3x3 cube for this challenge.

Rubik's cubers have their own notation for movements on the cube:

* Each of the 6 faces has a clockwise turn notated with a single capital letter: `UDLRFB`. There are three additional letters `MES` denoting the three center slices.
* Counterclockwise rotations have a prime symbol appended: `U => U'`. The prime symbol for this challenge will be an ASCII apostrophe.
* A move rotated twice (either CW or CCW) has a `2` appended: `U => U2`.
* A move cannot be rotated twice and prime at the same time.
* Individual moves are separated by spaces: `U F D' B2 E M' S2`
* This challenge **will not** be using lowercase letters, which signify moving two layers at the same time.

Commutators, coming from group theory, is an operation of two elements \\$g,h\\$ such that \\$\left\[g,h\right\]=ghg^\prime h^\prime\\$, where \\$g^\prime\\$ is the inverse of \\$g\\$, e.g. `R U F' => F U' R'`

Rubik's cubers use a similar notation to describe commutators, used for swapping two or three pieces without disturbing any others.

Some examples of commutators:

```
[F U R, D B] = (F U R) (D B) | (R' U' F') (B' D')
[F' U2 R, D B2] = (F' U2 R) (D B2) | (R' U2 F) (B2 D') // note how B2 and U2 aren't primed

```

## The Challenge

Given a Rubik's cube commutator, expand the commutator to list out all the moves performed in it.

### Input

Input is a Rubik's cube commutator. Each side of the commutator are guaranteed to be at least 1 move long. Each part of the commutator can be a separate value. Each move in each commutator part can be separate values, as long as a CCW/prime or double move is within the value of the move (e.g. `[[R2], ...]` is valid, but `[[R,2], ...]` is not).

### Output

Output is a list of moves of the commutator. All moves must be capital letters in the set `UDLRFBMES`, with an optional prime `'` or double move `2`.

## Test Cases

```
[[F U R], [D B]] = F U R D B R' U' F' B' D'
[[F' U2 R], [D B2]] = F' U2 R D B2 R' U2 F B2 D'
[[U F' R2 F' R' F R F2 U' F R2], [F U2 F' U2 F2]] = U F' R2 F' R' F R F2 U' F R2 F U2 F' U2 F2 R2 F' U F2 R' F' R F R2 F U' F2 U2 F U2 F'
[[M2 E2 S2], [B2 D2 F2]] = M2 E2 S2 B2 D2 F2 S2 E2 M2 F2 D2 B2
[[F], [B]] = F B F' B'
[[U], [U]] = U U U' U'

```

### Additional Rules

# Answer
> 4 votes
# , ~~85~~ 82 bytes

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

```
function(g,h,`[`=gsub,`!`=function(s)rev("''"["","(\\D)$"["\\1'",s]]))c(g,h,!g,!h)

```

Try it online!

Input as two vectors of strings.

# Answer
> 2 votes
# 05AB1E, ~~14~~ 12 bytes

```
í''««˜ε¤ºK2£

```

Try it online or verify all test cases.

**Explanation:**

```
í             # Reverse each inner list of the (implicit) input-pair
 ''«          # Append a "'" to each inner-most string
    «         # Merge this modified list to the (implicit) input-list
     ˜        # Flatten it to a single list of strings
      ε       # Map over each string:
       ¤      #  Push its last character (without popping the string)
        º     #  'Double' it with a horizontal mirror
         K    #  Remove all those substrings from the string
              #  (which will only remove potential "''")
          2£  #  Only leave (up to) the first two characters of the string
              # (after which the result is output implicitly)

```

# Answer
> 1 votes
# BQN, 20 bytesSBCS

```
∾⊢∾(¬∘≠↓·⍷∾⟜"'")¨∘⌽¨

```

Run online!

`¬∘≠↓·⍷∾⟜"'"` is a function that inverts a single move:
`∾⟜"'"` Append a prime symbol
Deduplicate, This removes one `'` if the move already contained one.
`¬∘≠` Complement (1-) of the length of the move. -1 for length 2 moves, 0 for length 1.  Drop this many characters (from the end because the value is negative)

```
(⍷∾⟜"'")¨ "U"‿"U'"‿"U2"
# → U' U' U2'
¬∘≠¨ "U"‿"U'"‿"U2"
# → 0 ¯1 ¯1
(¬∘≠↓·⍷∾⟜"'")¨ "U"‿"U'"‿"U2"
# → U' U U2

```

`⌽¨` Reverse each list
`( ... )¨∘` Invert each move inside of each list
`⊢∾` Prepend the input to the result of that
Flatten by one level

# Answer
> 1 votes
# Ruby, 65 bytes

```
->a{[a,a.map{|x|x.reverse.map{|m|(m+?').sub("''","")[0,2]}}]*" "}

```

Try it online!

# Answer
> 1 votes
# Jelly,  ~~15~~  14 bytes

```
ḟ;ċ?”'ḣ2)Ṛ)⁸;Ẏ

```

A monadic Link accepting a list of lists (parts) of lists of characters (moves) which yields a list of lists of characters (moves).

**Try it online!**

### How?

```
ḟ;ċ?”'ḣ2)Ṛ)⁸;Ẏ - Link: list of lists of moves, A
          )    - for each Part of A:
        )      -   for each Move in that part:
    ”'         -     yield a quote character
   ?           -     if...
  ċ            -     ...condition: count     (X' -> 1, X -> 0, X2 -> 0)
ḟ              -     ...then: filter discard (X' -> X)
 ;             -     ...else: concatenate    (X -> X', X2 -> X2')
      ḣ2       -     head to index 2         (X -> X, X'-> X', X2' -> X2)
         Ṛ     -   reverse (this Part)
           ⁸   - A
            ;  - concatenate (the reversed, altered Part)
             Ẏ - tighten from a list of four parts to a list of all of the resulting moves

```

# Answer
> 1 votes
# Pyth, 16 bytes

```
s+Qm_m+-k\'*\'hI

```

Try it online!

```
s+Qm_m+-k\'*\'hIkdQ
                  Q   parsed input (Q is implicit)
   m                  take each sublist d:
     m           d      map each move k inside the sublist d to (d is implicit)
       -k\'               the move k without the prime symbol
      +                   and append
              hIk         1 if the move k contains only one symbol, 0 otherwise
                          (k is implicit, actually checks if taking
                           the first character is still the complete move,
                           alternatively !tk also works)
           *\'            repeats of the prime symbol
    _                   reverse the sublists
 +Q                   prepend the complete input
s                     and merge everything into a single list of moves

```

# Answer
> 0 votes
# Charcoal, 28 bytes

```
ＷＳ⊞υι⪫⁺υＥυ⪫Ｅ⮌⪪ι ⁺⁻λ'×'№αλ ¦

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated string of space-separated moves. Explanation:

```
ＷＳ⊞υι

```

Input the list of moves.

```
⪫⁺υＥυ⪫Ｅ⮌⪪ι ⁺⁻λ'×'№αλ ¦

```

Extend the list by taking the list of moves, splitting on spaces, reversing, inverting each move, and joining with spaces, then join the extended list with spaces and output the result. Moves are inverted by removing any `'` but then adding a `'` if the move was a single letter.

# Answer
> 0 votes
# Python 3, ~~113~~ ~~107~~ 83 bytes

```
lambda g,h:g+h+[r(r(m+"'","2'","2"),"''","")for m in g[::-1]+h[::-1]]
r=str.replace

```

Attempt This Online!

Input is two lists of strings. Naive string operations.

* -6 bytes from @pajonk: alias `str.replace` to `r`
* -24 bytes from @Kevin Cruijssen: output a list instead of a string

---
Tags: code-golf, string, abstract-algebra, rubiks-cube
---


title: Make every fixed list

text:
# Question
Title: Make every fixed list
We are to define the idea of a *fixed list* as follows:

* A **fixed list** is a list of fixed lists.

This definition is recursive so it's useful to look at some examples.

* The empty list `[]` is a fixed list.
* And list of empty lists is a fixed list. e.g. `[[],[],[]]`
* Any list of the above two is also a fixed list. e.g. `[[],[],[[],[],[]]]`

We can also think of these as "ragged lists" with no elements, just more lists.

## Task

In this challenge you will implement a function \\$g\\$ which takes as input an fixed list and as output produces a fixed list.

The only requirement is that there must be some fixed list \\$e\\$, such that you can produce every fixed list eventually by just applying \\$g\\$ enough times.

For those more inclined to formulae, here's that expressed as symbols:

\\$ \exists e : \mathrm{Fixt}, \forall x : \mathrm{Fixt} , \exists n : \mathbb{N}, g^n(e) = x \\$

You can implement any function you wish as long as it meets this requirement.

This is so answers will be scored in bytes with fewer bytes being the goal

# Answer
> 7 votes
# Python 2,  ~~168~~  164 bytes

-3 thanks to pxeger! (In-place list addtion `r=...;r+=[]` to `r=...+[]` \>.\<)

No doubt there is a far terser way, but this is quite a fun way...

```
j=''.join
n=int(j(`ord(c)%3`for c in`input()`if','<c),2)
while 1:
 try:n+=1;r=eval(j('[]'[i<'1']for i in bin(n)[2:]).replace('][','],['))+[]
 except:1
 else:exit(r)

```

A full program that accepts a fixed list as input and prints the next fixed list in an order defined by a binary encoding where `[` is a `1` and `]` is a `0` (ignoring  and `,`). The integer sequence of this ordering is listed on the OEIS under A057547.

**Try it online!** ...or see this slightly augmented code to see the the ordering.

### How?

First the input list is encoded as a binary number by reading left to right and treating encountered `[` as `1`s and `]` as `0`s.
Then this number is incremented and we form the decoded pattern of `[` and `]` , place `,` between any `][` and try to evaluate this as Python code.
If this evaluates as a list\* we exit and print that list representation to STDERR. If not, we increment our number and try again.

* There are also strings we form that are valid tuples, rather than lists, like `"[],[]" -> ([], [])` which we must ignore. This is handled by attempting to concatenate an empty list to the end inside the `try` block, which fails for tuples, and is a no-op for lists.

# Answer
> 6 votes
# Python, 170 bytes

```
d=lambda X:(1-(","in str(X)))*len(str(X))//2
e=[[]]
def f(X):L,*R=X or e;return X and(d(R)and(d(L)and(R and[d(L)*e]+(d(R)-2)*e or d(X)*e)or[f(L)]+~-d(R)*e)or[L]+f(R))or e
```

Attempt This Online!

#### Old Python, 200 bytes

```
d=lambda X:1+max([*map(d,X),-1])
s=lambda X:1+sum(map(s,X))
e=[[]]
def f(X):L,*R=X or e;return X and(~d(R)==-s(R)and(~d(L)==-s(L)and(R and[-~d(L)*e]+~-d(R)*e or-~d(X)*e)or[f(L)]+d(R)*e)or[L]+f(R))or e
```

Attempt This Online!

This enumerates based on an order which sorts first by number of nodes and then by "breadth-over-depth", i.e. for example \[\[\],\[\],\[\]\] \< \[\[\[\[\]\]\]\]. These are the first and last with 3 nodes (plus root). How does it look in between? We split into first element and of root list and root list minus first element and order first by number of nodes within either; the example has 0,2 (\[\[\],\[\],\[\]\] -\> \[\], \[\[\],\[\]\]) and 2,0 (\[\[\[\[\]\]\]\] -\> \[\[\[\]\]\], \[\]). Whatever conceptual gaps may be still there are resolved recursively, with lexicographic order at each split.

The implementation has to find the direct successor of its input. This is done using the same recursive splitting. To manage the "carry" in the lexicographic and outermost orderings we use helper functions d (depth) which returns the height of subtree under investigation but only if it is a pure tower and therefore has no successor, triggering carry to the next more significant subtree. Carry simply means the triggering subtree is reset to a flat list and the triggered subtree is incremented if possible. If not, the number of nodes is incrermented and the entire tree reset to flat.

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

```
I=([h,...t])=>h?h[0]?[D(h),...I(t)]:[I(t)]:[[]]
D=([h,...t])=>t[0]?[I(h),...D(t)]:h[0]?[[],...D(h)]:[]

```

Try it online!

`I` calculate succ, while `D` calculate prev. I hope it corrects...

---

# JavaScript (SpiderMonkey), 94 bytes

```
I=([h,...t])=>h?h[0]?[D(h),...I(t)]:[I(t)]:[[]]
D=(a,b=[],U=uneval)=>U(I(b))==U(a)?b:D(a,I(b))

```

Try it online!

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

Expects and returns a string.

```
f=(S,i=0)=>(F=(n=i++,o=r=[],s=[])=>n?n%2?F(n>>1,q=[],[...s,o],o.push(q)):s[0]?F(n>>1,s.pop(),s):F():JSON.stringify(r))()==S?F():f(S,i)

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 54 bytes

```
,

(^|]\[)(\[)*(?<4-2>])*(]*)$
[$3$#4$*1]
1
[]
]\[
],[

```

Try it online! Link includes test cases. Directly calculates the next string of equal numbers of `[`s and `]`s that satisfy the conditions that every prefix contains more `[`s than `]`s, ordered by length and then lexicographically. Explanation:

```
,

```

Remove all commas from the input.

```
(^|]\[)(\[)*(?<4-2>])*(]*)$

```

Match a run of `[`s followed by a run of `]`s at the end of the string. Capture starting either at the beginning of the string (for an input of that form) or just after a `][` pair. Subtract the count of `[`s from the count of `]`s. (This is done by matching a `]` for every `[` using a .NET balancing group, and then matching the leftover `]`s at the end.)

```
[$3$#4$*1]

```

Insert the leftover `]`s followed by a `[]` pair (marked with a `1` for now) for each `[`, the whole thing being wrapped in `[` and `]`, which make up for the `][` pair matched at the start, but also serve to extend the string if it was of the form `[` followed by `]`s.

```
1
[]

```

Expand the `1`s into `[]`s. (This can be written more succinctly in Retina 1 using `[$3$#4*$([])]`.)

```
]\[
],[

```

Restore all necessary commas.

# Answer
> 1 votes
# Ruby, 156 bytes

```
f=->l,x=1,q=p{r=0;w=x.digits(2).map{|d|r+=d+d-1};w.pop==0&&w.max<0&&(k=eval x.digits(2).map{|x|"]["[x]}.reverse.join.gsub("][","],[");q)?k:f[l,x+1,q||l==k]}

```

Try it online!

Work in progress.

# Answer
> 1 votes
# Charcoal, 57 bytes

```
≔⁻Ｓ,θ≔…⮌θ⌕⮌⁺][θ[]η⪫⪪⪫⟦…θ⁻⁻ＬθＬη²[×]⁻№η]№η[×[]№η[¦]⟧ω][¦],[

```

Try it online! Link is to verbose version of code. Note that Charcoal's default input auto-converts a fixed list from JSON input format, so you actually have to wrap the string in JSON for Charcoal to read it as a string. Explanation: Port of my Retina 0.8.2 answer.

```
≔⁻Ｓ,θ

```

Remove commas from the input.

```
≔…⮌θ⌕⮌⁺][θ[]η

```

Get the suffix of the string after the last `][` (or the whole string if there is no `][`).

```
⪫⪪⪫⟦…θ⁻⁻ＬθＬη²[×]⁻№η]№η[×[]№η[¦]⟧ω][¦],[

```

Concatenate the prefix of the string, a `[`, `]`s to make up the difference in numbers of `[`s and `]`s in the suffix, `[]`s for each `[` in the suffix, and a final `]`, then reinsert commas as necessary.

# Answer
> 0 votes
# 05AB1E, 20 bytes

```
¯[Dæ«DÙDÅΔIQ}>èDgĀ#\

```

Try it online!

All values

Uses the fact that the infinite list defined by repeatedly applying `x += powerset(x)` (+ is list concatenation) contains all fixed lists (it's easily proven with induction). It repeatedly does that, starting from the empty set, and each time looks at the element following the input in the current list uniquified. If the input isn't in the array it will look at the -1 + 1 element which is an empty set so it will continue. If the input is the last element due to modular indexing it'll also look at the first element and continue. Otherwise, there is a next element, and it will output it.

---
Tags: code-golf, open-ended-function, ragged-list
---


title: Universal Command Sequence

text:
# Question
Title: Universal Command Sequence
# Universal Command Sequence

## Definition

An \\$n\\$-maze is a \\$n\times n\\$ chessboard which has "walls" on some edges, and a "king" on the board that can move to the 4 adjacent cells, which cannot pass through any walls. Starting from any cell the king should be able to reach every cell on the board.

A command sequence is an array consisting of 4 distinct types of element (for example `[1,2,3,4,1,4,2,3,1,...]`). Each type of element means a direction of the movement of the king. A command sequence can be "applied to" a maze, if the king can traverse every cell on the board by following the command sequence. For example a command sequence `[up,right,down]` can be applied to a 2-maze that has no walls and the king is placed at the botton-left cell. If the king is going to pass through a wall or go outside the board, the command will be skipped.

## Challenge

For a given positive integer \\$n\\$, output a command sequence that can be applied to any \\$n\\$-maze. The existence of this sequence can be proved mathematically.See 1998 All-Russian Math Olympiad, Grade level 9, Day 1, Problem 4.

### Input

A positive integer `n`. You can assume that `n>1`.

### Output

An array consisting of 4 distince types of elements.

###

#### Python 3 validator

Try it online. Test your generated sequence here. Usage tips can be found in the footer.

---

This is . Shortest code wins.

# Answer
> 11 votes
# Pyth, 7 bytes

```
s^S4^5*

```

We could construct a universal sequence of length \\$2^{2n(n-1)} ⋅ n^2 ⋅ (2n^2 - 2) \< 5^{n^2}\\$. Start with the empty sequence; then for each of the at most \\$2^{2n(n-1)}\\$ mazes and \\$n^2\\$ possible starts, imagine following all the previously appended commands to get a new location, and append \\$2n^2 - 2\\$ more commands representing a complete traversal of that maze from that new location.

But, since we know we could construct it, we don’t have to actually do it. Instead, just concatenate all length \\$5^{n^2}\\$ sequences of \\$1, 2, 3, 4\\$. Since we just proved at least one of those sequences is universal, so is their concatenation.

---
Tags: code-golf, sequence, board-game
---