Search code examples
phpoptimizationlevelsexp

Get level by experience


I have this code:

 function getLevels($cEXP) {  // $cEXP is current player experience

    $i = 1;
    while(!$n) {
    $NextLevelXP = pow($i,3) + 2 * $i;
        if($NextLevelXP > $cEXP) {
            $AllLevels = $i;
            break;
        }
    $i++;
    }
}

All what I need to know is about optimize possibilities for that, or alternative to get levels amount by $NextLevelXP = pow($CurrentLevel,3) + 2 * $CurrentLevel; equation.


Solution

  • You can even do binary search on the value to get O(logN) algorithm instead of O(N), but as N is the number of levels which I don't think that will be more than 1000, no need to complicate the code. You can do the same you did but with more short code:

    function getLevels($cEXP) {
        for($i = 1; ($i * $i + 2) * $i <= $cEXP; $i++);
        return $i - 1;
    }
    

    P.S. Note that I got rid of pow, try to avoid it to keep dealing with only integers.