-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07.js
108 lines (82 loc) · 2.12 KB
/
07.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const R = require('ramda')
const intcode = require('./intcode')
const { permutations } = require('../utils')
const assert = require('assert')
const NUM_AMPLIFIERS = 5
const runPhases = (rom) => (phases) => {
let input = 0
for (const phase of phases) {
input = intcode.arrayExecutor([phase, input], intcode.spawn(rom)).output[0]
}
return input
}
const spawnAmplifier = R.curry(function*(ram, phase) {
const thread = intcode.spawn(ram)
let lastOutput
assert.deepStrictEqual(
thread.next(),
{ done: false, value: { type: 'input' } },
'Expected request for phase',
)
for (;;) {
const input = yield lastOutput
{
const { value, done } = thread.next(phase)
if (done) {
return lastOutput
}
assert.strictEqual(value.type, 'input', 'Expected request for input')
}
{
const { value, done } = thread.next(input)
assert.strictEqual(done, false, 'Expected output')
assert.strictEqual(value.type, 'output', 'Expected output')
lastOutput = value.value
}
}
})
const runFeedbackPhases = (ram) => (phases) => {
const amplifiers = R.map(spawnAmplifier(ram), phases)
for (const amplifier of amplifiers) {
assert.deepStrictEqual(
amplifier.next(),
{ done: false, value: undefined },
'Expected start of amplifier',
)
}
let input = 0
for (;;) {
for (const amplifier of amplifiers) {
const { value, done } = amplifier.next(input)
if (done) {
return input
}
input = value
}
}
}
const part1 = (input) => {
const pipelineRunner = R.pipe(intcode.parseRAM, runPhases)(input)
const phaseCombinations = R.pipe(
R.range(0),
permutations,
R.map(pipelineRunner),
(x) => x.reduce(R.max),
)(NUM_AMPLIFIERS)
return phaseCombinations
}
const part2 = (input) => {
const pipelineRunner = R.pipe(intcode.parseRAM, runFeedbackPhases)(input)
const phaseCombinations = R.pipe(
R.range(0),
R.map(R.add(5)),
permutations,
R.map(pipelineRunner),
(x) => x.reduce(R.max),
)(NUM_AMPLIFIERS)
return phaseCombinations
}
module.exports = {
part1,
part2,
}