diff --git a/README.md b/README.md index 5e942bf..77dbf42 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Advent of Code 2022 - assignment 1 This is the first assignment for Advent of Code 2022. The provided solution uses 3 variables: currentScore, highestCalorieScore, currentElf, highestElf. -It is complexity O(n²) since it loops through every line exactly once and the iterates for recalculating highscore. +It is complexity O(n+m) since it loops through every line exactly once (n) and the iterates for recalculating highscore (m). ## Solution description Every iteration the score is added to the currentScore. If an empty line is detected we check if currentscore exceeds one of our highestCalorieScore, if yes we assign currentElf to highestElf. @@ -12,4 +12,5 @@ Every iteration the score is added to the currentScore. If an empty line is dete - https://stackoverflow.com/questions/154059/how-do-i-check-for-an-empty-undefined-null-string-in-javascript - https://www.geeksforgeeks.org/convert-a-string-to-an-integer-in-javascript/#:~:text=In%20JavaScript%20parseInt()%20function,argument%20of%20parseInt()%20function. - https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers -- https://www.w3schools.com/js/js_break.asp \ No newline at end of file +- https://www.w3schools.com/js/js_break.asp +- https://2ality.com/2018/12/creating-arrays.html diff --git a/script.js b/script.js index f4d3a8f..0b1f29f 100644 --- a/script.js +++ b/script.js @@ -1,6 +1,7 @@ const ASSIGNMENT = 'assignment'; const ANSWER = 'answer'; const NEWLINE_CHARACTER = '\n'; +const TOP_N = 3; /** * Main function @@ -15,7 +16,7 @@ window.onload = function() { */ function calculateAnswer(event) { console.info("Calculating answer for input..."); - let answer = algorithm(event.target.value); + let answer = algorithm(event.target.value, TOP_N); document.getElementById(ANSWER).innerText = answer; } @@ -23,11 +24,12 @@ function calculateAnswer(event) { /** * 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) { +function algorithm(assignment, topn) { let currentCalorieScore = 0; - let highestCalorieScores = [0,0,0]; + let highestCalorieScores = Array.from({length: topn}, () => (0)); let currentElf = 1; let lines = assignment.trim().split(NEWLINE_CHARACTER);