Optimized 2019 day 2

This commit is contained in:
Brian Buller 2019-12-03 08:48:05 -06:00
parent 0cbaa45155
commit 0d92efbff4

View File

@ -36,14 +36,14 @@ func part1(prog []int) {
} }
} }
func part2(prog []int) { func slowPart2(prog []int) {
for n := 0; n <= 99; n++ { for n := 0; n <= 99; n++ {
for v := 0; v <= 99; v++ { for v := 0; v <= 99; v++ {
progcpy := make([]int, len(prog)) progcpy := make([]int, len(prog))
copy(progcpy, prog) copy(progcpy, prog)
progcpy[1], progcpy[2] = n, v progcpy[1], progcpy[2] = n, v
for i := 0; i < len(progcpy); i += 4 { for i := 0; i < len(progcpy); i += 4 {
switch prog[i] { switch progcpy[i] {
case 1: case 1:
progcpy[progcpy[i+3]] = add(progcpy[i+1], progcpy[i+2], progcpy) progcpy[progcpy[i+3]] = add(progcpy[i+1], progcpy[i+2], progcpy)
case 2: case 2:
@ -53,6 +53,8 @@ func part2(prog []int) {
fmt.Println("Found value:", n, v) fmt.Println("Found value:", n, v)
fmt.Println("Answer:", (100*n + v)) fmt.Println("Answer:", (100*n + v))
os.Exit(0) os.Exit(0)
} else {
fmt.Println(n, v, ":", progcpy[0])
} }
i = len(progcpy) i = len(progcpy)
} }
@ -61,6 +63,51 @@ func part2(prog []int) {
} }
} }
func part2(prog []int) {
target := 19690720
useN := 0
for n := 0; n <= 99; n++ {
progcpy := make([]int, len(prog))
copy(progcpy, prog)
progcpy[1] = n
for i := 0; i < len(progcpy); i += 4 {
switch progcpy[i] {
case 1:
progcpy[progcpy[i+3]] = add(progcpy[i+1], progcpy[i+2], progcpy)
case 2:
progcpy[progcpy[i+3]] = mult(progcpy[i+1], progcpy[i+2], progcpy)
case 99:
i = len(progcpy)
}
}
if progcpy[0] > target {
useN = n - 1
break
}
}
for v := 0; v <= 99; v++ {
progcpy := make([]int, len(prog))
copy(progcpy, prog)
progcpy[1] = useN
progcpy[2] = v
for i := 0; i < len(progcpy); i += 4 {
switch progcpy[i] {
case 1:
progcpy[progcpy[i+3]] = add(progcpy[i+1], progcpy[i+2], progcpy)
case 2:
progcpy[progcpy[i+3]] = mult(progcpy[i+1], progcpy[i+2], progcpy)
case 99:
if progcpy[0] == target {
fmt.Println("Found value:", useN, v)
fmt.Println("Answer:", (100*useN + v))
os.Exit(0)
}
i = len(progcpy)
}
}
}
}
func printState(prog []int) { func printState(prog []int) {
fmt.Println(prog) fmt.Println(prog)
} }