-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday01_calories.go
71 lines (54 loc) · 1.57 KB
/
day01_calories.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
package main
// have to install ioutil
// go get io/ioutil
import (
"fmt"
"io/ioutil"
"log"
"sort"
"strconv"
"strings"
)
func readElfCalorieFile(filePath string) [][]int {
body, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatalf("unable to read file: %v", err)
}
allElfCalories := make([][]int, 0)
// run through each elf seprately
caloriesString := strings.Split(strings.Trim(string(body), "\n"), "\n\n")
for _, elfCaloriesString := range caloriesString {
elfCalories := make([]int, 0)
itemCalories := strings.Split(elfCaloriesString, "\n")
for _, itemCalorie := range itemCalories {
i, _ := strconv.Atoi(itemCalorie)
elfCalories = append(elfCalories, i)
}
allElfCalories = append(allElfCalories, elfCalories)
}
return allElfCalories
}
func sumElfCalories(caloriesByElf [][]int) []int {
// return sorted array
summedCalories := make([]int, 0)
for _, elfCalories := range caloriesByElf {
var currElfTotal = 0
for _, itemCalorie := range elfCalories {
currElfTotal += itemCalorie
}
summedCalories = append(summedCalories, currElfTotal)
}
sort.Ints(summedCalories)
return summedCalories
}
func day01() {
var caloriesByElf = readElfCalorieFile("2022/data/day01_sample.txt")
result := sumElfCalories(caloriesByElf)
if result[len(result)-1] != 24000 {
panic("Part 1 example is failing")
}
caloriesByElf = readElfCalorieFile("2022/data/day01_input.txt")
result = sumElfCalories(caloriesByElf)
fmt.Println("Part 1:", result[len(result)-1])
fmt.Println("Part 2:", result[len(result)-1]+result[len(result)-2]+result[len(result)-3])
}