J  Calbreath
J Calbreath

Reputation: 2705

Scala: Condense Array[(String, Array[Double])] to Array[(String)]

I have an array that looks like this Array((1,Array(1.0,0.0,3.0)), (2,Array(0.0,2.0,1.0))) that I want to turn into and array that looks like: Array((1,1.0,0.0,3.0),(2,0.0,2.0,1.0)).

Is there an easy way to do that? I'm guessing there is some sort of map I can do but I haven't been able to figure out the syntax.

Thanks.

Upvotes: 3

Views: 177

Answers (2)

hellraiser
hellraiser

Reputation: 1451

Please specify the types of input and output. As i understand the task is Array[String, Array[Double]] => Array[Array[Double]]

 scala> val r = Array(("1", Array(1.0, 2.0, 1.0, 0.0, 3.0)), ("2", Array(0.0, 2.0, 1.0)))
r: Array[(String, Array[Double])] = Array((1,Array(1.0, 2.0, 1.0, 0.0, 3.0)), (2,Array(0.0, 2.0, 1.0)))

scala> val res = r map { case (s, Array(xs @ _*)) => (s.toDouble +: xs).toArray }
res: Array[Array[Double]] = Array(Array(1.0, 1.0, 2.0, 1.0, 0.0, 3.0), Array(2.0, 0.0, 2.0, 1.0))

Upvotes: 3

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179179

You could do this:

a.map { case (a, Array(b,c,d)) => (a,b,c,d) }

scala> val a = Array((1,Array(1.0,0.0,3.0)), (2,Array(0.0,2.0,1.0)))
a: Array[(Int, Array[Double])] = Array((1,Array(1.0, 0.0, 3.0)), (2,Array(0.0, 2.0, 1.0)))

scala> a.map({ case (a, Array(b,c,d)) => (a,b,c,d) })
res4: Array[(Int, Double, Double, Double)] = Array((1,1.0,0.0,3.0), (2,0.0,2.0,1.0))

A solution with support for up to 22-tuple. Of course, even this one assumes that all array members have the same lengths.

a.map {
  case (a, Array(b))           => (a,b)
  case (a, Array(b,c))         => (a,b,c)
  case (a, Array(b,c,d))       => (a,b,c,d)
  // pseudo-scala
  case (n1, Array(n2,...,n22)) => (n1,n2,...,n22)
}

Upvotes: 4

Related Questions