繁体   English   中英

如何将排序应用于Scala优先级队列?

[英]How to apply ordering to a Scala Priority Queue?

我已经定义了这样的优先级队列

import scala.collection.mutable.PriorityQueue
...
val queue = new PriorityQueue[(Int,Int)]()

我想使用以下顺序:

如果我们比较队列中的两个项目A和B,则如果其(Int,Int)元组的第一个元素大于B的元素,则A 大于 B。 如果它们是相同的,那么A比B大如果的第二个元素(Int,Int)元组比B的

如何定义这种排序?

如果您的元素是Int ,定义这种Ordering的最简单方法是对元素取负数,这些元素应按相反的顺序排序。

您可以使用对象Ordering提供的方法创建Ordering ,并将其显式传递给PriotityQueue

// I'm using the data format, you have provided originally, before the edit
val queue = PriorityQueue(
  (1, (2,3), (4,5)), 
  (2, (3,4), (5,6)), 
  (2, (4,5), (6,7))
)(Ordering.by {
  case (fst, (snd, _), (_, _)) => (fst, -snd)
})

或隐式地:

implicit val MyOrdering: Ordering[(Int, (Int, Int), (Int, Int))] = 
  Ordering.by {
    case (fst, (snd, _), (_, _)) => (fst, -snd)
  }
val queue = PriorityQueue(
  (1, (2,3), (4,5)), 
  (2, (3,4), (5,6)), 
  (2, (4,5), (6,7)))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM