Sign in to follow this  

computing a permutation

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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 elements
def 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 v
def __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[i]
v[i] = v[start]
v[start] = tmp
__permute_recursive(v, n, start+1, result)
v[start] = v[i]
v[i] = tmp



[edit]Added source tags[/edit]

Share this post


Link to post
Share on other sites
homework?

integer array permutation
boolean array used
for 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[i] = rand
used[rand] = true
end for

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this