Files
advent-of-code/script.js

70 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-12-04 18:24:26 +01:00
const ASSIGNMENT = 'assignment';
const ANSWER = 'answer';
2022-12-05 01:09:57 +01:00
const ALGORITHM_CHECKBOX = 'algorithm';
2022-12-04 18:24:26 +01:00
const NEWLINE_CHARACTER = '\n';
2022-12-05 01:09:57 +01:00
const TOP_1 = 1;
const TOP_N = 3;
2022-12-04 18:24:26 +01:00
/**
* Main function
*/
window.onload = function() {
document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer);
2022-12-05 01:09:57 +01:00
document.getElementById(ALGORITHM_CHECKBOX).addEventListener("click", calculateAnswer);
2022-12-04 18:24:26 +01:00
}
/**
* Listener function for input in assignment field.
* @param event the onInput event
*/
function calculateAnswer(event) {
console.info("Calculating answer for input...");
2022-12-05 01:09:57 +01:00
let assignment = document.getElementById(ASSIGNMENT).value;
let top3 = document.getElementById(ALGORITHM_CHECKBOX).checked;
let answer = algorithm(assignment, (top3)? TOP_N: 1);
2022-12-04 18:24:26 +01:00
document.getElementById(ANSWER).innerText = answer;
}
/**
2022-12-05 01:09:57 +01:00
* Calculate the answer to assignment1 with 2 variables, count and highest.
2022-12-04 18:24:26 +01:00
* @param assignment the input from the assignment.
2022-12-05 01:09:57 +01:00
* @param topn the
* @return string the elf with the highest calory count
2022-12-04 18:24:26 +01:00
*/
2022-12-05 01:09:57 +01:00
function algorithm(assignment, topn) {
let currentCalorieScore = 0;
let highestCalorieScores = Array.from({length: topn}, () => (0));
let currentElf = 1;
2022-12-04 18:24:26 +01:00
let lines = assignment.trim().split(NEWLINE_CHARACTER);
console.info("Linecount:" + lines.length);
2022-12-05 01:09:57 +01:00
for(var i = 0; i < lines.length; i++){
let line = lines[i];
if(!line && currentCalorieScore > 0) { // Check for empty line and skip subsequent emptylines
console.debug("Calculated score for elf " + currentElf + ": " + currentCalorieScore);
for(let j=0; j < highestCalorieScores.length; j++) {
if(currentCalorieScore > highestCalorieScores[j]) {
console.debug("New highest #"+(j+1) + " elf found, with score:" + currentCalorieScore);
let oldHighestCalorieScore = highestCalorieScores[j];
highestCalorieScores[j] = currentCalorieScore;
currentCalorieScore = oldHighestCalorieScore;
}
}
// Reset values
currentCalorieScore = 0;
currentElf++;
continue;
}
let calorieScore = parseInt(line);
currentCalorieScore += calorieScore;
}
console.debug(highestCalorieScores);
return "The highest of sum of calorie amount: " + highestCalorieScores.reduce(function(a, b) { return a + b; }, 0);
2022-12-04 18:24:26 +01:00
}