C# 数组间搜索的最佳算法
我有一个问题需要用我能找到的最好的算法来解决。 让我先描述一下这个问题。 我有一个类a,其中Hashset的个数是Z,items的个数是ZC# 数组间搜索的最佳算法,c#,algorithm,search,C#,Algorithm,Search,我有一个问题需要用我能找到的最好的算法来解决。 让我先描述一下这个问题。 我有一个类a,其中Hashset的个数是Z,items的个数是Z A -> {x,y,z | x = {0,1,2} , y = {-1,0,9} ... } B -> {x,y,z,k | x = {0,1,-2} , y = {-1,0,19} ... } 当用户输入一个新的int{…}数组时,结果应该是hashset最多的组,该组的输入和组之间有匹配的数字 例如: A : {[1,2,3][2,3,8
A -> {x,y,z | x = {0,1,2} , y = {-1,0,9} ... }
B -> {x,y,z,k | x = {0,1,-2} , y = {-1,0,19} ... }
当用户输入一个新的int{…}数组时,结果应该是hashset最多的组,该组的输入和组之间有匹配的数字
例如:
A : {[1,2,3][2,3,8][-1,-2,2]}
B : {[0,-9,3][12,23,68][-11,-2,2]}
输入:
[2,3,-19]
result A : {[2,3][2,3][2]}
result B : {[3][][2]}
A : 3
B : 2
A是正确答案
或者类似的。
是的,我知道这是一个主观的问题,但这是为了一个好的理由。显然你想用C来实现这一点。我不知道在任何情况下这是否是最好的算法,但您可以使用LINQ将其写得非常简单明了:
int[][] arrays = new[] { new[] { 1, 2 }, new[] { 2, 3 }, new[] {3, 4} };
int[] input = new[] { 1, 4 };
Console.WriteLine(arrays.Count((itemarray) => itemarray.Any((item) => input.Contains(item))));
在int数组的数组中,它查找至少具有输入数组的一个值的数组数。这就是您正在做的,尽管我不确定这是否是您要求我们做的。给定一个示例类HashHolder和它的一个实例:
然后,如果maxhHash不为null,则结果将是maxHash.Hash。假设要检查输入集的样本数未知,此Linq查询应该可以完成此操作
from sample in samples
let intersectedSets =
from set in sample
let intersection = input.Intersect(set)
where intersection.Count() > 0
select intersection
orderby intersectedSets.Count() descending
select intersectedSets;
最上面的元素是您想要的样本,因此是您的集合。首先将生成您的结果集-在给定的示例中:
var samples = new[] {
new[]{
new[]{1, 2, 3},
new[]{2, 3, 8},
new[]{-1, -2, 2}
},
new[]{
new[]{0, -9, 3},
new[]{12, 23, 68},
new[]{-11, -2, 2}
}
};
var input = new[]{2, 3, -19};
var result =
(from sample in samples
let intersectedSets =
from set in sample
let intersection = input.Intersect(set)
where intersection.Count() > 0
select intersection
orderby intersectedSets.Count() descending
select intersectedSets).First();
result.Dump(); // LINQPad extension method
请使用{}工具箱按钮来表示代码部分。现在我这样做是为了你。你自己的例子似乎有缺陷,输入[2,3,-11]的结果B不应该出现为:{[3][[-11,2]}?如果你想得到最好的结果,你必须告诉我们如何测量它。你想要最简单的理解吗?平均速度最快?最好的情况下最快的?最坏情况下最快的?等
from sample in samples
let intersectedSets =
from set in sample
let intersection = input.Intersect(set)
where intersection.Count() > 0
select intersection
orderby intersectedSets.Count() descending
select intersectedSets;
var samples = new[] {
new[]{
new[]{1, 2, 3},
new[]{2, 3, 8},
new[]{-1, -2, 2}
},
new[]{
new[]{0, -9, 3},
new[]{12, 23, 68},
new[]{-11, -2, 2}
}
};
var input = new[]{2, 3, -19};
var result =
(from sample in samples
let intersectedSets =
from set in sample
let intersection = input.Intersect(set)
where intersection.Count() > 0
select intersection
orderby intersectedSets.Count() descending
select intersectedSets).First();
result.Dump(); // LINQPad extension method