elementaryDeduction
elementaryDeduction

Reputation: 13

Array to Sort High Scores

I'm working on a project in C# that involves keeping track of the top five high scores for a rock paper scissors game. Right now I have an array to hold the top five scores (which are integers), I sort the array in descending order, and I use a for loop to compare the score just earned by the user to the scores currently in the array. If the new score is higher than one in the array, right now the new score just takes the space in the array that the lower one occupied.

For example, if the scores were 9, 8, 5, 3, 1 and the user scored a 6, the scores would then look like this: 9, 8, 6, 3, 1. I wondered if there's a way for me to shift the lower scores over and insert the new one, so the list would look like this: 9, 8, 6, 5, 3.

This is the code I currently have, where successPercent is the score, calculated as wins divided by losses and ties:

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

Upvotes: 1

Views: 2433

Answers (3)

Azeem Ghumman
Azeem Ghumman

Reputation: 71

You can do this without creating a new list.

[Algo]: Replace the smallest number by the new number and then sort!

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

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

I believe your way is correct and more effient than creating redundant lists, just you are calling the Reverse method unnecessarily.Instead, leave your elements sorted in ascending order, then loop through the array, and sort it in descending order.

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

Note: My first solution was throwing away the second highest score so I have deleted it.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

Something like this can do the trick:

  • Create temporary list
  • Add new score
  • Sort it by descending order
  • Take top 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();
    

Upvotes: 4

Related Questions