Search code examples
carraysrandomsrand

Generating random number without repetitions. Is my logic correct?


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);
}

Solution

  • You can use a variant of the Fisher-Yates shuffle algorithm to quickly produce a randomly-ordered sequence without duplicates. A slightly simplified version of the "inside-out" algorithm is:

    void shuffle(int *array, int length) {
        int i, value;
    
        array[0] = 0;
    
        for (i = 1 ; i < length ; i++) {
            value = rand() % (i + 1);
    
            array[i] = array[value];
            array[value] = i;
        }
    }
    

    You could do something similar to generate a random array of integers, then use those integers to index your word array.