🌅
This commit is contained in:
59
solutions/day1/day1.go
Normal file
59
solutions/day1/day1.go
Normal file
@@ -0,0 +1,59 @@
|
||||
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])
|
||||
}
|
||||
Reference in New Issue
Block a user