gonum.org/v1/gonum@v0.15.1-0.20240517103525-f853624cb1bb/internal/order/order.go (about)

     1  // Copyright ©2024 The Gonum Authors. 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 order
     6  
     7  import (
     8  	"cmp"
     9  	"slices"
    10  	"sort"
    11  
    12  	"gonum.org/v1/gonum/graph"
    13  )
    14  
    15  // ByID sorts a slice of graph.Node by ID.
    16  func ByID(n []graph.Node) {
    17  	sort.Slice(n, func(i, j int) bool { return n[i].ID() < n[j].ID() })
    18  }
    19  
    20  // BySliceValues sorts a slice of []cmp.Ordered lexically by the values of
    21  // the []cmp.Ordered.
    22  func BySliceValues[S interface{ ~[]E }, E cmp.Ordered](c []S) {
    23  	slices.SortFunc(c, func(a, b S) int {
    24  		l := min(len(a), len(b))
    25  		for k, v := range a[:l] {
    26  			if n := cmp.Compare(v, b[k]); n != 0 {
    27  				return n
    28  			}
    29  		}
    30  		return cmp.Compare(len(a), len(b))
    31  	})
    32  }
    33  
    34  // BySliceIDs sorts a slice of []graph.Node lexically by the IDs of the
    35  // []graph.Node.
    36  func BySliceIDs(c [][]graph.Node) {
    37  	sort.Slice(c, func(i, j int) bool {
    38  		a, b := c[i], c[j]
    39  		l := len(a)
    40  		if len(b) < l {
    41  			l = len(b)
    42  		}
    43  		for k, v := range a[:l] {
    44  			if v.ID() < b[k].ID() {
    45  				return true
    46  			}
    47  			if v.ID() > b[k].ID() {
    48  				return false
    49  			}
    50  		}
    51  		return len(a) < len(b)
    52  	})
    53  }
    54  
    55  // LinesByIDs sort a slice of graph.LinesByIDs lexically by the From IDs,
    56  // then by the To IDs, finally by the Line IDs.
    57  func LinesByIDs(n []graph.Line) {
    58  	sort.Slice(n, func(i, j int) bool {
    59  		a, b := n[i], n[j]
    60  		if a.From().ID() != b.From().ID() {
    61  			return a.From().ID() < b.From().ID()
    62  		}
    63  		if a.To().ID() != b.To().ID() {
    64  			return a.To().ID() < b.To().ID()
    65  		}
    66  		return n[i].ID() < n[j].ID()
    67  	})
    68  }