Files
aoc-2025/day06/js/day06a.js
2025-12-06 02:27:12 -05:00

50 lines
1.1 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 data = `
123 328 51 64
45 64 387 23
6 98 215 314
* + * +
`.trim()
.split("\n");
*/
const data = await asyncReadFile("../input.txt");
const parsedData = data.map((val) => val.trim().split(/\s+/));
const rowCount = parsedData.length,
colCount = rowCount ? parsedData[0].length : 0;
const numRegex = /\d+/;
let total = 0;
for (let c = 0; c < colCount; c++) {
let operands = [];
let result = 0;
for (let r = 0; r < rowCount; r++) {
const val = parsedData[r][c];
if (numRegex.test(val)) operands.push(val * 1);
else if (val === "+")
result = operands.reduce((acc, curr) => acc + curr, 0);
else if (val === "*")
result = operands.reduce((acc, curr) => acc * curr, 1);
}
console.log(`> result: ${result}`);
total += result;
}
console.log(`>> total: ${total}`);