首页 > 解决方案 > 从一个数组中获取索引并更新第二个数组中相同索引上的元素

问题描述

我有两个数组,上限和下限。

val solution : Array[Double] = Array(1.0, 33.0, 31.0, 82.0, 51.0, 25.0, 39.0, 96.0, 95.0, 49.0)
val original : Array[Double] = Array(3.0, 45.0, 18.0, 25.0, 99.0, 6.0, 36.0, 61.0, 82.0, 62.0)
val lower = 30
val upper = 90

布尔类型的数组是使用解决方案数组创建的。

val idx_lowest : Array[Boolean]  = solution.map ( x => x < lower )
idx_lowest: Array[Boolean] = Array(true, false, false, false, false, true, false, false, false, false)

在idx_lowest中查找值为 true的索引

val trueIndexes = idx_lowest .zipWithIndex filter(x => x._1  ) map(_._2)
trueIndexes: Array[Int] = Array(0, 5)

根据原始数组中的trueIndexes查找值。

val tmp = trueIndexes map original
Array[Double] = Array(3.0, 6.0)

对tmp数组的元素执行操作。

val tmp1 = tmp  map (x => (x+lower)/2.0)
Array[Double] = Array(16.5, 18.0)

更新解决方案数组的元素。索引由trueIndexes指定。小于下限的元素将被更新。

for(i <- tmp1.indices)  {
    solution(trueIndexes(i)) = tmp1(i)
  }

更新后的解决方案数组是:

Array[Double] = Array(16.5, 33.0, 31.0, 82.0, 51.0, 18.0, 39.0, 96.0, 95.0, 49.0)

必须执行相同的步骤来更新大于上限的元素。这是代码。

val idx_false : Array[Boolean]  = solution.map ( x => x > upper )
val falseIndexes = idx_false .zipWithIndex filter(x => x._1  ) map(_._2)
val tmp2 = falseIndexes map original 
val tmp3 = tmp2 map (x => (x+upper)/2.0)
for(i <- tmp3.indices)  {
   solution(falseIndexes(i)) = tmp3(i)
}
solution

这段代码完全符合我的需要,但必须执行大量操作。在迭代算法中,我必须在每个数组的每次迭代中执行这些操作。是否有更高效、最佳和更快的方式来执行相同的操作?

标签: arraysscalalambdafunctional-programmingscala-collections

解决方案


您可以zip在一个操作中进行它们和映射:

solution.zip(original)
  .map { case(s, o) => if(s < lower) ((o + lower) / 2, o) else (s, o) }
  .map { case(s, o) => if(s > upper) (o + upper) / 2 else s }

推荐阅读