Add day one
This commit is contained in:
commit
68d5191021
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
*.txt
|
||||
|
43
day_1.js
Normal file
43
day_1.js
Normal 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);
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user