Day 8: registers

This commit is contained in:
Meutel 2017-12-10 17:32:13 +01:00
parent 7530c41af3
commit 680a7edce4
2 changed files with 104 additions and 0 deletions

4
08dec/input_test Normal file
View File

@ -0,0 +1,4 @@
b inc 5 if a > 1
a inc 1 if b < 5
c dec -10 if a >= 1
c inc -20 if c == 10

100
08dec/main.go Normal file
View File

@ -0,0 +1,100 @@
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
}