@@ -4,46 +4,68 @@ import (
4
4
"bufio"
5
5
"log"
6
6
"os"
7
+ "sort"
7
8
"strconv"
8
9
)
9
10
10
11
func main () {
11
- lines := readAllLines ("./2022/day01/input .txt" )
12
+ lines := readAllLines ("./2022/day01/input_test .txt" )
12
13
13
14
log .Println ("Day 01 Part 01" )
14
15
partOne (lines )
16
+ //log.Println("Day 01 Part 02")
17
+ //partTwo(lines)
15
18
}
16
19
17
20
func partOne (lines []string ) {
18
- elfCaloriesMap := getSummedUpCaloriesPerElf (lines )
19
- elf , calories := getElfMostCalories (elfCaloriesMap )
20
- log .Println (elf , calories )
21
+ elves := getElves (lines )
22
+ elvesMostCalories := getElvesMostCalories (elves , 1 )
23
+ solution := 0
24
+ for _ , elf := range elvesMostCalories {
25
+ solution += elf .CaloriesSum
26
+ }
27
+ log .Println (solution )
21
28
}
22
29
23
- func getElfMostCalories (elfMap map [string ]int ) (string , int ) {
24
- var elf = "1"
25
- var calories = 0
26
- for key , value := range elfMap {
27
- if value > calories {
28
- calories = value
29
- elf = key
30
- }
30
+ func partTwo (lines []string ) {
31
+ elves := getElves (lines )
32
+ elvesMostCalories := getElvesMostCalories (elves , 3 )
33
+ solution := 0
34
+ for _ , elf := range elvesMostCalories {
35
+ solution += elf .CaloriesSum
31
36
}
32
- return elf , calories
37
+ log .Println (solution )
38
+ }
39
+
40
+ func getElvesMostCalories (elfs []Elf , count int ) []Elf {
41
+ elvesMostCalories := make ([]Elf , count )
42
+ sort .Slice (elfs , func (i , j int ) bool {
43
+ return elfs [i ].CaloriesSum > elfs [j ].CaloriesSum
44
+ })
45
+ for i , _ := range elvesMostCalories {
46
+ elvesMostCalories [i ] = elfs [i ]
47
+ }
48
+ return elvesMostCalories
49
+ }
50
+
51
+ type Elf struct {
52
+ Number string
53
+ CaloriesSum int
33
54
}
34
55
35
- func getSummedUpCaloriesPerElf (lines []string ) map [ string ] int {
36
- var elfCalories = make ( map [ string ] int )
37
- var elfNumber = 1
38
- for _ , stringCalories := range lines {
39
- if stringCalories == "" {
56
+ func getElves (lines []string ) [] Elf {
57
+ var elves [] Elf
58
+ var elfNumber = 0
59
+ for _ , line := range lines {
60
+ if line == "" {
40
61
elfNumber ++
41
62
} else {
42
- calorie , _ := strconv .Atoi (stringCalories )
43
- elfCalories [strconv .Itoa (elfNumber )] += calorie
63
+ elves [elfNumber ].Number = strconv .Itoa (elfNumber + 1 )
64
+ calorie , _ := strconv .Atoi (line )
65
+ elves [elfNumber ].CaloriesSum += calorie
44
66
}
45
67
}
46
- return elfCalories
68
+ return elves
47
69
}
48
70
49
71
func readAllLines (filePath string ) []string {
0 commit comments