【问题标题】:Array to Sort High Scores对高分进行排序的数组
【发布时间】:2014-05-19 14:46:45
【问题描述】:

我正在使用 C# 编写一个项目,该项目涉及跟踪石头剪刀布游戏的前五名高分。现在我有一个数组来保存前五个分数(它们是整数),我按降序对数组进行排序,并使用 for 循环将用户刚刚获得的分数与数组中当前的分数进行比较。如果新分数高于数组中的 1,则现在新分数只占用数组中较低分数所占用的空间。

例如,如果分数是 9、8、5、3、1,而用户的分数是 6,那么分数将如下所示:9、8、6、3、1。我想知道是否有办法让我把较低的分数移过来并插入新的,所以列表看起来像这样:9、8、6、5、3。

这是我目前拥有的代码,其中 successPercent 是得分,计算方式为胜利除以失败和平局:

int[] scoreArray = { 84, 25, 36, 40, 50 };

Array.Sort(scoreArray);
Array.Reverse(scoreArray);

for (int x = 0; x <= scoreArray.Length; ++x)
{
    if (successPercent > scoreArray[x])
    {
        scoreArray[x] = Convert.ToInt32(successPercent);
        break;
    }
}

【问题讨论】:

  • 调用 Sort 时,Array 会进行排序。不清楚为什么每次添加新分数时不能只调用 Sort?
  • 是的,为什么不直接添加新分数、排序并删除最后一个元素?甚至不用费心循环。为了提高效率,您可以跟踪前 5 名中的最低分数。如果分数不大于最低分数,您就什么也不做。
  • 如果需要,只需将分数存储在 List&lt;T&gt; 中,而不是数组,这样可以提供更多方法。就像在某个位置添加和删除一样。

标签: c# arrays sorting


【解决方案1】:

这样的事情可以解决问题:

  • 创建临时列表
  • 添加新分数
  • 降序排列
  • 获得前 5 名...

    int[] scoreArray = { 84, 25, 36, 40, 50 };
    
    var tempList = new List<int>(scoreArray );
    int newScore = ...;//Get the new score
    tempList.Add(newScore);
    
    scoreArray = tempList.OrderByDescending(x=>x)
                     .Take(5)
                     .ToArray();
    

【讨论】:

    【解决方案2】:

    您可以在不创建新列表的情况下执行此操作。

    [算法]:用新数替换最小的数,然后排序!

    int[] scoreArray = { 5, 3, 9, 8, 1 };
    
            int new_number = 6;
    
            //Replaces smallest number by your new number
            int min_index = Array.IndexOf(scoreArray, scoreArray.Min());
            scoreArray[min_index] = new_number;
    
            Array.Sort(scoreArray);
            Array.Reverse(scoreArray);
    

    【讨论】:

      【解决方案3】:

      我相信你的方法是正确的,比创建冗余列表更有效,只是你不必要地调用Reverse 方法。相反,让你的元素按升序顺序排序,然后循环遍历数组,并按降序顺序对其进行排序。

      int[] scoreArray = { 84, 25, 36, 40, 50 };
      int userScore = 100;
      
      Array.Sort(scoreArray);
      
      for (int x = 0; x <= scoreArray.Length; ++x)
      {
           if (userScore > scoreArray[x])
           {
               scoreArray[x] = Convert.ToInt32(userScore);
               break;
           }
      }
      
      Array.Sort(scoreArray,(x,y) => y.CompareTo(x));
      

      注意:我的第一个解决方案是丢弃第二高的分数,因此我将其删除。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-28
        • 2012-07-04
        • 2019-06-22
        • 2023-01-26
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多