Skip to content

Instantly share code, notes, and snippets.

@donatj donatj/day7.go
Last active Dec 17, 2015

Embed
What would you like to do?
package main
import (
"fmt"
"strconv"
"strings"
)
var input = `bn RSHIFT 2 -> bo
lf RSHIFT 1 -> ly
... more input ...`
func main() {
wires := make(map[string]uint16)
pile := input
for {
pile = parseInput(pile, &wires)
if pile == "" {
break
}
fmt.Println(wires, len(pile))
}
fmt.Println("answer:", wires["a"])
}
func parseInput(in string, wires *map[string]uint16) string {
getVal := func(key string) (uint16, error) {
i, err := strconv.Atoi(key)
if err != nil {
if a, b := (*wires)[key]; b {
return a, nil
} else {
return 0, fmt.Errorf("undefined")
}
}
return uint16(i), nil
}
pile := ""
sets := strings.Split(in, "\n")
for _, set := range sets {
parts := strings.Split(set, " ")
num := len(parts)
if num == 3 {
a, err1 := getVal(parts[0])
if err1 != nil {
pile += set + "\n"
continue
}
(*wires)[parts[2]] = a
} else if num == 4 {
a, err1 := getVal(parts[1])
if err1 != nil {
pile += set + "\n"
continue
}
switch parts[0] {
case "NOT":
(*wires)[parts[3]] = ^a
default:
panic("unhandled operator")
}
} else if num == 5 {
a, err1 := getVal(parts[0])
b, err2 := getVal(parts[2])
if err1 != nil || err2 != nil {
pile += set + "\n"
continue
}
switch parts[1] {
case "AND":
(*wires)[parts[4]] = a & b
break
case "OR":
(*wires)[parts[4]] = a | b
break
case "LSHIFT":
(*wires)[parts[4]] = a << b
break
case "RSHIFT":
(*wires)[parts[4]] = a >> b
break
default:
panic("unhandled operator")
}
} else {
panic("unhandled size")
}
}
return strings.TrimSpace(pile)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.