| Bytes | Lang | Time | Link |
|---|---|---|---|
| 045 | Ruby | 220103T093043Z | G B |
| 051 | jq | 240603T122500Z | GammaFun |
| 009 | Jelly | 240602T233902Z | DLosc |
| 037 | Arturo | 230212T133531Z | chunes |
| 011 | Burlesque | 220106T145122Z | DeathInc |
| 012 | Vyxal | 220811T041122Z | naffetS |
| 081 | Julia 1.0 | 220310T132447Z | MarcMush |
| 071 | R | 220103T074447Z | pajonk |
| 006 | 05AB1E | 220105T184728Z | Kevin Cr |
| 005 | Japt | 220103T224835Z | Shaggy |
| 011 | Jelly | 220103T143108Z | lynn |
| 021 | Haskell + hgl | 220103T152821Z | Wheat Wi |
| 068 | Python 2 | 220103T061015Z | loopy wa |
| 079 | Python 2 | 220103T010254Z | pxeger |
| 057 | JavaScript Node.js | 220104T015334Z | tsh |
| 053 | Perl 5 & probable regex polyglot | 220103T140219Z | Dominic |
| 087 | Python 3 | 220103T133153Z | Surculos |
| 046 | Juby | 220103T020819Z | Razetime |
| 029 | Retina | 220103T095615Z | Neil |
| 029 | Charcoal | 220103T094955Z | Neil |
| 034 | Retina 0.8.2 | 220103T060833Z | Neil |
| 042 | Factor + splitting.extras | 220103T020912Z | chunes |
| 2219 | J | 220103T005646Z | Jonah |
| 011 | Jelly | 220103T011925Z | Jonathan |
| 027 | Wolfram Language Mathematica | 220103T014758Z | att |
| 006 | Add++ | 220103T004331Z | lyxal |
| 006 | Vyxal 2.7.1 | 220103T010531Z | lyxal |
jq, 51 bytes
reduce.[]as$i([[]];.[-1]+=[0+$i]?//.+=[$i,[]])-[[]]
reduce .[] as $i ( # iterate over all elements of the input array
[[]]; # start with an array containing an empty array
.[-1] += [0 + $i]? # if $i is not a number, 0 + $i will throw an error, suppressed by `?`
# otherwise, append this element to the last subarray
// . += [$i, []] # if the previous statement was null or empty,
# add two new elements to the array: This one, and an empty array
) - [[]] # remove all empty arrays
Jelly, 9 bytes
ŒḊ€»ƝÄŻFƙ
Explanation
Something of a Frankenstein's monster combination of the Jelly answers by lynn and Jonathan Allan, but with the magic of ƙ:
ŒḊ€»ƝÄŻFƙ
ŒḊ€ Depth of each (0 for integers, 1 for lists)
»Ɲ Max of each adjacent pair of depths
Ä Cumulative sum
Ż Prepend a 0
Fƙ Group the original list by unique values in that list, then flatten each group
For example:
[[1, 1], 2, 3, [4], 5, [4], 2]
ŒḊ€ [1, 0, 0, 1, 0, 1, 0]
»Ɲ [1, 0, 1, 1, 1, 1]
Ä [1, 1, 2, 3, 4, 5]
Ż [0, 1, 1, 2, 3, 4, 5]
Fƙ [[1, 1], [2, 3], [4], [5], [4], [2]]
Burlesque, 13 11 bytes
{n!z?}gB)FL
{
n! # Not for ints (if 0 then 1 else 0); most common element for lists
z? # Is zero
}gB # Group by is list
)FL # Flatten each resulting list (double groups those already as lists)
Since the lists are always non-zero we can get away with this hack.
An alternative is doing a list/int only op and then seeing if there's an error (e.g tpis transpose-iserr) unfortunately no single op I know can test for is list
Julia 1.0, 81 bytes
+(x,y=[])=x>[] ? x[1] isa Int ? x[2:end]+[[y...;x[1]]] : [y;[x[1]];+x[2:end]] : y
a recursive approach
Julia 1.0, 82 bytes
f(;y=[])=y
f(x::Int,X...;y=[])=f(X...;y=[[y...;x]])
f(x,X...;y=[])=[y;[x];f(X...)]
the same idea, but with multiple dispatch
R, 76 75 71 bytes
Or R>=4.1, 64 bytes by replacing the word function with a \.
Edit: -1 byte thanks to @Dominic van Essen.
function(x){y[]=cumsum(c(T,y<-sapply(x,is.list))|y);tapply(x,y,unlist)}
Explanation
function(x) # take x as input
{
y[]= # assign to elements of y (to preserve length of y)
cumsum( # cumulative sum of
c(T, # TRUE followed by
y<-sapply(x,is.list)) # which elements of x are lists themselves
# (assign this to y)
|y # or y
); # this creates a mask on the positions of lists or first non-list elements
tapply(x,y,unlist) # apply unlist to x splitted by y
}
05AB1E, 6 bytes
.γd}€˜
Try it online or verify all test cases.
Explanation:
.γ # Adjacent group-by:
d # Transform every integer into a 1 (with a >=0 check)
}€ # After the group-by: map over each group:
˜ # Flatten it
# (after which the list of lists is output implicitly as result)
Japt, 6 5 bytes
If the sub-arrays in the input could be nested another level deep in the output then the last 3 bytes could be removed.
ó* mc
Jelly, 12 11 bytes
ŒḊ€aJŒg⁸ṁF€
ŒḊ€ Depth of each (1 for lists, 0 for numbers)
aJ Replace each 1 with its index [0 0 1 0 1 1] -> [0 0 3 0 5 6]
Œg Group runs of equal elements [[0 0] [3] [0] [5] [6]]
⁸ṁ Reshape the original input to this list
F€ Flatten each element (turns entries like [[1 2]] back into [1 2])
This approach feels elegant in theory, but a lot of bytes are wasted on €@µ€, so there might be saves.
Jonathan Allan saved a byte! Thanks.
Haskell + hgl, 21 bytes
In order to do this I needed to add support for Either types to hgl.
I was planning on doing this eventually and I don't think knowledge of this challenge influenced the way things were implemented.
So this is non-competing for whatever that means to you.
fR p<tv(mst p)<+gB ø
This takes a List (Either Int (List Int)) to represent a ragged array.
Surprisingly we can do flip the order of the Either at no cost to bytes.
fL p<tv(mst p)<+gB ø
Relfections
There are some things here that could be improved.
m<mstshould get it's own command. It's not used here but if I had had it this could have been 1 byte shorter:
wherefR p<sQ<m2t p<+gB øm2t = m<mst. (Implemented in 871c2406)- There needs to be a
Bitraversableclass. The whole reason we havemst pa very costly construct is that we need to massage the correct monoid instance onto the left hand side of theEither. If we hadBitraversable, the entiretv(mst p)could just be abisequence. - Other
Bifunctorclasses might have also helped here and are probably needed in the long run.Eitherisn't the only type that would benefit from this. We have other bifunctors like(,)andThesewhich would benefit as well. - Here I expressed ragged lists as lists of either the element or more lists. This works for ragged lists of max depth 2 fine, but it would also be possible to represent ragged lists more generally using the free monad combinator. If I had that I could have tried an approach with that, and even so I should probably have that for future challenges where the depth restriction might not exist.
Most of these basically boil down to "better bifunctor" support, so I think some of that is warranted.
Python 2, 68 bytes
lambda L:eval(re.sub("[^\d]{3,}","],[",`[[0,L,0]]`))[1:-1]
import re
Textually replaces every stretch of more than 2 non digit characters (i.e. everything that is not ", ") with "],[". A little trickery at the ends is required to guarantee balanced brackets.
Old Python 2, 73 bytes
lambda L:[map(int,x[1::3])for x in re.findall("(?:.\d.)+",`L`)]
import re
Just a stoopid regex that finds stretches of digits alternating with two arbitrary other characters (in the repr of the input).
Python 2, 84 79 bytes
s=[]
for x in input()+[{}]:
if x>9:
if s:print s
s=x[:0];print x
else:s+=x,
-5 bytes thanks to @ovs
JavaScript (Node.js), 57 bytes
a=>a.flatMap(c=n=>n[0]?c=[,n]:c[0]?c.push(n)&&[]:[c=[n]])
Perl 5 & probable regex polyglot, 53 bytes
s/(?<!\]),\[|],(?!\[)/],[/g;s/^\[+(.*[^]])]+$/[[\1]]/
First change all "]," or ",[" to "],["; then make sure it's all enclosed in "[[...]]".
I forgot the second bit on my first attempt, so it seemed a bit golfier than it turned out...
Python 3, 87 bytes
lambda L:[[*x]for t,g in groupby(L,type)for x in[g,[g]][t==int]]
from itertools import*
Group the list by type (int or list), then wrap the int groups in list.
I thought groupby would be great for this job, however the itertools import ended up costing too many characters.
Python 2, 84 bytes
def f(L,s=[]):t=s and[s];return L and[f(L[1:],s+L[:1]),t+L[:1]+f(L[1:])][L>[[]]]or t
f=lambda L,s=[]:L and[f(L[1:],s+L[:1]),(s and[s])+L[:1]+f(L[1:])][L[0]>9]or s and[s]
I tried to golf @pxeger's answer by using recursive function, but wasn't able to save any bytes.
These 2 functions simply loop through each element. If the current element is a digit, accumulate it in the list s. If the current element is a list, add the accumulated elements (s) if not empty to the result, followed by the current element.
J-uby, 46 bytes
:slice_when+:|%([~:*&0|:!=&0]*2)|:map+:flatten
Today I learned about slice_when, and J-uby's +.
-4 from translating GB's idea.
Ruby, 49 bytes
->a{a.slice_when{_1*0!=0||_2*0!=0}.map &:flatten}
-6 bytes from GB.
Retina, 29 bytes
["[["|"], ["]"]]"L`\b[^][]+\b
Try it online! Link includes test cases. Explanation: Based on @loopywalt's idea. Would be 28 bytes if I could be bothered to remove all the spaces from the lists.
L`\b[^][]+\b
List all runs of digits and separators (but excluding []s).
["[["
Precede the entire result with [[.
|"], ["
Separate each run with ], [.
]"]]"
Suffix ]] to the result.
Charcoal, 29 bytes
⊞υ⟦⟧FA¿⁺ι⟦⟧⊞⊞Oυι⟦⟧⊞§υ±¹ι⭆¹Φυλ
Try it online! Link is to verbose version of code. Explanation:
⊞υ⟦⟧
Push an empty list to the result in case the first element of the input is not a list.
FA
Loop through all of the elements of the input list.
¿⁼ι⟦⟧«
If adding the empty list to the element doesn't produce an empty list, then...
⊞⊞Oυι⟦⟧
... the element was a list, so push it to the result, plus another empty list in case the next element of the input is not a list, otherwise...
⊞§υ±¹ι
... append the element to the last list of the result.
⭆¹Φυλ
Filter out any empty lists (e.g. from consecutive lists in the input) and pretty-print the result.
Retina 0.8.2, 34 bytes
(?<=^\[|], )[^][]+(?=, \[|]$)
[$&]
Try it online! Link includes test cases. Would be 32 bytes if I could be bothered to remove all of the spaces from the lists. Explanation: Simply matches sublists composed of non-lists that are between two lists or positioned at the start and/or end of the main list and wraps them in a list. Using lookarounds to anchor the match avoids having to explicitly capture the sublist thus saving a byte.
(?<=^\[|], )
Match at the beginning of the main list or after a list.
[^][]+
Match anything that isn't a list.
(?=, \[|]$)
Match at the end of the main list or before a list.
[$&]
Wrap the sublist in a list.
Factor + splitting.extras, 43 42 bytes
[ [ array? ] split*-when [ flatten ] map ]
Explanation
[ array? ] split*-whenSplit on arrays (sublists) and keep the delimiters.[ flatten ] mapFlatten each element.flattendoesn't touch arrays of depth 1 but otherwise decreases depth to 1.
! { 1 { 2 2 } 3 { 4 4 } 5 }
[ array? ] split*-when ! { { 1 } { { 2 2 } } { 3 } { { 4 4 } } { 5 } }
[ flatten ] map ! { { 1 } { 2 2 } { 3 } { 4 4 } { 5 } }
J, 22 19 bytes
<@;;.1~2+./\1,#@$&>
-3 thanks to Bubbler
This is a little tricky in J, which requires boxes for heterogeneous arrays. The task becomes to "collect" iff the box contents are atoms. Contents which are already lists (either 1 items or more) should remain as single boxes.
Our strategy is then to "cut" (start a new group) unless adjacent elements are both atoms.
Jelly, 11 bytes
Really not sure if this is optimal, it's just the first way I though of...
,⁻;ɗƝŻœṗ⁸F€
How?
,⁻;ɗƝŻœṗ⁸F€ - Link: list, A
Ɲ - for each of the neighbours:
ɗ - last three links as a dyad, f(left, right):
, - pair them (e.g. [1,2] and 3 -> [[1,2],3]])
; - concatenate them (e.g. [1,2] and 3 -> [1,2,3])
⁻ - are these not equal? (i.e. was either left or right a list?)
Ż - prefix a zero
⁸ - use A as the right argument of...
œṗ - partition right at truthy indices of left
F€ - flatten each
Wolfram Language (Mathematica), 30 27 bytes
##&@@@#&/@Split[#,#>0<#2&]&
Split[# ] group adjacent items which
,#>0<#2& are both positive (non-lists)
##&@@@#&/@ remove extraneous brackets
At times like this, it'd be nice if @@, @@@ generalized to more @s...
Add++, 6 bytes
L*~,BC
Wow holy crap a challenge where Add++ will probably win. Nevermind I tied myself with vyxal.
Explained
L*~,BC
L*~, ; a lambda that dumps its arguments onto the stack and returns the entire stack that:
BC ; calls the built-in this challenge is all about.
Vyxal 2.7.1, 6 bytes
ƛf⁼;Ġ•
The link uses the latest version of vyxal (2.7.3 at the time of writing) which has a bug fix where molding no longer wraps singletons in lists, hence the extra vf.
Explained
ƛf⁼;Ġ•
ƛf⁼; # For each item in the input, does the flattened version equal the item? For integers, this returns a list, which does not equal the item. For lists, this just returns the list - this wouldn't work if there wasn't any depth restriction.
Ġ # Group on consecutive items
• # and mold the input to that shape