我有点晚了,但我想我有一个尚未展示的方法。
我记得有一种算法,给定所有 K 个项目的起始顺序和一个整数索引,它会在大致与 K 成比例的时间内生成 K 个项目的第 index 个排列。知道它们的 K!(阶乘)K个项目的排列,只要你能随机生成一个零到K之间的整数!您可以使用该例程在内存中生成 N 个唯一随机索引,然后将相应的排列打印到磁盘。
这是算法的 Python 版本,其中 N 设置为 10,k 设置为 25,尽管我已成功使用 k = 144:
from math import factorial
from copy import copy
import random
def perm_at_index(items, index):
'''
>>> for i in range(10):
print i, perm_at_index([1,2,3], i)
0 [1, 2, 3]
1 [1, 3, 2]
2 [2, 1, 3]
3 [2, 3, 1]
4 [3, 1, 2]
5 [3, 2, 1]
6 [1, 2, 3]
7 [1, 3, 2]
8 [2, 1, 3]
9 [2, 3, 1]
'''
itms, perm = items[:], []
itmspop, lenitms, permappend = itms.pop, len(itms), perm.append
thisfact = factorial(lenitms)
thisindex = index % thisfact
while itms:
thisfact /= lenitms
thischoice, thisindex = divmod(thisindex, thisfact)
permappend(itmspop(thischoice))
lenitms -= 1
return perm
if __name__ == '__main__':
N = 10 # Change to 1 million
k = 25 # Change to 144
K = ['K%03i' % j for j in range(k)] # ['K000', 'K001', 'K002', 'K003', ...]
maxperm = factorial(k) # You need arbitrary length integers for this!
indices = set(random.randint(0, maxperm) for r in range(N))
while len(indices) < N:
indices |= set(random.randint(0, maxperm) for r in range(N - len(indices)))
for index in indices:
print (' '.join(perm_at_index(K, index)))
其输出如下所示:
K008 K016 K024 K014 K003 K007 K015 K018 K009 K006 K021 K012 K017 K013 K022 K020 K005 K000 K010 K001 K011 K002 K019 K004 K023
K006 K001 K023 K008 K004 K017 K015 K009 K021 K020 K013 K000 K012 K014 K016 K002 K022 K007 K005 K018 K010 K019 K011 K003 K024
K004 K017 K008 K002 K009 K020 K001 K019 K018 K013 K000 K005 K023 K014 K021 K015 K010 K012 K016 K003 K024 K022 K011 K006 K007
K023 K013 K016 K022 K014 K024 K011 K019 K001 K004 K010 K017 K018 K002 K000 K008 K006 K009 K003 K021 K005 K020 K012 K015 K007
K007 K001 K013 K003 K023 K022 K016 K017 K014 K018 K020 K015 K006 K004 K011 K009 K000 K012 K002 K024 K008 K021 K005 K010 K019
K002 K023 K004 K005 K024 K001 K006 K007 K014 K021 K015 K012 K022 K013 K020 K011 K008 K003 K017 K016 K019 K010 K009 K000 K018
K001 K004 K007 K024 K011 K022 K017 K023 K002 K003 K006 K021 K010 K014 K013 K020 K012 K016 K019 K000 K015 K008 K018 K009 K005
K009 K003 K010 K008 K020 K024 K007 K018 K023 K013 K001 K019 K006 K002 K016 K000 K004 K017 K014 K011 K022 K021 K012 K005 K015
K006 K009 K018 K010 K015 K016 K011 K008 K001 K013 K003 K004 K002 K005 K022 K020 K021 K017 K000 K019 K024 K012 K023 K014 K007
K017 K006 K010 K015 K018 K004 K000 K022 K024 K020 K014 K001 K023 K016 K005 K011 K002 K007 K009 K013 K019 K012 K021 K003 K008