HiveBrain v1.2.0
Get Started
← Back to all entries
principlecsharpMinor

Optimal way to Compare two arrays that are widely different

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraysoptimalarewaydifferenttwothatwidelycompare

Problem

I have two different arrays that are widely different in length, arrayA, arrayB

for example:arrayA.Length=1000 and arrayB.Length=100,000

Create a boolean function that returns true if each item in arrayA are also present in arrayB, at least the same number of times as in arrayA.

Please review my code below and help me with siuggestions to improve this code below

private static bool IsMinRequiredFrequencyMatch(int[] arrA,int[] arrB)
    {
    bool result = false;        
    Array.Sort(arrA);

    //create dictionary from shorter array 
    var dict = new Dictionary();
    for (int i = 0; i = expectedcount)
            {
                result = true;
                break;
            }
        }

        if (actualCount < expectedcount)
        {
            result = false;             
            break;
        }
    }

    return result;

}

Solution

Sure, you can always write your own method for everything but if you are lazy you could just use LINQ with ToLookup + All + Count

var arr1 = new[] { 1, 2, 3, 4, 3, 2 };
var arr2 = new[] { 6, 7, 3, 4, 1, 2, 2, 3 };

var lookup1 = arr1.ToLookup(x => x);
var lookup2 = arr2.ToLookup(x => x);

var isFullyContained = lookup1.All(x => lookup2[x.Key].Count() == x.Count());


false - means arr1 is fully contained in arr2

The good thing about lookup is that you don't need the ContainsKey method because if the key does not exist it'll return an empty collection.

Review

You create a dictionary only for the first array but you need one for the second array too or otherwise you need to loop over it each time which is unnecessary. Just count the items and compare their counts.

Code Snippets

var arr1 = new[] { 1, 2, 3, 4, 3, 2 };
var arr2 = new[] { 6, 7, 3, 4, 1, 2, 2, 3 };

var lookup1 = arr1.ToLookup(x => x);
var lookup2 = arr2.ToLookup(x => x);

var isFullyContained = lookup1.All(x => lookup2[x.Key].Count() == x.Count());

Context

StackExchange Code Review Q#159871, answer score: 2

Revisions (0)

No revisions yet.