github.com/frodejac/aoc-2022@v0.0.0-20221213081734-037c741b1c89/pkg/arraytools/arraytools.go (about)

     1  package arraytools
     2  
     3  import (
     4  	"github.com/frodejac/aoc-2022/pkg/math"
     5  	"golang.org/x/exp/constraints"
     6  )
     7  
     8  type Number interface {
     9  	constraints.Integer | constraints.Float
    10  }
    11  
    12  func Sum[T Number](array []T) T {
    13  	sum := T(0)
    14  	for _, value := range array {
    15  		sum += value
    16  	}
    17  	return sum
    18  }
    19  
    20  func Max[T Number](array []T) T {
    21  	max := array[0]
    22  	for _, value := range array {
    23  		if value > max {
    24  			max = value
    25  		}
    26  	}
    27  	return max
    28  }
    29  
    30  func Min[T Number](array []T) T {
    31  	min := array[0]
    32  	for _, value := range array {
    33  		if value < min {
    34  			min = value
    35  		}
    36  	}
    37  	return min
    38  }
    39  
    40  func Intersect[T comparable](as, bs []T) []T {
    41  	i := make([]T, 0, math.Max(len(as), len(bs)))
    42  	for _, a := range as {
    43  		for _, b := range bs {
    44  			if a == b {
    45  				i = append(i, a)
    46  			}
    47  		}
    48  	}
    49  	return i
    50  }