【问题标题】:Number counting to find subsets frequency计数以查找子集频率
【发布时间】:2016-09-22 01:15:04
【问题描述】:

我正在尝试查找 N 组中经常出现的数字组合(相同大小,一组中没有重复)。

例如:

{3, 5, 2, 4, 6, 11}
{3, 7, 2, 11, 5, 14}
{8, 2, 1, 11, 14, 6}
{9, 1, 12, 8, 17, 4}
{4, 10, 16, 5, 14, 3}

我使用数字计数算法来查找集合中单个数字的出现次数。

public static int[] Counting (int []A, int m )
{
    int n = A.Length;
    int[] count = new int[m+1];
    Array.Clear(count, 0, m+1);
    for (int k = 0; k < n; k++)
        count[A[k]] += 1;
    return count;
}

是否有一种算法可以对子集执行相同的操作。在上面的示例中,{2, 11}、{3,2, 11}、{11, 14} 一起出现的频率更高。输出应具有子集的计数,即对于上面的示例 {2, 11},频率为 3

【问题讨论】:

    标签: c# algorithm sorting


    【解决方案1】:

    这对你有用吗?

    Func<IEnumerable<int>, IEnumerable<IEnumerable<int>>> getAllSubsets = null;
    getAllSubsets = xs =>
        (xs == null || !xs.Any())
            ? Enumerable.Empty<IEnumerable<int>>()
            :  xs.Skip(1).Any()
                ? getAllSubsets(xs.Skip(1))
                    .SelectMany(ys => new [] { ys, xs.Take(1).Concat(ys) })
                : new [] { Enumerable.Empty<int>(), xs.Take(1) };
    
    var source = new int[][]
    {
        new [] {3, 5, 2, 4, 6, 11},
        new [] {3, 7, 2, 11, 5, 14},
        new [] {8, 2, 1, 11, 14, 6},
        new [] {9, 1, 12, 8, 17, 4},
        new [] {4, 10, 16, 5, 14, 3},
    };
    
    var subsets = source.Select(x => getAllSubsets(x).Select(y => new { key = String.Join(",", y), values = y.ToArray() }).ToArray()).ToArray();
    
    var keys = subsets.SelectMany(x => x.Select(y => y.key)).Distinct().ToArray();
    
    var query =
        from key in keys
        let count = subsets.Where(x => x.Select(y => y.key).Contains(key)).Count()
        where count > 1
        orderby count descending
        select new { key, count, };
    

    我得到这个结果:

    5 的第一个结果是空集,每个集合都包含。

    【讨论】:

    • 很好,我很难用 linq 创建所有排列。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 2014-05-18
    • 2019-10-17
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多