Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. # given a list of categories giving the number of multi-combinations of each type,
  2. # e.g. [1, 3, 2] would correspond to strings like 011122
  3. # generate each permutation in order
  4. # if two categories have the same quantity, only generates permutations in which
  5. # the first element of the lower-numbered category comes before the first element of the higher-numbered category
  6. def combEnum2(categories):
  7. n = sum(categories)
  8. # start with minimum permutation
  9. result = []
  10. for j,k in enumerate(categories):
  11. result.extend([j]*k)
  12. n = len(result)
  13. teamsUsed = list(categories)
  14. while True:
  15. print result
  16. x = n-2
  17. teamsUsed[result[x+1]] -= 1
  18. teamsUsed[result[x]] -= 1
  19. while True:
  20. if result[x] < result[x+1]:
  21. firstX = teamsUsed[result[x]] == 0
  22. swap = 9999
  23. swapIndex = -1
  24. for y in xrange(x+1,n):
  25. if result[y] < swap and result[y] > result[x] \
  26. and (not firstX or categories[result[y]] != categories[result[x]]):
  27. if teamsUsed[result[y]] == 0:
  28. ok = True
  29. for t in xrange(result[y]):
  30. if teamsUsed[t] == 0 and categories[result[y]] == categories[t]:
  31. ok = False
  32. if ok:
  33. swap = result[y]
  34. swapIndex = y
  35. if swapIndex > -1:
  36. teamsUsed[swap] += 1
  37. result[x] = swap
  38. z = 0
  39. for y in xrange(x+1, n):
  40. while teamsUsed[z] == categories[z]:
  41. z += 1
  42. result[y] = z
  43. teamsUsed[z] += 1
  44. break
  45. x-=1
  46. if x < 0:
  47. break
  48. teamsUsed[result[x]] -= 1
  49. if x < 0:
  50. break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement