Nghia Le
Nghia Le

Reputation: 51

Shorten the foreach index

This program was written so that for a user to input a list of number from 0-10 and then the program determines how many values were inputted and Output a list of distinct entries and a count of how many times that entry occurred.

Im looking for a way to shorten the foreach index.

    static void Main(string[] args)
    {
        int [] emptyArray = new int [100];
        string inPut;
        int count= 0;


        Console.WriteLine("Please enter intergers between 0-10: " + "((00 to exit)) ", count + 1);
        inPut= Console.ReadLine();

        while(inPut !="00")
        {
            emptyArray[count]= Convert.ToInt32(inPut);
            ++count;
            Console.WriteLine("Please enter intergers between 0-10: " + "((00 to exit)) ", count + 1);
            inPut= Console.ReadLine();
        }

            int a = 0;
            foreach (int value in emptyArray)
            if (value == 1) ++a;
            Console.WriteLine("The number of times ONE was inputed was {0}",a);

            int b = 0;
            foreach (int value in emptyArray)
            if (value == 2) ++b;
            Console.WriteLine("The number of times TWO was inputed was {0}", b);

            int c = 0;
            foreach (int value in emptyArray)
            if (value == 3) ++c;
            Console.WriteLine("The number of times THREE was inputed was {0}", c);

            int d = 0;
            foreach (int value in emptyArray)
            if (value == 4) ++d;
            Console.WriteLine("The number of times FOUR was inputed was {0}", d);

            int e = 0;
            foreach (int value in emptyArray)
            if (value == 5) ++e;
            Console.WriteLine("The number of times FIVE was inputed was {0}", e);

            int f = 0;
            foreach (int value in emptyArray)
            if (value == 6) ++f;
            Console.WriteLine("The number of times SIX was inputed was {0}", f);

            int g = 0;
            foreach (int value in emptyArray)
            if (value == 7) ++g;
            Console.WriteLine("The number of times SEVEN was inputed was {0}", g);

            int h = 0;
            foreach (int value in emptyArray)
            if (value ==8) ++h;
            Console.WriteLine("The number of times EIGHT was inputed was {0}", h);

            int i = 0;
            foreach (int value in emptyArray)
            if (value == 9) ++i;
            Console.WriteLine("The number of times NINE was inputed was {0}", i);

            Console.Read();
    }
}

}

Upvotes: 0

Views: 268

Answers (5)

ilias
ilias

Reputation: 2682

Lots of ways to do this I suppose. You will be spoilt for choice :) Here's mine

var l = emptyArray.ToLookup (a => a);
var nums = new string[]{"zero","one","two","three","four","five","six","seven","eight","nine"};
foreach (var element in l)
{
    Console.WriteLine ("The number of times " + nums[element.Key] + " was inputed was " + element.Count ());          
}

Upvotes: 0

tukaef
tukaef

Reputation: 9214

var counts = emptyArray.GroupBy(x => x)
                       .Select(x => new {Key = x.Key, Count = x.Count()});

foreach (var p in counts)
{
    Console.WriteLine("The number of times {0} was inputed was {1}", 
                      p.Key.AsWord(), p.Count);
}

Extension Method AsWord is defined here:

public static class Extensions
{
    public static string AsWord(this int num)
    {
        switch (num) 
        {
            case 1: return "ONE";  
            case 2: return "TWO";
            // ...
            default: throw new ArgumentException("num");
        }
    }
}

Upvotes: 2

Kiril
Kiril

Reputation: 40345

Solution #1

Use a dictionary to count the frequency of inputs:

string[] digits = new string[]{"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"};

Dictionary<int, int> frequencyMap = new Dictionary<int,int>();

int [] emptyArray = new int[100];

After you get your input and you populate the "emptyArray", then you map the frequencies:

//... blah blah 
foreach(int value in emptyArray)
{
    if(!frequencyMap.ContainsKey(value))
    {
        frequencyMap.Add(value, 0);
    }
    frequencyMap[value]+=1;
}

// Now print the frequencies
foreach(int key in frequencyMap.Keys)
{
    Console.WriteLine("The number of times {0} was inputed was {1}", digits[key], frequencyMap[key]);
}

Solution #2

The above solution is very robust and if you get rid of having to print the digits, then you will be able to count any digit input without having to worry about printing it. If you're strictly falling within the range of 0-9, then you can do skip the dictionary and directly use an array:

int[] frequencyMap = new int[10];
for(int i = 0; i < frequencyMap.Length; i++)
{
    frequencyMap[i] = 0;
}

foreach(int value in emptyArray)
{
    if(value>0 && value <10)
    {
        frequencyMap[value]+=1;
    }
}

// Now print the frequencies
foreach(int key in frequencyMap)
{
    Console.WriteLine("The number of times {0} was inputed was {1}", digits[key], frequencyMap[key]);
}

Upvotes: 2

phoog
phoog

Reputation: 43046

Perhaps you want a List<int> rather than an int[100] -- the List<int> will adjust to the count of items actually added to it, so foreach will return only the number of items actually input by your user.

This smells a bit like a homework exercise, so you might be required to use an array. In case this is correct, I won't give a full solution, but just suggest that you should use a for loop rather than a foreach loop.

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156469

Use a Lookup:

var lookup = emptyArray.ToLookup(i => i);

Console.WriteLine("The number of times ONE was inputed was {0}", lookup[1].Count());
Console.WriteLine("The number of times TWO was inputed was {0}", lookup[2].Count());
/// etc.

Upvotes: 4

Related Questions