2015-04-03 32 views
0

我是Scala新手。我正在使用谷歌番石榴库Collections2.permutations()方法作为输入java.util.Collection collectionScala.List和Java.util.List之间的互操作

我有下面的代码,改编自我写的相应的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

你确定[这](http://stackoverflow.com/questions/8124440/code-to-enumerate-排列在斯卡拉)不是一个更好的解决方案?已经有一种方法... – 2015-04-03 21:26:57

+0

@BoristheSpider感谢您指出,我正在适应我的代码直接使用List方法 – vsnyc 2015-04-03 21:36:07

回答

1

更地道,你可以尝试使用permutationsminBy

points.permutations.minBy(permutation => findCost(permutation)) 
points.permutations.minBy(findCost) //equivalent 
+0

谢谢,看起来更好。我会试试看,并发表评论 – vsnyc 2015-04-04 12:55:27

+0

已验证并已接受 – vsnyc 2015-04-06 14:40:56

0

正如鲍里斯指出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 
    } 
} 
相关问题