Skip to content

Instantly share code, notes, and snippets.

@henkman
Created December 15, 2021 16:34
Show Gist options
  • Save henkman/15b15835bd225d9ae0a43fa69e881d8f to your computer and use it in GitHub Desktop.
Save henkman/15b15835bd225d9ae0a43fa69e881d8f to your computer and use it in GitHub Desktop.
package main
import (
"sort"
"fmt"
"constraints"
)
type Vec2[T constraints.Ordered] struct {
X, Y T
}
func (v Vec2[T]) Add (o Vec2[T]) Vec2[T] {
return Vec2[T]{
X: v.X + o.X,
Y: v.Y + o.Y,
}
}
func (v Vec2[T]) Eq (o Vec2[T]) bool {
return v.X == o.X && v.Y == o.Y
}
func Reverse [T any] (s []T) {
first := 0
last := len(s) - 1
for first < last {
s[first], s[last] = s[last], s[first]
first++
last--
}
}
func Min [T constraints.Ordered] (x, y T) T {
if x > y {
return y
}
return x
}
func Max [T constraints.Ordered] (x, y T) T {
if x < y {
return y
}
return x
}
func SliceMin [T constraints.Ordered] (s []T) T {
r := s[0]
for _, v := range s[1:] {
if v < r {
r = v
}
}
return r
}
func SliceMax [T constraints.Ordered] (s []T) T {
r := s[0]
for _, v := range s[1:] {
if v > r {
r = v
}
}
return r
}
func Abs [T constraints.Signed] (x T) T {
if x < 0 {
return -x
}
return x
}
type orderedSlice[T constraints.Ordered] []T
func (s orderedSlice[T]) Len() int { return len(s) }
func (s orderedSlice[T]) Less(i, j int) bool { return s[i] < s[j] }
func (s orderedSlice[T]) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func OrderedSlice[T constraints.Ordered](s []T) {
sort.Sort(orderedSlice[T](s))
}
func main() {
var v = Vec2[int]{3, 6}
var o = Vec2[int]{15, 12}
fmt.Println(v.Add(o))
data := []int{5,8,1,9,3,5,7,12,5,2,6,8,3}
OrderedSlice(data)
fmt.Println(data)
fmt.Println(Abs(1+5))
fmt.Println(Abs(1-5))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment