3

間のすべての可能な組み合わせを生成する必要があり{"a", "b","c"}ます。

たとえば、 のような入力セットの場合{"a", "b","c"}、期待される出力は{"a", "b", "c" "ab", "ac", "bc", "abc"}です。

4

1 に答える 1

10

あなたが探しているのは、基本的にpower setの形式のようです。これは簡単な実装です(このサイトから取得):

public IEnumerable<IEnumerable<T>> GetPowerSet<T>(this IList<T> list)
{
    return from m in Enumerable.Range(0, 1 << list.Count)
           select
               from i in Enumerable.Range(0, list.Count)
               where (m & (1 << i)) != 0
               select list[i];
}

演算子のおかげで<<、30 を超える要素を持つリストではこのメソッドを使用できないことに注意してください。要素数が 30 の場合、結果セットには 2 30または 1073741824 の要素が含まれるため、これに近い数の要素を持つリストで試してみることはお勧めしません。

このメソッドを使用して、このように必要な結果を得ることができます

public IEnumerable<string> GetPermutations(IList<string> strings)
{
    return from s in strings.GetPowerSet()
           select string.Concat(s);
}

ただし、パワー セットには null セットが含まれているため、実際には結果が返され{"", "a", "b", "c", "ab", "ac", "bc", "abc"}ます。空の文字列を除外するには、次を使用します。

public IEnumerable<string> GetPermutations(IList<string> strings)
{
    return from s in strings.GetPowerSet()
           let str = string.Concat(s)
           where str.Length > 0 // exclude null set result
           select str;
}

またはもっと簡単に:

public IEnumerable<string> GetPermutations(IList<string> strings)
{
    return from s in strings.GetPowerSet().Skip(1)
           select string.Concat(s);
}
于 2013-03-18T06:22:51.140 に答える