Gixty
Gixty

Reputation: 202

How to get a user level from total points and known factor?

I know this is basic calc but I am a bit rusty and I want to be sure I am doing it right.

I am implementing a user level system on my site and I need to display each user's level on their profile. They already have some points and from this I want to calculate what level they are on.

I want to increase the level by a factor of 3 where the first level is just 1 point.

So, I would proceed as follows:

level = 0;
factor = 3;
points = 243; //as an example, this would be level 6.

while (points >= 1) {
  points = points/factor;
  level++;
}

What would you recommend me do? Is this the best way? Is there a more effective way? I am looking for performance and scalability.

Upvotes: 0

Views: 36

Answers (1)

Kolmar
Kolmar

Reputation: 14224

The easiest way is to use the equivalent of ceiling(log base 3 of (points + 0.5)) in your language. The +0.5 here fixes possible floating point errors and allows to use 0 for points.

For example in Python:

import math

def levels(points):
    return math.ceil(math.log(points + 0.5, 3))

In C/C++:

#include "math.h"

int levels(int points) {
    return 1 + (int)(log(points + 0.5) / log(3.0));
}

And so on.

If this approach works too slowly for your taste in your target language, then just do what you have proposed: divisions in a cycle.

Upvotes: 1

Related Questions