我有List的List,并在我的代码中将其称为BAT。每个BAT具有2个属性。第一个是位置,第二个是健身。对于BAT中的每个列表,我正在使用Sphere函数计算其适用性。基于适应度,我应用了筛选器,该筛选器仅筛选适合度小于称为GF的对象的那些列表。这使我得到了BAT。 我的代码是
var GlobalBest_Fitness = Double.PositiveInfinit
var BAT = List.fill(N)(new BAT1(d, MinVal, MaxVal))
BAT.map { x =>
x.fitness = sphere(x.position)
}
BAT.filter(_.Fitness < GF).map { x =>
GF = x.Fitness
}
def sphere(list: List[Double]): Double = {
list.foldLeft(0.0)((x, xs) => x + xs * xs)
}
class BAT1 ( dim:Int , min:Double , max:Double) {
val random = new Random()
var position : List[Double] = List.fill(dim)(random.nextDouble() * (max-min)+min )
var fitness :Double = math.random
}
此代码设置了BAT的最后一个成员的GF Fitness,但是我想将Object GF的值设置为“最低适应性列表”。
这里有一些输出来解释问题。具有5个列表的BAT,
(List(-67.33460898977961, -71.09215709663737, 55.89607430834903, -43.23771807116002),14581.91575554507)
(List(90.12684307743376, 43.946793301728036, -93.06789837138616, -76.86083905559525),24623.390772205956)
(List(12.619843833260006, -86.17961848282789, 48.99208107528267, 24.69991428409682),10596.496873950442)
(List(96.24721330545535, 54.598176031247306, -92.20930457845513, -42.450241098519385),22549.06571516962)
(List(71.10095207554104, 74.02738064902607, 93.76767384566747, 40.917896190085656),21002.04935885428)
Output ==>> GF = 21002.04935885428
这是将GF的值设置为最后一个列表适应性,而应将其设置为最低值10596.496873950442,这是第三个列表的适应性。
此列表可能非常大,必须遍历数百万次。我想找到最佳解决方案。
答案 0 :(得分:0)
根据我对问题的理解,您希望从BAT1对象列表(List[BAT1]
中获得最小适应度值。
发现的问题:
以后无需通过映射设置适应性,.map用于 列表/集合/单子的转换(例如,您要转换 列出[A]到列出[B])。
因此,您的BAT1类应如下所示:
class BAT1(dim:Int, min:Double, max:Double) {
val random = new Random()
var position: List[Double] = List.fill(dim)(random.nextDouble() * (max-min)+min )
val fitness: Double = sphere(position) //no need of var and can be directly computer here only
}
要获得最低的适应性,您不需要过滤
val minFitness = BAT.map(_.fitness).min
/*
we will first convert the list BAT which has type List[BAT1] to a
List[Double] containing fitness of each BAT1 object in the list
we will then get the minimum value in the List[Double] by .min method
List[BAT1] -> List[Double] -> Double
*/
另一种方式:
val minFitness = BAT.minBy(_.fitness).fitness //please read about minBy, maxBy in Scala documentations.