Advertisement

Generating permutations

Started by January 08, 2003 03:09 PM
8 comments, last by Dave007 22 years, 1 month ago
Hi! I have an array of indices (eg. {1,2,3,4,7,6...}) and I need 2 things. 1. Generate all possible permutations of this array 2. Create a random parmutation of this array What''s the most effective way to do this? I need it for my pattern matching algorithm in my CAS. ------- Dave
--------Dave[ Math Studio ] A Computer Algebra System
The number of permutations is the factorial of the number of elements in the array.

Death of one is a tragedy, death of a million is just a statistic.
If at first you don't succeed, redefine success.
Advertisement
There's a function in STL/C++ that's called 'std::next_permutation'.
That should be what you're looking for.

/John

[edited by - FunkyTune on January 8, 2003 4:45:24 PM]
/John
Thanks Funky, it seems to be what I needed, in some way.
But I''d rather know the algorithm...

---------
Dave
--------Dave[ Math Studio ] A Computer Algebra System
Why don''t you check out the source code then?
If you''re running VC++, right click on the function name and choose ''Go To Definition of'', and all will be revealed to you. Well sort of, I find STL soruce code kind of hard to read, but I''m sure you''ll figure it out.

/John
/John
some recursive pseudocode:

void permute(int *buf, int len)
{
if len>1
{
for(i=0;i {
exchange(buf[0],buf);<br> permute(&buf[1],len-1);<br> exchange(buf[0],buf);<br> }<br> }<br> else<br> {<br> output(whole_buffer);<br> }<br>}<br><br><SPAN CLASS=editedby>[edited by - ga &#111;n January 8, 2003 5:21:44 PM]</SPAN>
Visit our homepage: www.rarebyte.de.stGA
Advertisement
quote:
Original post by Dave007
2. Create a random parmutation of this array


Just go through the list tossing the elements around randomly.

Pseudocode:

for i = 0 to n
switch a a[rand(n)]
Stupid formatting!
for i = 0 to n  switch a a[rand(n)] 
3rd try...

  for i = 0 to n  switch a[i] a[rand(n)]  

std::random_shuffle will give a random permutation.

This topic is closed to new replies.

Advertisement