jeudi 1 juin 2017

C Function to create array X of X numbers from a random selection of Y numbers in Y array without repetition

I've done some looking around and found an old solution to a similar problem. As I understand it this program should shuffle an array of numbers 0-32 the place the first 16 numbers from the shuffled array in array b.

However as it stands now every time its run it will print the same set of numbers unless the shuffle # is changed in this case: 25

shuffle(a,33,25);

I get the feeling that shuffle is not doing what it is supposed to do.

I copied this code and edited it to suit my needs, however eventually I want main to return an array [b,r] the numbers generated to be used against an array containing strings labeled to be found using [b,r] and create a file with just the strings from the output of this function (as opposed to the entire list of strings) which is why I have r commented out.

#include <stdio.h>
#include <stdlib.h>

void shuffle(int *array, size_t array_size, size_t shuff_size)
{   
    if (array_size > 1)  
    {   
        size_t i;
        for (i = 0; i < shuff_size - 1; i++) 
        {   
            size_t j = i + rand() / (RAND_MAX / (array_size - i) + 1); 
            int t = array[j];
            array[j] = array[i];
            array[i] = t;
    }
    }
}

int main(int argc, char * argv[]) 
{
    int a[33];
    int b[16];
    int i,j, k=0;
    /*int r=0;*/

    for(i=0; i<33;++i)

        a[i]=i;
        shuffle(a,33,25);

    for(j=0;j<16;++j)
    {
        b[j]= a[k++];
        /*r = rand() % 6;   */
        printf("%d ",b[j]);
        /*printf("%d, ",r); */
    }

    printf("\n");
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire