Search code examples
pythonalgorithmpermutationpython-itertools

Itertools.permutations create n random solutions to the TSP


I'm working on a script which creates random solutions to the traveling salesman problem. I have a set of cities, as well as a set of distances (which I not yet need since I'm creating random solutions).

I am attempting to use Itertools.permutations on the list of cities in order to create unique routes. My questions are:

  1. Is there any way in which I can make Itertools.permutations generate random solutions? Right now, it starts with cities[0]->cities[1]->cities[2] and so on. Can I randomize this?
  2. Can I make itertools generate only n permutations before returning? I have a list of 29 cities, and as you might have guessed that's a whole lot of permutations!

Thanks in advance!


Solution

  • This Python code will generate the permutations based on a random starting point and will stop after 6 permutations:

    from itertools import permutations
    from random import shuffle
    A=range(26)
    shuffle(A)
    for i,perm in enumerate(permutations(A)):
        print perm
        if i>=5:
            break
    

    Note that the permutations still have a lot of structure so the second permutation will be a lot like the first.

    You may do better simply using shuffle(A) each time to try a different permutation. (It may regenerate a permutation but with very low probability for 29 cities.) For example,

    for i in range(10):
        shuffle(A)
        print A