2
ヒープ順列アルゴリズムを使用して配列の並べ替えを行うクラスがありますが、すべての並べ替えを印刷するときに、正しい順列をすべて取得してリストに追加し、私は同じ項目を繰り返す。ここに私のコード並べ替えでの再帰の動作が一貫しない
using System;
using System.Collections.Generic;
namespace HeapsPermutation
{
class Program
{
static void Main(string[] args)
{
string[] numbers = new string[4];
numbers[0] = "a";
numbers[1] = "b";
numbers[2] = "c";
numbers[3] = "d";
Permutation<string>.permutate(numbers.Length, numbers);
Console.Read();
}
}
class Permutation<T>
{
static List<T[]> permutated_items = new List<T[]>();
public static void permutate(int n, params T[] array)
{
if (n == 1)
{
foreach (T x in array)
{
Console.Write(x); // gives correct result
}
Console.WriteLine();
permutated_items.Add(array); // does no add correct result
}
else
{
for (int i = 0; i < n - 1; i++)
{
permutate(n - 1, array);
if (n % 2 == 0)
{
swap(ref array[i], ref array[n - 1]);
}
else
{
swap(ref array[0], ref array[n - 1]);
}
}
permutate(n - 1, array);
}
}
private static void swap(ref T x, ref T y)
{
T temp = x;
x = y;
y = temp;
}
}
}
[mcve]を入力してください。コンソールアプリケーションでコードをコピーアンドペーストして実行し、直面している問題を見たいと思っています。 – Enigmativity
リストに 'static'を追加することにより、リスト permutated_items = new List ();(コンパイルの問題を修正します)を実行して、正しく指定した引数で実行すると順列が出力されます。 –
@Enigmativity私はちょうど、最小、完全で、検証可能な例を追加しました – Ogbe