| Bytes | Lang | Time | Link |
|---|---|---|---|
| 004 | Vyxal 3 | 250722T172923Z | pacman25 |
| 011 | Uiua | 241202T142445Z | nyxbird |
| 016 | Wolfram Language Mathematica | 231019T074040Z | att |
| 002 | Nekomata | 231019T012714Z | alephalp |
| 048 | Raku | 160210T063308Z | raiph |
| 008 | Brachylog | 220202T024831Z | Unrelate |
| 048 | tinylisp | 220201T091841Z | Razetime |
| 028 | Whython | 220201T222851Z | DLosc |
| 062 | C gcc | 220201T141447Z | anon |
| 029 | Haskell + free | 220107T154100Z | Wheat Wi |
| 007 | 05AB1E | 220106T135941Z | Kevin Cr |
| 020 | Haskell + hgl | 220106T134718Z | Wheat Wi |
| 100 | Lua | 200731T014247Z | Benrob03 |
| 003 | Jelly | 201004T212715Z | caird co |
| 076 | Swift | 200802T070408Z | user1979 |
| 014 | Pip | 200801T013019Z | DLosc |
| 056 | Scala | 200731T234425Z | user |
| 064 | C gcc | 200731T015936Z | kaadmy |
| 053 | Io | 200730T134532Z | user9649 |
| 042 | Ruby | 170907T165728Z | thisismy |
| 060 | PHP | 160210T124211Z | aross |
| 061 | PHP | 161220T022722Z | Titus |
| 053 | R | 161220T015202Z | skan |
| 048 | brainfuck | 161219T150433Z | Mitch Sc |
| 057 | Clojure | 161219T110754Z | NikoNyrh |
| 067 | C++14 | 161128T115631Z | Karl Nap |
| 106 | Axiom | 161128T113644Z | user5898 |
| 061 | Hexagony | 161012T120120Z | Sunny Pu |
| 095 | Java 8 | 160210T041942Z | Jack Amm |
| 026 | Julia | 160209T033227Z | Alex A. |
| 133 | Oracle SQL 11.2 | 160210T144457Z | Jeto |
| 041 | Ruby | 160210T123227Z | manatwor |
| 020 | Mathematica | 160208T235719Z | LegionMa |
| 040 | Sed | 160210T095243Z | manatwor |
| 015 | CJam | 160210T092125Z | Peter Ta |
| 099 | C# | 160210T085043Z | downrep_ |
| 024 | Minkolang 0.15 | 160208T234331Z | El'e |
| 039 | Python 3 | 160210T065550Z | El'e |
| 018 | Mathematica | 160210T071725Z | alephalp |
| 070 | Perl 6 | 160209T215612Z | gfldex |
| 010 | Retina | 160208T231851Z | Digital |
| 029 | Octave | 160209T020403Z | beaker |
| 069 | C | 160208T230522Z | removed |
| 004 | K | 160208T232207Z | JohnE |
| 051 | Ruby | 160209T100927Z | manatwor |
| 034 | Perl 5 | 160209T073310Z | msh210 |
| 007 | Jelly | 160208T221817Z | Dennis |
| 043 | Haskell | 160209T000919Z | nimi |
| 011 | MATL | 160208T221734Z | Luis Men |
| 019 | CJam | 160208T225045Z | Luis Men |
| 033 | Python 2 | 160208T223603Z | xnor |
| 013 | Pyth | 160208T221654Z | lirtosia |
| 007 | Pyth | 160208T222021Z | Maltysen |
| 053 | Ruby | 160208T222919Z | Doorknob |
| 035 | JavaScript ES6 | 160208T221833Z | user8165 |
Vyxal 3, 4 bytes
⑴⎘iL
flattens by 1 layer until the result no longer changes, then gets the number of iterations needed
Uiua, 11 bytes
-2⧻{⍥⊸/◇⊂∞}
Repeatedly reduce with conjoin (/◇⊂) until a fixed point (⍥...∞), then get the number of iterations (⧻{...⊸...}) and subtract 2 (-2).
Wolfram Language (Mathematica), 16 bytes
Max[#0/@-1^#]+1&
The relatively low precedence of prefix - means -1^# is evaluated before the high-precedence /@.
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.
Brachylog, 8 bytes
>0|↰ᵐ⌉+₁
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.
tinylisp, 48 bytes
(load library
(d f(q((x)(i(v x)0(+ 1(max(map f x
-11 from Dlosc
gets depth of a quoted list.
Whython, 28 bytes
f=lambda l:1+max(map(f,l))?0
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
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)
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].
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
dpFproperlydPF()$. 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
fixfunction. Should probably add that before I hit a place where I really need it.
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))
How it works
-- 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)
```
Jelly, 3 bytes
ẎƬL
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.
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.
Pip, 14 bytes
{a*0&1+MX:fMa}
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
Scala, 56 bytes
val f:Any=>Int={case l:Seq[_]=>l.map(f).max+1 case _=>0}
Make sure the inputs are Seqs and not Lists (I used Seq to save a byte).
Io, 53 bytes
Port of the JavaScript (ES6) answer.
f :=method(x,if(x type=="List",x map(i,f(i))max+1,0))
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. :)
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
$ito an int. String offsets are casted to an int implicitly - Saved 3 bytes by using combined comparison operator instead of ordinal number
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.
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...
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.
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.
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]")
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;
}
}
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]
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!
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.
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!
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.
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
Mathematica, 27 20 bytes
Max[#0/@#]+1&[0#]-1&
Simple recursive function.
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
CJam (15 bytes)
q~{__e_-M*}h],(
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-
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;}
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
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
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.
Mathematica, 18 bytes
Max@#+1&//@(0#-1)&
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.
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\wcharacters. 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.
If that's too much of a stretch, then the previous answer was:
Retina, 13
Assumes lists are contained in curly braces {}.
+`[^}{]|}{
{
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.
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
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
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
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
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.
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.
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.
% 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
CJam, 19 22 23 bytes
0l{_91=\93=-+_}%:e>
Similar idea to my MATL answer.
Thanks to Peter Taylor for removing 3 bytes
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
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.
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.
Pyth - 11 10 7 bytes
1 bytes saved thanks to @Dennis
4 bytes saved thanks to @Thomas Kwa
eU.usNQ
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.
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
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>






