0

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, i.e. passing scala List into a method that expects Java Collection?

vsnyc
  • 2,117
  • 22
  • 35
  • Are you sure that [this](http://stackoverflow.com/questions/8124440/code-to-enumerate-permutations-in-scala) isn't a better solution? There's already a method for that... – Boris the Spider Apr 03 '15 at 21:26
  • @BoristheSpider Thanks for pointing it out, I'm adapting my code to using the List method directly – vsnyc Apr 03 '15 at 21:36

2 Answers2

1

More idiomatically, you can try using permutations and minBy:

 points.permutations.minBy(permutation => findCost(permutation))
 points.permutations.minBy(findCost) //equivalent
Ben Reich
  • 16,222
  • 2
  • 38
  • 59
0

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
  }
}
vsnyc
  • 2,117
  • 22
  • 35