既然你已经在javascript中几乎完成了它,那么我将提供实现Steinhaus排列算法的Java代码。我基本上只是将你的代码移植到了Java中,尽可能保留了它的原貌,包括注释。
我测试了N = 7。我试图让它计算N = 8,但它已经在2 GHz英特尔Core 2 Duo处理器上运行了将近10分钟,还在继续,哈哈。
我相信如果你真的努力去做,你可以显著加快它的速度,但即使这样,你可能只能从中挤出几个N值,除非当然你有超级计算机的访问权限;-)。
警告-此代码是正确的,但不是稳健的。如果您需要它稳健,通常不需要为作业任务,那么这将成为您的练习。我还建议使用Java集合来实现它,因为这将是学习集合API的好方法。
包括一个打印2D数组的“helper”方法。享受吧!
更新:N = 8花费了25分钟38秒。
编辑:修复了N == 1和N == 2。
public class Test
{
public static void main (String[] args)
{
printArray (allPermutations (8));
}
public static int[][] allPermutations (int N)
{
if (N == 2)
{
return new int[][] {{1, 2}, {2, 1}};
}
else if (N > 2)
{
int[][] permutations = allPermutations (N - 1);
for (int i = 0; i < factorial (N); i += N)
{
for (int j = 0; j < N - 1; ++j)
{
permutations = insertRow (permutations, i, permutations [i]);
}
}
for (int i = 0, j = N - 1, d = -1; i < permutations.length; ++i)
{
permutations = insertColumn (permutations, i, j, N);
j += d;
if (j < 0 || j > N - 1)
{
d *= -1;
j += d;
}
}
return permutations;
}
else
{
throw new IllegalArgumentException ("N must be >= 2");
}
}
private static void arrayDeepCopy (int[][] src, int srcRow, int[][] dest,
int destRow, int numOfRows)
{
for (int row = 0; row < numOfRows; ++row)
{
System.arraycopy (src [srcRow + row], 0, dest [destRow + row], 0,
src[row].length);
}
}
public static int factorial (int n)
{
return n == 1 ? 1 : n * factorial (n - 1);
}
private static int[][] insertColumn (int[][] src, int rowIndex,
int columnIndex, int columnValue)
{
int[][] dest = new int[src.length][0];
for (int i = 0; i < dest.length; ++i)
{
dest [i] = new int [src[i].length];
}
arrayDeepCopy (src, 0, dest, 0, src.length);
int numOfColumns = src[rowIndex].length;
int[] rowWithExtraColumn = new int [numOfColumns + 1];
System.arraycopy (src [rowIndex], 0, rowWithExtraColumn, 0, columnIndex);
System.arraycopy (src [rowIndex], columnIndex, rowWithExtraColumn,
columnIndex + 1, numOfColumns - columnIndex);
rowWithExtraColumn [columnIndex] = columnValue;
dest [rowIndex] = rowWithExtraColumn;
return dest;
}
private static int[][] insertRow (int[][] src, int rowIndex,
int[] rowElements)
{
int srcRows = src.length;
int srcCols = rowElements.length;
int[][] dest = new int [srcRows + 1][srcCols];
arrayDeepCopy (src, 0, dest, 0, rowIndex);
arrayDeepCopy (src, rowIndex, dest, rowIndex + 1, src.length - rowIndex);
System.arraycopy (rowElements, 0, dest [rowIndex], 0, rowElements.length);
return dest;
}
public static void printArray (int[][] array)
{
for (int row = 0; row < array.length; ++row)
{
for (int col = 0; col < array[row].length; ++col)
{
System.out.print (array [row][col] + " ");
}
System.out.print ("\n");
}
System.out.print ("\n");
}
}
allPermutations(1)
会递归直到发生StackOverflow
。 - rsp