82 lines
2.0 KiB
JavaScript
82 lines
2.0 KiB
JavaScript
import { promises as fsPromises } from "node:fs";
|
|
|
|
async function asyncReadFile(filename) {
|
|
try {
|
|
const contents = await fsPromises.readFile(filename, "utf-8");
|
|
|
|
const arr = contents.split(/\r?\n/);
|
|
|
|
return arr;
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
const findDividers = (rows) => {
|
|
let spaceIndexes = [];
|
|
rows.forEach((row, rowIndex) => {
|
|
if (row == "") return;
|
|
if (rowIndex === 0) {
|
|
Array.from(row).forEach((theChar, charIndex) => {
|
|
if (theChar === " ") spaceIndexes.push(charIndex);
|
|
});
|
|
return;
|
|
}
|
|
const rowArray = Array.from(row);
|
|
spaceIndexes = spaceIndexes.filter(
|
|
(spaceIndex) => rowArray[spaceIndex] === " "
|
|
);
|
|
});
|
|
return spaceIndexes;
|
|
};
|
|
|
|
const calculateValues = (operands, operation) => {
|
|
if (operation === "+")
|
|
return operands.reduce((acc, curr) => acc + curr * 1, 0);
|
|
else if (operation === "*")
|
|
return operands.reduce((acc, curr) => acc * curr, 1);
|
|
};
|
|
|
|
/*
|
|
const data = `
|
|
123 328 51 64
|
|
45 64 387 23
|
|
6 98 215 314
|
|
* + * +
|
|
`
|
|
.trim()
|
|
.split("\n");
|
|
*/
|
|
|
|
const data = await asyncReadFile("../input.txt");
|
|
|
|
let total = 0;
|
|
|
|
const dividers = findDividers(data);
|
|
|
|
let newOperands = [];
|
|
let operation = "";
|
|
|
|
for (let c = data[0].length - 1; c >= 0; c--) {
|
|
if (dividers.includes(c) || c === -1) {
|
|
const result = calculateValues(newOperands, operation);
|
|
total += result;
|
|
console.log(`> result: ${result}`);
|
|
operation = "";
|
|
newOperands = [];
|
|
}
|
|
|
|
let newOperandParts = [];
|
|
data.forEach((row) => {
|
|
const charArray = Array.from(row);
|
|
if (/\d+/.test(charArray[c])) newOperandParts.push(charArray[c]);
|
|
else if (["+", "*"].includes(charArray[c])) operation = charArray[c];
|
|
});
|
|
if (newOperandParts.join("") !== "")
|
|
newOperands.push(newOperandParts.join(""));
|
|
}
|
|
const result = calculateValues(newOperands, operation);
|
|
total += result;
|
|
|
|
console.log(`>> total: ${total}`);
|