Reputation: 5259
First the thread name might be a little strange but i will try my best to explain what i want to do here so you can suggest me a good thread name.
I want to create a function to return the employee level by checking his experience
If experience is 0~50 he is level 1 If experience is 50~150 he is level 2 ... and so on till level 100
What i am thinking of is creating a const int that holds all required exp for each level
public const int Level1 = 50,
Level2 = 150...;
so is there a way to make a function to return what i want ? without the use of 1000++ lines ?!.
Please don't consider my question as a spam i am only very confused and i will try my best to clarify my idea if needed.
Upvotes: 1
Views: 137
Reputation: 1917
Since the formula for the xp required for the level x
seems to be 25*(x²+x)
You can use the inverse function :
public int GetLevel(int xp)
{
return (int)(Math.Sqrt(1 + 4 * xp / 25) - 1) / 2;
}
Upvotes: 1
Reputation: 3548
int level = Math.Min(10, experience / 10);
Would that do?
If you want to have 0-10 -> 1 and 11-20 -> 2 etc, change it like this:
int level = Math.Min(10, (experience + 9) / 10);
If there is no pattern at all in experience gains, or some very obscure one, you could use this:
var level = 1;
var levelRequirements = new int[] {10, 20, 50, 150, 300};
for (int i = 0; i < levelRequirements.Length; i++)
{
if (levelRequirements[i] > currentExperience)
break;
level++;
}
And now for my final update:
var level = 0;
var levelRequirement = 0;
var levelRequirementAddition = 50;
while (currentExperience >= levelRequirement)
{
levelRequirement += levelRequirementAddition;
levelRequirementAddition += 50;
level++;
}
Upvotes: 2
Reputation: 31184
public int ReturLevel(int experience)
{
return (experience-1)/10 + 1;
}
you may remove the -1
in (experience-1)
if you meant "If experience is 1~9"
leave it if you meant "If experience is 11~20 he is level 2"
Edit:
IF your experience to level function doesn't follow any pattern, than Yes, you'll have to make a separate case for each one of them.
if(experience > 20)
return level 3;
else if(experience > 10)
return level 2;
else
return level 1;
different design patterns can affect how and were you add these different cases, but they'll have to be added if you have no pattern.
Upvotes: 1