Solution for assignment1.

This commit is contained in:
2022-12-05 01:09:57 +01:00
parent 8d25208c83
commit 3f3daab726
4 changed files with 65 additions and 6 deletions

View File

@@ -1,12 +1,16 @@
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);
}
/**
@@ -15,19 +19,52 @@ window.onload = function() {
*/
function calculateAnswer(event) {
console.info("Calculating answer for input...");
let answer = algorithm(event.target.value);
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 assignment.
* Calculate the answer to assignment1 with 2 variables, count and highest.
* @param assignment the input from the assignment.
* @return string the answer
* @param topn the
* @return string the elf with the highest calory count
*/
function algorithm(assignment) {
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);
// TODO: implement assignment
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);
}