adventofcode/2016/day10/main.go

120 lines
2.3 KiB
Go
Raw Normal View History

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
2016-12-10 17:49:18 +00:00
botNum := inst[0] + inst[1]
botIdx := findBotIdx(botNum)
2016-12-10 17:49:18 +00:00
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])
2016-12-10 17:49:18 +00:00
botNum := inst[4] + inst[5]
botIdx := findBotIdx(botNum)
allBots[botIdx].chips = append(allBots[botIdx].chips, val)
allBots[botIdx].Trigger()
}
}
2016-12-10 17:49:18 +00:00
for i := range allBots {
fmt.Println(allBots[i])
}
}
2016-12-10 17:49:18 +00:00
func findBotIdx(id string) int {
fmt.Println("Find bot", id)
for i := range allBots {
if allBots[i].id == id {
return i
}
}
2016-12-10 17:49:18 +00:00
// We didn't find the bot
b := new(Bot)
b.id = id
allBots = append(allBots, *b)
return len(allBots) - 1
}
type Bot struct {
2016-12-10 17:49:18 +00:00
id string
chips []int
2016-12-10 17:49:18 +00:00
giveLowTo string
giveHighTo string
}
func (b *Bot) Trigger() {
2016-12-10 17:49:18 +00:00
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
}