-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01.js
85 lines (70 loc) · 1.84 KB
/
01.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
import path from 'node:path';
import {fileURLToPath} from 'node:url';
import {readInput} from '../../../util.js';
const directoryPath = path.dirname(fileURLToPath(import.meta.url));
const input = await readInput(directoryPath);
const lines = input.trim().split('\n');
let sumCalibrationValues = 0;
for (const line of lines) {
let firstDigit;
let lastDigit;
for (const character of line) {
if (!firstDigit && Number.isInteger(Number(character))) {
firstDigit = character;
}
if (Number.isInteger(Number(character))) {
lastDigit = character;
}
}
const combinedNumber = `${firstDigit}${lastDigit}`;
sumCalibrationValues += Number(combinedNumber);
}
console.log('Sum of calibration values:', sumCalibrationValues);
const numberWords = [
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
];
let sumAllCalibrationValues = 0;
for (const line of lines) {
let firstDigit;
let lastDigit;
for (let index = 0; index < line.length; index++) {
const character = line[index];
if (!firstDigit) {
if (Number.isInteger(Number(character))) {
firstDigit = Number(character);
} else {
for (const numberWord of numberWords) {
if (!firstDigit && line.indexOf(numberWord) === index) {
firstDigit = numberWords.indexOf(numberWord) + 1;
break;
}
}
}
}
if (Number.isInteger(Number(character))) {
lastDigit = Number(character);
} else {
for (const numberWord of numberWords) {
// eslint-disable-next-line unicorn/prefer-string-slice
if (line.substring(index).indexOf(numberWord) === 0) {
lastDigit = numberWords.indexOf(numberWord) + 1;
break;
}
}
}
}
const combinedNumber = `${firstDigit}${lastDigit}`;
sumAllCalibrationValues += Number(combinedNumber);
}
console.log(
'Sum of calibration values including spelled out numbers:',
sumAllCalibrationValues,
);