-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathday01_2.go
85 lines (62 loc) · 1.02 KB
/
day01_2.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
package main
import (
"bufio"
"container/heap"
"fmt"
"log"
"os"
"strconv"
)
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 interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
last := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return last
}
func day1_2() {
file, err := os.Open("day01_1.input")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
soFar := 0
h := &IntHeap{}
heap.Init(h)
for scanner.Scan() {
text := scanner.Text()
if text == "" {
heap.Push(h, soFar)
if h.Len() > 3 {
heap.Pop(h)
}
soFar = 0
} else {
value, err := strconv.Atoi(text)
if err != nil {
log.Fatal(err)
}
soFar += value
}
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
total := 0
for _, num := range *h {
total += num
}
fmt.Println(total)
}