github.com/chain5j/chain5j-pkg@v1.0.7/collection/queues/preque/prque.go (about)

     1  // CookieJar - A contestant's algorithm toolbox
     2  // Copyright (c) 2013 Peter Szilagyi. All rights reserved.
     3  //
     4  // CookieJar is dual licensed: use of this source code is governed by a BSD
     5  // license that can be found in the LICENSE file. Alternatively, the CookieJar
     6  // toolbox may be used in accordance with the terms and conditions contained
     7  // in a signed written agreement between you and the author(s).
     8  
     9  // Package prque implements a priority queue data structure supporting arbitrary
    10  // value types and float priorities.
    11  //
    12  // The reasoning behind using floats for the priorities vs. ints or interfaces
    13  // was larger flexibility without sacrificing too much performance or code
    14  // complexity.
    15  //
    16  // If you would like to use a min-priority queue, simply negate the priorities.
    17  //
    18  // Internally the queue is based on the standard heap package working on a
    19  // sortable version of the block based stack.
    20  package prque
    21  
    22  import (
    23  	"container/heap"
    24  	"sort"
    25  )
    26  
    27  // Prque Priority queue data structure.
    28  type Prque struct {
    29  	cont *sstack
    30  }
    31  
    32  // New Creates a new priority queue.
    33  func New() *Prque {
    34  	return &Prque{newSstack()}
    35  }
    36  
    37  // Push a value with a given priority into the queue, expanding if necessary.
    38  func (p *Prque) Push(data interface{}, priority float32) {
    39  	heap.Push(p.cont, &item{data, priority})
    40  }
    41  
    42  // Pop the value with the greates priority off the stack and returns it.
    43  // Currently no shrinking is done.
    44  func (p *Prque) Pop() (interface{}, float32) {
    45  	item := heap.Pop(p.cont).(*item)
    46  	return item.value, item.priority
    47  }
    48  
    49  // PopItem Pops only the item from the queue, dropping the associated priority value.
    50  func (p *Prque) PopItem() interface{} {
    51  	return heap.Pop(p.cont).(*item).value
    52  }
    53  func (p *Prque) PeekFront() (interface{}, float32) {
    54  	res := p.cont.PeekFront()
    55  	if res == nil {
    56  		return nil, 0
    57  	}
    58  	item := res.(*item)
    59  	return item.value, item.priority
    60  }
    61  
    62  // Empty Checks whether the priority queue is empty.
    63  func (p *Prque) Empty() bool {
    64  	return p.cont.Len() == 0
    65  }
    66  
    67  // Size Returns the number of element in the priority queue.
    68  func (p *Prque) Size() int {
    69  	return p.cont.Len()
    70  }
    71  
    72  // Reset Clears the contents of the priority queue.
    73  func (p *Prque) Reset() {
    74  	*p = *New()
    75  }
    76  
    77  func (p *Prque) Sort() {
    78  	sort.Sort(p.cont)
    79  }