I was wondering if there was a nice algorithm or if anyone know what would it be the best way to achieve the following:
I have 3 players competing online. I have to give them a place depending on the amount of fish the catch, first place, second place, and third place…
What would be the best way to calculate their respective places without having to use a long if() else{} or switch() statements? Is there a good method for this operation? Can anyone light my way?
Thanks for all of your input guy! The problem is that sorting doesn’t resolve the problem, because there are some times when 2 of the players will be tied. for example if there is a player with 2 fish, and the other two with 1 fish each one, then one player should be with a gold medal, and the other two with a silver medal each… Do you get it?
This isn’t really a math problem, and rather a logic problem.
step 1 - sort the collection, I would personally sort it descending so that index 0 is 1st place, index 1 is second, etc. This allows us to be independent of the number of players with out complicating the indexing
step 2 - set a flag for which place we’re giving out currently, it can be an int with values 1,2,3. We’re going to hand out awards in order from 1st to last place. So set the value to 1.
step3 - begin a loop over the collection
loop step 1 - hand out current award
loop step 2 - check if next player in collection exists,
next player exists: compare the number of fish to the current player. If the value differs increment the award. continue looping
next player doesn’t exist: exit loop
done
If we have a collection that hands out only 3 types of awards, and the player pool can be more than that. Then make sure you only loop for as many awards there are.
Thank you so much lordofduct. Got it. that is clever! I will go with that approach.
For a moment I thought that it was a math problem but when you describe the solution it was totally a logic problem.
players would be a array of your player objects, and this will return the same player objects but in the order of how many fish they caught descending. Than after this you can easily figure out who is 1st 2nd and 3rd place just by accessing the array index’s 0, 1, and 2.
edit:
to use the OrderBy method you will need to System.Linq Namespace