60 lines
1.1 KiB
Go
60 lines
1.1 KiB
Go
package day1
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"sort"
|
|
"strconv"
|
|
)
|
|
|
|
func Run(filename string) {
|
|
file, err := os.Open(filename)
|
|
|
|
if err != nil {
|
|
fmt.Println("Error opening file:", err)
|
|
return
|
|
}
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
scanner.Split(bufio.ScanLines)
|
|
|
|
var elf_totals []int
|
|
var current_total int
|
|
var max_total int
|
|
|
|
max_total = 0
|
|
for scanner.Scan() {
|
|
num, err := strconv.Atoi(scanner.Text())
|
|
|
|
if err == nil {
|
|
current_total += num
|
|
} else {
|
|
// this means we got a newline, I'd guess
|
|
elf_totals = append(elf_totals, current_total)
|
|
|
|
if current_total > max_total {
|
|
max_total = current_total
|
|
}
|
|
|
|
current_total = 0
|
|
}
|
|
}
|
|
|
|
if current_total > 0 {
|
|
elf_totals = append(elf_totals, current_total)
|
|
if current_total > max_total {
|
|
max_total = current_total
|
|
}
|
|
}
|
|
|
|
file.Close()
|
|
|
|
fmt.Println("Maximum food value is", max_total)
|
|
sort.Slice(elf_totals, func(i, j int) bool {
|
|
return elf_totals[i] > elf_totals[j]
|
|
})
|
|
fmt.Println("Top three items are", elf_totals[0:3])
|
|
fmt.Println("which adds to", elf_totals[0]+elf_totals[1]+elf_totals[2])
|
|
}
|