【问题标题】:Using two different priority queues in Golang在 Golang 中使用两个不同的优先级队列
【发布时间】:2022-01-06 01:09:36
【问题描述】:

我是 Gopher Noob。我最近遇到了这个关于在 Golang 中实现优先级队列的问题。我通过https://pkg.go.dev/container/heap@go1.17.3 实现了优先级队列。只需为容器实现 heap.Interface 即可。它很简单,我对此没有任何疑问。

我的问题是: 我需要两个优先级队列。一种是最小和最大优先级队列。在 Java 中,这很容易被初始化。我只需要在初始化期间更改比较器就可以了。 在 golang 中,我只需要更改 sort.Interface 中的 Less 方法就可以了。 然而,我对编写冗余代码不感兴趣,我正在寻找更简洁的方法来创建两个优先级队列。

这是我想要做的一个例子:

// A PriorityQueue1

type PriorityQueue1 []*Item

// Implement all the following methods for the min Prioirity queue
func (pq PriorityQueue1) Len() int { return len(pq) }

func (pq PriorityQueue1) Less(i, j int) bool {
    // We want Pop to give us the highest, not lowest, priority so we use greater than here.
    return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue1) Swap(i, j int) {
  //Swap
}

func (pq *PriorityQueue1) Push(x interface{}) {
  //Define push logic
}

func (pq *PriorityQueue1) Pop() interface{} {
  //Define pop logic
}

Now, I define the maximum priority queue (**everything is the same except Less**), which goes like this.. 

// A PriorityQueue2

type PriorityQueue2 []*Item

// Implement all the following methods for the max Prioirity queue
func (pq PriorityQueue2) Len() int { return len(pq) }

func (pq PriorityQueue2) Less(i, j int) bool {
    return **pq[i].priority < pq[j].priority**  // Thats it. One line change..
}

func (pq PriorityQueue2) Swap(i, j int) {
  //Swap
}

func (pq *PriorityQueue2) Push(x interface{}) {
  //Define push logic
}

func (pq *PriorityQueue2) Pop() interface{} {
  //Define pop logic
}

现在我为什么要经历这种重写几乎与最小队列相同的方法来改变Less中的一行。我希望减少样板,我想知道解决这个问题的最简洁明了的方法是什么。我也对使用任何第三方库不感兴趣(但我对它的逻辑感兴趣,如果有一个提供干净的包装器)。

请提供一些意见。谢谢..

【问题讨论】:

  • 您可以在go中查看适配器模式

标签: go design-patterns priority-queue


【解决方案1】:

您可以将该函数作为依赖项注入到 Priority Queue 结构的构造函数中。

它应该如下工作:

type Item int

type PriorityQueue []Item

var lesser LessFunction

func GetPriorityQueue(l LessFunction) PriorityQueue {
    lesser = l
    return []Item{}
}

type LessFunction func(i, j int) bool

func (pq PriorityQueue) Less(i, j int) bool {
    return lesser(i, j)
}

在代码中使用如下:

q := GetPriorityQueue(func(i, j int) bool { return i < j })

请注意:
除了我所展示的之外,还有多种方法可以解决这个问题。这显示了与 Java 的 lambda 函数的相似性。

【讨论】:

  • 谢谢。那行得通。只是想知道还有什么其他方法?
猜你喜欢
  • 2019-04-21
  • 2023-04-02
  • 1970-01-01
  • 2016-12-19
  • 2014-01-19
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 2011-12-20
相关资源
最近更新 更多