Added map and reduce to utils with testing code in day5

main
oabrivard 2 years ago
parent 25d07f62b8
commit 870c689063

@ -1,6 +1,11 @@
package day15
import "strconv"
import (
"strconv"
"strings"
"gitea.paas.celticinfo.fr/oabrivard/aoc2023/utils"
)
func hash(bytes []byte) int {
val := 0
@ -169,3 +174,20 @@ func SumBoxes(line string) int {
return sum
}
func Hash(bytes []byte) int {
return utils.Reduce(bytes, 0, func(acc int, curr byte) int {
return (acc + int(curr)) * 17 % 256
})
}
func Part1(line string) int {
/*
fmt.Println(utils.Reduce(
utils.Map(strings.Split(line, ","), func(step string) int { return Hash([]byte(step)) }),
0,
func(acc int, curr int) int { return acc + curr }))
*/
hashes := utils.Map(strings.Split(line, ","), func(step string) int { return Hash([]byte(step)) })
return utils.Reduce(hashes, 0, func(acc int, curr int) int { return acc + curr })
}

@ -73,3 +73,13 @@ func TestSumBoxesWithInput(t *testing.T) {
t.Fatalf("expected 290779, got %v", result)
}
}
func TestPart1WithInput(t *testing.T) {
lines := utils.ReadLines("input.txt")
result := Part1(lines[0])
if result != 511416 {
t.Fatalf("expected 511416, got %v", result)
}
}

@ -175,3 +175,19 @@ func RotateClockwise[T any](slice [][]T) [][]T {
}
return result
}
func Reduce[T, M any](s []T, initValue M, f func(M, T) M) M {
acc := initValue
for _, v := range s {
acc = f(acc, v)
}
return acc
}
func Map[T, M any](s []T, f func(T) M) []M {
res := []M{}
for _, v := range s {
res = append(res, f(v))
}
return res
}

Loading…
Cancel
Save