Competitive Gaming
1 min readJul 26, 2021
--
Here is the code challenge I solved this week!
A group of friends are playing a video game together. During the game, each player earns a number of points. At the end of a round, players who achieve at least a certain rank get to “level up” their characters to gain increased abilities. Given the scores of the players at the end of a round, how many players will be able to level up?
My approach to the challenge:
- Sort the scores from greatest to lowest.
- The first score gets the highest rank (1).
- Go down the scores and assign ranks in descending order (highest score to lowest).
- If the ranks are greater than k, and if the score is more than 0, the number of players who will level up increase.
- Return the number of players leveling up.
function numPlayers(k, scores) {
const sortedScores = scores.sort(function(a, b) {return b-a})
let rank = 0
let levelUp = 0 for (let i = 0; i < sortedScores.length; i++) {
if (i == 0) {
rank = 1
} else if (sortedScores[i] != sortedScores[i-1] {
rank = i + 1
} if (rank <= k && sortedScores[i] > 0) {
levelUp+=1
}
}
return levelUp
}
That’s all to it!