检查 2 个 int 数组是否仅包含同一索引处的唯一数字
Check if 2 int arrays contain only unique numbers at the same index
如果我有 2 个 int
数组 a 和 b,它们包含这样的数据..
a[0] = 1
a[1] = 3
a[2] = 7
b[0] = 6
b[1] = 3
b[2] = 5
我如何检查所有数字对是否都是唯一的,例如a[i]
和 b[i]
在同一索引处的每个组合都不会在数组的其余部分重复...所以上面的数据会通过但如果我在下面介绍它会失败..
a[24] = 7
b[24] = 5
因为这个组合已经存在于索引 2 的数组中。我可以在 LINQ 中这样做吗?
试试这个示例:
int [] aa = a.Distinct().ToArray();
或:
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> map = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (map.ContainsKey(items[i]))
{
return true; // has duplicates
}
map.Add(items[i], true);
}
return false; // no duplicates
}
并致电:
string[] strings = new[] { "1", "2", "3" };
Utility.HasDuplicates(strings)// this will return false
int[] items=new []{1,2,3,1};
Utility.HasDuplicates(items)// this will return true
如果两个数组中值对的顺序很重要(即 a[0] == 1, b[0] == 2
被认为不同于 a[0] == 2, b[0] == 1
),那么使用 Linq 检查唯一性的一种方法如下:
bool unique = a.Zip(b).Distinct().Count() == a.Length;
如果对中值的顺序不重要,则稍微复杂一些:
bool unique = a.Zip(b).DistinctBy(
x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second)))
.Count() == a.Length;
这些解决方案假定将忽略其中一个数组中的缺失值。
(注意:DistinctBy()
仅在 .Net 6.0 或更高版本中可用,或通过 NuGet 包提供。)
我已经设法解决了这个问题并解决了这个问题:
a.Zip(b, (aPos, bPos) => new { aPosition = aPos, bPosition = bPos }).Distinct().Count()
这将告诉我在同一索引处有多少组不同的两个值,因此我可以从这里算出其余的。
抱歉,如果我的问题不清楚。
如果我有 2 个 int
数组 a 和 b,它们包含这样的数据..
a[0] = 1
a[1] = 3
a[2] = 7
b[0] = 6
b[1] = 3
b[2] = 5
我如何检查所有数字对是否都是唯一的,例如a[i]
和 b[i]
在同一索引处的每个组合都不会在数组的其余部分重复...所以上面的数据会通过但如果我在下面介绍它会失败..
a[24] = 7
b[24] = 5
因为这个组合已经存在于索引 2 的数组中。我可以在 LINQ 中这样做吗?
试试这个示例:
int [] aa = a.Distinct().ToArray();
或:
public static bool HasDuplicates<T>(IList<T> items)
{
Dictionary<T, bool> map = new Dictionary<T, bool>();
for (int i = 0; i < items.Count; i++)
{
if (map.ContainsKey(items[i]))
{
return true; // has duplicates
}
map.Add(items[i], true);
}
return false; // no duplicates
}
并致电:
string[] strings = new[] { "1", "2", "3" };
Utility.HasDuplicates(strings)// this will return false
int[] items=new []{1,2,3,1};
Utility.HasDuplicates(items)// this will return true
如果两个数组中值对的顺序很重要(即 a[0] == 1, b[0] == 2
被认为不同于 a[0] == 2, b[0] == 1
),那么使用 Linq 检查唯一性的一种方法如下:
bool unique = a.Zip(b).Distinct().Count() == a.Length;
如果对中值的顺序不重要,则稍微复杂一些:
bool unique = a.Zip(b).DistinctBy(
x => (Math.Min(x.First, x.Second), Math.Max(x.First,x.Second)))
.Count() == a.Length;
这些解决方案假定将忽略其中一个数组中的缺失值。
(注意:DistinctBy()
仅在 .Net 6.0 或更高版本中可用,或通过 NuGet 包提供。)
我已经设法解决了这个问题并解决了这个问题:
a.Zip(b, (aPos, bPos) => new { aPosition = aPos, bPosition = bPos }).Distinct().Count()
这将告诉我在同一索引处有多少组不同的两个值,因此我可以从这里算出其余的。
抱歉,如果我的问题不清楚。