adventofcode/day10/main.go

120 lines
2.3 KiB
Go

package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
var allBots []Bot
var watch1, watch2 int
//var outputBins map[int][]int
func main() {
input := stdinToStringSlice()
for i := 0; i < 500; i++ {
allBots = append(allBots, Bot{id: i})
}
watch1 = 61
watch2 = 17
//outputBins := make(map[int][]int)
for i := range input {
inst := strings.Fields(input[i])
if inst[0] == "bot" {
// And instruction
// make sure we have this bot
botNum := atoi(inst[1])
botIdx := findBotIdx(botNum)
if inst[5] == "bot" {
allBots[botIdx].giveLowTo = atoi(inst[6])
}
if inst[10] == "bot" {
allBots[botIdx].giveHighTo = atoi(inst[11])
}
}
}
// Run sim
for i := range input {
inst := strings.Fields(input[i])
if inst[0] == "value" {
val := atoi(inst[1])
botNum := atoi(inst[5])
botIdx := findBotIdx(botNum)
allBots[botIdx].chips = append(allBots[botIdx].chips, val)
allBots[botIdx].Trigger()
}
}
}
func findBotIdx(id int) int {
for i := range allBots {
if allBots[i].id == id {
return i
}
}
return -1
}
type Bot struct {
id int
chips []int
giveLowTo int
giveHighTo int
}
func (b *Bot) Trigger() {
if len(b.chips) == 2 {
fmt.Println("Triggering", b.id, b.chips)
//checkWatches(b)
low := b.chips[0]
high := b.chips[1]
if b.chips[0] > b.chips[1] {
high = b.chips[0]
low = b.chips[1]
}
giveLowIdx := findBotIdx(b.giveLowTo)
fmt.Println("Trig2: ", b.giveLowTo, allBots[giveLowIdx])
allBots[giveLowIdx].chips = append(allBots[giveLowIdx].chips, low)
fmt.Println("3")
giveHighIdx := findBotIdx(b.giveHighTo)
allBots[giveHighIdx].chips = append(allBots[giveHighIdx].chips, high)
allBots[giveLowIdx].Trigger()
allBots[giveHighIdx].Trigger()
}
}
func checkWatches(b *Bot) {
if b.chips[0] == watch1 && b.chips[1] == watch2 || b.chips[0] == watch1 && b.chips[1] == watch2 {
fmt.Println("Watch triggered:", b.id)
}
}
func stdinToStringSlice() []string {
var input []string
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
input = append(input, scanner.Text())
}
return input
}
func itoa(i int) string {
return strconv.Itoa(i)
}
func atoi(i string) int {
var ret int
var err error
if ret, err = strconv.Atoi(i); err != nil {
log.Fatal("Invalid Atoi")
}
return ret
}