Scala用排列列表进行统一交叉操作的最佳方法? [英] Scala best way to make uniform crossover operation with permutation list?

查看:51
本文介绍了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

这篇关于Scala用排列列表进行统一交叉操作的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆