How do I split an array into two different arrays?

I cannot figure out how to fix my code to make it work. I need the user to be able to enter their name followed by a space followed by what they typed. Then I need to split the array into two different arrays and pass them to four different ways of displaying to the user what they typed, etc. Can anyone help me understand this problem?

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
            int[] array = new int[10];

            Console.WriteLine("\nSaturday Coder 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 < array.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string userInput;
                string[] parsedInput;
                parsedInput = userInput.Split();
                string name = parsedInput[0];
                int score = int.Parse(parsedInput[1]);

            }

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

            DisplayScore(array);
            HighScore(array);
            LowScore(array);
            AverageScore(array);

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

        static void DisplayScore(int[] array)
        {
            foreach (int n in array)
            {
                Console.WriteLine("{0} score was {0}.\n", array);
            }
        }

        static void HighScore(int[] array)
        {
            int max = array.Max();
            Console.WriteLine("Congratulations {0}, your score of {0} was the highest.", max);
        }

        static void LowScore(int[] array)
        {
            int min = array.Min();
            Console.WriteLine("{0}, your score of {0} was the lowest. Better get some practice.", min);
        }

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

      

+3


source to share


4 answers


If you absolutely need to use simple primitive arrays, you will need two different arrays of the same size to hold names as strings and evaluates as ints:

class Program
{
    const int MaxScores = 10;  // .. Use a constant to ensure the sizes remain in sync
    static void Main(string[] args)
    { ///
        string[] names = new int[MaxScores];
        int[] scores = new int[MaxScores];
        // ... parse names into names[] and scores into scores[]

        DisplayScore(names, scores);

      

Then you need to pass both arrays to different methods:

static void DisplayScore(string[] names, int[] scores)
{
   for(int i=0; i < MaxScores; i++)
   {
       Console.WriteLine("{0} score was {1}.\n", names[i], scores[i]);
   }
}
// etc

      

However, there are more efficient ways to do this, for example. defining a custom class for the tuple Name, Score

:



class PersonScore
{
    public string Name {get; set;}
    public int Score {get; set;}
}

      

Then you can declare and pass a single array PersonScore[]

around.

PersonScore[] personScores = new PersonScore[MaxScores];
for (... prompting the user for data) 
{
   ... parsing user input
   personScores[i] = new PersonScore{Name = name, Score = score};
}
DisplayScore(personScores); // Pass around the single array

static void DisplayScore(IEnumerable personScores)
{
   foreach(var personScore in personScores)
   {
       Console.WriteLine("{0} score was {1}.\n", personScore.Name, personScores.Score);
   }
}
// etc - other methods

      

As mentioned, other collections are also an array alternative, more often than not List

.

+1


source


You can do it. Just use Console.ReadLine () to get user input. This is what you do in your code. There are better ways to do this, but the following will solve your problem. Also you need to do a check.



for (int i = 0; i < array.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string userInput = Console.ReadLine();
                string[] parsedInput;
                parsedInput = userInput.Split(' ');
                string name = parsedInput[0];
                int score = int.Parse(parsedInput[1]);
                array[i] = score;
            }

      

0


source


Why do you need to split the array into two arrays for names and others containing an evaluation. Better to create a structure that has a String field for the name and an integer field to evaluate, and write a Comparator to sort the elements containing an Array of that data structure type and sort them.

It will solve all your problems and it will be too effective.

0


source


Not a lot of data consistency checks in the methods you use, but here are the extensions I use to split arrays or any type of enumeration. I haven't tested that many of them, so I cannot guarantee that they will work. I removed all my input checks, but I suggest you add them back in your own way.

    public static List<List<T>> Split<T>(this IEnumerable<T> collection, Int32 groupSize)
    {
        var collectionList = collection.ToList();
        if (groupSize > collectionList.Count)
            groupSize = collectionList.Count;

        var chunks = new List<List<T>>();
        while (collectionList.Any())
        {
            var chunk = collectionList.Take(groupSize);
            chunks.Add(chunk.ToList());
            collectionList = collectionList.Skip(groupSize).ToList();
        }

        return chunks;
    }

    public static List<List<T>> Split<T>(this IEnumerable<T> collection, Func<T, Boolean> splitFunction)
    {
        var collectionList = collection.ToList();

        if (collectionList.IsNullOrEmpty())
            return new List<List<T>>();
        var indices = collectionList.FindIndices(splitFunction); // Custom method that searches for the indices that satisfy the predicate and returns the index of each matching item in the list.
        if (indices.IsNullOrEmpty()) // equivalent to indices == null || !indices.Any()
            return new List<List<T>> { collectionList };

        var chunks = new List<List<T>>();
        var lastIndex = 0;
        if (indices[0] > 0)
        {
            chunks.Add(collectionList.Take(indices[0]).ToList());
            lastIndex = indices[0];
        }

        for (var i = 1; i < indices.Count; i++)
        {
            var chunkSize = indices[i] - lastIndex;
            var chunk = collectionList.Skip(lastIndex).Take(chunkSize).ToList();
            if (chunk.IsNullOrEmpty())
            {
                break;
            }
            chunks.Add(chunk);
            lastIndex = indices[i];
        }

        if (collectionList.Count - lastIndex > 0)
        {
            var lastChunk = collectionList.Skip(lastIndex).ToList();
            chunks.Add(lastChunk);
        }

        return chunks;
    }

      

0


source







All Articles