Prepare your favorite cup of coffee, because we are about to enter the fantastic world of Breaking records.
The problem
The solution
To start the solution, let's start by defining the breakingRecords
function that will receive a scores
parameter, which is an array of scores:
function breakingRecords(scores) {}
To save the best score, we will define the variable best
, starting at 0, so it will consider the highest score so far:
var best = 0;
We will also define a variable to compute the worst score so far, which will be worst
:
var worst = 0;
Next we will define the variable currentBest
which will consider the first score in the scores
array as the best score so far:
var currentBest = scores[0];
The variable currentWorst
defines the current score as the worst score to date:
var currentWorst = scores[0];
Now let's go through the scores
array, starting from the second element (i = 1
), because the first element was already considered previously in the currentBest
and currentWorst
variables:
for (var i = 1; i < scores.length; i++) {}
Inside the loop we will perform validation, comparing the current value in the scores
array with the currentBest
variable:
if (scores[i] > currentBest) {}
If the condition is met, we will update the value of currentBest
and increment the best
variable to indicate that there has been a positive record break:
currentBest = scores[i];
best++;
If the previous condition is not met, we will compare the current value in the scores
array with the currentWorst
variable:
else if (scores[i] < currentWorst) {}
If the condition is met, we will update the value of currentWorst
and increment the worst
variable to indicate that there has been a negative record break:
currentWorst = scores[i];
worst++;
Finally, we will return an array containing the number of positive record breaks (best
) and the number of negative record breaks (worst
):
return [best, worst];
Final resolution
After following the step by step we have our final resolution:
function breakingRecords(scores) {
var best = 0;
var worst = 0;
var currentBest = scores[0];
var currentWorst = scores[0];
for (var i = 1; i < scores.length; i++) {
if (scores[i] > currentBest) {
currentBest = scores[i];
best++;
} else if (scores[i] < currentWorst) {
currentWorst = scores[i];
worst++;
}
}
return [best, worst];
}
Share the code, spread knowledge and build the future! 😉
Images generated by DALL·E 3
Top comments (2)
Thr problem is interesting and the solution is well founded
Thank you for your feedback Lala! ❤️