73 lines
2.1 KiB
JavaScript
73 lines
2.1 KiB
JavaScript
const fs = require('fs');
|
|
|
|
// const inputArray = fs.readFileSync('sample.txt').toString().split("\n");
|
|
const inputArray = fs.readFileSync('input.txt').toString().split("\n");
|
|
|
|
// Part One
|
|
|
|
const lineCount = inputArray.length;
|
|
const realPartNumbers = [];
|
|
|
|
for (i in inputArray) {
|
|
let line = inputArray[i];
|
|
const lineLength = line.length;
|
|
const possiblePartNumbers = [];
|
|
const parsedLine = line.split(/\D+/g);
|
|
for (part of parsedLine) {
|
|
!!parseInt(part) && possiblePartNumbers.push(parseInt(part));
|
|
}
|
|
|
|
for (part of possiblePartNumbers) {
|
|
let isRealPart = false;
|
|
const regex = new RegExp(`(?<!\\d)${part}(?!\\d)`);
|
|
const startingPosition = line.search(regex);
|
|
line = line.replace(part, '0'.repeat(part.toString().length)); // dang duplicates
|
|
const endingPosition = startingPosition + part.toString().length - 1;
|
|
if (startingPosition > 0 && line[startingPosition - 1] !== ".") {
|
|
isRealPart = true;
|
|
}
|
|
if (endingPosition < lineLength - 1 && line[endingPosition + 1] !== "." && !isRealPart) {
|
|
isRealPart = true;
|
|
}
|
|
if (i > 0 && !isRealPart) {
|
|
let stringAbove = inputArray[i - 1].substring(startingPosition === 0 ? startingPosition : startingPosition - 1, endingPosition != lineLength - 1 ? endingPosition + 2 : undefined);
|
|
stringAbove = stringAbove.replaceAll(".", "0");
|
|
for (char of stringAbove) {
|
|
if (!parseInt(char) && parseInt(char) !== 0) {
|
|
isRealPart = true;
|
|
}
|
|
};
|
|
}
|
|
if (i < lineCount - 1 && !isRealPart) {
|
|
let stringBelow = inputArray[parseInt(i) + 1].substring(startingPosition === 0 ? startingPosition : startingPosition - 1, endingPosition !== lineLength - 1 ? endingPosition + 2 : undefined);
|
|
stringBelow = stringBelow.replaceAll(".", "0");
|
|
for (char of stringBelow) {
|
|
if (!parseInt(char) && parseInt(char) !== 0) {
|
|
isRealPart = true;
|
|
}
|
|
};
|
|
}
|
|
|
|
if (isRealPart) {
|
|
realPartNumbers.push(part);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
console.log(realPartNumbers.reduce((a, b) => a + b, 0));
|
|
|
|
|
|
// Part Two
|
|
|
|
for (i in inputArray) {
|
|
const contents = inputArray[i].split(" ");
|
|
|
|
}
|
|
|
|
|
|
console.log();
|
|
|
|
// functions
|
|
|