82 lines
1.9 KiB
JavaScript
82 lines
1.9 KiB
JavaScript
const { inputs } = require("./inputs/03.json");
|
|
|
|
const joltageBanks = new Array();
|
|
|
|
/**
|
|
*
|
|
* @param {String} bank
|
|
*/
|
|
function getHighestJoltages(bank) {
|
|
// Turn the string into an array of battery joltage values and their associated index
|
|
const joltages = new Array();
|
|
for (let i = 0; i < bank.length; i++) {
|
|
joltages.push({
|
|
"value": bank[i],
|
|
"index": i
|
|
});
|
|
}
|
|
|
|
// Sort them highest to lowest
|
|
joltages.sort((a, b) => {
|
|
if (a.value < b.value) return 1;
|
|
else if (a.value === b.value) {
|
|
if (a.index > b.index) return 1;
|
|
}
|
|
else return -1;
|
|
});
|
|
|
|
if (joltages[0].index == bank.length - 1) {
|
|
const tmp0 = joltages[0];
|
|
let tmp1;
|
|
let nextLowestFound = false;
|
|
let k = 1;
|
|
while(nextLowestFound == false) {
|
|
if (joltages[k].value < joltages[0].value) {
|
|
tmp1 = joltages[k];
|
|
nextLowestFound = true;
|
|
} else {
|
|
k++;
|
|
}
|
|
}
|
|
joltages[0] = tmp1;
|
|
joltages[1] = tmp0;
|
|
}
|
|
|
|
const finalJoltages = [
|
|
joltages[0]
|
|
];
|
|
|
|
let foundValid = false;
|
|
let j = 1;
|
|
while (foundValid == false) {
|
|
if (joltages[j].index > joltages[0].index) {
|
|
finalJoltages.push(joltages[j]);
|
|
foundValid = true;
|
|
} else {
|
|
j++;
|
|
}
|
|
}
|
|
|
|
return finalJoltages;
|
|
}
|
|
|
|
let counter = 1;
|
|
|
|
|
|
inputs.forEach(bank => {
|
|
console.log("Bank: ", counter);
|
|
const highestJoltages = getHighestJoltages(bank);
|
|
if (highestJoltages[0].index > highestJoltages[1].index) {
|
|
console.error(`Indexes must be in order!`);
|
|
}
|
|
joltageBanks.push("".concat(highestJoltages[0].value, highestJoltages[1].value));
|
|
counter++;
|
|
});
|
|
|
|
let joltageSum = 0;
|
|
joltageBanks.forEach(bank => {
|
|
const value = Number.parseInt(bank);
|
|
joltageSum += value;
|
|
});
|
|
|
|
console.log(joltageSum); |