Shape of an array
Given a non-ragged array (an array where all sub-arrays at a particular level have the same length) of non-negative integers, answer its shape, that is, the length along every dimension. You may assume that the given array has at least one empty dimension, and that only the trailing dimension can have length 0.
Test cases
[]
→ [0]
[0]
→ [1]
[[]]
→ [1,0]
[[],[]]
→ [2,0]
[[4,4],[0,3]]
→ [2,2]
[[[4],[6]]]
→ [1,2,1]
[[[[7],[0]]]]
→ [1,1,2,1]
[Python 2], 37 bytes …
~2mo ago
[Raku], 32 bytes {m …
~2mo ago
[JavaScript (Node.js)], 36 byt …
~2mo ago
JavaScript (Node.js), 39 bytes …
~2mo ago
4 answers
Python 2, 37 bytes
l=input()
while 1:print len(l);l=l[0]
This makes heavy use of programs being allowed to terminate with error, which I assume is allowed by default because it is on SE. We repeatedly print the length, and then replace the list with its first entry. This will fail when we're at a leaf, which is when the list is empty or is actually a number.
0 comments
JavaScript (Node.js), 39 bytes
Returns dimensions from innermost to outermost
f=a=>a?.pop?f(a[0]).concat(a.length):[]
JavaScript (Node.js), 41 bytes
Returns dimensions from outermost to innermost
f=a=>a?.pop?[a.length].concat(f(a[0])):[]
0 comments
Raku, 32 bytes
{map +*,($_,*[0]...^9 ge*.gist)}
It's difficult to tell the difference between one element arrays and just plain numbers, since Raku translates between the two. However, gist
returns the list formatted with brackets surrounding it, so we are able to use that to our advantage using string comparison.
5 comments
Do we get bonus points for not using
⍴
here? — Razetime about 2 months agoWhat can the non-array contents of the arrays be - only numbers, or any arbitrary non-array object? — dzaima about 2 months ago
@Razetime No. :-) — Adám about 2 months ago
@dzaima Updated. — Adám about 2 months ago
Is there an order we have to output in? (my solution outputs the dimensions in the reverse order of your test cases) — Moshi about 2 months ago