105 lines
2.6 KiB
Go
105 lines
2.6 KiB
Go
package day07
|
|
|
|
import (
|
|
"strconv"
|
|
"strings"
|
|
"tools"
|
|
)
|
|
|
|
func calcWires(wires map[string]uint16, input []string, ignoreInputWire string) map[string]uint16 {
|
|
for len(input) > 0 {
|
|
var leftOver []string
|
|
for _, v := range input {
|
|
instructions := strings.Split(v, " -> ")
|
|
if instructions[1] == ignoreInputWire {
|
|
continue
|
|
}
|
|
values := strings.Split(instructions[0], " ")
|
|
if len(values) == 1 { // assign number or other wire to wire
|
|
preInt, err := strconv.Atoi(values[0])
|
|
if err == nil {
|
|
wires[instructions[1]] = uint16(preInt)
|
|
} else {
|
|
if _, ok := wires[values[0]]; ok {
|
|
wires[instructions[1]] = wires[values[0]]
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
}
|
|
|
|
} else if len(values) == 2 { // NOT
|
|
if _, ok := wires[values[1]]; ok {
|
|
wires[instructions[1]] = ^wires[values[1]]
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
} else { // wire (AND|RSHIFT|LSHFIT|OR)
|
|
switch values[1] {
|
|
case "AND":
|
|
theOne, err := strconv.Atoi(values[0])
|
|
theUINT16One := uint16(theOne)
|
|
if _, ok := wires[values[0]]; ok || err == nil {
|
|
if _, ok := wires[values[2]]; ok {
|
|
if err == nil {
|
|
wires[instructions[1]] = theUINT16One & wires[values[2]]
|
|
} else {
|
|
wires[instructions[1]] = wires[values[0]] & wires[values[2]]
|
|
}
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
case "OR":
|
|
if _, ok := wires[values[0]]; ok {
|
|
if _, ok := wires[values[2]]; ok {
|
|
wires[instructions[1]] = wires[values[0]] | wires[values[2]]
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
case "LSHIFT":
|
|
if _, ok := wires[values[0]]; ok {
|
|
shifter, _ := strconv.Atoi(values[2])
|
|
wires[instructions[1]] = wires[values[0]] << shifter
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
case "RSHIFT":
|
|
if _, ok := wires[values[0]]; ok {
|
|
shifter, _ := strconv.Atoi(values[2])
|
|
wires[instructions[1]] = wires[values[0]] >> shifter
|
|
} else {
|
|
leftOver = append(leftOver, v)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
input = leftOver
|
|
}
|
|
|
|
return wires
|
|
}
|
|
|
|
func Part1(puzzle tools.AoCPuzzle) interface{} {
|
|
input := puzzle.GetInputArray()
|
|
wires := make(map[string]uint16)
|
|
wires = calcWires(wires, input, "")
|
|
return int(wires["a"])
|
|
}
|
|
|
|
func Part2(puzzle tools.AoCPuzzle) interface{} {
|
|
input := puzzle.GetInputArray()
|
|
wires := make(map[string]uint16)
|
|
wires = calcWires(wires, input, "")
|
|
wires2 := make(map[string]uint16)
|
|
wires2["b"] = wires["a"]
|
|
wires = calcWires(wires2, input, "b")
|
|
|
|
return int(wires["a"])
|
|
}
|