-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpart-two.js
36 lines (28 loc) · 1.08 KB
/
part-two.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
const fs = require('fs');
const path = require('path');
let raw_input = fs.readFileSync(path.resolve(__dirname, './input.txt'), 'utf8');
// Need last `filter` because 'input.txt' contains an empty line at the end, which parseInt parses as `NaN`
let input = raw_input
.split('\n')
.map(n => parseInt(n.replace('+', '')))
.filter(n => !Number.isNaN(n));
const STARTING_VALUE = 0;
let accumulator = STARTING_VALUE;
let frequency_list = {
[accumulator.toString()]: true,
};
let first_duplicated_frequency;
while (!first_duplicated_frequency) {
for (let i = 0; i < input.length; i++) {
let value = input[i];
accumulator += value;
// If we've seen this frequency before, log out the value and break the loop
if (frequency_list[accumulator.toString()]) {
console.log(`Frequency ${accumulator} has been seen before!`);
first_duplicated_frequency = accumulator.toString();
return;
}
// Otherwise, add the frequency to our lookup table
frequency_list[accumulator.toString()] = true;
}
}