Useful utility functions for NEAT
Useful util functions for implementing the NEAT algorithm
I am going to write some basic utility functions that will help when writing my NEAT algorithm implementation.
Random number generation
package util
import (
"math/rand"
)
// RandFloatProvider returns a random float between min and max.
type RandFloatProvider func(min, max float64) float64
// FloatBetween returns a random float between min and max.
func FloatBetween(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
// RandIntProvider returns a random int between min and max.
type RandIntProvider func(min, max int) int
// IntBetween returns a random int between min and max.
func IntBetween(min, max int) int {
if max < min {
panic("min must be smaller than max")
}
if min == max {
return min
}
return min + rand.Intn((max+1)-min)
}
Slice manipulation
package util
// RemoveSliceIndex removes the given index from a slice.
func RemoveSliceIndex[T any](s []T, i int) []T {
s[i] = s[len(s)-1]
return s[:len(s)-1]
}
// InSlice returns true if the given value is in the slice.
func InSlice[T comparable](s []T, search T) bool {
for _, v := range s {
if v == search {
return true
}
}
return false
}
// RandSliceElement returns a random element from the given slice.
func RandSliceElement[T comparable](s []T) T {
if len(s) == 1 {
return s[0]
}
choice := IntBetween(0, len(s)-1)
return s[choice]
}