Basically I’m trying to get a “rankings” between 4 people. I have an array of player scores which contains the scores of each person such that person 1’s score is at index 0, person 2’s score is at index 1, etc… I want to obtain the index of the top scorer in the list and get the second, and the third, and the last.
My attempt at the solution:
I made a list out of the array playerScores (I feel like it might not be necessary, but due to what I’m about to do, I didn’t want to ruin the original scores) which contains the scores in order. And then, I find the max number in the list and get its index. Then I change the value to a negative value at that index. And then I redo the steps.
List<int> listOfScores = new List<int>(playerScores.ToList());
// We get the max value to determine the top scorer of the game
// and then we insert a negative value at that same spot of the list so we can
// continue on figuring out the following max value in the list, etc.
rank1 = listOfScores.IndexOf(listOfScores.Max());
listOfScores[rank1] = -1;
rank2 = listOfScores.IndexOf(listOfScores.Max());
listOfScores[rank2] = -1;
rank3 = listOfScores.IndexOf(listOfScores.Max());
listOfScores[rank3] = -1;
rank4 = listOfScores.IndexOf(listOfScores.Max());
listOfScores[rank4] = -1;
I feel like I can do this in a much more efficient manner and as less messy as this code…
Well, this is also assuming that negative is not a score a person can get. Is there any other way, to be more efficient than this? And what about if say we want to have negative scores?
Using LINQ:
And then display the winner, for example: