Search code examples
c#.netarrayspercentageequivalence

Equivalence percentage between two array


i need a way to compare two array and compute the Equivalence percentage so if equivalence Percentage exceed (for example 60%) do some actions used language is C# .NET 4.0


Solution

  • The question is poorly defined, so I've taken some broad assumptions, but here's a sample implementation that measures equivalence based on element equality:

    int[] a = new int[] { 1, 2, 3, 4, 5 };
    int[] b = new int[] { 1, 7, 3, 4 };
    
    int equalElements = a.Zip(b, (i, j) => i == j).Count(eq => eq);
    double equivalence = (double)equalElements / Math.Max(a.Length, b.Length);
    if (equivalence >= .6)
    {
        // 60%+ equivalent
    }
    

    Zip: "Applies a specified function to the corresponding elements of two sequences." In this case, we're comparing each element from a with the corresponding element from b, and producing true if they're equal. For example, we compare 1 with 1, 2 with 7, 3 with 3, and 4 with 4. We then count the number of equalities we encountered, storing this value into equalElements. Finally, we divide this by the total number of elements in the larger sequence, and thus get the equivalence ratio.