title: Reverse a Rubik's Cube Algorithm

text:
# Question
Title: Reverse a Rubik's Cube Algorithm
Whenever you make a move on a Rubik's Cube, there is a reverse move which undoes the first move. Because of this, every algorithm (set of moves) has a reverse algorithm which undoes the first algorithm.

The goal of this challenge is to find the reverse of a given algorithm.

# Specification:

The input consists of an array of individual moves. Each move is a string of length 1 or 2. Of course, you can use whatever input format makes the most sense in your language. Each move consists of the structure `X` or `X'` or `X2`, where `X` is an uppercase or lowercase letter.

To reverse `X`, simply replace it with `X'`. Likewise, `X'` becomes `X`. `X2` on the other hand does not get changed.

To create the output, reverse each move, and then reverse the array.

# Examples (strings separated by spaces):

`R` =\> `R'`

`D U'` =\> `U D'`

`S T A C K` =\> `K' C' A' T' S'`

`A2 B2` =\> `B2 A2`

# Scoring:

This is code-golf, so the fewest amount of bytes win. Standard loopholes are not allowed.

# Answer
# Python 2, ~~71~~ ~~57~~ ~~54~~ 53 bytes

*-15 bytes thanks to ovs! -3 bytes thanks to Rod.*

```
lambda l:[i.strip("'")+" '"[len(i):]for i in l[::-1]]

```

Try it online!

## String I/O, 70 bytes

```
lambda s:' '.join(i.strip("'")+"'"*(len(i)<2)for i in s.split()[::-1])

```

Try it online!
> 8 votes

# Answer
# Retina 0.8.2, ~~27~~ 26 bytes

```
\w
$&'
''

'2'
2
O$^`.'?2?

```

Try it online! Link includes test cases. Explanation: The first stage adds an apostrophe after every alphanumeric. This results in double apostrophes (with or without an inclusive 2) which need to be removed. The final stage reverses the moves.
> 7 votes

# Answer
# , ~~13~~ 10 bytes

```
æGÇä/á'Ó''

```

Try it online!

3 bytes saved thanks to @nmjmcman pointing out my favorite feature. Explanation:

```
æG          " Revere the order of every line
  Ç         " On every line not containing...
   ä/       " a digit:
     á'     "   Append an '
       Ó    "   Remove every instance on this line
        ''  "     Of two single quotes

```
> 7 votes

# Answer
# JavaScript (ES6), 45 bytes

```
s=>s.map(([a,b])=>b?+b?a+b:a:a+"'").reverse()

```

Shortest solution is to take Array IO. Simple and appropriate use of argument destruction.

String output is +8 bytes for `.join` ``.

## String input, Array output: 69 bytes

```
(s,k=[])=>s.replace(/\S\S?/g,([a,b])=>k.unshift(b?+b?a+b:a:a+"'"))&&k

```

```
f=

(s,k=[])=>s.replace(/\S\S?/g,([a,b])=>k.unshift(b?+b?a+b:a:a+"'"))&&k

;

console.log(["R", "D U'", "S T A C K", "A2 B2"].map(e => `${e} => ${f(e)}`));
```

```
<textarea oninput="out.value=(f(this.value)||[]).join` `" placeholder="input here"></textarea>
<textarea id="out" readonly></textarea>
```
> 5 votes

# Answer
# JavaScript (ES6), 46 bytes

Takes input as an array of moves.

```
a=>a.map(m=>m[1]?+m[1]?m:m[0]:m+"'").reverse()

```

---

## Test it

Enter a comma separated list of moves.

```
o.innerText=(f=
a=>a.map(m=>m[1]?+m[1]?m:m[0]:m+"'").reverse()
)((i.value="S,T,A,C,K").split`,`);oninput=_=>o.innerText=f(i.value.split`,`)
```

```
<input id=i><pre id=o>
```

---

## Explanation

```
a=>

```

Anonymous function taking the array of moves as an argument via parameter `a`.

```
a.map(m=>                       )

```

Map over the array, passing each string through a function, where `m` is the current string.

```
 m[1]?

```

Check if the string contains a second second character (`"'"` or `"2"`).

```
+m[1]?

```

If it does try to cast that character string to an integer. If the string is `"2"`, it becomes `2`, which is truthy. If the string is `"'"`, it becomes `NaN`, which is falsey.

```
m

```

If the previous test is truthy, simply return `m`.

```
:m[0]

```

Otherwise, return the first character of `m`.

```
:m+"'"

```

If the string does not contain a second character then return `m` appended with a `'`.

```
.reverse()

```

Reverse the modified array.
> 4 votes

# Answer
# Jelly, 10 bytes

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

```

A monadic link taking an returning a list of lists of characters (an "array" of "strings").

**Try it online!** (The footer avoids smashing the output, displaying the list split with spaces.)

### How?

```
ḟ;ċ?”'ḣ2)Ṛ - Link: list of lists of characters             e.g. ["F'", "D2" , "R"]
        )  - for each turn instruction:
    ”'     -   literal "'" character
   ?       -   if:
  ċ        -     count (number of "'" in the instruction) i.e.:  1   , 0    , 0
ḟ          -   then: filter out                                  "F"
 ;         -   else: concatenate                                       "D2'", "R'"
      ḣ2   -   head to index 2                                   "F" , "D2" , "R'"
         Ṛ - reverse                                            ["R'", "D2" , "F"]

```
> 4 votes

# Answer
# Python 3, ~~91~~ ~~89~~ ~~72~~ ~~70~~ ~~69~~ 65 bytes

```
lambda s:[i[0]+(len(i)-2and"'"or"2"*("2"==i[1]))for i in s[::-1]]

```

Try it online! (With testcases)

Apparantly you don't need to take input and output as strings, so a 69 byte solution is possible
> 2 votes

# Answer
# Python,  ~~51~~  48 bytes

```
lambda a:[(v+"'")[:2-("'"in v)]for v in a[::-1]]

```

An unnamed function taking and returning lists of strings.

**Try it online!**

Reverses the input list with `a[::-1]`; appends a `'` to *every* entry with `v+"'"`; heads each one to 1 or 2 characters depending on whether the original had a `'` in or not with `[:2-("'"in v)]`.
> 2 votes

# Answer
# Haskell, 43 bytes

```
map f.reverse
f[x]=x:"'"
f[x,c]=x:[c|c>'1']

```

Try it online! Declares an anonymous function `map f.reverse`. Bind to `g` and use as `g["S","T","A","C","K"]`.
> 1 votes

# Answer
# PHP, 81 bytes

```
<?foreach(array_reverse($_GET)as$v)$r[]=$v[1]?$v[1]<2?$v[0]:$v:"$v'";print_r($r);

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 13 bytes

```
RεÐ1èQ''si«ëK

```

Try it online!

### Explanation

```
RεÐ1èQ''si«ëK
R             # Reverse input array
 ε            # Map over each element...
  Ð1èQ         # Is the second char in the element the first one? (Uses the fact that in python indexing loops)
      ''       # Push '
        s      # Swap top items of stack
         i     # If the question above is true...
          «     # Concatenate
           ë   # Else
            K   # Push element without '

```
> 1 votes

# Answer
# J, 25 bytes

J handles this one well, other than the unfortunate escape sequence needed to represent a single quote:

```
|.,&''''`}:@.(''''={:)&.>

```

We need to represent the list using boxed data, since it's a mix of one and two character items, hence:

* `&.>` \- "under unbox", which means unbox each element, perform the operation that follows (ie, the symbols explained below) and then rebox when done
* `(''''={:)` "if the 2nd character is a single quote"....
* `@.` (J's agenda verb, a kind of generalized ternary statement, or a case statement) "then perform the 2nd item on the agenda list, otherwise perform the first"
* `}:` (the 2nd item on the agenda list), "remove the last character", ie, the single quote
* \` (J's tie verb) You can think of this as the agenda item separator
* `,&''''` (first item on agenda list) "add a single quote to the end"
* `|.` "reverse"

Try it online!
> 1 votes

# Answer
# 05AB1E, 10 bytes

```
Rε''«¤ºK2£

```

I/O as a list of moves.

This is a subset of my answer for the *Expand a Rubik's Cube Commutator* challenge.

Try it online or verify all test cases.

**Explanation:**

```
R           # Reverse the (implicit) input-list
 ε          # Map over its strings:
  ''«       #  Append a "'" to each string
     ¤      #  Push the last character (the "'") without popping the string
      º     #  Mirror it to "''"
       K    #  Remove all "''" from the string
        2£  #  Only keep the first two characters of the string
            # (after which the result is output implicitly)

```
> 1 votes

# Answer
# , 51 bytes

```
function(u)sub("((2)|')'","\\2",paste0(rev(u),"'"))

```

Try it online!
> 0 votes

# Answer
# Java 8, ~~141~~ ~~128~~ ~~126~~ 115 bytes

```
a->(new StringBuffer(a).reverse()+"").replaceAll(".","'$0").replace("'''","").replaceAll("('(2)'|('))(.)","$4$2$3")

```

Takes input as single `String` without spaces (i.e. `RUR'URU2R'U`).

Try it online.

**Explanation:**

```
a->                      // Method with String as both parameter and return-type
  (new StringBuffer(a).reverse()+"")
                         //1  Reverse the input
  .replaceAll(".","'$0") //2  Prepend an apostrophe before each character
  .replace("'''","")     //3  Remove all occurrences of three adjacent apostrophes
  .replaceAll("('(2)'|('))(.)","$4$2$3")
                         //4  Replace '2'C with C2 OR 'C with C' (C is any character)

```

Example of the result after each step, with `RUR'URU2R'U` as given input:

1. `U'R2URU'RUR`
2. `'U'''R'2'U'R'U'''R'U'R`
3. `'UR'2'U'R'UR'U'R`
4. `U'RU2R'U'RU'R'`
> 0 votes

# Answer
# Ruby, 44 bytes

```
->a{a.reverse.map{|i|i[1]?i.tr(?',''):i+?'}}

```

Try it online!
> 0 votes

# Answer
# Scala, 47 bytes

Golfed version. Try it online!

```
_.reverse.map(i=>if(i.last=='\'')i else i+" '")

```

Ungolfed version. Try it online!

```
object Main {
  def f(l: List[String]): List[String] = {
    l.reverse.map(i => if (i.last == '\'') i else i + " '")
  }

  val tests: List[List[String]] = List(
    List("R"),
    List("D", "U'"),
    List("S", "T", "A", "C", "K"),
    List("A2", "B2")
  )

  def main(args: Array[String]): Unit = {
    tests.foreach(test => println(f(test)))
  }
}

```
> 0 votes

---
Tags: code-golf, string, array, rubiks-cube
---


title: Golfed fixed point combinator

text:
# Question
Title: Golfed fixed point combinator
Write a fixed point combinator in as few characters as possible, in the language of your choice.

* free form (*i.e.*, whatever's shortest): whole program, actual function, code snippet
* you may not use your standard library's if it has one
* you may however extract it from other high-level functions it you'd rather do that than construct it from the bases

Please include a recursive factorial or Fibonacci that uses it as a demo.

In this question, self-reference is acceptable, the aim is solely to remove it from the recursive function it will apply to.

# Answer
## Haskell: 10 characters

```
y f=f$y f

```

Example of use to create recursive definitions of factorial or nth-Fibonacci:

```
> map ( y(\f n->if n <= 1 then 1 else n*f(n-1)) ) [1..10]
[1,2,6,24,120,720,5040,40320,362880,3628800]

> map ( y(\f n->if n <= 1 then 1 else f(n-1)+f(n-2)) ) [0..10]
[1,1,2,3,5,8,13,21,34,55,89]

```

Though, a more common way to use `y` would be to generate these sequences directly, rather than as functions:

```
> take 10 $ y(\p->1:zipWith (*) [2..] p)
[1,2,6,24,120,720,5040,40320,362880,3628800]

> take 11 $ y(\f->1:1:zipWith (+) f (tail f))
[1,1,2,3,5,8,13,21,34,55,89]

```

Of course, with Haskell, this is a bit like shooting fish in a barrel! The `Data.Function` library has this function, called `fix`, though implemented somewhat more verbosely.
> 15 votes

# Answer
## Perl, 37

```
sub f{my$s=$_[0];sub{$s->(f($s),@_)}}

```

Factorial demonstration:

```
sub fact {
  my ($r, $n) = @_;
  return 1 if $n < 2;
  return $n * $r->($n-1);
}
print "Factorial $_ is ", f(\&fact)->($_), "\n" for 0..10;

```

Fibonacci demonstration:

```
sub fib {
  my ($r, $n) = @_;
  return 1 if $n < 2;
  return $r->($n-1) + $r->($n-2);
}
print "Fibonacci number $_ is ", f(\&fib)->($_), "\n" for 0..10;

```
> 4 votes

# Answer
## GNU C - 89 chars

```
#define fix(f,z)({typeof(f)__f=(f);typeof(__f(0,z))x(typeof(z)n){return __f(x,n);}x(z);})

```

Example:

```
#define lambda2(arg1, arg2, expr) ({arg1;arg2;typeof(expr)__f(arg1,arg2){return(expr);};__f;})

int main(void)
{
    /* 3628800 */
    printf("%ld\n", fix(lambda2(
        long factorial(int n), int n,
            n < 2 ? 1 : n * factorial(n-1)
        ), 10));

    /* 89 */
    printf("%ld\n", fix(lambda2(
        long fibonacci(int n), int n,
            n < 2 ? 1 : fibonacci(n-1) + fibonacci(n-2)
        ), 10));

    return 0;
}

```
> 3 votes

# Answer
# k2, 12 char

The obvious self-referential implementation is the shortest. This is a sign of good language design. Unfortunately, K isn't lazy, so we can only manage call-by-value.

```
Y:{x[Y[x]]y}

```

This definition should also work in k4 and q without trouble, though I assume k2 for the examples below.

```
  Y:{x[Y[x]]y}
  fac: {[f;arg] :[arg>0; arg*f[arg-1]; 1]}
  Y[fac] 5
120
  fib: {[f;arg] :[arg>1; f[arg-1] + f[arg-2]; arg]}
  Y[fib]' !10
0 1 1 2 3 5 8 13 21 34

```

A more modest 18 characters lets us exactly transcribe `(λx. x x) (λxyz. y (x x y) z)` into K.

```
{x[x]}{y[x[x;y]]z}

```

Maybe someday (k7?), this could look like `Y:{x Y x}`.
> 2 votes

# Answer
# Python 3, 30 Bytes

```
Y=lambda f:lambda a:f(Y(f))(a)

```

Demo :

```
Y=lambda f:lambda a:f(Y(f))(a)
quicksort = Y(
lambda f:
    lambda x: (
        f([item for item in x if item < x[0]])
        + [y for y in x if x[0] == y]
        + f([item for item in x if item > x[0]])
    ) if x
    else []
)
print(quicksort([1, 3, 5, 4, 1, 3, 2]))

```

Credits : https://gist.github.com/WoLpH/17552c9508753044e44f
> 0 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
v_//Z@g_=Z@g~g~v           (* golfed   *)
Z[g_][v_] = g[Z[g],v]      (* ungolfed *)

```

Try it online!

This definition of the *Z* combinator uses the Wolfram Language's pattern-matching to make sure that any expression of the form `Z[g]` remains unevaluated as long as the second argument is missing; only the two-argument form `Z[g][v]` matches the above pattern and is replaced by `g[Z[g],v]`, which in turn contains the single-argument form `Z[g]` that remains unevaluated until later. This distinction between an inert single-argument form `Z[g]` and an automatically-substituted two-argument form `Z[g][v]` allows for a controlled recursion process that remains tied to the application of the second argument.

## examples

### factorial

```
fac[r_, n_] = If[n==0, 1, n*r[n-1]];
Table[Z[fac][i], {i, 0, 10}]
(*    {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}    *)

```

Same with an anonymous function:

```
Table[Z[If[#2==0, 1, #2*#1[#2-1]]&][i], {i, 0, 10}]
(*    {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}    *)

```

Same but using Mathematica's built-in self-reference operator `#0`: we don't actually need a combinator to define recursive anonymous functions,

```
Table[If[#1==0, 1, #1*#0[#1-1]]&[i], {i, 0, 10}]
(*    {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800}    *)

```

### Fibonacci sequence

```
fib[r_, n_] = If[n<=1, n, r[n-2]+r[n-1]];
Table[Z[fib][i], {i, 0, 10}]
(*    {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55}    *)

```
> 0 votes

# Answer
# APL (Dyalog Unicode), 9 bytes

```
{∇(⍎⍺⍺)⍵}

```

Try it online!

An operator whose left operand is a string representing the function to be combinatorified and whose right argument is passed to the function once it is combinatorised. I *think* it's okay to pass the function as a string, but if not, I will delete this answer.

Explanation

```
{∇(⍎⍺⍺)⍵}
 ∇(⍎⍺⍺)     ⍝ Equivalent to f ( Fix f )
     ⍺⍺      ⍝ Left operand
   ⍎        ⍝ Evaluate to get monadic operator
 ∇           ⍝ Self-reference (Fix f). Pass as operand to f (or ⍎⍺⍺)
        ⍵    ⍝ Apply the derived function to the right argument ⍵

```
> 0 votes

# Answer
# Java 8, 104 bytes

```
interface C{int t(int n);}interface F{C f();}interface P{C c(F f);static F g(P p){return()->p.c(g(p));}}

```

Based on *@user*'s Java answer for the related *Implement Fix2 combinator* challenge.

**Explanation:**

```
interface C{       // Completed Function interface
  int t(int n);}   //  Using a function that transforms a given integer

interface F{       // Function interface
  C f();}          //  A wrapper to pass the 'Completed Function' as function

interface P{       // Program interface
  C c(F f);        //  Which takes a 'Function' as argument, and returns a 'Completed Function'

  static F g(P p){ //  Recursive function that accepts a 'Program' as argument, and returns a 'Function'
    return()->     //   Return a new function, which wraps:
      p.c(         //    A completed call to its own 'Program' interface
       g(          //     Using a recursive call to its own function
         p));}}    //     with the given 'Program' as argument

```

The method to call is `P::g`, which takes `P` as argument and returns `F`. To obtain a completed function `C` from an `F`, we can call `F::f` on it. `P` represents the function to be fixed, and its method `c` takes `F` as argument to prevent immediate evaluation, returning a `C` that represents a complete function to transform a given integer `n` with `C`'s `t(n)`.

**Example Fibonacci implementation:**

```
P fix = fibonacci -> n -> n>1? fibonacci.f().t(n-1)+fibonacci.f().t(n-2) : 1;
C func = P.g(fix).f();
int result = func.t(input);

```

Try it online.
> 0 votes

---
Tags: code-golf, functional-programming
---


title: American odds to probabilities

text:
# Question
Title: American odds to probabilities
American odds (aka *moneyline odds*) are numbers like \\$+150\\$ or \\$-400\\$ used to express how much a winning bet would pay out. Convert odds to a fair win probability like this:

* Positive odds \\$+n\\$ with \\$n \geq 100\\$ correspond to $$p=\frac{100}{100+n},$$ producing a probability with \\$0 \
 100\\$ correspond to $$p=\frac{n}{100+n},$$ producing a probability with \\$1/2 \< p \< 1\\$.

Note that in both formulas above, \\$n\\$ is the absolute value of the input. Inputs with absolute value under \\$100\\$ are invalid, and so is \\$-100\\$ (since \\$+100\\$ is used for \\$p=1/2\\$), so you don't need to handle these.

The input will be a whole number. If you take it as a string, expecting a leading `+` for positive values is optional.

Your output can be a decimal to some reasonable precision or a reduced fraction.

**Test cases**

```
+1500   0.0625
 +256   0.2808988764044944
 +100   0.5
 -200   0.6666666666666666
 -300   0.75

```

# Answer
# Python, 25 bytes

```
lambda x:x/(~99-abs(x))%1

```

Attempt This Online!

#### Thanks @Jonathan Allan for -1.

### Original Python, 26 bytes

```
lambda x:-x/(100+abs(x))%1

```

Attempt This Online!

Test bed from @MTN via @AnttiP.

### How?

Based on the observation

\\$-n \equiv 100 \mod 100+n\\$
> 26 votes

# Answer
# Jelly, 7 bytes

```
,³ṢAÄ÷/

```

Try it online!

Function I/O only because lmao `³`. (Replace with `ȷ2` if that's too borderline.)

```
                                  n ≥ 100         | n < -100
,³         Pair n with 100.       [n, 100]        | [n, 100]
  Ṣ        Sort.                  [100, n]        | [n, 100]
   A       Map absolute value.    [100, n]        | [-n, 100]
    Ä      Cumsum.                [100, 100 + n]  | [-n, 100 - n]
     ÷/    Divide.                100 / (100 + n) | -n / (100 - n)

```
> 12 votes

# Answer
# , 24 bytes

```
\(n)(-n/(100+abs(n)))%%1

```

Attempt This Online!

Port of loopy walt's Python answer.
> 7 votes

# Answer
# Python, 33 bytes

```
lambda n:1/[1+n/100,1-100/n][n<0]

```

Attempt This Online!

Testing code from MTN's answer
> 6 votes

# Answer
# Ruby, ~~29~~ 26 bytes

```
->n{(n>0?100:n=-n)/n+=1e2}

```

Attempt This Online!

Saved 3 bytes thanks to @MTN and @G B.

Ports Luis felipe De jesus Munoz’s JavaScript submission.

# Ruby, ~~34~~ 28 bytes

```
->n{[-n,o=1e2].max/o+=n.abs}

```

Attempt This Online!

Thanks to @G B for saving 8 bytes!

I'm still learning Ruby, so this answer might be improvable, although @G B has improved it quite a bit already.
> 5 votes

# Answer
# Vyxal, 55 bitsv2, 6.875 bytes

```
₁"sȧ¦ƒ/

```

Try it Online!

Port of Jelly.
> 4 votes

# Answer
# Vyxal, 50 bitsv2, 6.25 bytes

```
ȧ₁+/N1%

```

Try it Online!

Port of loopy walt's Python. It's longer in Jelly due to the argument order for division, but I intuited it would at least tie in Vyxal SBCS bytes, and it turns out it also Vyncodes marginally better.

```
 ₁+        Add 100 to
ȧ          the absolute value of n.
   /       Divide n by that,
    N      negate the result,
     1%    and mod 1.

```
> 4 votes

# Answer
# Pip, 12 bytes

```
-a/(h+ABa)%1

```

Attempt This Online! | *Based on @loopy\_walt's Python answer*

Trivial implementation, 16 bytes.

```
(@YABSNgAEh)/$+y

```

Attempt This Online!
> 4 votes

# Answer
# JavaScript (Babel Node), 25 bytes

```
_=>(_>0?100:_=-_)/(100+_)

```

Try it online!
> 3 votes

# Answer
# Arturo, 34 bytes

```
$->n[abs//(n<0)?->n[100]100+abs n]

```

Try it!
> 3 votes

# Answer
# Excel, 30 bytes

```
=1/(1+IF(A1<0,-100/A1,A1/100))

```

Input in cell `A1`.
> 3 votes

# Answer
# , 31 bytes

```
\(n)"if"(n<0,n<--n,100)/(100+n)

```

Attempt This Online!

# , 31 bytes

```
\(n,z=sign(n))1/(1+(n/100)^z*z)

```

Attempt This Online!

I feel like *one* of these can be golfed down.
> 3 votes

# Answer
# , 9 bytes

```
1|-%100+|

```

-5 bytes by porting loopy walt's answer!

Attempt This Online!

## , original answer, 14 bytes

```
(100>.-)%100+|

```

Attempt This Online!

* `100>.-` The larger of the negative of the input and 100
* `%` Divided by...
* `100+|` 100 plus the absolute value of the input

My attempts to avoid repeating 100 led to longer solutions.
> 3 votes

# Answer
# Forth (gforth), ~~51~~ 42 bytes

```
: f dup 100 min abs s>f abs 100 + s>f f/ ;

```

Try it online!

## Explanation

Originally, I used a conditional statement, but those use a lot of characters in gforth. I eventually realized that the goal is mostly just to determine what goes on top of the fraction, 100 or n. Since n will always be greater than 100 or less than -100, we can use min to get the value we want (if negative, n will always be less than 100, if positive, 100 will always be smaller).

## Code Explanation

```
: f         \ Begin word definition
  dup       \ duplicate n on the top of the stack
  100 min   \ take the smaller of n and 100
  abs s>f   \ send the absolute value to the floating point stack
  abs 100 + \ add 100 to the absolute value of n
  s>f       \ move the result to the floating point stack
  f/        \ divide the top two floating point stack values
;           \ end word definition

```
> 3 votes

# Answer
# Julia, ~~29~~ 24 bytes

```
!n=mod(n/(~99-abs(n)),1)

```

Attempt This Online!

A port of loopy walt's solution.

`mod` is used (suggested by MarcMush), since Julia's default modulo `%` doesn't match Python's convention for negative numbers; using `rem` with rounding mode `RoundDown` would also work.
> 3 votes

# Answer
# Python, 37 bytes

```
lambda n:(100,x:=abs(n))[n<0]/(100+x)

```

Attempt This Online!
> 2 votes

# Answer
# Octave / MATLAB, 30 bytes

```
@(n)min(100,n)/(n+100*sign(n))

```

Try it online! Or verify all test cases.
> 2 votes

# Answer
# Charcoal, 18 bytes

```
ＮθＩ∕↔⌊⟦¹⁰⁰θ⟧⁺¹⁰⁰↔θ

```

Try it online! Link is to verbose version of code. Explanation: Turns out to be a port of @noodleman's original Ruby answer.

```
Ｎθ                  Input `n` as a number
       ¹⁰⁰          Literal integer `100`
          θ         Input `n`
      ⟦    ⟧        Make into list
     ⌊              Take the minimum
    ↔               Absolute value
   ∕                Divided by
             ¹⁰⁰    Literal integer `100`
            ⁺       Plus
                 θ  Input `n`
                ↔   Absolute value
  Ｉ                 Cast to string
                    Implicitly print

```

A slightly less accurate version is 16 bytes:

```
ＮθＩ∕χ⁺χ⌈⟦∕θχ±∕φθ

```

Try it online! Link is to verbose version of code. Explanation: "Illegal" positive odds and negative odds can be converted into "legal" odds by dividing into `-10000`, but we can also use this to convert all odds into positive odds and then use a modified version of the formula for those odds, the modification being `10/(10+n/10)`, since this is golfier in Charcoal.

```
Ｎθ                  First input as a number
    χ               Predefined variable `10`
   ∕                Divided by
      χ             Predefined variable `10`
     ⁺              Plus
          θ         Input odds
         ∕          Divided by
           χ        Predefined variable `10`
              φ     Predefined variable `1000`
             ∕      Divided by
               θ    Input odds
            ±       Negated
        ⟦           Make into list
       ⌈            Take the maximum
  Ｉ                 Cast to string
                    Implicitly print

```
> 2 votes

# Answer
# 05AB1E (legacy), 7 bytes

```
Äт+/(1%

```

Port of *@loopyWalt*'s Python answer, so make sure to upvote that answer as well!

Try it online or verify all test cases.

A port of *@UnrelatedString*'s Jelly answer (in the new 05AB1E version) would be a byte longer:

```
т‚{ÄηO`/

```

Try it online or verify all test cases.

**Explanation:**

```
         #  Example inputs: +256               -256

```

Uses the legacy version of 05AB1E built in Python 3 for `1%` to work. In the new version built in Elixir, it'll give incorrect results.

```
Ä        # Get the absolute value of the (implicit) input-integer
         #                  256                256
 т+      # Add 100 to it
         #                  356                356
   /     # Divide the (implicit) input by this abs(input)+100
         #                  0.719...           -0.719...
    (    # Negate it
         #                  -0.719...          0.719...
     1%  # (Python-style) modulo-1
         #                  0.280...           0.719...
         # (after which it's output implicitly as result)

```

Uses the new version of 05AB1E builtin Elixir for `{` to work. In the legacy version, it'll always keep the input first because it's seen as \[string,integer\] instead of \[integer,integer\].

```
т‚       # Pair the (implicit) input-integer with 100
         #                  [256,100]          [-256,100]
  {      # Sort this pair
         #                  [100,256]          [-256,100]
   Ä     # Get the absolute value of each
         #                  [100,256]          [256,100]
    η    # Get the prefixes of this pair
         #                  [[100],[100,256]]  [[256],[256,100]]
     O   # Sum each inner list
         #                  [100,356]          [256,356]
      `  # Pop and push both values separated to the stack
       / # Divide them from one another
         #                  0.280...           0.719...
         # (after which it's output implicitly as result)

```
> 2 votes

# Answer
# Uiua, 10 bytes

```
◿1`÷+100⌵.

```

Try it online!

Port of loopy walt's Python answer. If scored in UTF-8, beats the solution I wanted to post even harder because ``` autoformats to `¯` to save a single byte.

The solution I wanted to post:

# Uiua, 11 bytes

```
÷+,⊙⌵⊃↥↧100

```

Try it online!

Indirect port of my Jelly solution. A direct port comes out considerably longer due to scan/reduce operating right to left and it taking 3 characters to sort an array, but `⊃↥↧ fork max min` sorts the top two values on the stack right in place on the stack, taking arrays out of the picture entirely... unfortunately also needing an extra `⊙ dip` (or some restructuring and a `: flip`) to abs afterwards.
> 2 votes

# Answer
# Google Sheets, 25 bytes

`=mod(-A1/(abs(A1)+100),1)`

Put the input in cell `A1` and the formula in `B1`.

Uses `mod()` like the Python answer.
> 1 votes

# Answer
# Ruby, 21 bytes

Direct port of loopy walt's Python answer, for completeness.

```
->n{n/(-1e2-n.abs)%1}

```

Attempt This Online!
> 1 votes

# Answer
# C (GCC), ~~49~~ ~~36~~ ~~34~~ 33 bytes

```
f(n,r){r=(n?100:(n=-n))/(1e2+n);}

```

Saved a byte by negating `n` within the ternary and eliminating the `abs` call.

Attempt This Online!

---

```
f(n,r){r=(n?100:-n)/(1e2+abs(n));}

```

Changed `100.0` to `1e2` to save 2 bytes, since want 100 as float.

Attempt This Online!

---

```
f(n,r){r=(n?100:-n)/(100.0+abs(n));}

```

Changed the function name to a single char :P, used just `n` instead of `n>0` in the ternary to check for positivity of the number `n`, used the out param `r` to store the return value.

Attempt This Online!

---

```
float golf(n){return(n>0?100:-n)/(100.0+abs(n));}

```

Attempt This Online!

This is my low effort attempt at golfing this problem using C. Need help!
> 1 votes

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


title: Most Common Multiple

text:
# Question
Title: Most Common Multiple
*Not to be confused with Least Common Multiple.*

Given a list of positive integers with more than one element, return the most common product of two elements in the array.

For example, the MCM of the list `[2,3,4,5,6]` is `12`, as a table of products is:

```
    2  3  4  5  6
  ---------------
2 | #  6  8  10 12
3 | #  #  12 15 18
4 | #  #  #  20 24
5 | #  #  #  #  30
6 | #  #  #  #  #

```

*Thanks DJMcMayhem for the table*

As `12` appears the most times (two times as `2*6` and `3*4`). Note that we aren't including the product of an element and itself, so `2*2` or `4*4` do not not appear in this list. However, identical elements will still be multiplied, so the table for `[2,3,3]` looks like:

```
    2  3  3
  ----------
2 | #  6  6
3 | #  #  9
3 | #  #  #

```

With the MCM being `6`.

In the event of a tie, you may return any of the tied elements, or a list of all of them.

* This is , so the shortest byte count for each language wins!

### Test-cases:

```
[2,3,4,5,6] -> 12
[7,2] -> 14
[2,3,3] -> 6
[3,3,3] -> 9
[1,1,1,1,2,2] -> 2
[6,200,10,120] -> 1200
[2,3,4,5,6,7,8,8] -> 24
[5,2,9,10,3,4,4,4,7] -> 20
[9,7,10,9,7,8,5,10,1] -> 63, 70, 90 or [63,70,90]

```

# Answer
> 12 votes
# Brachylog, 11 bytes

```
{⊇Ċ×}ᶠọtᵒth

```

Try it online!

### Explanation

```
{   }ᶠ          Find all:
 ⊇Ċ×              Product of a subset of 2 elements
      ọtᵒ       Order by occurrences
         th     Take the last element and discard the number of occurrences

```

# Answer
> 12 votes
# , ~~54~~ ~~50~~ 41 bytes

```
order(-tabulate(combn(scan(),2,prod)))[1]

```

Try it online!

Alternatively, for ~~54~~ ~~53~~ 44 bytes:

```
names(sort(-table(combn(scan(),2,prod))))[1]

```

Try it online!

In principle, the latter version outputs the relevant result even without the `names` function, but followed by the count of such most frequent products, which isn't asked for...

Thanks to CriminallyVulgar for -4 and -1, and Giuseppe for -9 on both.

# Answer
> 9 votes
# Jelly, 6 bytes

```
ŒcP€Æṃ

```

Try it online! or Check out the test suite.

### How it works

```
ŒcP€Æṃ – Full program / Monadic link.
Œc     – Unordered pairs without replacement.
  P€   – Product of each.
    Æṃ – Mode (most common element).

Alternative: ŒcZPÆṃ

```

# Answer
> 7 votes
# Pyth, 12 bytes

```
eo/QN=*M.cQ2

```

Test suite

First, we take all 2 element combinations of the input without replacement (`.cQ2`). Then, we map each of these pairs to their product (`*M`). Next, we overwrite the input variable with the list of products (`=`). Next, we sort the list of products by the number of occurrences in the list of products (`o/QN`). Finally, the take the final element of the sorted list (`e`).

# Answer
> 7 votes
# MATL, ~~8~~ 7 bytes

```
2XN!pXM

```

Try it online!

*(-1 byte by using the method from @Mr. Xcoder's Jelly answer.)*

```
2XN     % nchoosek - get all combinations of 2 elements from input
!p      % get the product of each combination
XM      % 'mode': get the most common value from that

```

---

Older answer:

### 8 bytes

```
&*XRXzXM

```

Try it online!

```
&*    % multiply input by its transpose,
      %  getting all elementwise products
XR    % take the upper-triangular portion of that,
      %  zeroing out repetitions and mainly self-multiplications
Xz    % remove the zeroed out parts
XM    % 'mode' calculation - get the most common value from that

```

# Answer
> 6 votes
# Mathematica, 32 bytes

*-17 bytes (and a fix) thanks to JungHwan Min.*

```
Commonest[1##&@@@#~Subsets~{2}]&

```

Pure function. Takes a list of numbers as input and returns the list of MCMs as output.

# Answer
> 6 votes
# 05AB1E, ~~8~~ 6 bytes

```
æ2ùP.M

```

-2 bytes thanks to *@Kaldo*.

Try it online or verify all test cases.

**Explanation:**

```
æ         # Take the powerset of the input-list
          #  i.e. [2,3,3] → [[],[2],[3],[3],[2,3],[2,3],[3,3],[2,3,3]]
 2ù       # Leave only the inner lists of size 2:
          #  i.e. [[],[2],[3],[3],[2,3],[2,3],[3,3],[2,3,3]] → [[2,3],[2,3],[3,3]]
   P      # Take the product of each remaining pair
          #  i.e. [[2,3],[2,3],[3,3]] → [6,6,9]
    .M    # Only leave the most frequent value(s) in the list
          #  i.e. [6,6,9] → [6]

```

# Answer
> 5 votes
# Perl 6, ~~41~~ 38 bytes

```
{key max bag(@_ X*@_)∖@_»²: *{*}:}

```

Try it online!

# Answer
> 5 votes
# MATLAB, 43 bytes

```
I=input('');i=I'*I*1-eye(nnz(I));mode(i(:))

```

It's also kind of a tongue twister!

**Explanation**

```
I=input('');           % Takes an input like "[2,3,4,5,6]"
i=I'*I                 % Multiplies the input by its own transverse
      *1-eye(nnz(I));  % Multiplies by 1-identity matrix to remove diagonal
mode(i(:))             % Calculates most common value and prints it

```

# Answer
> 4 votes
# Stax, ~~12~~ 10 bytes

```
╢êv^⌐ö►♣Ä»

```

Run and debug it

# Answer
> 4 votes
# JavaScript (ES6), ~~72~~ 70 bytes

```
a=>a.map(m=o=(y,Y)=>a.map(x=>Y--<0?m=(o[x*=y]=-~o[x])<m?m:o[r=x]:0))|r

```

Try it online!

# Answer
> 4 votes
# Python 3, ~~77~~ 72 bytes

```
f=lambda k,*l,m=[]:l and f(*l,m=m+[k*x for x in l])or max(m,key=m.count)

```

Try it online!

# Answer
> 4 votes
# Attache, 59 bytes

```
Last##~SortBy#`&&:`~##{Flat[UpperTriangle&1!Table&_!`*]^^0}

```

Try it online!

Still working on golfing this down a bit, but I think this is near optimal for the approach I've chosen.

## Explanation

This is a composition of three functions:

1. `{Flat[UpperTriangle&1!Table&_!`*]^^0}`
2. `SortBy#`&&:`~`
3. `Last`

The first function does the bulk of the computation:

```
{Flat[UpperTriangle&1!Table&_!`*]^^0}
{                                   }    anonymous lambda; input: _ (e.g.: [2,3,4,5,6])
                      Table&_!`*         shorthand for Table[`*, _]
                                         this creates a multiplication table using the input
                                         e.g.:
                                           4  6  8 10 12
                                           6  9 12 15 18
                                           8 12 16 20 24
                                          10 15 20 25 30
                                          12 18 24 30 36

      UpperTriangle&1!                   takes the strict upper triangle of this matrix
                                         e.g.:
                                          0 6  8 10 12
                                          0 0 12 15 18
                                          0 0  0 20 24
                                          0 0  0  0 30
                                          0 0  0  0  0
Flat[                           ]^^0     flattens this list and removes all 0s
                                         e.g.: [6, 8, 10, 12, 12, 15, 18, 20, 24, 30]

```

The second is a bit complicated but does something rather simple. First, it is useful to know that `f&n` is a function which, when called with arguments `...x`, returns `f[...x, n]`. `f&:n` is similar, returning `f[n, ...x]`. Now, let's decompose this:

```
( ~SortBy ) # (`& &: `~)

```

First, `f#g` creates a fork. With input `n`, it returns `f[n, g[n]]`. However, in this case, `f` is the function `~SortBy`. `~f` reverses the arguments of the function. This means that `~f#g` is equivalent to `f[g[n], n]`, or here, `SortBy[(`& &: `~)[n], n]`.

``& &: `~` follows the form `f&:n`. But what are ``&` and ``~`? They are "operator quotes", and return a function equivalent to the quoted operator. So, in this case, ``&` is the same thing as `${ x & y }`. With that in mind, this expression is equivalent to the following for binary operators:

```
f&:n   <=>   ${ f[n, x] }
       <=>   ${ (`&)[`~, x] }
       <=>   ${ `~ & x }

```

This yields the function ``~&x`, where `x` is the result from the first function. `n ~ a` counts the occurrences of `n` in `a`. So, this returns a function which counts the occurrences of the argument in the computed array from function 1.

Going back to `SortBy`, this each element in the array by the number of times it appears in it.

Finally, `Last` takes the element which occurs the most. Ties are broken by the sorting algorithm.

# Answer
> 4 votes
# APL (Dyalog Unicode), ~~29 27~~ 19 bytes

```
{⌈/⊢/⊣¨⌸∊⍵}⍳∘≢↓¨⊢×⊂

```

Try it online!

Tacit fn.

Thanks to Adám for the tacit version and 2 bytes.

Thanks to ngn for 8 bytes!

### How:

```
{⌈/⊢/⊣¨⌸∊⍵}⍳∘≢↓¨⊢×⊂
                ⊢×⊂   ⍝ Multiply each element with the entire argument, then
           ⍳∘≢↓¨      ⍝ Remove 1 from the first, two from the next etc. (removes repeated multiplications);
                      ⍝ The result is then fed into the function:
{       ∊⍵}           ⍝ Flatten the result;
     ⊣¨⌸              ⍝ Key; creates a matrix in which each row corresponds to a unique product;
   ⊢/                 ⍝ Get the rightmost column of the matrix;
 ⌈/                   ⍝ Get the highest value.

```

# Answer
> 4 votes
# Thunno 2, 5 bytes

```
2ċ€pṀ

```

#### Explanation

```
2ċ€pṀ  # Implicit input
2ċ     # Combinations of length 2 of the input
  €p   # Product of each pair in this list
    Ṁ  # Mode of this list
       # Implicit output

```

#### Screenshot

# Answer
> 3 votes
# Charcoal, 24 bytes

```
ＷθＦ×⊟θθ⊞υκＩ⊟Φυ⁼№υι⌈Ｅυ№υλ

```

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

```
Ｗθ

```

While the input array is non-empty...

```
×⊟θθ

```

... pop the last element and multiply the rest of the array by that element...

```
Ｆ...⊞υκ

```

... and push the results to the predefined empty list.

```
⌈Ｅυ№υλ

```

Count the number of times each product appears in the list and take the maximum...

```
Φυ⁼№υι...

```

... then filter for the products whose count equals that maximum...

```
Ｉ⊟

```

...then pop the last element and cast to string for implicit print.

# Answer
> 3 votes
# Japt, ~~20~~ 16 bytes

* -4 bytes from @Shaggy

---

```
£s°Y m*XÃc
ñ@è¥X

```

Try it online!

# Answer
> 3 votes
# Husk, 7 bytes

```
Ṡ►#mΠṖ2

```

Try it online!

## Explanation

```
Ṡ►#mΠṖ2  -- example input [3,3,3]
     Ṗ2  -- subsequences of length 2: [[3,3],[3,3],[3,3]]
   mΠ    -- map product: [9,9,9]
Ṡ        -- apply
  #      -- | count occurences in list
 ►       -- to maxOn that list: [9]

```

# Answer
> 3 votes
# CJam, ~~70~~ 68 bytes

```
q',/S*~_,(:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,(=

```

Try it online!

## Explanation

```
q',/S*~                                                                  Turn input string into a valid CJam array
       _,(                                                               Find the length of the array and subtract 1
          :L                                                             Assign the result to L
            {                                 }fX                        Outer for loop
             LX-,0a\+[{X1++}*](;                                         Create an array with all the array indexes bigger than X
                                {          }fY                           Inner for loop
                                 _X=\_Y=@*\                              Create a multiple of array[X] and array[Y] (Guaranteed to be from a unique combination of factors)
                                                 ~;]                     Casts away all stack items except for an array of the multiples
                                                    _{\_@e=}$\;          Sorts array by number of occurrences (largest number of occurences at the end)
                                                               _,(=      Gets the last element of the array

```

You will need to scroll right to see the explanations as the code is quite long, as well as the explanations.

---

This was an absolute nightmare to write. CJam doesn't have a powerset function (unlike a ton of other golfing languages - great choice on my part), which means that I had to manually find the powerset. However, this gave me the opportunity to ignore any invalid number of factors, unlike other answers with a powerset function.

This should be golfable, considering I'm terrible at CJam.

---

### Changes:

Helen cut off 2 bytes!

Old: `q',/S*~_,1-:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,1-=`
New: `q',/S*~_,(:L{LX-,0a\+[{X1++}*](;{_X=\_Y=@*\}fY}fX]~;]_{\_@e=}$\;_,(=`

By changing the `1-`s to simply `(` we get the same effect but with a lower byte count.

# Answer
> 3 votes
# Vyxal, ~~7~~ 6 bytes

*-1 byte thanks to The Thonnu*

```
2ḋvΠ∆M

```

Try it Online!

# Answer
> 2 votes
# Java (JDK 10), 132 bytes

```
a->{int l=a.length,i=l,j=0,r=99999,m[]=new int[r];for(;i-->0;)for(j=l;--j>i;)m[a[i]*a[j]]++;for(;r-->0;)i=m[r]<i?i:m[j=r];return j;}

```

Try it online!

# Answer
> 2 votes
# Haskell, ~~96~~ 94 bytes

-2 bytes thanks to nimi (using `sortOn(0<$)` instead of `length`)!

```
import Data.List
f a|b<-zip[0..]a=last.last.sortOn(0<$).group$sort[x*y|(i,x)<-b,(j,y)<-b,i/=j]

```

Try it online!

# Answer
> 2 votes
## MATLAB 39 bytes

```
a=input('');
b=triu(a'*a,1);
mode(b(b~=0))

```

Also check out answer by Jacob Watson

# Answer
> 2 votes
# SQL Server, 93 bytes

```
SELECT TOP 1a.a*b.a
FROM @ a
JOIN @ b ON a.i<b.i
GROUP BY a.a*b.a
ORDER BY COUNT(a.a*b.a)DESC

```

Input is assumed to come from a table of the form

```
DECLARE @ TABLE (A int, i int identity);

```

Example table population:

```
INSERT INTO @ VALUES (9), (7), (10), (9), (7), (8), (5), (10), (1);

```

Explanation:

I assume a "list of integers" will have an index associated with them, which in my case is the column `i`. The column `a` contains the values of the list.

I create products of every pair, where the left pair comes in the list earlier than the right pair. I then group on the product, and sort by the most populous number.

I'm a little sad I didn't get to use any cte or partitioning clauses, but they were just too long. `SELECT` is a very expensive keyword.

# Alternative, 183 bytes

```
WITH c
AS(SELECT a,ROW_NUMBER()OVER(ORDER BY a)r
FROM @),d AS(SELECT a.a*b.a p,COUNT(a.a*b.a)m
FROM c a
JOIN c b ON a.r<b.r GROUP BY a.a*b.a)SELECT TOP 1p
FROM d
ORDER BY m DESC

```

If SQL doesn't get to have a separate index column, here is a solution where I create an index using the `ROW_NUMBER` function. I personally don't care about the order, but an order is required and using the `a` column is the shortest.

# Answer
> 2 votes
# CJam, 29 bytes

```
q~:L,2m*{:-},{Lf=:*}%$e`:e>1=

```

Try it online!

# Answer
> 2 votes
# J, ~~29~~ ~~25~~ ~~24~~ 23 bytes

```
(0{~.\:1#.=)@(</#&,*/)~

```

Try it online!

## how

```
(~. {.@\: 1 #. =)@(</ #&, */)~
                  (</ #&, */)~  NB. all products, dups removed:
                          */    NB. create the times table
                   </           NB. lower triangular ones matrix
                       &,       NB. flatten each and
                      #         NB. filter based on lower triangle
                 @              NB. pass that result to
(~. {.@\: 1 #. =)               NB. get the most frequent list item:
       \:                       NB. sort down
 ~.                             NB. the uniq elements
          1 #. =                NB. by their count
    {.@                         NB. and take the first element

```

# Answer
> 2 votes
## Burlesque - 8 bytes

```
Jcp)pdn!

J        duplicate
 cp      cross product
   )pd   map . product
      n! most common element

```

Try it online here.

(and yes, Burlesque also has a command for "least common element")

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 95 bytes

```
x=>x.SelectMany(y=>(x=x.Skip(1)).Select(z=>y*z)).GroupBy(y=>y).OrderBy(y=>y.Count()).Last().Key

```

Try it online!

Less golfed code:

```
// x is a list of integers
x=>
  // iterate over each integer and
  // return a list per element.
  // flatten the list of lists to 1 list
  x.SelectMany(y=>
    // skip the current value and save
    // newly offset list to x so that it
    // can be incrementally offset
    // again next pass
    (x=x.Skip(1))
      // compute the product
      .Select(z=>y*z))
    // get the unique products
    .GroupBy(y=>y)
    // sort the products by number
    // of occurrences
    .OrderBy(y=>y.Count())
    // pick the product with the
    // greatest number of occurrences
    .Last().Key

```

# Answer
> 2 votes
# Husk, 6 bytes

```
►=mΠṖ2

```

Try it online!

`►=` gives -1 over the other answer.

`×*` has too many duplicates and doesn't give the right value.

# Answer
> 2 votes
# Julia 1.0, ~~99~~ 83 bytes

```
~=length
!x=argmax(sum.(.==(1:max((M=[x[i]x[j] for i=1:~x for j=i+1:~x])...)),[M]))

```

Try it online!

-16 bytes (!!) thanks to MarcMush:

* Remove `*` (use implicit multiplication)
* Replace `map` with a broadcast
* Replace `findmax` with `argmax`
* Use the return value of a variable assignment
* Use `sum` instead of `count`

# Answer
> 2 votes
# C (gcc), 131 bytes

This code compiles and runs fine on my machine, but not on TIO or ATO... probably because the function leaks a few gigabytes of memory each time.

I've included my test suite below if you'd like to try it for yourself. Run at your own risk!

```
m,p,T;f(n,z,r,b)int*n,*r,*b;{for(r=calloc(T=~(1<<31),4);z--;n++)for(b=n;b++<n+z;)r[*n**b]++;for(m=p=0;T--;p++)m=r[p]>r[m]?p:m;m=m;}

```

```
#include <stdio.h>
#include <assert.h>

int main(int argc, char *argv[])
{
    int tests[][9] = {
        {2,3,4,5,6},
        {7,2},
        {2,3,3},
        {3,3,3},
        {1,1,1,1,2,2},
        {6,200,10,120},
        {2,3,4,5,6,7,8,8},
        {5,2,9,10,3,4,4,4,7},
        {9,7,10,9,7,8,5,10,1},
    };

    int expected[] = {
        12,
        14,
        6,
        9,
        2,
        1200,
        24,
        20,
        63
    };

    int sizes[] = {5,2,3,3,6,4,8,9,9};

    for (int i = 0; i < 9; i++)
    {
        printf("[");
        for (int j = 0; j < sizes[i] - 1; j++)
            printf("%d, ", tests[i][j]);
        printf("%d] -> ", tests[i][sizes[i] - 1]);

        int result = f(tests[i], sizes[i]);
        printf("%d\n", result);

        assert(result == expected[i]);
    }

    return 0;
}

```

# Answer
> 2 votes
# Uiua, 16 bytes

```
⊡1⍖⍘⊚♭×⊞>.⇡⊃⧻⊞×.

```

Try it!

```
⊡1⍖⍘⊚♭×⊞>.⇡⊃⧻⊞×.
      ×⊞>.⇡⊃⧻⊞×.  # upper matrix of multiplication table
     ♭            # deshape
⊡1⍖⍘⊚             # number that occurs second most often

```

# Answer
> 1 votes
# PHP, 91 bytes

```
while($c=$argv[++$i])for($k=$i;--$k;)$r[$c*$argv[$k]]++;asort($r);echo end(array_flip($r));

```

takes input from command line arguments; run with `-nr` or try it online.

Use PHP 7 to avoid STRICT MODE warning.

# Answer
> 1 votes
# Japt `-h`, 11 bytes

```
à2 ®×Ãü ñÊÌ

```

Try it

```
á2 ®×
ñ@è¥X

```

Try it

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

```
a=>+a.flatMap((x,i)=>a.map(y=>a[y*=i--&&-x]=0+a[y]||[-y])).sort()[0]

```

Try it online!

# Answer
> 1 votes
# PowerShell, 71 bytes

```
$m=@()
while($l){$k,$l=$l;$m+=($l|%{$k*$_})}($m|group|sort c*)[-1].Name

```

Try it online!

Powershell beats python very occasionally.....

# Answer
> 1 votes
# Factor \+ `math.matrices`, 48 bytes

```
[ dup outer [ 1 + tail ] map-index concat mode ]

```

Try it online!

* `dup outer` Take the outer product between the input and itself, forming a matrix
* `[ 1 + tail ] map-index` Get the upper triangle of the matrix without the main diagonal
* `concat` Flatten to a list
* `mode` Find the most frequent number

# Answer
> 1 votes
# Arturo, 57 bytes

```
$=>[z:combine.by:2&|map=>[∏&]|tally|maximum[k,v][v]z\0]

```

Try it

# Answer
> 1 votes
# Stax, 8 bytes

```
ä+G+·♀v▐

```

Run and debug it

Unpacked:

# Stax, 9 bytes

```
2S{{*km:M

```

Run and debug it

```
 S        # Get all combinations of length
2         # 2
  {   m   # And map the following over them:
   { k    # Reduce by
    *     # Multiplication
       :M # Get the mode

```

# Answer
> 1 votes
# Nekomata, 6 bytes

```
Sđ*aŢṂ

```

Attempt This Online!

```
Sđ*aŢṂ
S       Subset
 đ      Unpair; check if length is 2, and push the two elements
  *     Multiply
   a    All possible values
    Ţ   Tally; return a list of unique values and a list of their counts
     Ṃ  Find the minimum value by its count

```

# Answer
> 0 votes
# APL(NARS), 53 chars, 106 bytes

```
{0=l←↑⍴⍵:⍵⋄t⊃⍨q⍳⌈/q←{+/t=⍵}¨t←×/¨(∊(⍳l)∘.<⍳l)/,⍵∘.,⍵}

```

Test:

```
  p←{0=l←↑⍴⍵:⍵⋄t⊃⍨q⍳⌈/q←{+/t=⍵}¨t←×/¨(∊(⍳l)∘.<⍳l)/,⍵∘.,⍵}
  p 9
9
  p 1 3
3
  p 2 3 4 5 6
12
  p 7 2
14
  p 2 3 3
6
  p 3 3 3
9
  p 1 1 1 1 2 2
2
  p 6 200 10 120
1200
  p 2 3 4 5 6 7 8 8
24
  p 5 2 9 10 3 4 4 4 7
20
  p 9 7 10 9 7 8 5 10 1
63
  p 3 3
9

```

# Answer
> 0 votes
# Scala, 140 bytes

Golfed version. Try it online!

```
def f(_l:Seq[Int],m:Seq[Int]):Int={var l=_l.tail;var k=_l.head;if(l.isEmpty)m.groupBy(identity).maxBy(_._2.size)._1 else f(l,m++l.map(_*k))}

```

Ungolfed version.

```
object Main {
  def f(_l: List[Int], m: List[Int]): Int = {
    var l=_l.tail;var k=_l.head;
    if (l.isEmpty) m.groupBy(identity).maxBy(_._2.size)._1
    else f(l, m ++ l.map(_ * k))
  }

  def main(args: Array[String]): Unit = {
    val input = List(
      List(2, 3, 4, 5, 6),
      List(7, 2),
      List(2, 3, 3),
      List(1, 1, 1, 1, 2, 2),
      List(6, 200, 10, 120),
      List(2, 3, 4, 5, 6, 7, 8, 8),
      List(5, 2, 9, 10, 3, 4, 4, 4, 7)
    )
    for (l <- input) {
      val res = f(l, Nil)
      println(res)
    }
  }
}

```

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


title: Determine the depth of an array

text:
# Question
Title: Determine the depth of an array
A simple challenge for your Monday evening (well, or Tuesday morning in the other half of the world...)

You're given as input a nested, potentially ragged array of positive integers:

```
[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]

```

Your task is to determine its depth, which is the greatest nesting-depth of any integer in the list. In this case, the depth of `11` is `6`, which is largest.

You may assume that none of the arrays will be empty.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Input may be taken in any convenient list or string format that supports non-rectangular arrays (with nested arrays of different depths), as long as the actual information isn't preprocessed.

You must not use any built-ins related to the shape of arrays (including built-ins that solve this challenge, that get you the dimensions of a nested array). The only exception to this is getting the length of an array.

Standard rules apply.

### Test Cases

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

```

# Answer
# K, 4 bytes

```
#,/\

```

In K, `,/` will join all the elements of a list. The common idiom `,//` iterates to a fixed point, flattening an arbitrarily nested list completely. `,/\` will iterate to a fixed point in a similar way, but gather a list of intermediate results. By counting how many intermediate results we visit before reaching the fixed point (`#`), we get the answer we want: the maximum nesting depth.

"Count of join over fixed-point scan".

In action:

```
 (#,/\)'(,1
        1 2 3
        ,1 2 3
        (3;(3;,3;3);3)
        ,((,1;2);(3;,4)))
1 1 2 3 4

```
> 21 votes

# Answer
# Retina, 10

* Saved 1 byte thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ
* Saved 14 extra bytes thanks to @MartinBüttner

```
+`\w|}{

{

```

Here the input format is a bit contrived - `_` characters are used for list separators, so an input would look like this `{1_{{2_3_{{4}_5}_6_{7_8}}_9_{10_{{{11}}}}_12_13}_14}`

* Stage 1 - repeatedly remove `}{` and all other `\w` characters. This has the effect of a) making all lists at all levels consist of only one element and b) removing all non-list-structural characters.
* Stage 2 - count remaining `{`. This gives the deepest level of nesting.

Try it online.

---

If that's too much of a stretch, then the previous answer was:

# Retina, 13

Assumes lists are contained in curly braces `{}`.

```
+`[^}{]|}{

{

```

Try it online.
> 15 votes

# Answer
## Python 2, 33 bytes

```
f=lambda l:l>{}and-~max(map(f,l))

```

Recursively defines the depth by saying the depth of a number is 0, and the depth of a list is one more than the maximum depth of its elements. Number vs list is checked by comparing to the empty dictionary `{}`, which falls above numbers but below lists on Python 2's arbitrary ordering of built-in types.
> 12 votes

# Answer
# Pyth - ~~11~~ ~~10~~ 7 bytes

*1 bytes saved thanks to @Dennis*

*4 bytes saved thanks to @Thomas Kwa*

```
eU.usNQ

```

Try it online here.

Keeps on summing the array till it stops changing, which means its just a number, does this cumulatively to save all the intermediate results and gets length by making a urange with the same length as list and taking the last element.
> 6 votes

# Answer
## Haskell, 43 bytes

```
'['#x=x-1
']'#x=x+1
_#x=x
maximum.scanr(#)0

```

Usage example: `maximum.scanr(#)0 $ "[1, [[3]], [5, 6], [[[[8]]]], 1]"` -\> `5`.

Haskell doesn't have mixed lists (`Integer` mixed with `List of Integer`), so I cannot exploit some list detection functions and I have to parse the string.

Im starting at the right with `0` and add 1 for every `]`, subtract 1 for every `[` and keep the value otherwise. `scanr` keeps all intermediate results, so `maximum` can do it's work.
> 6 votes

# Answer
# Julia, ~~55~~ 26 bytes

```
f(a)=0a!=0&&maximum(f,a)+1

```

This is a recursive function that accepts a one-dimensional array with contents of type `Any` and returns an integer. When passing an array to the function, prefix all brackets with `Any`, i.e. `f(Any[1,Any[2,3]])`.

The approach is pretty simple. For an input *a*, we multiply *a* by 0 and check whether the result is the scalar 0. If not, we know that *a* is an array, so we apply the function to each element of *a*, take the maximum and add 1.

Saved 29 bytes thanks to Dennis!
> 6 votes

# Answer
# JavaScript (ES6), 35 bytes

```
f=a=>a[0]?Math.max(...a.map(f))+1:0

```

## Explanation

Recursive function that returns the maximum depth of an array, or `0` if passed a number.

```
var solution =

f=a=>
  a[0]?                   // if a is an array
    Math.max(...a.map(f)) // return the maximum depth of each element in the array
    +1                    // add 1 to increase the depth
  :0                      // if a is a number, return 0

// Test cases
result.textContent =
`[1]                                                              -> 1
[1, 2, 3]                                                         -> 1
[[1, 2, 3]]                                                       -> 2
[3, [3, [3], 3], 3]                                               -> 3
[[[[1], 2], [3, [4]]]]                                            -> 4
[1, [[3]], [5, 6], [[[[8]]]], 1]                                  -> 5
[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14] -> 6
[[[[[[[3]]]]]]]                                                   -> 7`
.split`\n`.map(t=>(c=t.split`->`.map(p=>p.trim()),c[0]+" == "+c[1]+": "+(solution(eval(c[0]))==c[1]?"Passed":"Failed"))).join`\n`
```

```
<input type="text" id="input" value="[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]" />
<button onclick="result.textContent=solution(eval(input.value))">Go</button>
<pre id="result"></pre>
```
> 5 votes

# Answer
# MATL, 11 ~~14 15~~ bytes

```
'}{'!=dYsX>

```

Curly braces are used in MATL for this type of arrays. Anyway, the input is taken and processed as a string, so square brackets could equally be used, modifying the two characters in the code.

**Try it online!**

```
          % implicitly take input as a string (row array of chars)
'}{'!     % 2x1 (column) char array with the two curly brace symbols
=         % 2-row array. First / second row contains 1 where '}' / '{' is found
d         % second row minus first row
Ys        % cumulative sum of the array
X>        % maximum of the array
          % implicitly display result

```
> 4 votes

# Answer
# Jelly, ~~10~~ 7 bytes

```
¬;/SÐ¿L

```

Try it online! or verify all test cases.

### How it works

```
¬;/SÐ¿L  Main link. Input: A (list)

¬        Negate all integers in A. This replaces them with zeroes.
    Ð¿   Cumulative while loop.
   S       Condition: Compute the sum of all lists in A.
                      If the sum is an integer, it will be zero (hence falsy).
 ;/        Body:      Concatenate all lists in A.
      L  Count the number of iterations.

```

### Update

While writing this answer, I noticed that Jelly behaves rather weirdly for ragged lists, because I calculated the depth of a list as the incremented *minimum* of depths of its items.

This has been addressed in the latest version, so the following code (**6 bytes**) would work now.

```
¬SSÐ¿L

```

This sums the rows of the array instead of concatenating them.
> 4 votes

# Answer
# Octave, 29 bytes

```
@(a)max(cumsum(92-(a(a>90))))

```

Maps `[` to 1 and `]` to -1, then takes the max of the cumulative sum.

Input is a string of the form

```
S6 = '[1, [[3]], [5, 6], [[[[8]]]], 1]';

```

Sample run on ideone.
> 4 votes

# Answer
## Ruby, 53 bytes

```
i=0;p gets.chars.map{|c|i+=('] ['.index(c)||1)-1}.max

```

Input from STDIN, output to STDOUT.

```
i=0;                 initialize counter variable
p                    output to STDOUT...
gets                 get line of input
.chars               enumerator of each character in the input
.map{|c|             map each character to...
i+=                  increment i (and return the new value) by...
('] ['.index(c)||1)  returns 0 for ], 2 for [, 1 for anything else
-1                   now it's -1 for ], 1 for [, 0 for anything else
                     therefore: increment i on increase in nesting, decrement i
                       on decrease, do nothing otherwise
}.max                find the highest nesting level that we've seen

```
> 3 votes

# Answer
# Mathematica, ~~27~~ 20 bytes

```
Max[#0/@#]+1&[0#]-1&

```

Simple recursive function.
> 3 votes

# Answer
# Mathematica, 18 bytes

```
Max@#+1&//@(0#-1)&

```
> 3 votes

# Answer
# PHP, ~~84~~ ~~72~~ ~~64~~ ~~63~~ 60 bytes

Note: requires PHP 7 for the combined comparison operator. Also uses IBM-850 encoding

```
for(;$c=$argv[1][$i++];)$c>A&&$t=max($t,$z+=~ú<=>$c);echo$t;

```

Run like this:

```
php -r 'for(;$c=$argv[1][$i++];)$c>A&&$t=max($t,$z+=~ú<=>$c);echo$t;' "[1, [[3]], [5, 6], [[[[8]]]], 1]"

```
* Saved 12 bytes by just counting braces of the string representation instead
* Saved 8 bytes by simplifying string comparisons and using ordinal number of the char in case of `[` and `]`
* Saved a byte by not casting `$i` to an int. String offsets are casted to an int implicitly
* Saved 3 bytes by using combined comparison operator instead of ordinal number
> 3 votes

# Answer
# PHP, 61 bytes

```
function d($a){return is_array($a)?1+max(array_map(d,$a)):0;}

```

recursive function that uses itself as a mapping function to replace each element with its depth.
> 3 votes

# Answer
# Haskell \+ free, 29 bytes

Haskell doesn't have a built in ragged list type so we need to build one out of free monads from the free package.

```
iter((+1).maximum).fmap(*0)

```

Try it online!
> 3 votes

# Answer
# C, ~~98~~ 69 bytes

29 bytes off thanks @DigitalTrauma !!

```
r,m;f(char*s){for(r=m=0;*s;r-=*s++==93)r+=*s==91,m=r>m?r:m;return m;}

```

Takes an *string* as input and return the result as integer.

Live example in: http://ideone.com/IC23Bc
> 2 votes

# Answer
# Raku, 53 48 bytes

The closure:

```
{my $d;/[\[{$d++;$!=max $!,$d}|\]{$d--}|.]*/;$!}

```

Needs an argument, eg:

```
> {my $d;/[\[{$d++;$!=max $!,$d}|\]{$d--}|.]*/;$!}("[[[3]][2]]")
3

```

Explanation:

```
{                 # start outer IIFE closure;

  my $d;            # declare depth variable `$d`;

  /                 # start IIFE regex match;

    [                 # start (non-capturing) group;

                      # EITHER:

      \[                # match `[` in input; if successful then:

      {                 # start inner (within regex) IIFE closure;

        $d++;             # increment depth variable; and then:

        $! = max $!, $d   # (ab)use `$!` variable to track MAX depth;

      }                 # end inner IIFE closure;

    |                 # OR:

      \]                # match `[` in input; if successful then:

      {$d--}            # decrement depth variable in IIFE closure;

    |                 # OR:

      .                 # match one character;

    ]*                # end capture group; match zero or more times;

  /;                # end regex;

  $!                # max depth as last value in closure;

}                 # end outer closure, returning last value (max depth);

("[[[3]][2]]")    # pass string "[[[3]][2]]" as outer closure argument.

```
> 2 votes

# Answer
## Python 3, ~~42~~ 39 bytes

*-3 bytes thanks to Sp3000*

This is essentially a port of xnor's Python 2 solution:

```
f=lambda l:"A"<str(l)and-~max(map(f,l))

```

Unfortunately, `[] > {}` returns an `unorderable types` error, so that particular clever trick of xnor's cannot be used. In its place, `-0123456789` are lower in ASCII value than `A`, which is lower than `[]`, hence the string comparison works.
> 2 votes

# Answer
## CJam (15 bytes)

```
q~{__e_-M*}h],(

```

Online demo

### Dissection

```
q~      e# Read line and parse to array
{       e# Loop...
  _     e#   Leave a copy of the array on the stack to count it later
  _e_-  e#   Remove a flattened version of the array; this removes non-array elements from
        e#   the top-level array.
  M*    e#   Remove one level from each array directly in the top-level array
}h      e# ...until we get to an empty array
],(     e# Collect everything together, count and decrement to account for the extra []

```

---

For the same length but rather more in ugly hack territory,

```
q'[,-{:~_}h],2-

```
> 2 votes

# Answer
# Sed, 40 characters

(39 characters code + 1 character command line option.)

```
s/[^][]+//g
:;s/]\[//;t
s/]//g
s/\[/1/g

```

Input: string, output: unary number.

Sample run:

```
bash-4.3$ sed -r 's/[^][]+//g;:;s/]\[//;t;s/]//g;s/\[/1/g' <<< '[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]'
111111

```

## Sed, 33 characters

(32 characters code + 1 character command line option.)

If trailing spaces are allowed in the output.

```
s/[^][]+//g
:;s/]\[//;t
y/[]/1 /

```

Input: string, output: unary number.

Sample run:

```
bash-4.3$ sed -r 's/[^][]+//g;:;s/]\[//;t;y/[]/1 /' <<< '[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]'
111111

```
> 2 votes

# Answer
## Hexagony, 61 bytes

*Edit*: Thanks @Martin Ender♦ for saving me 1 byte from the marvelous -1 trick!

```
|/'Z{>"-\..(.."/'&<'..{>-&,=+<$.{\$._{..><.Z=/...({=Z&"&@!-"

```

Try it online to verify test cases!

The images below are not modified but the flow is basically the same. Also note that this will return `-1` if the input is not an array (i.e. without `[]`).

I have lots of no-ops inside the Hexagon... I guess it can definitely be golfed more.

### Explanation

In brief, it adds `-1` when encounters a `[` and adds `1` when encounters a `]`. Finally it prints the max it has got.

Let's run along Test Case 5 to see its behaviour when it runs along the String `[1, [[3]], [5, 6], [[[[8]]]], 1]`:

It starts at the beginning and takes its input at the W corner:

Since there is still input (not the null character `\0` or EOL), it wraps to the top and starts the crimson path.

Here is what happens when from there till cute `><`:

`,` reads `[` into Buffer, and `{` and `Z` sets the constant Z to be 90. `'` moves to Diff and `-` calculates the difference. For `[` and `]` the difference will be `1` and `3` respectively. For numbers and spaces and commas it'll be negative.

Then we run `(` twice (once at the end of crimson path, one at the start after wrapping at the green path) to get `-1` and `1` resp for `[` and `]`. Here we change the naming of `Diff` to `Value`. Add this Value to Depth. (I used `Z&` to ensure that it copies the right neighbor). Then we calculate `lastMin - Depth` and got a number on the Memory edge `minLR`.

Then we apply `&` (at the end of green path) to `minLR`: If the number is \<=0, it copies the left value (i.e. `lastMin - Depth <= 0 => lastMin <= Depth`), otherwise it takes the right value.

We wraps to the horizontal blue path and we see `Z&` again which copies the `minLR`. Then we `"&` and made a copy of the calculated min. The brackets are assumed to be balanced, so the min must be \<=0. After wrapping, the blue path go left and hit `(`, making the copy `1` less than the real min. Reusing the `-`, we created one more 1-off copy as a neighbor of Buffer:

Note: `copy` is renamed as `1-off`

When blue path hits `\` and got a nice `"` and `<` catches it back to the main loop.

When the loop hits `1`, `,` or  or other numbers as input:

The Diff will become negative and it got reflected back to the main loop for next input.

When everything has gone through the main loop, we reach EOL which makes Buffer `-1` and it finally goes to the bottom edge:

`'` moves the MP to the `1-off copy` and `)` increments it, and with `~` negation it got the correct Max Depth value which is printed with `!`

And the story ends with a `@`.

I guess I must have over complicating things a little bit. If I have had to only "move back" and "print" without incrementing and negation, I would have well saved 2 bytes without using the full Hexagon.

Great thanks to Timwi for Esoteric IDE and Hexagony Colorer!
> 2 votes

# Answer
## brainfuck, 48 bytes

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

```

Formatted:

```
,
[
  <++[>-<------]>++
  [
    not close paren
    +
    [
      not open paren
      <
    ]
    >>[-]
  ]
  +<,
]
-[<[>+<-]>>]
<.

```

Takes input formatted like `(1, ((3)), (5, 6), ((((8)))), 1)` and outputs a byte value.

Try it online.

This stores the depth by memory location, moving the pointer right for `(` and left for `)` and ignoring other characters. Visited cells are marked with a `1` flag, so at the end of the main loop there will be `depth + 1` flags to the right of the current cell. These are then added to print the final result.

---

A previous 69-byte solution using a different approach:

```
,
[
  >>++[<<->>------]<-<++
  [
    not close paren
    >++<+
    [
      not open paren
      >-<[-]
    ]
  ]
  <
  [
    [>+>]
    <[<-<]
    >
  ]
  >>[<+> >+<-]
  ,
]
<.

```

In this version, the depth and max depth are stored explicitly in cells.
> 2 votes

# Answer
# Io, 53 bytes

Port of the JavaScript (ES6) answer.

```
f :=method(x,if(x type=="List",x map(i,f(i))max+1,0))

```

Try it online!
> 2 votes

# Answer
# C (gcc), 64 bytes

```
d,l;f(char*s){return*s?l=d?d>l?d:l:0,d+=*s>90?92-*s:0,f(s+1):l;}

```

Try it online!
> 2 votes

# Answer
# Jelly, 3 bytes

```
ẎƬL

```

Try it online!

This is a translation of JohnE's K answer.

is the "tighten" command. When applied to a list, it "unwraps" each list in it, essentially reducing the depth by one. `Ƭ` repeated applies  to the input until it reaches a fixed point. We then count the number of iterations with `L`.
> 2 votes

# Answer
# 05AB1E, 7 bytes

```
dΔ€`}N>

```

Try it online or verify all test cases.

**Explanation:**

```
d     # Convert each integer in the (implicit) input-list to 1 (with a >=0 check)
 Δ    # Loop until the result no longer changes:
  €   #  Map over each inner item:
   `  #   Pop and dump its contents to the stack
 }N   # After the loop, push the last 0-based index
   >  # Increase it by 1 to make it a 1-based index
      # (which is output implicitly as result)

```

The ``` basically flattens a list one level down, but will push its items in reversed order. E.g. list `[[1,[2,3],4]]` will become `[4,[2,3],1]`. In addition, it will do the same for multi-digit numbers, hence the need for the leading `d` to convert every integer to a single digit first. E.g. list `[12,345,67]` will become `[2,1,5,4,3,7,6]`.
> 2 votes

# Answer
# Whython, 28 bytes

```
f=lambda l:1+max(map(f,l))?0

```

Attempt This Online!

### Explanation

The depth of a list is the maximum depth of its elements; the depth of an integer is 0.

```
f=lambda l:1+max(map(f,l))?0
f=                            # Define f as
  lambda l:                   # a function of one argument, l:
                 map(f,l)     #  Call f recursively on each element of l
             max(        )    #  Take the maximum
           1+                 #  Add 1
                              #  If l is an integer, map raises an exception
                          ?0  #  Catch that exception and return 0

```
> 2 votes

# Answer
# Brachylog, 8 bytes

```
>0|↰ᵐ⌉+₁

```

Try it online!

```
 0|         Output 0
>           if the input is a positive integer;
  |↰ᵐ       else map this over the elements of the input
      +₁    and add 1 to
     ⌉      the largest result.

```
> 2 votes

# Answer
## Pyth, ~~15~~ 13 bytes

*-2 bytes by @Maltysen*

```
eSm-F/Ld`Y._z

```

Counts the difference between the cumulative counts of `[` and `]`, and takes the maximum. `Y` is the empty array, and its string representation (```) is conveniently `[]`.

Try it here.
> 1 votes

# Answer
# CJam, 19 ~~22 23~~ bytes

```
0l{_91=\93=-+_}%:e>

```

Similar idea to my MATL answer.

*Thanks to Peter Taylor for removing 3 bytes*

**Try it here**

```
0                            push a 0
l                            read line as string
{            }%              map this block on the string
  _91=\93=-                  1 if it's an opening bracket, -1 if closing
           +_                cumulative sum
               :e>           fold maximum function

```
> 1 votes

# Answer
## Minkolang 0.15, ~~31~~ ~~29~~ 24 bytes

Overhauled my algorithm upon inspiration by Luis Mendo's CJam answer and saved 5 bytes!

```
od5&j$ZN.d"["=$r"]"=~++d

```

Try it here!

### Explanation

Essentially, what this code does is keep a running total with +1 for each `[` and -1 for each `]`, keeping track of the maximum value reached, outputting that maximum at the end. Looping is handled by the toroidal nature of Minkolang's codebox.

```
od           Take character from input and duplicate it (0 if input is empty)
  5&         Pop top of stack and skip the following five spaces if 0
    j$Z      Push the maximum value of the stack
       N.    Output as number and stop.

  d                  Duplicate top of stack for character tests
   "["=              +1 if the character is [
       $r            Swap top two items of stack
         "]"=~       -1 if the character is ]
              ++     Add twice
                d    Duplicate top of stack for the running total

```
> 1 votes

# Answer
# Perl 5, 34 bytes

32, plus two for `-p`

```
{s&]\[|[^][]&&g&&redo}$_=@a=/]/g

```

Stolen from Digital Trauma's Retina answer… which is 26% shorter than this. `:-)`

Or, equally:

```
{s&]\[|[^][]&&g&&redo}$_=y///c/2

```
> 1 votes

# Answer
# Ruby, 51 characters

(Started as improvement suggestion for Doorknob's Ruby answer but ended differently. So I posted it as separate answer. Upvotes for the depth counting idea (`?\\<=>$&`, descending from `'] ['.index(c)`) should go to the original answer.)

```
m=i=0
gets.gsub(/\[|\]/){m=[m,i+=?\\<=>$&].max}
p m

```

Input: string, output: number.

Sample run:

```
bash-4.3$ ruby -e 'm=i=0;gets.gsub(/\[|\]/){m=[m,i+=?\\<=>$&].max};p m' <<< '[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]'
6

```
> 1 votes

# Answer
# Java 8, 95

This is a lambda expression for a `ToIntFunction<String>`. Input is taken as a `String` in the OP's examples format.

```
s->{int d=e=-1;for(String t:s.split("[")){d=++e>d?e:d;e-=t.split("]",-1).length()-1;}return d;}

```

fairly straightfoward. Split the string using `[` as the delimiter. For each of them, increment the counter `e` and compare it with the counter `d`, keeping the larger of them in `d`. Then split the current iteration's string using `]` as the delimiter this time and subtract the number of extra splits from `e`.
> 1 votes

# Answer
# Ruby, 41 characters

```
f=->a,d=1{a.map{|e|f[e,d+1]rescue d}.max}

```

Parameter: array, return: number.

Sample run:

```
2.1.5 :001 > f=->a,d=1{a.map{|e|f[e,d+1]rescue d}.max}
 => #<Proc:0x0000000214d258@(irb):1 (lambda)>

2.1.5 :002 > f[[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]]
 => 6

```
> 1 votes

# Answer
# Oracle SQL 11.2, 133 bytes

```
SELECT MAX(d)FROM(SELECT SUM(DECODE(SUBSTR(:1,LEVEL,1),'[',1,']',-1,0))OVER(ORDER BY LEVEL)d FROM DUAL CONNECT BY LEVEL<=LENGTH(:1));

```

Un-golfed

```
SELECT MAX(d)
FROM   (
         SELECT SUM(DECODE(SUBSTR(:1,LEVEL,1),'[',1,']',-1,0))OVER(ORDER BY LEVEL) d
         FROM   DUAL
         CONNECT BY LEVEL<=LENGTH(:1)
       );

```

The CONNECT BY creates one row per character in the input string.

The SUBSTR isolates the character corresponding to the row number.

The DECODE translates each '\[' to 1, each '\]' to -1 and every other character to 0.

The analytic SUM sums each 1, -1 and 0 from the preceding rows, including the current row;

The MAX sums is the depth.
> 1 votes

# Answer
# Ruby, 42 characters

```
f=->a{a==a.flatten(1)?1:f[a.flatten(1)]+1}

```

Example:

```
irb(main):001:0> f.call([[[1,2],[2,3]],[[3,4],[5]]])
=> 3

```

And it's actually readable. :)
> 1 votes

# Answer
# Lua, 101 100 bytes

```
d,c=0,0 print((...):gsub(".",function(s)c=s=='['and c+1 or s==']'and c-1 or c d=c>d and c or d end))

```

Try it online!

### How it works

<pre><code>-- Passed To Command Line: "[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]"

-- Deepest Sub-Array Count, Current Depth
deepest, current = 0, 0

-- We abuse gsub() to iterate over every character in the input string and run a function for it
(...):gsub(".", function(s)
    -- The current depth is incremented if s (the current character) is equal to [, OR decremented if s is equal to ], OR left alone
    current = (s == '[' and current+1) or (s == ']'and current-1) or current
    -- If current is > deepest then deepest = current else deepest = current, we're using boolean logic like a ternary operator
    deepest = current > deepest and current or deepest
end)

print(deepest)
```
</code></pre>
> 1 votes

# Answer
# Swift - 76 bytes

```
func d(_ a:[Any])->Int{return 1+(a.map{$0 is Int ?0:d($0 as![Any])}).max()!}

```

A recursive function that returns one plus the max of all non ints in the array using map.
> 1 votes

# Answer
# Haskell + hgl, 20 bytes

```
y=dPF(p 0)$P1<mx<m y

```

Takes input as a free monad of lists (`Free List a`).

## Explanation

A ragged list can contain either a terminal element or a list of more ragged lists.

`dPF` is a function which takes a function to convert terminal elements and a function to convert lists of ragged lists and uses them to convert a ragged list. This is captured in the type signature:

```
dPF :: (a -> b) -> ([Free [] a] -> b) -> Free [] a -> b

```

We give it two functions, for terminal elements it is very simple, terminal elements always have depth 0, so we give it `p 0`, meaning always return zero.

For lists we get the maximum depth of each element and add 1 using the function we are defining recursively. `P1<mx<m y`.

## Reflections

* We spend 6 bytes to envoke `dpF` properly `dPF()$`. This should have an infix function. Even if the operator precedence was bad it would have saved a byte.
* It's not an issue here because the lists can't be empty, but we should have a maximum with default function.
* Max with map also seems common enough to implement.
* Might have not saved bytes here, but this is the second time I have wanted a `fix` function. Should probably add that before I hit a place where I really need it.
> 1 votes

# Answer
# tinylisp, 48 bytes

```
(load library
(d f(q((x)(i(v x)0(+ 1(max(map f x

```

Try it online!

-11 from Dlosc

gets depth of a quoted list.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
Max[#0/@-1^#]+1&

```

Try it online!

The relatively low precedence of prefix `-` means `-1^#` is evaluated before the high-precedence `/@`.
> 1 votes

# Answer
## Perl 6, 70 bytes

Whole program that reads the given examples terminated with newline or EOF from STDIN.

```
# perl6 % <<< '[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]'

my $i;dd [max] lines.comb.map:{$i++when '[';$i--when ']'}

```

`lines` takes text line by line from STDIN and returns a list of `Str`. Calling `.comb` on a list will convert that into a `Str` and then split it into graphenes. Any block in Perl 6 is born with one positional argument that ends up in `$_`. `map` called with any callable expect it to have one positional argument. What is nice because `when ']'` is short for `when $_ ~~ ']'`. The returned list is fed to `[max]` and reduced to it's biggest value.
> 0 votes

# Answer
## C#, 99 Bytes

```
int f(string s){int m=0,w=0;foreach(char c in s){if(c=='[')w++;if(c==']')w--;if(w>m)m=w;}return m;}

```
> 0 votes

# Answer
# Axiom 106 bytes

```
RL(a:Union(List(Any),Any)):INT==(a case List(Any)=>(g:List(Any):=a;r:=1;for i in g repeat r:=r+RL(i);r);0)

```

ungolf

```
RL(a:Union(List(Any),Any)):INT==
  a case List(Any)=>
          g:List(Any):=a
          r:=1
          for i in g repeat r:=r+RL(i)
          r
  0

```

results

```
(3) -> for i in[[1],[1,2,3], [[1,2,3]], [3,[3,[3],3],3]]repeat output[i, RL(i)]
   [[1],1]
   [[1,2,3],1]
   [[[1,2,3]],2]
   [[3,[3,[3],3],3],3]

```
> 0 votes

# Answer
# C++14, ~~72~~ ~~70~~ 67 bytes

-2 bytes for removing the curly brackets at `for` and -3 bytes for replacing `m=l>m?l:m` with `m+=l>m`.

As unnamed lambda returning via reference parameter:

```
[](auto&s,int&m){int l=m=0;for(auto c:s)l+=(c==91)-(c==93),m+=l>m;}

```

`s` can be `std::string` or `char[]`

Ungolfed and usage:

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

auto f=
[](auto&s,int&m){
 int l=m=0;
 for(auto c:s)
  l+=(c==91)-(c==93),
  m+=l>m;
}
;

int main(){
 std::string S[] = {
  "[1]",
  "[1, 2, 3]",
  "[[1, 2, 3]]",
  "[3, [3, [3], 3], 3]",
  "[[[[1], 2], [3, [4]]]]",
  "[1, [[3]], [5, 6], [[[[8]]]], 1]",
  "[1, [[2, 3, [[4], 5], 6, [7, 8]], 9, [10, [[[11]]]], 12, 13], 14]",
  "[[[[[[[3]]]]]]]"
 };

 for (auto s:S){
  int m;
  g(s,m);
  std::cout << m << std::endl;
 }

}

```
> 0 votes

# Answer
**Clojure, 57 bytes**

```
(fn[s](apply max(reductions +(map #({\[ 1 \] -1}% 0)s))))

```

Also based on parsing a string:

```
(f "[3, [3, [3], 3], 3]")

```
> 0 votes

# Answer
R: 53 bytes.

```
d=function(L) ifelse(is.list(L),max(sapply(L,d))+1,0)

```

Recursive function, it adds one point everytime it finds an inner list. It chooses only the element with the maximum depth...
> 0 votes

# Answer
# Scala, 56 bytes

```
val f:Any=>Int={case l:Seq[_]=>l.map(f).max+1 case _=>0}

```

Make sure the inputs are `Seq`s and not `List`s (I used Seq to save a byte).

Try it online!
> 0 votes

# Answer
# Pip, 14 bytes

```
{a*0&1+MX:fMa}

```

Try it online!

### Explanation

A recursive function that takes the list as its argument.

```
{            }  Anonymous function:
 a               The first argument
  *0             Times 0
                 (This gives 0 if the argument is a number, or a [possibly nested]
                  list of 0s if the argument is a list)
    &            Logical AND (short-circuiting)
                 (Since 0 is falsey and non-empty lists are truthy in Pip, this
                  halts the recursion and returns 0 if we've reached the inside of
                  the innermost lists; otherwise...)
          fMa    Map this function recursively to each element of a
       MX:       Get the max (: is a no-op to manipulate operator precedence)
     1+          Add 1

```
> 0 votes

# Answer
# C (gcc), 62 bytes

```
n;m;f(char* s){for(;*s;s++)*s^91?*s^93?0:n--:++n>m?m=n:0;m=m;}

```

Try it online!
> 0 votes

# Answer
# Nekomata, 2 bytes

```
ˡ∑

```

Attempt This Online!

```
ˡ∑
ˡ   Loop until failure and return the number of iterations:
 ∑      Sum

```
> 0 votes

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


title: Array depth of a ragged list

text:
# Question
Title: Array depth of a ragged list
*This is not a duplicate of this challenge.*

Here by an *array*, I mean a nested list that is "not ragged", i.e., it is either a list of elements, or a list of arrays of the same shape. For example, this is an array of shape `(2,3)`:

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

```

The *depth* (or *rank*) of an array is the length of its shape. The depth of the array above is `2`.

But we can see every ragged-list as an array, where every element of the array is a either an atom (e.g., an integer) or a ragged-list. For example, the following ragged-list can be seen as an array of shape `(2,3)`:

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

```

The six elements of this array are `1`, `2`, `[3]`, `4`, `[5]`, `[6, [7]]`. As an array, its depth is `2`.

So we can define the ***array depth*** of a ragged list to be its maximum depth as an array.

Or more formally:

* If a ragged list has length \\$a\\$, we say it is an array of shape \\$(a)\\$.
* If every element of a ragged list is an array of shape \\$(a\_1,\dots,a\_n)\\$, and the length of the ragged list is \\$a\_0\\$, then we say it is an array of shape \\$(a\_0,a\_1,\dots,a\_n)\\$. (So it is also an array of shape \\$(a\_0,a\_1,\dots,a\_{n-1})\\$.)
* The ***array depth*** of a ragged list is the maximum length of its shape when we see it as an array.

## Task

Given a non-empty ragged list of positive integers, output its array depth. You may assume that the input does not contain any empty list.

This is , so the shortest code in bytes wins.

## Testcases

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

```

# Answer
# JavaScript (ES6), 54 bytes

```
f=a=>a.some(n=>+n.length!=a[0].length)?1:f(a.flat())+1

```

A quite simple approach: check if all elements are the same length, increment a counter if they are and repeat with the list flattened by one level, then return the counter.

-3 bytes thanks to tsh. -1 more thanks to l4m2.

```
f=a=>a.some(n=>+n.length!=a[0].length)?1:f(a.flat())+1

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

# Answer
# Python/NumPy, 23 bytes

Thx @pxeger for clarifying the legalese.

```
from numpy import*
ndim
```

Attempt This Online!

#### Not entirely legal Python/NumPy 22 bytes

```
from numpy import ndim
```

Attempt This Online!

Builtin (in case you haven't noticed).
> 4 votes

# Answer
# Haskell + hgl, 22 bytes

```
l<itr(K**l$rH lp)<pM[]

```

Takes input as a free monad of lists (`Free List a`).

## Explanation

Our strategy here is to calculate the "shape" of the array first and then derive its depth from that. We represent a shape as a list of sizes.

We are going to use a recursive strategy. Our base case is a terminal element which has shape `[]` and our inductive case is a list. If we have the shape of every element of a list then we know its shape is longest common prefix of all their shapes and add its own length to the front.

With that `itr x<pM y` will let us do this recursion. We already said `y` was `[]` so that's easy. Now we just need the other function.

`lp` gets the longest common prefix of two lists so `rH lp` gets the longest common prefix of a list of lists. We add `K**l` to put its own length on the front.

So our result is

```
itr(K**l$rH lp)<pM[]

```

which gets the shape of a array. But we need the *depth* so we add an extra `l<` to get the length of the shape.

## Reflections

* On my dev branch I've already made a alias for `(**)K`. This would have come in use on this challenge here as well. It would have saved 2 bytes `l<itr(l*:*rH lp)<pM[]`
* This is not the first time I've used `itr` and `pM` together in this way. When we only care about the shape of a free it's very useful to first replace all the elements and then iterate. This should have it's own name. It would have saved ~~3~~ 4 bytes: `l<shp(K**l$rH lp)i` (an extra byte is saved because `[]` can be replaced with `i` to save a byte whereas in the original `i` and `[]` are the same length)
> 4 votes

# Answer
# , 78 bytes

```
f=function(r)sum(1,if(all(Map(is.list,r))&!sd(lengths(c(r,r))))f(unlist(r,F)))

```

Try it online!
> 3 votes

# Answer
# Python3, 107 bytes:

```
f=lambda x,c=0:int in[*map(type,x)]or any(len(i)!=(c:=c or len(x[0])) for i in x)or min(1+f(i,c)for i in x)

```

Try it online!
> 2 votes

# Answer
# Charcoal, 43 bytes

```
Ｗ⁼⌊ＥθＬ⁺⟦⟧κ∨⌈ＥθＬ⁺⟦⟧κω«≔⟦⟧ζＦθＦκ⊞ζλ≔ζθ⊞υω»Ｉ⊕Ｌυ

```

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

```
Ｗ⁼⌊ＥθＬ⁺⟦⟧κ∨⌈ＥθＬ⁺⟦⟧κω«

```

Convert any numbers in the array to empty lists by vectorised adding them to the empty list (this leaves arrays unchanged). Compare their minimum and maximum length, unless the maximum length is `0` i.e. if the array only contains integers. Repeat while all arrays have the same length.

```
≔⟦⟧ζＦθＦκ⊞ζλ≔ζθ

```

Flatten the array.

```
⊞υω

```

Keep track of the number of loops.

```
»Ｉ⊕Ｌυ

```

Output the final depth.

33 bytes using the newer version of Charcoal on ATO:

```
Ｗ⁼⌊ＥθＬ⁺⟦⟧κ∨⌈ＥθＬ⁺⟦⟧κω«≔Σθθ⊞υω»Ｉ⊕Ｌυ

```

Attempt This Online! Link is to verbose version of code.
> 2 votes

# Answer
# Jelly, 14 bytes

Seems long!

```
¬RẎƬṖẈ€E€i0oLƲ

```

A monadic Link accepting a list that yields the "array-depth".

**Try it online!**

### How?

Uses the same intuition as emanresu A's JavaScript answer

```
¬RẎƬṖẈ€E€i0oLƲ - Link: list, A
¬              - logical NOT - converts all integers to zeros
 R             - range (vectorises) - converts all zeros to empty lists
   Ƭ           - collect up inputs while distinct, applying:
  Ẏ            -   tighten
    Ṗ          - pop - remove the final one
     Ẉ€        - lenth of each for each
       E€      - all-equal for each
             Ʋ - last four links as a monad, f(that):
         i0    -   first 1-indexed index of a zero (or zero)
           oL  -   logical OR with the length

```
> 1 votes

# Answer
# 05AB1E, 18 bytes

```
SмΔ¼D€gË≠i¾q}€`}¾<

```

Inspired by *@emanresuA*'s JavaScript answer.

Try it online or verify all test cases.

I initially had this 13-byter, but unfortunately it fails for test cases like `[[[1,2]],[[3,4],[5,6]]]`.

**Explanation:**

```
Sм           # Convert all integers to an empty string:
S            #  Convert the (implicit) input-list to a flattened list of digits
 м           #  Remove all those digits from each inner-most integer/string of
             #  the (implicit) input-list
  Δ          # Loop until the list no longer changes:
   ¼         #  Increase the counter variable by 1 (starts at 0)
   D         #  Duplicate the current list
    €g       #  Get the length of each inner item
      Ë≠i    #  If they are NOT all the same length:
         ¾   #   Push the counter variable
          q  #   And stop the program
             #   (after which this is output implicitly as result)
        }    #  Close the if-statement
         €`  #  Flatten one level down
  }¾         # After the loop: push the counter variable
    <        # Decrease it by 1 (because the last two iterations were the same
             # for the loop to stop)
             # (after which this is output implicitly as result)

```
> 1 votes

# Answer
# Ruby, ~~75~~...... 54 bytes

```
f=->a{a.map(&:size).uniq.one?&&a.flatten!(1)?1+f[a]:1}

```

Try it online!
> 1 votes

# Answer
# Nekomata, 5 bytes

```
Uˡ{Ťj

```

Attempt This Online!

```
Uˡ{Ťj
U       Wrap the input in a singleton list
 ˡ{     Loop until failure, and return the number of iterations:
   Ť        Transpose; fails if it is not a rectangular 2D array
    j       Join

```
> 0 votes

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