2015-04-03 51 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 
    } 
} 
相關問題