-4

我需要一种方法来比较两个数组并计算等价百分比,所以如果等价百分比超过(例如 60%),则使用 C# .NET 4.0 语言执行一些操作

4

2 回答 2

2

这个问题定义不明确,所以我做了一些广泛的假设,但这里有一个示例实现,它基于元素相等性来衡量等价性:

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: "将指定函数应用于两个序列的对应元素。" 在这种情况下,我们将每个元素 froma与对应的元素 from进行比较btrue如果它们相等则产生。例如,我们比较1with 1, 2with 7, 3with 3, and 4with 4。然后我们计算遇到的等式的数量,将此值存储到equalElements. 最后,我们将其除以较大序列中的元素总数,从而得到等价比。

于 2014-06-17T20:08:16.533 回答
-1

假设您正在比较两个 int 列表(或数组,它是相同的),您可以通过以下方式计算等效元素的list1百分比list2

List<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
List<int> list2 = new List<int>() { 3, 5, 8 };
var res = list1.Intersect(list2).ToList().Count();
float perc = (float)list1.Count() / res;
于 2014-06-17T20:08:02.720 回答