Skip to content

Commit 16df61d

Browse files
committed
2021/day-1 part 2: Windowing
1 parent 92e4fe1 commit 16df61d

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

2021/day-1.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,24 @@ import { createInterface } from 'readline';
77
function processInput(input: string) {
88
const rl = createInterface(createReadStream(input));
99

10-
let lastValue: number|undefined = undefined;
10+
const windowSize = 3;
11+
const window: number[] = [];
1112
let increases: number = 0;
1213
rl.on('line', line => {
1314
const value = Number(line);
14-
if (lastValue && value > lastValue) {
15-
increases++;
15+
let lastSum;
16+
if (window.length === windowSize) {
17+
lastSum = window.reduce((s, v) => s + v, 0);
18+
window.splice(0, 1);
19+
}
20+
window.push(value);
21+
if (typeof lastSum !== 'undefined') {
22+
// We removed one, and we added one -- so window.length is still equal to the window size.
23+
const sum = window.reduce((s, v) => s + v, 0);
24+
if (sum > lastSum) {
25+
increases++;
26+
}
1627
}
17-
lastValue = value;
1828
});
1929
rl.on('close', () => {
2030
console.log(`Results for ${input}: ${increases} increases`);

0 commit comments

Comments
 (0)