17

我正在尝试在 Scala(2.10 版)中实现 A* 搜索,但我遇到了障碍——我不知道如何使用 Scala 的优先级队列。这似乎是一项简单的任务,但在 Google 上搜索并没有发现任何结果(除了在 2.8 版中停止工作的单个代码示例)

我有一组正方形,用(Int, Int)s 表示,我需要用Ints 表示的优先级插入它们。在 Python 中,这非常简单,因为您只有一个键、值对列表并使用 heapq 函数对其进行排序。但似乎 Scala 的元组甚至没有可比性。

那么你是怎么做到的呢?考虑到它应该是多么简单,我对完全缺乏在线信息感到惊讶。

4

2 回答 2

25

There is actually pre-defined lexicographical order for tuples -- but you need to import it:

import scala.math.Ordering.Implicits._

Moreover, you can define your own ordering. Suppose I want to arrange tuples, based on the difference between first and second members of the tuple:

scala> import scala.collection.mutable.PriorityQueue
//  import scala.collection.mutable.PriorityQueue

scala> def diff(t2: (Int,Int)) = math.abs(t2._1 - t2._2)
// diff: (t2: (Int, Int))Int

scala> val x = new PriorityQueue[(Int, Int)]()(Ordering.by(diff))
// x: scala.collection.mutable.PriorityQueue[(Int, Int)] = PriorityQueue()

scala> x.enqueue(1 -> 1)

scala> x.enqueue(1 -> 2)

scala> x.enqueue(1 -> 3)

scala> x.enqueue(1 -> 4)

scala> x.enqueue(1 -> 0)

scala> x
// res5: scala.collection.mutable.PriorityQueue[(Int, Int)] = PriorityQueue((1,4), (1,3), (1,2), (1,1), (1,0))
于 2013-02-17T23:48:17.160 回答
0

Indeed, there is no implicit ordering on pairs of integers (a, b). What would it be? Perhaps they are both positive and you can use (a - 1.0/b)? Or they are not, and you can use, what, (a + atan(b/pi))? If you have an ordering in mind, you can consider wrapping your pairs in a type that has your ordering.

于 2013-02-17T23:45:49.220 回答