github.com/searKing/golang/go@v1.2.117/exp/slices/heap_test.go (about)

     1  // Copyright 2023 The searKing Author. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slices_test
     6  
     7  import (
     8  	"cmp"
     9  	"container/heap"
    10  	"fmt"
    11  
    12  	"github.com/searKing/golang/go/exp/slices"
    13  )
    14  
    15  // This example inserts several ints into an MinHeap, checks the minimum,
    16  // and removes them in order of priority.
    17  func Example_minHeap() {
    18  	h := &slices.MinHeap[int]{2, 1, 5}
    19  	heap.Init(h)
    20  	heap.Push(h, 3)
    21  	fmt.Printf("minimum: %d\n", (*h)[0])
    22  	for h.Len() > 0 {
    23  		fmt.Printf("%d ", heap.Pop(h))
    24  	}
    25  
    26  	// Output:
    27  	// minimum: 1
    28  	// 1 2 3 5
    29  }
    30  
    31  // This example inserts several ints into an MaxHeap, checks the maximum,
    32  // and removes them in order of priority.
    33  func Example_maxHeap() {
    34  	h := &slices.MaxHeap[int]{2, 1, 5}
    35  	heap.Init(h)
    36  	heap.Push(h, 3)
    37  	fmt.Printf("maximum: %d\n", (*h)[0])
    38  	for h.Len() > 0 {
    39  		fmt.Printf("%d ", heap.Pop(h))
    40  	}
    41  
    42  	// Output:
    43  	// maximum: 5
    44  	// 5 3 2 1
    45  }
    46  
    47  // This example inserts several ints into an Min Heap, checks the minimum,
    48  // and removes them in order of priority.
    49  func Example_heapMin() {
    50  	h := slices.NewHeapMin([]int{2, 1, 5})
    51  	heap.Init(h)
    52  	heap.Push(h, 3)
    53  	fmt.Printf("minimum: %d\n", h.S[0])
    54  	for h.Len() > 0 {
    55  		fmt.Printf("%d ", heap.Pop(h))
    56  	}
    57  
    58  	// Output:
    59  	// minimum: 1
    60  	// 1 2 3 5
    61  }
    62  
    63  // This example inserts several ints into an Max Heap, checks the maximum,
    64  // and removes them in order of priority.
    65  func Example_heapMax() {
    66  	h := slices.NewHeapMax([]int{2, 1, 5})
    67  	heap.Init(h)
    68  	heap.Push(h, 3)
    69  	fmt.Printf("maximum: %d\n", h.S[0])
    70  	for h.Len() > 0 {
    71  		fmt.Printf("%d ", heap.Pop(h))
    72  	}
    73  
    74  	// Output:
    75  	// maximum: 5
    76  	// 5 3 2 1
    77  }
    78  
    79  // This example inserts several ints into an Min Heap, checks the minimum,
    80  // and removes them in order of priority.
    81  func Example_heapFunc() {
    82  	h := slices.NewHeapFunc([]int{2, 1, 5}, cmp.Compare[int])
    83  	heap.Init(h)
    84  	heap.Push(h, 3)
    85  	fmt.Printf("minimum: %d\n", h.S[0])
    86  	for h.Len() > 0 {
    87  		fmt.Printf("%d ", heap.Pop(h))
    88  	}
    89  
    90  	// Output:
    91  	// minimum: 1
    92  	// 1 2 3 5
    93  }