mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2025-01-10 14:50:46 +00:00
58 lines
943 B
Go
58 lines
943 B
Go
|
package two
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"math"
|
||
|
"slices"
|
||
|
)
|
||
|
|
||
|
type operand int
|
||
|
type instructionFn func(operand) (int, bool, int64, bool)
|
||
|
|
||
|
func Solve(buf []byte) (int64, error) {
|
||
|
r := bytes.NewReader(buf)
|
||
|
_, program, err := parseLines(r)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
computer := newComputer(make(map[string]int64))
|
||
|
a := lowestA(program, computer)
|
||
|
|
||
|
return a, nil
|
||
|
}
|
||
|
|
||
|
func lowestA(program []int64, computer *computer) int64 {
|
||
|
var a int64 = 1
|
||
|
computer.bumpRegisters(a)
|
||
|
var results []int64
|
||
|
for {
|
||
|
results = computer.run(program)
|
||
|
|
||
|
if slices.Equal(results, program) {
|
||
|
return a
|
||
|
}
|
||
|
|
||
|
if len(program) > len(results) {
|
||
|
a *= 2
|
||
|
computer.bumpRegisters(a)
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
if len(program) == len(results) {
|
||
|
for j := len(program) - 1; j >= 0; j-- {
|
||
|
if program[j] != results[j] {
|
||
|
a += int64(math.Pow(8, float64(j)))
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if len(program) < len(results) {
|
||
|
a /= 2
|
||
|
}
|
||
|
|
||
|
computer.bumpRegisters(a)
|
||
|
}
|
||
|
}
|