Jump to content
  • Advertisement
Sign in to follow this  

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.

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:
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

[edit]Added source tags[/edit]

Share this post

Link to post
Share on other sites

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 = rand
used[rand] = true
end for

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!