-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.go
70 lines (55 loc) · 1.24 KB
/
solution.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
package d01
import (
"fmt"
"io"
"sort"
"strconv"
"github.com/Mike-Burton/advent-of-code/helpers"
)
// PartOne solves the first problem of day 1 of Advent of Code 2022.
func PartOne(r io.Reader, w io.Writer) error {
lines, err := elfCalories(r)
if err != nil {
return fmt.Errorf("could not read input: %w", err)
}
_, err = fmt.Fprintf(w, "%d", lines[0])
if err != nil {
return fmt.Errorf("could not write answer: %w", err)
}
return nil
}
// PartTwo solves the second problem of day 1 of Advent of Code 2022.
func PartTwo(r io.Reader, w io.Writer) error {
lines, err := elfCalories(r)
if err != nil {
return fmt.Errorf("could not read input: %w", err)
}
_, err = fmt.Fprintf(w, "%d", lines[0]+lines[1]+lines[2])
if err != nil {
return fmt.Errorf("could not write answer: %w", err)
}
return nil
}
func elfCalories(r io.Reader) ([]int, error) {
lines, err := helpers.LinesFromReader(r)
if err != nil {
return nil, err
}
var elfCals []int
thisElf := 0
for _, l := range lines {
if len(l) == 0 {
elfCals = append(elfCals, thisElf)
thisElf = 0
continue
}
c, err := strconv.Atoi(l)
if err != nil {
return nil, err
}
thisElf += c
}
//
sort.Sort(sort.Reverse(sort.IntSlice(elfCals)))
return elfCals, nil
}