2016-09-22 9 views
-2

N個のセット(同じサイズで、1セット内に重複がない)で頻繁に発生する数字の組み合わせを見つけようとしています。 EXのためにサブセット頻度を見つけるためのカウント数

{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}の周波数はである。

答えて

2

これはあなたのために機能しますか?

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, }; 

私はこの結果を得る:

result

5の最初の結果は、各セットが含まれている空のセット、のためです。

+0

linqを使用してすべての順列を作成するのが面倒だった。 – Jules

+0

@Enigmativityあなたは男です! – tarzan

関連する問題