adventofcode/08dec/main.go
2017-12-10 17:32:13 +01:00

101 lines
1.8 KiB
Go

package main
import (
"bufio"
"fmt"
"log"
"os"
"strconv"
"strings"
)
var (
registers map[string]int
)
type Instr struct {
TargetReg string
Op string
Var int
CondReg string
Cond string
CondVal int
}
func (i Instr) String() string {
return i.TargetReg + " " + i.Op + " " + strconv.Itoa(i.Var) + " if " + i.CondReg + " " + i.Cond + " " + strconv.Itoa(i.CondVal)
}
func main() {
registers = make(map[string]int)
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
instr := parseLine(sc.Text())
if cond(instr) {
run(instr)
}
}
var maxreg string
var maxval int
for reg, val := range registers {
if val >= maxval {
maxval = val
maxreg = reg
}
}
fmt.Println(registers)
fmt.Println(maxreg)
fmt.Println(maxval)
}
func cond(instr Instr) bool {
switch instr.Cond {
case "<":
return registers[instr.CondReg] < instr.CondVal
case ">":
return registers[instr.CondReg] > instr.CondVal
case ">=":
return registers[instr.CondReg] >= instr.CondVal
case "<=":
return registers[instr.CondReg] <= instr.CondVal
case "==":
return registers[instr.CondReg] == instr.CondVal
case "!=":
return registers[instr.CondReg] != instr.CondVal
}
return false
}
func run(instr Instr) {
switch instr.Op {
case "inc":
registers[instr.TargetReg] = registers[instr.TargetReg] + instr.Var
case "dec":
registers[instr.TargetReg] = registers[instr.TargetReg] - instr.Var
}
}
func parseLine(in string) Instr {
//fmt.Println(in)
toks := strings.Split(in, " ")
if len(toks) != 7 {
log.Fatalln("Invalid instruction", in)
}
v, _ := strconv.Atoi(toks[2])
c, _ := strconv.Atoi(toks[6])
i := Instr{
toks[0],
toks[1],
v,
toks[4],
toks[5],
c,
}
//fmt.Println(i)
if in != i.String() {
log.Fatalln("Parse error")
}
return i
}