2016-05-29 9 views
2

世代順列を呼び出すと、2nd GeneratePermutations(list, startCount, permutationCount)は6回戻り値を返します(yield return permutationList;)。しかし、何らかの理由で、最初にGetPermutationsのには、結果が.ToList()となっても何も含まれていません。".ToList()"コールの後でも、再帰の戻り値が返されません

これに再帰的な処理がありますか?

Test.cs

IEnumerable<int[]> actual = _sut.GetPermutations(3).ToList(); 

Perm.cs

public class Perm 
{ 
    public IEnumerable<int[]> GetPermutations(int permutationCount) 
    { 
     int[] permutationList = Enumerable.Range(1, permutationCount).ToArray(); 
     IEnumerable<int[]> result = GeneratePermutations(permutationList, 0, permutationCount - 1).ToList(); 

     // Doesn't contain any value! 
     return result; 
    } 

    // http://stackoverflow.com/a/756083/4035 
    private IEnumerable<int[]> GeneratePermutations(int[] permutationList, int startCount, int permutationCount) 
    { 
     if (startCount == permutationCount) 
     { 
      // Does return 6 times here. 
      yield return permutationList; 
     } 
     else 
     { 
      for (int i = startCount; i <= permutationCount; i++) 
      { 
       Swap(ref permutationList, startCount, i); 
       GeneratePermutations(permutationList, startCount + 1, permutationCount).ToList(); 
       Swap(ref permutationList, startCount, i); 
      } 

     } 
    } 

    // http://stackoverflow.com/a/2094316/4035 
    public static void Swap(ref int[] list, int index1, int index2) 
    { 
     int tmp = list[index1]; 
     list[index1] = list[index2]; 
     list[index2] = tmp; 
    } 
} 
+0

問題から独立して:GetPermutations()でソートされたデータ型の奇妙さを取得します。 'List 'は必要ありません。キャストを放棄してください。 –

+0

@QualityCatalyst:ソースコードとコードの両方の場合にのみ、タイプを変更しました。 – Sung

+1

'Swap'メソッドで' ref'は必要ないことに注意してください。 –

答えて

3

あなたの問題は、あなたの再帰呼び出しの結果を返さないとあなたは同じ配列を持つすべての時間を働くことを決していること、です。これは、(最高ではないが、私はあなたがここからそれを把握思うよ)あなたのコードのための最速の修正のようになります。

ところで
IEnumerable<int[]> perms = GeneratePermutations(
    new List<int>(permutationList).ToArray(), 
    startCount + 1, permutationCount); 

foreach(int[] perm in perms) 
    yield return perm; 

:あなたは

、クラス全体が静的と総称することができます

Proof on dotNetFiddle

+0

はい、実際問題は、私が同じ 'permutationList'を使って作業していて、その問題を修正するたびにコピーを作成していることでした。ありがとう – Sung

関連する問題