0

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.

Jesse Jashinsky
  • 10,313
  • 6
  • 38
  • 63
Gixty
  • 202
  • 4
  • 13
  • _'I want to be sure I am doing it right'_ - most people test their code by running it and comparing the results with their objective. There's only a small amount of code here - what do you want us to say? –  Jan 20 '15 at 23:17

1 Answers1

1

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.

Kolmar
  • 14,086
  • 1
  • 22
  • 25
  • I like your answer. I am working with php... I will have to test which way is faster. – Gixty Jan 20 '15 at 23:39
  • 1
    @Gixty Approach with log is actually likely to be faster in PHP (it probably defers straight to the C++ library), than the division one starting from around levels 3-6. In PHP, I think, `ceil(log(points + 0.5, 3))` would work. – Kolmar Jan 20 '15 at 23:48