algorithm - Scala:如何根据添加到第三个列表的两个列表的加权差异创建一个新列表

标签 algorithm list scala random

作为 Differential Evolution 实现的一部分我需要实现“突变”步骤的算法:

  1. 从群体中随机挑选三个成员,他们必须彼此不同,并且与给定成员不同
  2. 通过将两个向量的加权差与第三个向量相加来计算施主成员

This是我想出的:

// Algorithm types
type Member = List[Double]
type Generation = Vector[Member]

def mutate(index: Int, generation: Generation): Member = {
  // Create a random number stream with distinct values
  val selector = Stream.continually(Random.nextInt(N)).distinct

  // Select 3 mates from the generation
  val mates = selector.filter(_ != index).take(3).map(generation(_))

  // Calculate the donor member
  (mates(0), mates(1), mates(2)).zipped map {
    case (e1, e2, e3) => e1 + F * (e2 - e3)
  }
}

(我按照说明实现了算法 here )

现在我的问题;有没有更好的方法来实现这一步?我一直在尝试找到一种更好的方法来从向量中选择 3 个列表并将它们压缩在一起,但是除了手动将所选列表放入元组之外我找不到任何其他方法。 Scala 编译器发出警告,应该使用 mates.head 而不是 mates(0),这让我知道这可以用更优雅的方式实现。

提前致谢!

最佳答案

您可以转置您的伙伴,然后使用Seq 提取器映射:

mates.transpose map {
  case Seq(e1, e2, e3) => e1 + F * (e2 - e3)
}

这将是一个 Stream[Double],因此要获得一个 Member,您必须对其调用 toList,或者使用 mates.toList.transpose ...

关于algorithm - Scala:如何根据添加到第三个列表的两个列表的加权差异创建一个新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33171357/

相关文章:

c - 如何将字符串分成唯一字符/字符串的数组

algorithm - MIPS 汇编语言中的内存访问

无法以正确的模式从文件复制/读取到列表

scala - 如何从磁盘加载 spark-nlp 预训练模型

algorithm - fun() 的时间复杂度?

c# - 如何将 IP 地址映射到八个字符长的字符串?

list - 在 Scala 中,如何将默认值传递给 List.find?

c# - 根据特定条件将列表分为两个列表

scala - 在 Scala 中合并包含公共(public)元素的 Sets

scala - 无法从 Gradle 解析 ScalaTest