这是我为 Set 和 Line Length 的所有值找到的通用解决方案。第一个假设您不希望两个解决方案共享相同的公共元素,但您希望每个解决方案都具有一个与其他解决方案相同的元素。给定一个无限池来选择形式,解决方案的总数受每个解决方案的长度限制。
SET_LENGTH = 10
CHOICE_LENGTH = 300
data = set(range(CHOICE_LENGTH))
solutions =[]
solution_sets = []
used = set()
while True:
new_solution = []
#Try to get unique values from each previous set
try:
for sol_set in solution_sets:
while True:
candidate = sol_set.pop()
if not candidate in used:
new_solution.append(candidate)
used.update([candidate])
break
except KeyError, e:
print e
break
#Fill with new data until the line is long enough
try:
while len(new_solution) < SET_LENGTH:
new_solution.append(data.pop())
except KeyError, e:
print e
break
solutions.append(new_solution)
solution_sets.append(set(new_solution))
#Show the results
for solution in solutions:
print solution
print "Orphans %s" % len(data)
例如 n = 300 x = 10 产生:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[1, 10, 19, 20, 21, 22, 23, 24, 25, 26]
[2, 11, 19, 27, 28, 29, 30, 31, 32, 33]
[3, 12, 20, 32, 34, 35, 36, 37, 38, 39]
[4, 13, 21, 33, 34, 40, 41, 42, 43, 44]
[5, 14, 22, 27, 36, 40, 45, 46, 47, 48]
[6, 15, 23, 28, 37, 41, 45, 49, 50, 51]
[7, 16, 24, 29, 38, 42, 47, 49, 52, 53]
[8, 17, 25, 30, 39, 43, 48, 50, 52, 54]
[9, 18, 26, 31, 35, 44, 46, 51, 53, 54]
Orphans 245
如果您不在乎有多少解决方案共享相同的公共元素,那么它会更容易:
SET_LENGTH = 2
CHOICE_LENGTH = 300
data = set(range(CHOICE_LENGTH))
solutions =[]
alpha = data.pop()
while True:
new_solution = [alpha]
try:
[new_solution.append(data.pop()) for x in range(SET_LENGTH-1)]
except KeyError, e:
break
solutions.append(new_solution)
for solution in solutions:
print solution
print "Solutions: %s" % len(solutions)
print "Orphans: %s" % len(data)