Skip to content

Commit 07441b4

Browse files
committed
Add helpers for finding sum and product
1 parent ea0d40f commit 07441b4

File tree

4 files changed

+38
-19
lines changed

4 files changed

+38
-19
lines changed

day02/day02.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import (
66
"os"
77
"strconv"
88
"strings"
9+
10+
"github.com/aaronbee/aoc2023"
911
)
1012

1113
func main() {
@@ -97,9 +99,5 @@ func (cntr counter) union(o counter) {
9799
}
98100

99101
func (cntr counter) power() int {
100-
p := 1
101-
for _, c := range cntr {
102-
p *= c
103-
}
104-
return p
102+
return aoc2023.ProdMapVal(cntr)
105103
}

day03/day03.go

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import (
55
"os"
66
"strconv"
77
"strings"
8+
9+
"github.com/aaronbee/aoc2023"
810
)
911

1012
func main() {
@@ -37,11 +39,8 @@ func part1(data []string) int {
3739
i = x + 1
3840
}
3941
}
40-
sum := 0
41-
for _, part := range parts {
42-
sum += part
43-
}
44-
return sum
42+
43+
return aoc2023.SumMapVal(parts)
4544
}
4645

4746
func addPartsNear(data []string, parts map[loc]int, x, y int) {
@@ -113,9 +112,5 @@ func gearRatio(data []string, x, y int) int {
113112
if len(parts) != 2 {
114113
return 0
115114
}
116-
ratio := 1
117-
for _, part := range parts {
118-
ratio *= part
119-
}
120-
return ratio
115+
return aoc2023.ProdMapVal(parts)
121116
}

day04/day04.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"fmt"
55
"os"
66
"strings"
7+
8+
"github.com/aaronbee/aoc2023"
79
)
810

911
func main() {
@@ -26,10 +28,7 @@ func main() {
2628
counts[n+i+1] += count
2729
}
2830
}
29-
var part2 int
30-
for _, v := range counts {
31-
part2 += v
32-
}
31+
part2 := aoc2023.SumSlice(counts)
3332
fmt.Println("Part 1:", part1)
3433
fmt.Println("Part 2:", part2)
3534
}

utils.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package aoc2023
2+
3+
type addable interface {
4+
~int8 | ~uint8 | ~int16 | ~uint16 | ~int32 | ~uint32 | ~int64 | ~uint64 | ~int | ~uint
5+
}
6+
7+
func SumSlice[S ~[]V, V addable](s S) (sum V) {
8+
for _, v := range s {
9+
sum += v
10+
}
11+
return sum
12+
}
13+
14+
func SumMapVal[M ~map[K]V, K comparable, V addable](m M) (sum V) {
15+
for _, v := range m {
16+
sum += v
17+
}
18+
return sum
19+
}
20+
21+
func ProdMapVal[M ~map[K]V, K comparable, V addable](m M) (prod V) {
22+
prod = 1
23+
for _, v := range m {
24+
prod *= v
25+
}
26+
return prod
27+
}

0 commit comments

Comments
 (0)