Add day one

This commit is contained in:
Reimar 2023-12-06 22:00:08 +01:00
commit 68d5191021
Signed by: Reimar
GPG Key ID: 93549FA07F0AE268
2 changed files with 45 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.txt

43
day_1.js Normal file
View File

@ -0,0 +1,43 @@
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);
}