【问题标题】:best algorithm for search between arrays数组之间搜索的最佳算法
【发布时间】:2011-11-26 20:11:34
【问题描述】:

我有一个问题需要用我能找到的最佳算法来解决。
让我先描述一下问题。 我有一门课AHashset<int>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 { ... },结果应该是具有最多哈希集的组,并且输入和组之间的数字匹配。

例如:

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 是正确答案。

或者类似的东西。 是的,我知道这是一个主观问题,但这是有原因的。

【问题讨论】:

  • 请使用{} 工具箱按钮来表示您的代码部分。现在我为你做了这个。
  • 你自己的例子似乎有缺陷,输入 [2,3,-11] 不应该导致 B 出现:{[3][][-11,2]}?
  • 如果您想询问the best,您必须告诉我们如何衡量。你想要最简单的理解吗?平均最快?最好的情况下最快的?最坏情况下最快的?等等……

标签: c# algorithm search


【解决方案1】:

假设您有未知数量的样本要检查输入集,这个 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;

最上面的元素是您想要的样本,因此yourCollection.First() 将产生您的结果集 - 在您给定的示例中:

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】:

    给定一个示例类HashHolder 和它的一个实例A

    public class HashHolder
    {
        public HashHolder()
        {
            Hashes = new List<HashSet<int>>();
        }
        public List<HashSet<int>> Hashes { get; set; }
    }
    

    您可以按哈希集分组,并在所有组之间取最大计数:

    var maxHash = A.Hashes.GroupBy(h => h)
                   .Select(g => new { Hash = g.Key, Count = input.Count(num => g.Key.Contains(num)) })
                   .OrderByDescending(g => g.Count)
                   .FirstOrDefault();
    

    如果maxhHash 不为空,则结果将为maxHash.Hash

    【讨论】:

      【解决方案3】:

      显然您想使用 C# 来实现这一点。我不知道这是否是 best 算法(在任何情况下),但您可以使用 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 数组的数组中,这会找到至少具有输入数组值之一的数组的数量。这就是你正在做的,虽然我不确定这是否是你要求我们做的。

      【讨论】:

        猜你喜欢
        • 2012-05-18
        • 2020-09-03
        • 2011-09-18
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        • 2019-04-17
        相关资源
        最近更新 更多