2019-12-02 18:20:52 +00:00
|
|
|
package aoc2019
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io/ioutil"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2019-12-09 17:48:40 +00:00
|
|
|
func parseDay02Intcode(code string) ([]int64, error) { return parseIntcode(code) }
|
2019-12-02 18:20:52 +00:00
|
|
|
|
2019-12-09 17:48:40 +00:00
|
|
|
func executeDay02Intcode(code []int64) ([]int64, error) {
|
2019-12-05 15:53:40 +00:00
|
|
|
return executeIntcode(code, nil, nil) // Day02 intcode may not contain I/O
|
2019-12-02 18:20:52 +00:00
|
|
|
}
|
|
|
|
|
2019-12-09 17:48:40 +00:00
|
|
|
func solveDay2Part1(inFile string) (int64, error) {
|
2019-12-02 18:20:52 +00:00
|
|
|
raw, err := ioutil.ReadFile(inFile)
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to read input")
|
|
|
|
}
|
|
|
|
|
|
|
|
code, err := parseDay02Intcode(strings.TrimSpace(string(raw)))
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to parse Intcode")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Modify data for "1202 program alarm"
|
|
|
|
code[1] = 12
|
|
|
|
code[2] = 2
|
|
|
|
|
|
|
|
// Execute Intcode
|
|
|
|
code, err = executeDay02Intcode(code)
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to execute Intcode")
|
|
|
|
}
|
|
|
|
|
|
|
|
return code[0], nil
|
|
|
|
}
|
|
|
|
|
2019-12-09 17:48:40 +00:00
|
|
|
func solveDay2Part2(inFile string) (int64, error) {
|
2019-12-02 18:20:52 +00:00
|
|
|
raw, err := ioutil.ReadFile(inFile)
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to read input")
|
|
|
|
}
|
|
|
|
|
2019-12-09 17:48:40 +00:00
|
|
|
const expectedResult int64 = 19690720
|
2019-12-02 18:20:52 +00:00
|
|
|
|
2019-12-09 17:48:40 +00:00
|
|
|
for noun := int64(0); noun < 100; noun++ {
|
|
|
|
for verb := int64(0); verb < 100; verb++ {
|
2019-12-02 18:20:52 +00:00
|
|
|
|
|
|
|
// Re-initialize "memory"
|
|
|
|
code, err := parseDay02Intcode(strings.TrimSpace(string(raw)))
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to parse Intcode")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Modify code
|
|
|
|
code[1] = noun
|
|
|
|
code[2] = verb
|
|
|
|
|
|
|
|
// Execute Intcode
|
|
|
|
code, err = executeDay02Intcode(code)
|
|
|
|
if err != nil {
|
|
|
|
return 0, errors.Wrap(err, "Unable to execute Intcode")
|
|
|
|
}
|
|
|
|
|
|
|
|
if code[0] == expectedResult {
|
|
|
|
return 100*noun + verb, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0, errors.New("No valid result was found")
|
|
|
|
}
|