Skip to content

Commit d4d744e

Browse files
feat(2019-day-02): run multistep IntCode programs
1 parent a565094 commit d4d744e

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

2019/day-02/intcodeParser.js

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11

22
const add = ({ posIn1, posIn2, posOut, data }) => {
33
data[posOut] = data[posIn1] + data[posIn2]
4+
return true
45
}
56

67
const multiply = ({ posIn1, posIn2, posOut, data }) => {
78
data[posOut] = data[posIn1] * data[posIn2]
9+
return true
810
}
911

10-
const terminate = ({ data }) => {
11-
console.log('Reached terminator. Stopping.')
12+
const terminate = ({ position }) => {
13+
console.log(`Reached terminator at position ${position}. Stopping.`)
14+
return false
1215
}
1316

1417
const step = ({ position, data }) => {
@@ -19,14 +22,25 @@ const step = ({ position, data }) => {
1922
}
2023
const segment = data.slice(position, position + 4)
2124
// Run the correct opcode for the specified step
22-
opCodesMap[data[position]]({
25+
return opCodesMap[data[position]]({
2326
posIn1: segment[1],
2427
posIn2: segment[2],
2528
posOut: segment[3],
26-
data
29+
data,
30+
position
2731
})
2832
}
2933

34+
const runProgram = ({ data }) => {
35+
let position = 0
36+
let running = true
37+
while (running === true && position <= data.length) {
38+
running = step({ position, data })
39+
position += 4
40+
}
41+
}
42+
3043
module.exports = {
31-
step
44+
step,
45+
runProgram
3246
}

2019/day-02/intcodeParser.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ describe('--- 2019 Day 2: 1202 Program Alarm ---', () => {
4141
[30, 1, 1, 4, 2, 5, 6, 0, 99]
4242
]
4343
testInputs.forEach((data, idx) => {
44-
runProgram(data)
44+
runProgram({ data })
4545
expect(data).to.deep.equal(testOutputs[idx])
4646
})
4747
})

0 commit comments

Comments
 (0)