我正在寻找一种算法,给定一组数字(例如1,2,3)和一个索引(例如2),将根据字典顺序得到这些数字的第二个排列。例如,在本例中,算法将返回1 3 2。
发布于 2012-01-20 20:51:11
这里有一个简单的解决方案:
from math import factorial # python math library
i = 5 # i is the lexicographic index (counting starts from 0)
n = 3 # n is the length of the permutation
p = range(1, n + 1) # p is a list from 1 to n
for k in range(1, n + 1): # k goes from 1 to n
f = factorial(n - k) # compute factorial once per iteration
d = i // f # use integer division (like division + floor)
print(p[d]), # print permuted number with trailing space
p.remove(p[d]) # delete p[d] from p
i = i % f # reduce i to its remainder输出:
3 2 1如果p是一个列表,则时间复杂度为O(n^2);如果p是一个哈希表,并且预计算出factorial,则时间复杂度为O(n)。
发布于 2012-01-22 09:45:42
以下是Scala中的示例解决方案,我将对其进行详细说明:
/**
example: index:=15, list:=(1, 2, 3, 4)
*/
def permutationIndex (index: Int, list: List [Int]) : List [Int] =
if (list.isEmpty) list else {
val len = list.size // len = 4
val max = fac (len) // max = 24
val divisor = max / len // divisor = 6
val i = index / divisor // i = 2
val el = list (i)
el :: permutationIndex (index - divisor * i, list.filter (_ != el)) }由于Scala不是那么知名,我想我必须解释算法的最后一行,除此之外,这是非常不言自明的。
el :: elist从一个元素el和一个列表elist构造一个新列表。Elist是一个递归调用。
list.filter (_ != el)只是没有元素el的列表。
使用一个小列表对其进行详尽的测试:
(0 to fac (4) - 1).map (permutationIndex (_, List (1, 2, 3, 4))).mkString ("\n")用两个例子来测试更大列表的速度:
scala> permutationIndex (123456789, (1 to 12).toList)
res45: List[Int] = List(4, 2, 1, 5, 12, 7, 10, 8, 11, 6, 9, 3)
scala> permutationIndex (123456790, (1 to 12).toList)
res46: List[Int] = List(4, 2, 1, 5, 12, 7, 10, 8, 11, 9, 3, 6)结果立即出现在一台5岁的笔记本电脑上。有12个元素的列表有479001600个排列,但是对于100或1000个元素,这个解决方案应该仍然很快-您只需要使用BigInt作为索引。
它怎麽工作?为了使示例可视化,我制作了一个图形,其中包含(1,2,3,4)的列表和索引15:

包含4个元素的列表将生成4!排列(=24)。我们选择一个从0到4的任意索引!-1,比方说15。
我们可以可视化树中的所有排列,第一个节点来自1..4。我们平分4!乘以4,可以看到,每个第一个节点都指向6个子树。如果我们将索引15除以6,结果是2,索引为2的从零开始的列表中的值是3。因此,第一个节点是3,列表的其余部分是(1,2,4)。下面是一个表格,显示了15如何指向Array/List/ with中索引为2的元素:
0 1 2 3 4 5 | 6 ... 11 | 12 13 14 15 16 17 | 18 ... 23
0 | 1 | 2 | 3
| | 0 1 2 3 4 5 |现在我们减去12,最后3个元素的单元格(12...17)的第一个元素,这3个元素有6个可能的排列,看看15是如何映射到3的。数字3现在得到数组索引1,也就是元素2,所以到目前为止结果是List (3,2,...)。
| 0 1 | 2 3 | 4 5 |
| 0 | 1 | 3 |
| 0 1 |同样,我们减去2,并以具有2个排列和index (0,3)的剩余2个元素结束,映射到值(1,4)。我们看到,第二个元素,属于顶部的15,映射到值3,最后一步的剩余元素是另一个:
| 0 | 1 |
| 0 | 3 |
| 3 | 0 |我们的结果是列表( 3,2,4,1)或索引(2,1,3,0)。按顺序测试所有索引表明,它们按顺序产生所有排列。
发布于 2013-02-18 05:35:01
链接到提到的文章:http://penguin.ewu.edu/~trolfe/#Shuffle
/* Converting permutation index into a permutation
* From code accompanying "Algorithm Alley: Randomized Shuffling",
* Dr. Dobb’s Journal, Vol. 25, No. 1 (January 2000)
* http://penguin.ewu.edu/~trolfe/#Shuffle
*
* Author: Tim Rolfe
* RolfeT@earthlink.net
* http://penguin.ewu.edu/~trolfe/
*/
#include <stdio.h>
#include <stdlib.h>
// http://stackoverflow.com/questions/8940470/algorithm-for-finding-numerical-permutation-given-lexicographic-index
// Invert the permutation index --- generate what would be
// the subscripts in the N-dimensional array with dimensions
// [N][N-1][N-2]...[2][1]
void IndexInvert(int J[], int N, int Idx)
{ int M, K;
for (M=1, K=N-1; K > 1; K--) // Generate (N-1)!
M *= K;
for ( K = 0; M > 1; K++ )
{ J[K] = Idx / M; // Offset in dimension K
Idx = Idx % M; // Remove K contribution
M /= --N; // next lower factorial
}
J[K] = Idx; // Right-most index
}
// Generate a permutation based on its index / subscript set.
// To generate the lexicographic order, this involves _shifting_
// characters around rather than swapping. Right-hand side must
// remain in lexicographic order
void Permute (char Line[], char first, int N, int Jdx[])
{ int Limit;
Line[0] = first;
for (Limit = 1; Limit < N; Limit++)
Line[Limit] = (char)(1+Line[Limit-1]);
for (Limit = 0; Limit < N; Limit++)
{ char Hold;
int Idx = Limit + Jdx[Limit];
Hold = Line[Idx];
while (Idx > Limit)
{ Line[Idx] = Line[Idx-1];
Idx--;
}
Line[Idx] = Hold;
}
}
// Note: hard-coded to generate permutation in the set [abc...
int main(int argc, char** argv)
{ int N = argc > 1 ? atoi(argv[1]) : 4;
char *Perm = (char*) calloc(N+1, sizeof *Perm);
int *Jdx = (int*) calloc(N, sizeof *Jdx);
int Index = argc > 2 ? atoi(argv[2]) : 23;
int K, Validate;
for (K = Validate = 1; K <= N; K++)
Validate *= K;
if (Index < 0 || Index >= Validate)
{ printf("Invalid index %d: %d! is %d\n", Index, N, Validate);
return -1; // Error return
}
IndexInvert(Jdx, N, Index);
Permute (Perm, 'a', N, Jdx);
printf("For N = %d, permutation %d in [0..%d] is %s\n",
N, Index, Validate-1, Perm);
return 0; // Success return
}https://stackoverflow.com/questions/8940470
复制相似问题