查找多个数组元素的最常见的组合 [英] Find most common combination of elements in several arrays

查看:125
本文介绍了查找多个数组元素的最常见的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个阵列,如:

var arr1 = new[] { "A", "B", "C", "D" };
var arr2 = new[] { "A", "D" };
var arr3 = new[] { "A", "B", };
var arr4 = new[] { "C", "D" };
var arr5 = new[] { "B", "C", "D" };
var arr6 = new[] { "B", "A", };

...等。

我怎样才能得到最常见的在所有这些数组的元素组合

How can I get most common combination of elements in all of those arrays?

在这种情况下,它是A和B,因为它们发生在ARR1,ARR3和arr6,和C和D,因为它们发生在阵列ARR1,arr4和arr5

In this case it is A and B, because they occur in arr1, arr3 and arr6, and C and D, because they occur in arrays arr1, arr4 and arr5.

刚提及元件可以是任何类型的集合,即中的ArrayList也。

Just to mention that elements can be in any kind of collection, ie. in ArrayLists also.

更新 uuhhh,我不太清楚......最常见的两个元素在一个阵列的组合。这就是我试图例子来展示,但在我的问题并未提及。

UPDATE uuhhh, I was not clear enough...... Most common combinations of two elements in an array. That's what I tried to show in example, but did not mention in my question.

对不起
: - ((

Sorry :-((

推荐答案

如果您确定每个项目的每个阵列中只出现一次,你可以只将它们串联在一起,并获得数,例如:

If you are sure that each item appears only once in each array, you could just concatenate them together and get the counts, for example:

var arrs = new[] { arr1, arr2, arr3, arr4, arr5, arr6 };
var intermediate = arrs.SelectMany(a => a)
                       .GroupBy(x => x)
                       .Select(g => new { g.Key, Count = g.Count() })
                       .OrderByDescending(x => x.Count);
var maxCount = intermediate.First().Count;
var results = intermediate.TakeWhile(x => x.Count == maxCount);

或者,如果你preFER查询语法,这将是:

Or if you prefer query syntax, that would be:

var arrs = new[] { arr1, arr2, arr3, arr4, arr5, arr6 };
var intermediate = 
    from a in arrs.SelectMany(a => a)
    group a by a into g
    orderby g.Count() descending
    select new { g.Key, Count = g.Count() };
var maxCount = intermediate.First().Count;
var results = intermediate.TakeWhile(x => x.Count == maxCount);

结果集将有3款产品:

The result set will contain 3 items:

Key, Count
"A", 4 
"B", 4 
"D", 4 


更新

由于更新后的问题,这样的事情应该工作:

Given your updated question, something like this should work:

var items = arrs.SelectMany(a => a).Distinct();
var pairs =
    from a in items
    from b in items
    where a.CompareTo(b) < 0
    select new { a, b };
var results = 
    (from arr in arrs
     from p in pairs 
     where arr.Contains(p.a) && arr.Contains(p.b)
     group arr by p into g
     orderby g.Count() descending
     select g.Key)
    .First();

这里的逻辑是:


  1. 首先找到任何阵列中的所有物品鲜明

  2. 然后发现每对项搜索

  3. 获取每对,通过什么样的数组包含对列表分组的

  4. 排序组由包含每一对阵列,降数

  5. 返回第一个对

这篇关于查找多个数组元素的最常见的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆