lundi 4 mars 2019

About a non-repeat rand function

I tried to generate 25 arrays, each of them should contains number 1 to 25 without repetition and out of order. I executed the code to generate an array, there was no repetition. There were repeating numbers in the array when I tried to map the array into the 2D array.

Here is my code

int permutation(int arraystore[]){

int item[25], index;
for (int x = 0; x < 25; x++)
    item[x] = x;                  //input values into item array

for (int x = 25; x > 0; x--) {
    index = rand() % x;     //generate random numbers
    arraystore[x] = item[index];
    while (index < x - 1) {             
        item[index] = item[index + 1];
        index++;
        }
    }
}

I map the arraystore into the 2d array in main

int main(){
int ddarray[25][25];
for(int j=0;j<25)
    for(int i=0;i<25;i++){
        int array[25];
        permutation(array);
        ddarray[j][i]=array[i];
    }
}

Here are some of results

192,9,7,3,11,20,18,9,23,11,21,5,11,17,5,12,11,3,10,9,2,5,7,7,19, 192,5,0,14,23,22,6,2,20,24,13,12,21,24,21,6,11,21,1,20,5,8,6,12,15, 192,21,6,14,14,11,11,8,17,19,9,24,22,6,24,11,2,22,6,13,2,18,6,14,20,

Did I do any wrong in the permutation function or miss something?

Thank you for answering my question!




Aucun commentaire:

Enregistrer un commentaire