Search code examples
c#algorithmpseudocode

compare two arrays and show count of characters


I have two arrays:

 string[] array1 = {"a","b","c","d","e"}

 string[] array1 = {"x","y","a","b","a"}

I want to print the result like this:

a = 3
b = 2
c = 1
d = 1
e = 1
x = 1
y = 1
z = 1

I can run a loop inside the loop and find this out but is there a better way to achieve the same result?

I want to do this in plain C# without using LINQ.


Solution

  • You can use LINQ to accomplish this:

    var counts = array1.Concat(array2)
                      .GroupBy(v => v)
                      .Select(g => new { Value=g.Key, Number=g.Count() });
    
    foreach(var item in counts.OrderBy(i => i.Value))
        Console.WriteLine("{0} = {1}", item.Value, item.Number);
    

    Given that you want to avoid using LINQ and the extension methods for some reason, you could build your own dictionary:

    var counts = new Dictionary<string, int>();
    foreach(string item in array1)
    {
        if (counts.ContainsKey(item))
            counts[item]++;
        else
            counts[item] = 1;
    }
    foreach(string item in array2)
    {
        if (counts.ContainsKey(item))
            counts[item]++;
        else
            counts[item] = 1;
    }
    
    // Print out counts
    foreach(var kvp in counts)
        Console.WriteLine("{0} = {1}", kvp.Key, kvp.Value);
    

    Note that this doesn't sort the results - if you need them sorted, you'd have to do that as well.