day 6 complete!
This commit is contained in:
62
day03/js/day03b.js
Normal file
62
day03/js/day03b.js
Normal file
@@ -0,0 +1,62 @@
|
||||
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}`);
|
||||
@@ -6,9 +6,12 @@ But it was also brute force - literally stepping through each possible combinati
|
||||
|
||||
ATM (11:30p Wed), I've got an algorithm that tries to create the highest value number by pulling out numbers in reverse numerical order, but it isn't _quite_ working. My current hope is to come at it fresh tomorrow when I also tackle puzzle 4.
|
||||
|
||||
_UPDATE:_ Two days later, and I finally figured out the algorithm I needed to get the value. I thought I had it with an overcomplicated function that tried to count down from right to left, but in the end, the solution wound up being much simpler.
|
||||
|
||||
### JS Solutions
|
||||
|
||||
```
|
||||
cd js
|
||||
node day03a.js
|
||||
node day03b.js
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user