-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday01-2.go
48 lines (44 loc) · 1.23 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
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
// Read input from file
file, err := os.Open("input.txt")
if err != nil {
fmt.Println("Error opening file")
}
defer file.Close()
scanner := bufio.NewScanner(file)
// Find top three maximum sums of calories
maxThreeCalories := []int{0, 0, 0}
currentElfCalories := 0
for scanner.Scan() {
// Get line from file
line := scanner.Text()
// Convert string to int
calories, _ := strconv.Atoi(line)
// Add calories to current elf
currentElfCalories += calories
// If is different from nil (NULL) then you have found an empty line
if line == "" {
// Check if currentElf has more calories than the maximum
if currentElfCalories > maxThreeCalories[2] {
maxThreeCalories[2] = currentElfCalories
}
if maxThreeCalories[2] > maxThreeCalories[1] {
maxThreeCalories[2], maxThreeCalories[1] = maxThreeCalories[1], maxThreeCalories[2]
}
if maxThreeCalories[2] > maxThreeCalories[0] {
maxThreeCalories[2], maxThreeCalories[0] = maxThreeCalories[0], maxThreeCalories[2]
}
// Start with new Elf
currentElfCalories = 0
}
}
// Print sum of maxThreeCalories
fmt.Println(maxThreeCalories[0] + maxThreeCalories[1] + maxThreeCalories[2])
}