Array assistance... prob simple :S

My program is to shuffle from 1-52. It shouldnt have any duplicates. BUt anytime i try to fix 'i' so that it would repeat the procedure if it is equal to any number already there it doesnt work :(. Help

void shuffle(int num[], int length)
{
srand( time(NULL) );
for (int i=1; i<=length; i++)
{
int x = 1 + rand()% length;

for (int m=0l m<=i; m++)
{ if (x != num[m])
num[i] = x;
else
{ m = i + 2;
i--;
}
}
}
}

If i remove the i-- it works (of course with duplicating numbers). How else can i get this resolved? THe program prints the numbers in the array 1 to 52.

Thanks in advance.
for (int m=0l m<=i; m++)
remove this^ should be a ;
Your loop:

 
for( int m = 0; m <= i; ++m )


is checking not only all previously filled out elements, but also the current one you are looking
to fill out. You don't want to check the current one, so m <= i; should be m < i;.

But... there are not only easier ways, but also more efficient ways. Consider pre-filling the array
with the numbers 1-52 in order, then, in a loop, randomly choosing two elements to swap and
swapping them. If you repeat the swap a bunch of times, the effect will be to randomize the
ordering, which is what you want.

If this is not a homework assignment, then consider using the std::random_shuffle() algorithm, as
it does the random swap loop for you.

1
2
3
#include <algorithm>

std::random_shuffle( &num[0], &num[length], rand );


Ought to do the trick.
That was an error Kyle.
Thanks alot JSmith...
Topic archived. No new replies allowed.