计算2个数组有多少位置包含相等的元素
Calculate how much positions of 2 arrays contain equal elements
我有 2 个 arrays
长度相同,我需要计算它们的位置中有多少包含相同的元素。我做了这个函数,但我觉得它可以在不创建 tuple
的情况下完成。有没有更广泛、更简单的方法来做到这一点?
static int GetCoincidence(int[] a, int[] b)
{
return a.Zip(b, Tuple.Create).Where(x => x.Item1 == x.Item2).Select(x => 1).Sum();
}
恕我直言,由于使用 Zip()
创建所需的并行枚举,您的解决方案相当优雅。另一种方法是自己显式管理 IEnumerator<T>
对象,这不太好。
我要做的一个改变是使用 Count()
而不是 Where()
、Select()
和 Sum()
:
static int GetCoincidence(int[] a, int[] b)
{
return a.Zip(b, Tuple.Create).Count(x => x.Item1 == x.Item2);
}
请注意,使用这种方法,您可以使用任何 IEnumerable<T>
实现来实现目标,而不仅仅是数组。如果您对仅使用 数组感到满意,则可以使用提供索引的 Where()
重载,如 .
您可以使用 LINQ 除了这个。
以下是如何操作的示例:
public static int GetCoincidence(int[] a, int[] b)
{
return a.Count()-a.Except(b).Count();
}
这个怎么样:
static int GetCoincidence(int[] a, int[] b)
{
return a.Where((x,i)=>x==b[i]).Count();
}
试试这个 Example 用法:
int[] a= {1,2,3,4,55,6,77,7,8,9};
int[] b= {1,2,3,4,34,5,79,7,8,9};
Console.WriteLine(GetCoincidence(a,b));
// Output will be 7
没有 Tuple
的替代方案(我试图 保留 你的想法 Sum
):
int[] a = new int[] { 1, 2, 3, 4, 4, 5, 9};
int[] b = new int[] { 7, 8, 3, 4, 4, 8};
int count = a
.Zip(b, (left, right) => left == right ? 1 : 0)
.Sum();
var common = (from elemA in a.Select((x, y) => new { Value = x, Index = y })
join elemB in b.Select((x, y) => new { Value = x, Index = y })
on new { elemA.Index, elemA.Value } equals new { elemB.Index, elemB.Value }
select elemA).ToList();
我有 2 个 arrays
长度相同,我需要计算它们的位置中有多少包含相同的元素。我做了这个函数,但我觉得它可以在不创建 tuple
的情况下完成。有没有更广泛、更简单的方法来做到这一点?
static int GetCoincidence(int[] a, int[] b)
{
return a.Zip(b, Tuple.Create).Where(x => x.Item1 == x.Item2).Select(x => 1).Sum();
}
恕我直言,由于使用 Zip()
创建所需的并行枚举,您的解决方案相当优雅。另一种方法是自己显式管理 IEnumerator<T>
对象,这不太好。
我要做的一个改变是使用 Count()
而不是 Where()
、Select()
和 Sum()
:
static int GetCoincidence(int[] a, int[] b)
{
return a.Zip(b, Tuple.Create).Count(x => x.Item1 == x.Item2);
}
请注意,使用这种方法,您可以使用任何 IEnumerable<T>
实现来实现目标,而不仅仅是数组。如果您对仅使用 数组感到满意,则可以使用提供索引的 Where()
重载,如
您可以使用 LINQ 除了这个。 以下是如何操作的示例:
public static int GetCoincidence(int[] a, int[] b)
{
return a.Count()-a.Except(b).Count();
}
这个怎么样:
static int GetCoincidence(int[] a, int[] b)
{
return a.Where((x,i)=>x==b[i]).Count();
}
试试这个 Example 用法:
int[] a= {1,2,3,4,55,6,77,7,8,9};
int[] b= {1,2,3,4,34,5,79,7,8,9};
Console.WriteLine(GetCoincidence(a,b));
// Output will be 7
没有 Tuple
的替代方案(我试图 保留 你的想法 Sum
):
int[] a = new int[] { 1, 2, 3, 4, 4, 5, 9};
int[] b = new int[] { 7, 8, 3, 4, 4, 8};
int count = a
.Zip(b, (left, right) => left == right ? 1 : 0)
.Sum();
var common = (from elemA in a.Select((x, y) => new { Value = x, Index = y })
join elemB in b.Select((x, y) => new { Value = x, Index = y })
on new { elemA.Index, elemA.Value } equals new { elemB.Index, elemB.Value }
select elemA).ToList();