Genesis
Genesis

Reputation: 159

Randomizing the characters from a word

I am trying to figure out how to randomly sort the characters in a string such as "this", to "htis", or "tish", or "hsit". I believe my problem lies in the rand() possibly picking the same random number twice within the loop. Such as the second character applying twice during the loop. I'm also pretty sure that this loop at some point doesn't have anything to pick from during the last iteration of the loop as well.

My code is as follows:

 int main(void){
setvbuf(stdout,NULL,_IONBF,0);
int size=0;
char word[size];
int i;

printf("Please enter a word: ");
scanf(" %s",&word);
printf("Scanning the size of the word...");
size = strlen(word);
    for(i=0;i<size;i++){
    srand(time(0));
    int j = i + rand() / (RAND_MAX / (size - i) + 1);
    char t = word[j];
    word[j] = word[i];
    word[i] = t;
    }
printf("%i",size);
    for(i=1;i<size+1;i++){
        printf(" %c",word[i]);
    }
return 0;
}

Any thoughts?

Upvotes: 1

Views: 59

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The problem with your implementation is that you are calling srand in a loop. Since the loop goes pretty fast, you end uo calling srand with the same seed value, because time(0) does not get a chance to tick between loop iterations.

Move the call to srand outside the loop to fix this problem.

Note: see this answer for a good C implementation of Fisher-Yates shuffle.

Upvotes: 1

Related Questions