Scala: merge two arrays into one structure

I have two arrays:

val diceProbDist = new Array[Double](2 * DICE + 1)

and

val diceExpDist = new Array[Double](2 * DICE + 1)

and I want to merge into one structure (maybe some kind of tuple):

(0, 0.0, 0,0)(1, 0.0, 0.0)(2, 0.02778, 0.02878)...

where the first record is the index of the array, the second record is the first value of the array, and the third record is the second value of the array.

Is there any scala function for this (zip with map or something like that)?

thanks ML

+4
source share
3 answers
val diceProbDist = Array(0.1, 0.2, 0.3)
val diceExpDist = Array(0.11, 0.22, 0.33)

diceProbDist
 .zip(diceExpDist)
 .zipWithIndex
 .map { case ((v1, v2), i) => (i, v1, v2) }

// result: Array((0,0.1,0.11), (1,0.2,0.22), (2,0.3,0.33))
+6
source

A simple understanding forshould also do the trick if you don't mind:

for {
  index <- 0 until math.min(diceExpDist.length, diceProbDist.length)
} yield (index, diceProbDist(index), diceExpDist(index))
+4
source

Another solution similar to tkachuko one without understanding

val diceProbDist = List(0.1, 0.2, 0.3)
val diceExpDist = List(0.11, 0.22, 0.33)

val range = 0 until math.min(diceExpDist.length, diceProbDist.length)
range.map { idx => (idx, c(idx), d(idx)) }

// result : res0: List[(Int, Int, Int)] = List((0,0,11), (1,1,12), (2,2,13), (3,3,14), (4,4,15), (5,5,16), (6,6,17), (7,7,18), (8,8,19), (9,9,20))
+2
source

Source: https://habr.com/ru/post/1667272/


All Articles