samedi 11 février 2017

Shuffle an array of strings randomly

I am writing a program that reads a text file as an input and randomly shuffles the array of strings for the user. I have written a program that shuffles the string array randomly but I want to do it in a way that no two elements that are the same are beside each other.

Here's an example: The original array would look like this

{1,2,3,4,5,1,2}

The shuffled array would look like this

{5,3,1,2,4,2,1}

But currently my program creates an output array of this

{5,1,1,3,2,4,2}

Here is my code that shuffles the elements randomly:

    int i;  
    char s[11][100];
    char line[100], t[100];

    /*Open the text file*/
    FILE *fp;
    fp = fopen("players.txt", "r");

    /*Read each line and put it into an element in an array.
    Each line will be in a seperate element in the array.*/
    i=0;
    while(fgets(line, 100, fp)!= NULL){
        strcpy(s[i], line);
        i++;

    }


    /*Generates a random number stored in j and shuffles the order of the array randomly*/
    for(i=1; i<10; i++){

        j = rand()%(i+1);
        strcpy(t, s[j]);
        strcpy(s[j], s[i]);
        strcpy(s[i], t);    

    }




Aucun commentaire:

Enregistrer un commentaire