Scala用排列列表进行统一交叉操作的最佳方法?

问题描述:

我搜索使Scala中的GA跨界运算符起作用的最佳和最优雅的方法(没有"for"循环,如果可能的话,只有不可变的类型),例如,使用以下列表:

I search the best and the most elegant way to make GA crossover operator in Scala functional (No "for" loop, with only immutable type if possible), for example, with this list:

val A = IndexedSeq (5,4,8)
val B = IndexedSeq (3,2,6)

我想在IndexedSeq中的每个元素之间进行随机比特币置换(例如,用rng.nextBoolean),最后在对它们进行置换之后,得到两个列表A'和B'.

I want to make random bitcoin permutation (with rng.nextBoolean for example) between each element in my IndexedSeq, and finally I get the two lists A' and B' after permutation of their elements.

执行示例:

rng.nextBoolean <- (true,false,true)
A' = 3,4,6
B' = 5,2,8

谢谢.

def crossover[T](a: Seq[T], b: Seq[T], rs: Seq[Boolean]) =
  (a, b, rs).zipped.map((x, y, z) => if (z) Seq(x, y) else Seq(y, x)).transpose

使用布尔值作为第三个参数:

Use with Booleans as third argument:

scala> val Seq(a1, b1) = crossover(A, B, List(true, false, true))
a1: Seq[Int] = Vector(5, 2, 8)
b1: Seq[Int] = Vector(3, 4, 6)

如果您希望使用默认的布尔值序列,则可以提供这样的默认参数:

If you want it with a default sequence of Booleans, you could provide a default argument like this:

def crossover[T](a: Seq[T], b: Seq[T], rs: Seq[Boolean] = { 
                                       val rng = new util.Random
                                       Stream.continually(rng.nextBoolean) }) =
  (a, b, rs).zipped.map((x, y, z) => if (z) Seq(x, y) else Seq(y, x)).transpose