有没有一种巧妙的方法将枚举排序打包为数值
是的,您可以将排序表示为数值,但要使用它,您需要转换回 byte/int 数组。因为有 64 个! 64 个值的可能排序,以及 64!大于Long.MAX_VALUE
,您需要将数字存储在BigInteger
。我想这将是存储排序的最节省内存的方式,尽管您在内存中获得的内容会由于必须将数字转换为数组而失去时间。
有关在数字/数组表示之间进行转换的算法,请参阅这个问题 https://stackoverflow.com/questions/1506078/fast-permutation-number-permutation-mapping-algorithms.
这是上述方法的另一种选择,不知道它是否与那个方法一样有效,并且您必须将代码从int
to BigInteger
基于,但它应该足以给你这个想法:
/**
* Returns ith permutation of the n numbers [from, ..., to]
* (Note that n == to - from + 1).
* permutations are numbered from 0 to n!-1, if i is outside this
* range it is treated as i%n!
* @param i
* @param from
* @param n
* @return
*/
public static int[] perm(long i, int from, int to)
{
// method specification numbers permutations from 0 to n!-1.
// If you wanted them numbered from 1 to n!, uncomment this line.
// i -= 1;
int n = to - from + 1;
int[] initArr = new int[n]; // numbers [from, ..., to]
int[] finalArr = new int[n]; // permutation of numbers [from, ..., to]
// populate initial array
for (int k=0; k<n; k++)
initArr[k] = k+from;
// compute return array, element by element
for (int k=0; k<n; k++) {
int index = (int) ((i%factorial(n-k)) / factorial(n-k-1));
// find the index_th element from the initial array, and
// "remove" it by setting its value to -1
int m = convertIndex(initArr, index);
finalArr[k] = initArr[m];
initArr[m] = -1;
}
return finalArr;
}
/**
* Helper method used by perm.
* Find the index of the index_th element of arr, when values equal to -1 are skipped.
* e.g. if arr = [20, 18, -1, 19], then convertIndex(arr, 2) returns 3.
*/
private static int convertIndex(int[] arr, int index)
{
int m=-1;
while (index>=0) {
m++;
if (arr[m] != -1)
index--;
}
return m;
}
基本上,您按照自然顺序从初始化数组开始,然后循环最终数组,每次计算接下来应该放置哪些剩余元素。此版本通过将值设置为 -1 从 init 数组中“删除”元素。使用 a 可能会更直观List
or LinkedList
,我刚刚从我手边的一些旧代码中粘贴了这个。
使用上述方法并以此作为main
:
public static void main(String[] args) {
int n = (int) factorial(4);
for ( int i = 0; i < n; i++ ) {
System.out.format( "%d: %s\n", i, Arrays.toString( perm(i, 1, 4 ) ) );
}
}
您将得到以下输出:
0: [1, 2, 3, 4]
1: [1, 2, 4, 3]
2: [1, 3, 2, 4]
3: [1, 3, 4, 2]
4: [1, 4, 2, 3]
5: [1, 4, 3, 2]
6: [2, 1, 3, 4]
7: [2, 1, 4, 3]
8: [2, 3, 1, 4]
9: [2, 3, 4, 1]
10: [2, 4, 1, 3]
11: [2, 4, 3, 1]
12: [3, 1, 2, 4]
13: [3, 1, 4, 2]
14: [3, 2, 1, 4]
15: [3, 2, 4, 1]
16: [3, 4, 1, 2]
17: [3, 4, 2, 1]
18: [4, 1, 2, 3]
19: [4, 1, 3, 2]
20: [4, 2, 1, 3]
21: [4, 2, 3, 1]
22: [4, 3, 1, 2]
23: [4, 3, 2, 1]
这是 ideone 上的可执行版本 http://ideone.com/bq35C.
判断依据BigInteger.bitLength()
,应该可以在不超过 37 个字节中存储 64 个元素的排序(加上使用BigInteger
实例)。我不知道这是否值得,但这是一个很好的练习!