Sampling Permutations of [1,2,3,...,N] for large N

915 views Asked by At

I have to solve the Travelling Salesman Problem using a genetic algorithm that I will have to write for homework.

The problem consists of 52 cities. Therefore, the search space is 52!. I need to randomly sample (say) 1000 permutations of range(1, 53) as individuals for the initial population of my genetic algorithm.

In order to do this, I tried:

>>> random.sample(itertools.permutations(range(1, 53)), 1000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.6/random.py", line 314, in sample
    n = len(population)
TypeError: object of type 'itertools.permutations' has no len()

So I tried

>>> random.sample(list(itertools.permutations(range(1, 53))), 1000)

However, given that 52! is VERY large, the list operation is maxing out the memory and swap space on my computer. I can't just pick the first 1000 permutations generated by itertools.permutations because it's very deterministic and that would bias my genetic algorithm.

Is there a better way to achieve this sampling?

1

There are 1 answers

4
Marcelo Cantos On BEST ANSWER

You don't need to permute at all. Call random.sample(range(52), 52) 1000 times.

P.S.: You really should use zero-based indexing (range(52) as opposed to range(1, 53)) in all your work. Things generally work out better that way.