2014-05-19 43 views
1

我正在C#項目中工作,涉及跟蹤岩石剪刀遊戲的前五名高分。現在我有一個數組來保存前五個分數(它們是整數),我按降序對數組進行排序,然後使用for循環將剛剛由用戶獲得的分數與數組中當前的分數進行比較。如果新分數高於陣列中的一個分數,那麼現在新分數只需要陣列中較低分數佔據的空間。Array to Sort High得分

例如,如果得分爲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; 
    } 
} 
+0

當您調用Sort時,Array將進行排序。不清楚爲什麼每次添加新分數時都不能調用Sort? –

+4

是的,爲什麼不只是添加新的分數,排序,並刪除最後一個元素?甚至不打擾循環。爲了進一步提高效率,您可以跟蹤前5名的最低分數。如果分數不大於最低分數,那麼您就不會執行任何操作。 – tnw

+1

如果您需要,只需將分數存儲在'List '中,而不是數組,它將提供更多的方法來處理。如在某個位置添加和刪除。 – bubbinator

回答

0

您可以在不創建新列表的情況下執行此操作。

[算法]:將最小數字替換爲新數字,然後排序!

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); 
4

像這樣的事情可以做的伎倆:

  • 創建臨時表
  • 添加新的得分
  • 排序它由降序排列
  • 取前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(); 
    
0

我相信你的方法是正確的,更EFFIENT比創建多餘的名單,只是你不必要地調用Reverse方法。相反,將你的元素排序在升序順序,然後循環通過t他列陣,並在降序排序。

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)); 

注:我的第一溶液丟掉第二最高得分,所以我已經刪除了它。