これは、余分なメモリなしで、この問題をその場で解決しようとしています。これはO(n)アルゴリズムです。
jpalecekによるアルゴリズムは、少なくとも知的ではありますが、少なくとも私にとっては読解するのに直感的ではありません。私はそれを試して、それは動作しますが、私は理由とコメントが素晴らしいだろうと理解する時間がなかった。
配列が大きすぎない限り、Gracenotesによるアルゴリズムは素晴らしいです。データが大きい場合は、アレイを動的に作成する必要があります。
私のアルゴリズムの基本的な考え方は、インデックスと値のペアの連鎖に従って配列を更新することです。たとえば、インデックス0は値3にマッピングされます。インデックスとして値3を使用すると、配列内のインデックス3と値1の次のペアが見つけられます。基本的に次のインデックスと値のペアを保存し、前のインデックスとペア値私がチェーンをやるまで。
もっと効率的に、エレガントに、全体的にもっと良くすることができれば、私は興味があります。
以下のコードをコンパイルしてテストしましたが、他のテスト入力は使用していません。私はそれを試して、それがどのように動作するかをよりよく理解したい人のために、デバッグ出力に残しました。
// Array print routine.
void printArray (const char * str_p,int a[], int n)
{
printf ("%s\n", str_p);
for (int i = 0; i < n; i++)
{
printf ("%i ", i);
}
printf ("\n");
for (int i = 0; i < n; i++)
{
printf ("%i ", a[i]);
}
printf ("\n\n");
}
// The main code.
void PermuteTheDamnArray()
{
printArray ("Initial Array", a,n);
int i = 0; // Simply a counter.
int p_ix = 0; // Previous Index.
int p_val = a[0]; // Previous Value.
int n_ix = a[0]; // Next index.
int n_val = a[n_ix]; // Next Value.
for (i = 0; i < n; i++)
{
// Replace.
printf ("Swapping orig (%i,%i) with (%i,%i)\n", n_ix, n_val,p_val, p_ix);
a[p_val] = p_ix;
printArray ("Array after swap", a,n);
// The next index and value pair becomes the new previous index and value pair.
p_ix = n_ix;
p_val = n_val;
printf ("The previous pair is now: (%i,%i)\n", p_ix, p_val);
// Get the next index and value pair.
n_ix = n_val;
n_val = a[n_val];
printf ("The next pair is now: (%i,%i)\n", n_ix, n_val);
}
printArray ("Final Array", a,n);
}
Output:
Swapping orig (3,1) with (3,0)
Array after swap
0 1 2 3
3 2 0 0
The previous pair is now: (3,1)
The next pair is now: (1,2)
Swapping orig (1,2) with (1,3)
Array after swap
0 1 2 3
3 3 0 0
The previous pair is now: (1,2)
The next pair is now: (2,0)
Swapping orig (2,0) with (2,1)
Array after swap
0 1 2 3
3 3 1 0
The previous pair is now: (2,0)
The next pair is now: (0,3)
Swapping orig (0,3) with (0,2)
Array after swap
0 1 2 3
2 3 1 0
The previous pair is now: (0,3)
The next pair is now: (3,0)
Final Array
0 1 2 3
2 3 1 0
重複:それは本当に重複http://stackoverflow.com/questions/523861/permutation-of-a-vector –
ですか?リンクの問題は置換の構成に関するものですが、この問題(T(2)ではT(0)= 2であるため)は、置換の逆転によく似ています。 – jpalecek
はい、それを読んだ後は重複していません! – Ben