Update an Array based on its values and the values

2019-08-21 10:07发布

问题:

I am trying to change the value of an array based on the value of a different array. In particular these are the arrays I am working with:

val inpoly: Array[Boolean]=Array(false, true, true, false)
val idx1: Array[Boolean]=Array(true, false, false, false)

I would like to check the array idx1 and where it is true I would like to set inpoly to true in that specific position, otherwise, just leave the value that inpoly already has.

My expected result would be to have this array:

final_vector= true, true, true, false

since the first value of idx1 is true, assign true to inpoly. All the other values of idx1 are false, so leave inpoly as it is

I tried the following code:

idx1.map({
  case true => true
  case false => inpoly})

However I get the following result:

res308: Array[Any] = Array(true, Array(false, true, true, false), Array(false, true, true, false), Array(false, true, true, false))

Can anyone help?

回答1:

It looks like you'd like to use an "OR" on the pairs of booleans. Here's one approach using || which is Scala's OR function:

val updated = inpoly.zip(idx1).map(pair => pair._1 || pair._2)

which would give you:

updated: Array[Boolean] = Array(true, true, true, false)

Here, zip will combine the two arrays into one array of pairs. Then you will map through those pairs and return a true if either are true and a false if both are false.

You could also use a pattern match:

val updated = inpoly.zip(idx1).map {
 case (left, right) => left || right
 case _ => None 
}

You'll want to think about what you will do in the case that one Array has a different length than the other.

And, if you insist on modifying inpoly rather than creating a new array, do the following:

var inpoly: Array[Boolean]=Array(false, true, true, false)
val idx1: Array[Boolean]=Array(true, false, false, false)

inpoly = inpoly.zip(idx1).map(pair => pair._1 || pair._2)

Note that here, we declare inpoly to be a var, not a val. However, I would instead suggest keeping inpoly as a val and creating a new val for the updated version of that array. Using immutable values is a recommended practice in Scala, though it can take some getting used to.



回答2:

You need to zip both arrays, so you can iterate over pair of values fe.:

idx1.zip(inpoly).map{
  case (true, _) => true
  case (_, value) => value
}

But be aware that this code will create new array, inpoly won't be changed.