-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-1-part-2.js
64 lines (58 loc) · 1.36 KB
/
day-1-part-2.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
const fs = require('fs');
const fileContents = fs.readFileSync('./day-1-input.txt', 'utf-8').split('\n');
let sum = 0;
const numbers = [
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine'
]
const firstDigits = [];
const lastDigits = [];
for (const line of fileContents) {
for (let i = 0; i < line.length; i++) {
let found = false;
if (Number.isInteger(parseInt(line.charAt(i)))) {
firstDigits.push(parseInt(line.charAt(i)));
break;
}
for (let j = 0; j < numbers.length; j++) {
if (line.slice(i, i + numbers[j].length) === numbers[j]) {
firstDigits.push(j + 1);
found = true;
break;
}
}
if (found) {
break;
}
}
}
for (const line of fileContents) {
for (let i = 0; i < line.length; i++) {
let found = false;
if (Number.isInteger(parseInt(line.charAt(line.length - 1 - i)))) {
lastDigits.push(parseInt(line.charAt(line.length - 1 - i)));
break;
}
for (let j = 0; j < numbers.length; j++) {
if (line.slice(line.length - 1 - i, line.length - 1 - i + numbers[j].length) === numbers[j]) {
lastDigits.push(j + 1);
found = true;
break;
}
}
if (found) {
break;
}
}
}
for (let i = 0; i < firstDigits.length; i++) {
sum += parseInt(`${firstDigits[i]}${lastDigits[i]}`);
}
console.log(sum);