Search code examples
c#arraysnested-loops

How can I count the number of times a value reoccurs within the same array?


As the title says, I'm trying to count the number of times a value reoccurs within the same array. So, for example, if there was an array with the values 1, 1, 2, 2, the output would look something like: Value (1) occurred (2) times \n Value (2) occurred (2) times. Here's what I have so far:

foreach (var i in anArray)
{
    foreach (var m in secondArray)
    {
        if (i == m)
        {
            count++;
        }
    }
    Console.WriteLine("\nValue " + i + " occurred " + count + " times"); 
}

I created a copy of the first array(secondArray) and am trying to make due comparing the arrays, but something is not right. The nested loop counts my values twice. So, where it would say: value (1) occurred (2) times, the next readout says: value (1) occurred (4) times, instead of moving on to the next value that's not (1). I realize it's counting the second (1) and adding the previous count to it...least I think I realize. How can I get around this only using arrays and no lists?


Solution

  • In your current design, you can just set count up front:

    foreach (var i in anArray)
    {
        count = 0; // Initialize each loop
        foreach (var m in secondArray)
        {
            if (i == m)
            {
                count++;
            }
        }
        Console.WriteLine("\nValue " + i + " occurred " + count + " times"); 
    }
    

    That being said, you could build a dictionary from the second array, and use that:

    var dict = secondArray.GroupBy(v => v).ToDictionary(g => g.Key, g => g.Count());
    foreach(var i in anArray)
    {
        if (dict.ContainsKey[i])
            Console.WriteLine("\nValue " + i + " occurred " + dict[i] + " times"); 
        else
            Console.WriteLine("\nValue " + i + " occurred 0 times"); 
    }