I trying to create a points calculating system with javascript, but the problem is with the mathematical part. I have saved on the server the points number, and based on that number I want to decide the level. Sorry for my bad english, I cant explain very well :D. I want something like: level 1 need 0 points
level 2 needs 100 points
level 3 needs 240 points
level 4 needs 420 points
level 5 needs 640 points
and so on....
I need a mathematical function to calculate each level with it. Something that if I know the level to calculate the points needed, and if I know only the points to calculate the level.
views:
79answers:
4
+1
A:
ummm, I have a vague idea of what you're going for
var levels = [0, 100, 240, 420, 640];
function GetLevel(points)
{
for(i == levels.length - 1; i >= 0; i--)
{
if (points >= levels[i]) return i + 1;
}
}
points to next level
function PointsToNextLevel(currentPoints)
{
var level = GetLevel(currentPoints);
if (level == levels.length) return 0;
return levels[level - 1] - currentPoints;
}
hunter
2010-05-11 13:46:51
+2
A:
var levels = {
1: 0,
2: 100,
3: 240,
4: 420,
5: 640}
function get_level(points){
for (level in levels){
if (points < levels[level]){
return level - 1;
}
}
}
This simply takes the levels hash and itenerates through the levels, until the points is higher than the level's minimum, returning the last level.
CodeJoust
2010-05-11 13:47:14
While that works for the numbers given, I think the OP wants a general solution for the series he's given. See my answer below
pheelicks
2010-05-11 14:19:01
+1
A:
this function should solve your problem and, to me, seems very easy to understand:
function getLevel(points)
{
var levels = [0,100, 240, 420, 640];
var maxLevel = levels.length;
var i;
for (i=0;i<maxLevel;i++) {
if (levels[i]>points) return i;
}
return maxLevel;
}
Eineki
2010-05-11 13:49:22
+2
A:
To generate the series you've provided use:
function getPoints(level)
{
return 20*(level-1)*(level+3);
}
To get the level from the points is a bit more tricky, you need to invert the above formula using the quadratic formula and then take the positive solution:
function getLevel(points)
{
var level = -1 + Math.sqrt(4 + points/20);
// Round down to nearest level
return Math.floor(level);
}
Also, in the future try and make your questions clearer. As you can see three people (at least) misunderstood your question - it wasn't clear that you set of levels was a mathematical series.
pheelicks
2010-05-11 14:07:21
Thanks, I will try it, I was looking for something like this, thanks Hunter, and thanks for everybody who tried ! And sorry for the unclear question - I don`t know very well english :(
coolboycsaba
2010-05-11 17:03:10
Thanks for noticing the series part of the numbers, I didn't understand the question in that way.
CodeJoust
2010-05-12 01:24:12
The second function is working but I`ve noticed that the first one is not working , please help me to solve it :) ?
coolboycsaba
2010-05-14 21:47:11