我已经在这个论坛here上发布了这个问题,但看到没有人回答我决定在这里尝试。
基本上,我正在寻找一种方法来置换一个整数数组,给定一个没有重复排列的范围。我过去很难理解如何找到排列,所以我希望有人能够深入解释我需要实施的内容以及原因。
以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define LENGTH 2
double NumberOfPermuationsOfString( int length, char minimum, char maximum )
{
return pow( ( maximum - minimum ) + 1, length );
}
int NextPermutation( char * buffer, char minimum, char maximum )
{
const size_t length = strlen( buffer ) + 1;
int i = 0;
for ( ; i < length; ++i )
{
/* I don't know what to do here... */
}
return 0;
}
void DisplayPermutations( int length, char minimum, char maximum )
{
char buffer[( length + 1 )];
memset( buffer, 0, sizeof( buffer ) );
memset( buffer, minimum, sizeof( buffer ) - 1 );
int i = 0;
do
{
printf( "%s\n", buffer );
} while ( NextPermutation( &buffer[0], minimum, maximum ) );
}
int main( )
{
printf( "Iterating through %0.lf permuations...\n", NumberOfPermuationsOfString( LENGTH, 'a', 'z' ) );
DisplayPermutations( LENGTH, 'a', 'z' );
return 0;
}
这就是C#,不要让这个命名的公约愚弄你......
答案 0 :(得分:0)
Fabulous Adventures in Coding blog的作者Eric Lippert在Producing Permutations上有一个很好的系列。
在解释中,他提供了代码。例如,part four的以下代码段可以执行您想要的和允许随机访问(但使用自定义类型):
public static Permutation NthPermutation(int size, BigInteger index)
{
if (index < 0 || index >= Factorial(size))
throw new ArgumentOutOfRangeException("index");
if (size == 0) // index must be zero since it is smaller than 0!
return Empty;
BigInteger group = index / size; // What block are we in?
Permutation permutation = NthPermutation(size - 1, group);
bool forwards = group % 2 != 0; // Forwards or backwards?
int insert = (int) (index % size); // Where are we making the insert?
return new Permutation(
permutation.InsertAt(forwards ? insert : size - insert - 1, size - 1));
}