-
Notifications
You must be signed in to change notification settings - Fork 3
/
day01.go
110 lines (90 loc) · 1.91 KB
/
day01.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Package main provides ...
package main
import "fmt"
import "os"
import "bufio"
import "log"
import "strconv"
import "container/heap"
// An IntHeap is a max-heap of ints.
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Push(x any) {
// Push and Pop use pointer receivers because they modify the slice's length,
// not just its contents.
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() any {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}
func Parse(filename string) [][]int {
outer := make([][]int, 0)
inner := make([]int, 0)
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if text == "" {
outer = append(outer, inner)
inner = make([]int, 0)
continue
}
num, err := strconv.Atoi(text)
if err != nil {
log.Fatal(err)
}
inner = append(inner, num)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
outer = append(outer, inner)
return outer
}
func elfCalories(elf []int) int {
calories := 0
for _, item := range elf {
calories += item
}
return calories
}
func PartOne(elves [][]int) int {
maxCalories := 0
for _, elf := range elves {
calories := elfCalories(elf)
if calories > maxCalories {
maxCalories = calories
}
}
return maxCalories
}
func PartTwo(elves [][]int) int {
h := &IntHeap{}
heap.Init(h)
for _, elf := range elves {
calories := elfCalories(elf)
heap.Push(h, calories)
}
topThree := 0
for i := 0; i < 3; i++ {
topThree += heap.Pop(h).(int)
}
return topThree
}
func main() {
elves := Parse("../../inputs/01/input.txt")
fmt.Print("Part 1: ")
fmt.Println(PartOne(elves))
fmt.Print("Part 2: ")
fmt.Println(PartTwo(elves))
}