63 lines
1.4 KiB
JavaScript
63 lines
1.4 KiB
JavaScript
import { promises as fsp } from "node:fs";
|
|
|
|
async function asyncReadFile(filename) {
|
|
try {
|
|
const contents = await fsp.readFile(filename, "utf-8");
|
|
|
|
return contents.trim();
|
|
} catch (err) {
|
|
console.error(err);
|
|
}
|
|
}
|
|
|
|
const findIndexOfHighestNumber = (arrayOfNumbers, start, end) => {
|
|
let highestIndex = start;
|
|
for (let i = start; i <= end; i++) {
|
|
if (arrayOfNumbers[i] > arrayOfNumbers[highestIndex]) highestIndex = i;
|
|
}
|
|
return highestIndex;
|
|
};
|
|
|
|
const findHighestOutput = (bank) => {
|
|
let arr = Array.from(bank);
|
|
let curr = Array(arr.length).fill("");
|
|
let foundNumbers = 0;
|
|
const desiredNumbers = 12;
|
|
let start = 0;
|
|
|
|
while (foundNumbers < desiredNumbers) {
|
|
const index = findIndexOfHighestNumber(
|
|
bank,
|
|
start,
|
|
arr.length - desiredNumbers + foundNumbers
|
|
);
|
|
curr[index] = arr[index];
|
|
|
|
// prep next run
|
|
foundNumbers++;
|
|
start = index + 1;
|
|
}
|
|
return Number.parseInt(curr.join(""), 10);
|
|
};
|
|
|
|
/*
|
|
const dataToParse = `987654321111111
|
|
811111111111119
|
|
234234234234278
|
|
818181911112111`;
|
|
*/
|
|
|
|
const dataToParse = await asyncReadFile("../input.txt");
|
|
|
|
const banks = dataToParse.split("\n");
|
|
let total = 0;
|
|
|
|
banks.forEach((bank) => {
|
|
console.log(`Processing bank ${bank}`);
|
|
const output = findHighestOutput(bank);
|
|
console.log(`> found ${output}`);
|
|
total += output;
|
|
});
|
|
|
|
console.log(`Total: ${total}`);
|