Scala nested arrays flattening

会有一股神秘感。 提交于 2019-12-22 08:16:46

问题


How to flatten an array of nested arrays of any depth ?

For instance

val in = Array( 1, Array(2,3), 4, Array(Array(5)) )

would be flattened onto

val out = Array(1,2,3,4,5)

Thanks in Advance.


回答1:


If you have mixed Int and Array[Int], which is not a very good idea to begin with, you can do something like

in.flatMap{ case i: Int => Array(i); case ai: Array[Int] => ai }

(it will throw an exception if you've put something else in your array). You can thus use this as the basis of a 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 you don't know what you've got in your nested arrays, you can replace the above Ints by Any and get a flat Array[Any] as a result. (Edit: the Any case then needs to go last.)

(Note: this is not tail-recursive, so it can overflow the stack if your arrays are nested extremely deeply.)



来源:https://stackoverflow.com/questions/23055734/scala-nested-arrays-flattening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!