mercredi 13 janvier 2016

A function that shuffles an array passed as an argument

I'm working on a project at school and I want to create a function that shuffles an array passed as an argument. I tried to create one, but it didn't work as I expected...

In this code, I'm trying to copy the elements of the passed array and set them in random order in a second array. Then, copy them again in the passed array..

This is the source code:

void shufarray(int* array, int b)
{
    int hold[b];  
    int i,k;  
    int randV=0, randHold=0;
    srand(b);  
    for(i=0; i<b; ++i) {      
        hold[rand() % (b-1)] = array[i]; 
        k=0;
        do { 
            if(k==0) { 
                randHold = randV;
                k=-1;
            } //end if
            randV = rand()%(b-1);         
        } while(randHold != randV);//end of do\while stetment 
        hold[randV] = array[i];     
    } //end for  
    for(i=0;i<b;++i) {
        array[i]=hold[i]; 
    } //end for 
} //end shufarray()

And this is the output:

hold[ 0 ] = 8
hold[ 1 ] = 11
hold[ 2 ] = 2
hold[ 3 ] = 15
hold[ 4 ] = 18
hold[ 5 ] = 10
hold[ 6 ] = 11
hold[ 7 ] = 17
hold[ 8 ] = 24
hold[ 9 ] = 21
hold[ 10 ] = 12
hold[ 11 ] = 2
hold[ 12 ] = 15
hold[ 13 ] = 9
hold[ 14 ] = 13
hold[ 15 ] = 1
hold[ 16 ] = 15
hold[ 17 ] = 1
hold[ 18 ] = 22
hold[ 19 ] = 11
hold[ 20 ] = 11
hold[ 21 ] = 18
hold[ 22 ] = 17
hold[ 23 ] = 4
hold[ 24 ] = 7
shuffled_hold[ 0 ] = 7
shuffled_hold[ 1 ] = 32561
shuffled_hold[ 2 ] = 22
shuffled_hold[ 3 ] = 0
shuffled_hold[ 4 ] = 18
shuffled_hold[ 5 ] = 8
shuffled_hold[ 6 ] = -632114865
shuffled_hold[ 7 ] = 32561
shuffled_hold[ 8 ] = -628693440
shuffled_hold[ 9 ] = 11
shuffled_hold[ 10 ] = 15
shuffled_hold[ 11 ] = 18
shuffled_hold[ 12 ] = 1
shuffled_hold[ 13 ] = 13
shuffled_hold[ 14 ] = 15
shuffled_hold[ 15 ] = 12
shuffled_hold[ 16 ] = 17
shuffled_hold[ 17 ] = 0
shuffled_hold[ 18 ] = 4
shuffled_hold[ 19 ] = 17
shuffled_hold[ 20 ] = 7
shuffled_hold[ 21 ] = 0
shuffled_hold[ 22 ] = -1
shuffled_hold[ 23 ] = 0
shuffled_hold[ 24 ] = 0

So I'm trying to understand the principle of this operation, anyone helps me to find what is exactly the problem.. Thanks.




Aucun commentaire:

Enregistrer un commentaire