AOC2022/helper/helper.go

99 lines
1.6 KiB
Go
Raw Normal View History

2022-12-03 03:40:46 +01:00
package helper
import (
2022-12-11 04:28:52 +01:00
"constraints"
2022-12-07 16:45:39 +01:00
"fmt"
2022-12-03 03:40:46 +01:00
"os"
"strings"
2022-12-07 16:45:39 +01:00
"time"
2022-12-03 03:40:46 +01:00
)
func check(e error) {
if e != nil {
panic(e)
}
}
func RemoveError[T any](value T, e error) T {
check(e)
return value
}
func ReadTextFile(filePath string) []string {
file, err := os.ReadFile(filePath)
check(err)
return strings.Split(string(file), "\r\n")
}
2022-12-06 10:44:00 +01:00
func GetKeysOfSetMap[T int | string](inputMap map[T]bool) []T {
keys := make([]T, len(inputMap))
i := 0
for k := range inputMap {
keys[i] = k
i++
}
return keys
}
2022-12-07 16:45:39 +01:00
func MeasureTime(process string) func() {
fmt.Printf("Start %s\n", process)
start := time.Now()
return func() {
2022-12-07 18:47:24 +01:00
fmt.Printf("Time taken by %s is %v\n", process, time.Since(start).Nanoseconds())
2022-12-07 16:45:39 +01:00
}
}
2022-12-04 23:09:37 +01:00
func FindRepeatedItems[T int | int64](itemgroup1, itemgroup2 []T) []T {
elementsCompartment1 := map[T]bool{}
repeatedElemnts := map[T]bool{}
for _, item := range itemgroup1 {
elementsCompartment1[item] = true
}
for _, item := range itemgroup2 {
if elementsCompartment1[item] {
repeatedElemnts[item] = true
}
}
v := make([]T, 0, len(repeatedElemnts))
for key, _ := range repeatedElemnts {
v = append(v, key)
}
return v
}
2022-12-03 03:40:46 +01:00
func FindMax[T int | int64](slice []T) (m T) {
for i, e := range slice {
if i == 0 || e > m {
m = e
}
}
return
}
func Sum[T int | int64](slice []T) (s T) {
for _, e := range slice {
s += e
}
return
}
2022-12-09 21:37:26 +01:00
2022-12-11 04:28:52 +01:00
func Contains2Int[T [2]int](elems []T, v T) bool {
for _, s := range elems {
if v == s {
return true
}
}
return false
}
func Contains[T constraints.Ordered](elems []T, v T) bool {
2022-12-09 21:37:26 +01:00
for _, s := range elems {
if v == s {
return true
}
}
return false
}