63 lines
2.0 KiB
JavaScript
63 lines
2.0 KiB
JavaScript
const ASSIGNMENT = 'assignment';
|
|
const ANSWER = 'answer';
|
|
const NEWLINE_CHARACTER = '\n';
|
|
|
|
/**
|
|
* Main function
|
|
*/
|
|
window.onload = function() {
|
|
document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer);
|
|
}
|
|
|
|
/**
|
|
* Listener function for input in assignment field.
|
|
* @param event the onInput event
|
|
*/
|
|
function calculateAnswer(event) {
|
|
console.info("Calculating answer for input...");
|
|
let answer = algorithm(event.target.value);
|
|
|
|
document.getElementById(ANSWER).innerText = answer;
|
|
}
|
|
|
|
/**
|
|
* Calculate the answer to assignment1 with 2 variables, count and highest.
|
|
* @param assignment the input from the assignment.
|
|
* @return string the elf with the highest calory count
|
|
*/
|
|
function algorithm(assignment) {
|
|
let currentCalorieScore = 0;
|
|
let highestCalorieScores = [0,0,0];
|
|
let currentElf = 1;
|
|
|
|
let lines = assignment.trim().split(NEWLINE_CHARACTER);
|
|
console.info("Linecount:" + lines.length);
|
|
|
|
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);
|
|
} |