Skip to content

Commit c209224

Browse files
feat(2019-day-02): solution for part 2
Brute force the combination of acceptable program inputs until the desired program output is reached
1 parent 802bce1 commit c209224

File tree

1 file changed

+57
-8
lines changed

1 file changed

+57
-8
lines changed

2019/day-02/solution.js

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,66 @@ const filePath = path.join(__dirname, 'input.txt')
44
const { runProgram } = require('./intcodeParser')
55
const { inputToArray } = require('../../2018/inputParser')
66

7-
fs.readFile(filePath, { encoding: 'utf8' }, (err, data) => {
7+
fs.readFile(filePath, { encoding: 'utf8' }, (err, initData) => {
88
if (err) throw err
99

10-
data = inputToArray(data.trim())
11-
// Manipulate input per puzzle instructions for Part 1
12-
data[1] = 12
13-
data[2] = 2
10+
initData = inputToArray(initData.trim())
1411

15-
runProgram({ data })
16-
const answer = data[0]
12+
const resetInput = () => {
13+
// Deep copy to ensure we aren't mutating the original data
14+
return JSON.parse(JSON.stringify(initData))
15+
}
16+
17+
const part1 = () => {
18+
const data = resetInput()
19+
// Manipulate input per puzzle instructions for Part 1
20+
data[1] = 12
21+
data[2] = 2
22+
runProgram({ data })
23+
return data[0]
24+
}
25+
26+
const part2 = ({target, maxNoun, maxVerb}) => {
27+
28+
// Helper for running the program with specified noun and verb inputs
29+
const tryProgram = ({
30+
noun,
31+
verb
32+
}) => {
33+
const data = resetInput()
34+
data[1] = noun
35+
data[2] = verb
36+
runProgram({ data })
37+
console.debug(`Running with noun:${noun} and verb:${verb} produces ${data[0]}`)
38+
return Number(data[0])
39+
}
40+
41+
// Manipulate and loop through attempts for Part 2
42+
let noun = -1
43+
while ( noun <= maxNoun) {
44+
let verb = -1
45+
noun++
46+
while (verb <= maxVerb) {
47+
verb++
48+
output = tryProgram({
49+
noun,
50+
verb
51+
})
52+
// Break the search loop on success
53+
if(output === target) {
54+
return 100 * noun + verb
55+
}
56+
}
57+
}
58+
}
59+
60+
61+
const answer1 = part1()
62+
const answer2 = part2({ target:19690720, maxNoun: 99, maxVerb: 99})
1763

1864
console.log('-- Part 1 --')
19-
console.log(`Answer: ${answer}`)
65+
console.log(`Answer: ${answer1}`)
66+
67+
console.log('-- Part 2 --')
68+
console.log(`Answer: ${answer2}`)
2069
})

0 commit comments

Comments
 (0)