像这样的东西应该是你正在寻找的东西。请记住,考虑到我是按照大脑的想法写下来的,它并没有完全优化。
我们可以从我们的分数数组开始(根据提供的示例):
int[] scores = { 0, 0, 3, 3, 5 };
接下来,我们可以把数据换成不同的形式,这样更容易排序:
Dictionary<int, int> playerScorePair = new Dictionary<int, int>();
//Loop through scores[] and add each player # and score to the Dictionary.
for (int i = 0; i < scores.Length; i++)
playerScorePair.Add(i, scores[i]);
playerScorePair = playerScorePair.OrderByDescending(psp => psp.Value)
.ToDictionary(psp => psp.Key, psp => psp.Value);
这会根据每个玩家的分数按降序对字典进行排序。之后,我们可以找出每个玩家进来的地方:
int previousScore = -1, counter = 1, place = 1; //A few starting variables.
int totalPlayers = playerScorePair.Count;
int[] endScores = new int[scores.Length]; //This endScores[] array will hold the final scores for each player based on the place they finished in.
foreach (KeyValuePair<int, int> kvp in playerScorePair)
{
//If the previous score is not equal to the current score, then we can
// increment the current place. For example, if players 1-2-3 had scores of
// 10-10-5 respectively, players 1 and 2 would be in first, but player 3 would be
// equal to "counter", which would be the 3rd iteration, thus 3rd place.
if (previousScore != kvp.Value && previousScore != -1)
place = counter;
endScores[kvp.Key] = (totalPlayers - place) + 1;
previousScore = kvp.Value;
counter++;
}
endScores
现在将包含基于每个玩家进入的位置的所有分数。例如,玩家 #2 将endScores[2]
等于 4。