我是Scala新手。我正在使用Google guava库Collections2.permutations()
方法,该方法将java.util.Collection collection
我有以下代码,改编自我编写的相应Java程序。
import java.util
import com.google.common.collect.Collections2
import collection.JavaConversions._
class OptimalTSP {
def distance(point1: Point, point2: Point): Double = {
Math.sqrt(Math.pow(point2.y - point1.y, 2) + Math.pow(point2.x - point1.x, 2))
}
def findCheapestPermutation(points: java.util.List[Point]): java.util.List[Point] = {
var cost: Double = Double.MaxValue
var minCostPermutation: java.util.List[Point] = null
val permutations: util.Collection[java.util.List[Point]] = Collections2.permutations(points)
import scala.collection.JavaConversions._
for (permutation <- permutations) {
val permutationCost: Double = findCost(permutation)
if (permutationCost <= cost) {
cost = permutationCost
minCostPermutation = permutation
}
}
println("Cheapest distance: " + cost)
minCostPermutation
}
}
以上工作正常,但明确需要完整的包名java.util.List
。是否有更惯用的scala方法,即将scala List
传递给需要Java Collection
的方法?
答案 0 :(得分:1)
更通俗地说,您可以尝试使用permutations
和minBy
:
points.permutations.minBy(permutation => findCost(permutation))
points.permutations.minBy(findCost) //equivalent
答案 1 :(得分:0)
正如Boris所指出的,permutation
上的scala List
方法可以直接使用,如下所示。
class OptimalTSP {
def distance(point1: Point, point2: Point): Double = {
Math.sqrt(Math.pow(point2.y - point1.y, 2) + Math.pow(point2.x - point1.x, 2))
}
def findCheapestPermutation(points: List[Point]): List[Point] = {
var cost: Double = Double.MaxValue
var minCostPermutation: List[Point] = null
for (permutation <- points.permutations) {
val permutationCost: Double = findCost(permutation)
if (permutationCost <= cost) {
cost = permutationCost
minCostPermutation = permutation
}
}
println("Cheapest distance: " + cost)
minCostPermutation
}
}