Sunday, 15 February 2015

tuples - How to use priority queues in Scala? -



tuples - How to use priority queues in Scala? -

i trying implement a* search in scala (version 2.10), i've ran brick wall - can't figure out how utilize scala's priority queue. seems simple task, searching on google didn't turn (except single code sample stopped working in version 2.8)

i have set of squares, represented (int, int)s, , need insert them priorities represented ints. in python it's pretty simple, since have list of key, value pairs , utilize heapq functions sort it. appears scala's tuples aren't comparable.

so how do this? i'm surprised finish lack of online information, given how simple should be.

there pre-defined lexicographical order tuples -- but need import it:

import scala.math.ordering.implicits._

moreover, can define own ordering. suppose want arrange tuples, based on difference between first , sec members of 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))

scala tuples priority-queue scala-collections

No comments:

Post a Comment