生成不重复的随机数。我的逻辑正确吗?

Generating random number without repetitions. Is my logic correct?

我编写了以下代码,以便从给定的单词数组中随机选择一个单词,而无需两次选择相同的单词。 (我只想选择4个字)。在干燥 运行 程序并对其进行测试后,一切似乎都很有趣,并且没有遇到重复的地方,但是我想进行第二次验证,因为我是编程新手。

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

您可以使用 Fisher-Yates 混洗算法的变体来快速生成无重复的随机排序序列。 "inside-out" 算法的一个稍微简化的版本是:

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

您可以做类似的事情来生成随机整数数组,然后使用这些整数来索引您的单词数组。