github.com/mit-dci/lit@v0.0.0-20221102210550-8c3d3b49f2ce/qln/heap.go (about)

     1  package qln
     2  
     3  type nodeWithDist struct {
     4  	Dist float64
     5  	Node int
     6  	Amt  int64
     7  }
     8  
     9  // distanceHeap is a min-distance heap that's used within our path finding
    10  // algorithm to keep track of the "closest" node to our source node.
    11  type distanceHeap struct {
    12  	nodes []nodeWithDist
    13  }
    14  
    15  // Len returns the number of nodes in the priority queue.
    16  //
    17  // NOTE: This is part of the heap.Interface implementation.
    18  func (d *distanceHeap) Len() int { return len(d.nodes) }
    19  
    20  // Less returns whether the item in the priority queue with index i should sort
    21  // before the item with index j.
    22  //
    23  // NOTE: This is part of the heap.Interface implementation.
    24  func (d *distanceHeap) Less(i, j int) bool {
    25  	return d.nodes[i].Dist < d.nodes[j].Dist
    26  }
    27  
    28  // Swap swaps the nodes at the passed indices in the priority queue.
    29  //
    30  // NOTE: This is part of the heap.Interface implementation.
    31  func (d *distanceHeap) Swap(i, j int) {
    32  	d.nodes[i], d.nodes[j] = d.nodes[j], d.nodes[i]
    33  }
    34  
    35  // Push pushes the passed item onto the priority queue.
    36  //
    37  // NOTE: This is part of the heap.Interface implementation.
    38  func (d *distanceHeap) Push(x interface{}) {
    39  	d.nodes = append(d.nodes, x.(nodeWithDist))
    40  }
    41  
    42  // Pop removes the highest priority item (according to Less) from the priority
    43  // queue and returns it.
    44  //
    45  // NOTE: This is part of the heap.Interface implementation.
    46  func (d *distanceHeap) Pop() interface{} {
    47  	n := len(d.nodes)
    48  	x := d.nodes[n-1]
    49  	d.nodes = d.nodes[0 : n-1]
    50  	return x
    51  }