commit 3c88a4fbdd32983ee8f4978c94d155a405c550f4 Author: Karl Spickermann Date: Wed Dec 1 22:49:48 2021 +0100 Import helper diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0cda4fb --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module AOC2021 + +go 1.17 diff --git a/src/helper/helper.go b/src/helper/helper.go new file mode 100644 index 0000000..eaf9221 --- /dev/null +++ b/src/helper/helper.go @@ -0,0 +1,100 @@ +package helper + +import ( + "errors" + "io/ioutil" + "sort" + "strconv" + "strings" +) + +func GetInput(filename string) ([]string, error) { + content, err := ioutil.ReadFile(filename) + if err != nil { + return nil, err + } + lines := strings.Split(string(content), "\r\n") + return lines, err +} + +func GetFile(filename string) (string, error) { + content, err := ioutil.ReadFile(filename) + if err != nil { + return "", err + } + return string(content), err +} + +func MapToNumber(strings []string) ([]int, error) { + var numbers []int + for _, line := range strings { + number, err := strconv.Atoi(line) + if err != nil { + return numbers, err + } + numbers = append(numbers, number) + } + return numbers, nil +} + +func FindAddendsForSum(possibleAddends []int, sum int) (int, int, error) { + var array = make([]int, len(possibleAddends)) + copy(array, possibleAddends) + sort.Ints(array) + p1 := 0 + p2 := len(array) - 1 + for p1 < p2 { + if array[p1]+array[p2] < sum { + p1++ + } + if array[p1]+array[p2] > sum { + p2-- + } + if array[p1]+array[p2] == sum { + return array[p1], array[p2], nil + } + } + return 0, 0, errors.New("No fitting Addends found") +} + +func SliceIndex(limit int, predicate func(i int) bool) int { + for i := 0; i < limit; i++ { + if predicate(i) { + return i + } + } + return -1 +} + +func DeleteAt(a []int, i int, ) []int { + return append(a[:i], a[i+1:]...) +} + +func Equal(a, b []int) bool { + if len(a) != len(b) { + return false + } + for i, v := range a { + if v != b[i] { + return false + } + } + return true +} + +func Contains(elem int, array []int) bool{ + for _, val := range array{ + if val == elem{ + return true + } + } + return false +} + +func AddNummbers(numbers ...int) int { + result := 0 + for _, number := range numbers { + result += number + } + return result +}