87 lines
1.2 KiB
Go
87 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strconv"
|
|
)
|
|
|
|
func parseBank(text string) []int {
|
|
bank := make([]int, 0, len(text))
|
|
for _, char := range text {
|
|
battery, err := strconv.Atoi(string(char))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
bank = append(bank, battery)
|
|
}
|
|
|
|
return bank
|
|
}
|
|
|
|
func main() {
|
|
|
|
file, err := os.Open("three.txt")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer file.Close()
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
ch := make(chan int)
|
|
n_banks := 0
|
|
jolts := 0
|
|
|
|
for scanner.Scan() {
|
|
n_banks++
|
|
text := scanner.Text()
|
|
|
|
bank := parseBank(text)
|
|
|
|
go joltage(bank, ch)
|
|
}
|
|
|
|
for i := 0; i < n_banks; i++ {
|
|
jolts += <-ch
|
|
}
|
|
|
|
fmt.Println(jolts)
|
|
}
|
|
|
|
func joltage(bank []int, ch chan int) {
|
|
ch <- _joltage(bank)
|
|
}
|
|
|
|
func _joltage(bank []int) int {
|
|
out := 0
|
|
|
|
startIndex := 0
|
|
|
|
for endIndex := len(bank) - 11; endIndex <= len(bank); endIndex++ {
|
|
|
|
out *= 10
|
|
highest, index := highestEarly(bank, startIndex, endIndex)
|
|
out += highest
|
|
startIndex = index + 1
|
|
|
|
}
|
|
|
|
return out
|
|
}
|
|
|
|
func highestEarly(bank []int, start int, end int) (int, int) {
|
|
highest := 0
|
|
index := 0
|
|
|
|
for i := start; i < end; i++ {
|
|
val := bank[i]
|
|
if val > highest {
|
|
highest = val
|
|
index = i
|
|
}
|
|
}
|
|
|
|
return highest, index
|
|
}
|