I am a Scala newbie. I am using Google guava library Collections2.permutations()
method which takes as input a java.util.Collection collection
I have the following code, adapted from a corresponding Java program I had written.
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
}
}
The above works fine, but the full package name java.util.List
is explicitly needed. Is there a more idiomatic scala way of doing this, ie passing scala List
into a method that expects Java Collection
?
More idiomatically, you can try using permutations
and minBy
:
points.permutations.minBy(permutation => findCost(permutation))
points.permutations.minBy(findCost) //equivalent
As Boris pointed in the comment permutation
method on scala List
can be directly used as shown below.
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.