adventofcode/2016/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()
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 := inst[0] + inst[1]
botIdx := findBotIdx(botNum)
allBots[botIdx].giveLowTo = inst[5] + inst[6]
allBots[botIdx].giveHighTo = inst[10] + inst[11]
}
}
// Run sim
for i := range input {
inst := strings.Fields(input[i])
if inst[0] == "value" {
val := atoi(inst[1])
botNum := inst[4] + inst[5]
botIdx := findBotIdx(botNum)
allBots[botIdx].chips = append(allBots[botIdx].chips, val)
allBots[botIdx].Trigger()
}
}
for i := range allBots {
fmt.Println(allBots[i])
}
}
func findBotIdx(id string) int {
fmt.Println("Find bot", id)
for i := range allBots {
if allBots[i].id == id {
return i
}
}
// We didn't find the bot
b := new(Bot)
b.id = id
allBots = append(allBots, *b)
return len(allBots) - 1
}
type Bot struct {
id string
chips []int
giveLowTo string
giveHighTo string
}
func (b *Bot) Trigger() {
if strings.HasPrefix(b.id, "output") {
return
}
if len(b.chips) == 2 {
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)
allBots[giveLowIdx].chips = append(allBots[giveLowIdx].chips, low)
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
}