arrays - 从一个数组中获取索引并更新第二个数组中相同索引上的元素
问题描述
我有两个数组,上限和下限。
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
这段代码完全符合我的需要,但必须执行大量操作。在迭代算法中,我必须在每个数组的每次迭代中执行这些操作。是否有更高效、最佳和更快的方式来执行相同的操作?
解决方案
您可以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 }
推荐阅读
- php - 如何使用 $_POST 方法在 SQL 表中添加塞尔维亚拉丁语和塞尔维亚西里尔字母
- c# - Mongodb - 从集合中获取第二个项目
- c++ - Makefile:没有规则来制作目标。但从我所看到的它应该被覆盖
- ios - Flutter:iphone应用程序没有在模拟器中运行
- google-cloud-platform - 如何使 http 云功能只能从云端点访问
- c# - 在 DST 时间更改的情况下,将时间范围和间隔拆分为多个时间范围
- spring-cloud-task - 使用 DeployerPartitionHandler 为通过 spring 云任务运行的 spring 批处理在 launchWorker 中获取空指针异常
- maven - 通过 Maven 生成 EJB 2 STUBS & TIES
- c++ - GCC 和 Clang 之间关于重载和模板化流运算符的重载解析的区别<<
- python - 在第一个元素后使用 Selenium 返回空值