44 lines
1.0 KiB
JavaScript
44 lines
1.0 KiB
JavaScript
const fs = require("fs");
|
|
|
|
// PART 1
|
|
{
|
|
const result = fs.readFileSync("day_1.txt")
|
|
.toString()
|
|
.split("\n")
|
|
.map(line => line.split("").find(isFinite) + line.split("").findLast(isFinite))
|
|
.map(Number)
|
|
.filter(isFinite)
|
|
.reduce((acc, val) => acc + val, 0);
|
|
|
|
console.log(result);
|
|
}
|
|
|
|
// PART 2
|
|
const digits = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
|
|
|
|
function isNumber(char, i, arr) {
|
|
return isFinite(char) || digits.some(digit => arr.slice(i).join("").startsWith(digit));
|
|
}
|
|
|
|
function getNumber(line, index) {
|
|
if (isFinite(line.charAt(index)))
|
|
return line.charAt(index);
|
|
|
|
for (let i = 0; i < digits.length; i++)
|
|
if (line.slice(index).startsWith(digits[i])) return (i + 1).toString();
|
|
}
|
|
|
|
{
|
|
|
|
const result = fs.readFileSync("day_1.txt")
|
|
.toString()
|
|
.split("\n")
|
|
.map(line => getNumber(line, line.split("").findIndex(isNumber)) + getNumber(line, line.split("").findLastIndex(isNumber)))
|
|
.map(Number)
|
|
.filter(isFinite)
|
|
.reduce((acc, val) => acc + val, 0);
|
|
|
|
console.log(result);
|
|
}
|
|
|