Look up a player level
A game tracks experience points against a table of ascending thresholds. Find the highest level reached.
- The thresholds list is sorted ascending and contains the XP needed for each level.
- Return the index of the highest threshold the player has met or exceeded.
- If the player has not reached even the first threshold, return -1.
- An empty thresholds list means level 0 is returned.
levelProgress(xp: int, thresholds: list<int>) → int
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int levelProgress(int xp, std::vector<int> thresholds) {
}
Worked examples
| Call | Result |
|---|---|
levelProgress(50, std::vector<int>{10, 30, 60, 100}) | 1 |
levelProgress(100, std::vector<int>{10, 30, 60, 100}) | 3 |
levelProgress(5, std::vector<int>{10, 30, 60}) | -1 |
levelProgress(0, std::vector<int>{}) | 0 |
Hint
Walk the thresholds and remember the last one that was met.
Reference solution in C++
int levelProgress(int xp, std::vector<int> thresholds) {
if (thresholds.empty()) return 0;
if (xp < thresholds[0]) return -1;
int result = 0;
for (int i = 0; i < (int) thresholds.size(); i++) {
if (thresholds[i] <= xp) result = i;
}
return result;
}