# computing a permutation

This topic is 5096 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, could somebody please direct me to a good algorithm for generating a permutation. I need to randomly select a permutation of 1 to 6. I can easily select the first number, but then I have to make sure that the same numbers do not occur twice.

##### Share on other sites
Put all your numbers in an array. To select your next number generate a random index between 0 and the number of entries left in the array and take the number at that index. Everytime an entry is selected put the last entry in the array into the space of the one just picked. This way you'll not reproduce any entries.

##### Share on other sites
Here's an algorithm in Python that is use to generate all permutations of a set. I didn't think of the algorithm myself, I got if from some university site.

Note that the function is recursive.

# Start function, v is a set/list/array/whatever of elementsdef permute(v):    # Permutations is where we store the permutations of v    permutations = []    # Start the recursive function    __permute_recursive(v, len(v), 0, permutations)    # And return the result    return permutations# The recursive function where the real work is done# v is the set of elements whose permutations we want# n is the number of elements in v# start is used to remember what elements are being swapped# result is where we store the permutations of vdef __permute_recursive(v, n, start, result):    # End condition    if start == n-1:        result.append(v[:])    else:        for i in range(start, n):            # Swap i and start            tmp = v            v = v[start]            v[start] = tmp            __permute_recursive(v, n, start+1, result)            v[start] = v            v = tmp

##### Share on other sites
homework?
integer array permutationboolean array usedfor integer i = 1 to 6   integer rand = random integer from 1 to 6   while used[rand] = true      rand = random integer from 1 to 6   end while   permutation = rand   used[rand] = trueend for

##### Share on other sites
Hi,
no its not for homework - it's part of a game.

Thanks for all the help guys

##### Share on other sites
Look into the function: random_shuffle

I'm sure it can solve your problem.

1. 1
2. 2
3. 3
4. 4
Rutin
11
5. 5

• 12
• 19
• 10
• 14
• 10
• ### Forum Statistics

• Total Topics
632666
• Total Posts
3007718
• ### Who's Online (See full list)

There are no registered users currently online

×