Scala nested arrays flattening -
how flatten array of nested arrays of depth ?
for instance
val in = array( 1, array(2,3), 4, array(array(5)) ) would flattened onto
val out = array(1,2,3,4,5) thanks in advance.
if have mixed int , array[int], not idea begin with, can like
in.flatmap{ case i: int => array(i); case ai: array[int] => ai } (it throw exception if you've put else in array). can use basis of recursive function:
def flatint(in: array[any]): array[int] = in.flatmap{ case i: int => array(i) case ai: array[int] => ai case x: array[_] => flatint(x.toarray[any]) } if don't know you've got in nested arrays, can replace above ints any , flat array[any] result. (edit: any case needs go last.)
(note: not tail-recursive, can overflow stack if arrays nested extremely deeply.)
Comments
Post a Comment