Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 992
inspectorG4dget Avatar asked Jan 28 '12 23:01

inspectorG4dget


People also ask

How to generate all the permutations of n given numbers?

The idea is to generate each permutation from the previous permutation by choosing a pair of elements to interchange, without disturbing the other n-2 elements. Following is the illustration of generating all the permutations of n given numbers. Example:

How do you find the factorial of a permutation?

If the elements can repeat in the permutation, the formula is: In both formulas "!" denotes the factorial operation: multiplying the sequence of integers from 1 up to that number. For example, a factorial of 4 is 4! = 4 x 3 x 2 x 1 = 24. In some cases, repetition of the same element is allowed in the permutation.

What is the difference between the combinations and permutations calculator?

Like the Combinations Calculator the Permutations Calculator finds the number of subsets that can be taken from a larger set. However, the order of the subset matters. The Permutations Calculator finds the number of subsets that can be created including subsets of the same items in different orders.

Is there a good permutation of Pi = 2?

No good permutation exists. Position of 2 is 1 and position of 1 is 2. Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: Consider permutation p such that pi = i. Actually, p is a sequence of numbers from 1 to N and ppi = i .


1 Answers

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.

like image 121
Marcelo Cantos Avatar answered Oct 12 '22 15:10

Marcelo Cantos