Lyndsee Elizabeth
Lyndsee Elizabeth

Reputation: 19

How do I sort a split array to read highest to lowest?

I need a little help sorting a split array into highest to lowest while keeping the names next to the scores. Im a little unsure how to do so because the array is split. Also, is there a way to let the user enter as many names and scores as they want without the program giving the user an error? So if they only want to enter 4 names and scores, all they have to do is press enter?

This is the code I have so far.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace proj09LEA
{
    class Program
    {
        static void Main(string[] args)
        {
            // declare and array of integers          
            string[] name = new string[5];
            int[] score = new int[5];

            Console.WriteLine("\nSaturday Coder's Bowling Team");
            Console.WriteLine("Enter in a name and score for each person on the team.");
            Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");

            // fill an array with user input
            for (int i = 0; i < score.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string line = Console.ReadLine();

                name[i] = line.Substring(0, line.IndexOf(' '));
                score[i] = int.Parse(line.Substring(line.IndexOf(' ') + 1));
            }

            Console.WriteLine("------------ Input Complete ------------\n");
            Console.WriteLine("Here are the scores for this game, from highest to lowest:\n");

            for (int i = 0; i < score.Length; i++)
            {
                if (score[i] >= 300)
                {
                    Console.WriteLine("{0}'s score was {1}*.", name[i], score[i]);
                }
                else
                {
                    Console.WriteLine("{0}'s score was {1}.", name[i], score[i]);
                }
            }

            AverageScore(score);

            Console.WriteLine("Press Enter to continue. . .");
            Console.ReadLine();
        }

        static void AverageScore(int[] score)
        {
            int sum = score.Sum();
            int average = sum / score.Length;
            Console.WriteLine("The average score for this game was {0:d}.\n", average);
        }
    }
}

Upvotes: 1

Views: 718

Answers (4)

KJacobK
KJacobK

Reputation: 11

List would be a better option and these come in built sorting options that would make your task easier.

Upvotes: 0

Ali Jammal
Ali Jammal

Reputation: 9

sort the array first using the Arrays.sort method then loop from

 for(int i= x.length-1;i>=0;i--)
     System.out.print(x[i]+"");

Should work this way

Upvotes: 0

icktoofay
icktoofay

Reputation: 129011

Let me first address the infinite-players question. Arrays, as you know, have a size, fixed at creation. There’s a data structure, List, though, that can have an unbounded (well, practically) number of elements. You might create one like this:

List<string> names = new List<string>();

Then if you want to add a new name, you can, for example, use

names.Add("Mary");

The rest of your code should work about the same; indexing works as normal, summing works as normal, etc.


Now what about sorting both of them together? Well, you don’t really have a list of names and a list of scores; what you really semantically have is a list of pairs of names and scores, or a list of players. You could first define a structure that represents a player:

struct Player {
    public string Name { get; set; }
    public int Score { get; set; }

    public Player(string name, int score) {
        Name = name;
        Score = score;
    }
}

Then you could just have a list of players:

List<Player> players = new List<Player>();

Instead of adding names and scores separately, we add them together:

string name = /* ... */;
int score = /* ... */;
players.Add(new Player(name, score));

Represented like this, your printing routine also becomes simpler. You can iterate through both at once:

foreach(Player player in players) {
    Console.WriteLine("{0} scored {1}", player.Name, player.Score);
}

Lastly, summing is a little trickier, but not too hard. Basically, we extract all of the scores and sum those:

int sum = players.Select((player) => player.Score).Sum();

But for you, the real benefit is finally being able to sort it:

players.Sort((x, y) => y.Score - x.Score);

Upvotes: 5

FisherDisinformation
FisherDisinformation

Reputation: 159

What you basically need is to take a look at HashMaps which are ADT's specifically for this purpose. Their structure is as follows:
-key1 : value1
-key2 : value2
.....
-keyn : valuen
your key here should be your score (but it can be anything). The value will be the name associated to the score.
Then , you can create a method sortKeys, depending on your implementation, which would take each key in the HashMap, move it at the end or at the beginning, while pointing to your name.
But please note that some HashMaps are randomly stored, so you will have to possibly make an array to write the sorted order of keys (and then lookup the key's value in the HashMap).

Upvotes: 0

Related Questions