I wrote the following code i order to randomly choose a word from a given array of words without choosing the same word twice. (I want to choose only 4 words). After dry running the program and testing it, everything seems to be working fun and no duplicates where encountered, however I would like to have a second verification since I am new to programming.
char words[10][10] = {"dog", "cat", "horse", "cow", "goat", "monkey", "elephant", "crow", "fish", "snake"};
void getRandomWords()
{
int i = 0, k = 0;
srand((unsigned)time(NULL));
n = rand() % 10;
checkRandom[k] = n;
k ++;
for (int j = 0; j < 10; j ++) {
printf("%c\n", words[n][j]);
}
do {
n = rand() % 10;
for (int t = 0; t < 4; t ++) {
if (checkRandom[t] == n) {
found = 1;
break;
}
else
found = 0;
}
if (found == 0) {
checkRandom[k] = n;
k ++;
for (int j = 0; j < 10; j ++) {
printf("%c\n", words[n][j]);
}
i++;
}
} while (i < 3);
}
Aucun commentaire:
Enregistrer un commentaire