const ASSIGNMENT = 'assignment'; const ANSWER = 'answer'; const ALGORITHM_CHECKBOX = 'algorithm'; const NEWLINE_CHARACTER = '\n'; const TOP_1 = 1; const TOP_N = 3; /** * Main function */ window.onload = function() { document.getElementById(ASSIGNMENT).addEventListener("input", calculateAnswer); document.getElementById(ALGORITHM_CHECKBOX).addEventListener("click", calculateAnswer); } /** * Listener function for input in assignment field. * @param event the onInput event */ function calculateAnswer(event) { console.info("Calculating answer for input..."); let assignment = document.getElementById(ASSIGNMENT).value; let top3 = document.getElementById(ALGORITHM_CHECKBOX).checked; let answer = algorithm(assignment, (top3)? TOP_N: 1); document.getElementById(ANSWER).innerText = answer; } /** * Calculate the answer to assignment1 with 2 variables, count and highest. * @param assignment the input from the assignment. * @param topn the * @return string the elf with the highest calory count */ function algorithm(assignment, topn) { let currentCalorieScore = 0; let highestCalorieScores = Array.from({length: topn}, () => (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); }