【问题标题】:Generating random number without repetitions. Is my logic correct?生成不重复的随机数。我的逻辑正确吗?
【发布时间】:2015-12-04 22:53:18
【问题描述】:

我编写了以下代码,以便从给定的单词数组中随机选择一个单词,而不选择两次相同的单词。 (我只想选择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);
}

【问题讨论】:

  • 下面的洗牌算法提出了一个很好的观点:你没有生成伪随机数:你生成的是一个洗牌序列。真正的随机序列允许重复。

标签: c arrays random srand


【解决方案1】:

您可以使用Fisher-Yates shuffle 算法的变体来快速生成无重复的随机排序序列。 “由内而外”算法的一个稍微简化的版本是:

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

您可以执行类似的操作来生成一个随机整数数组,然后使用这些整数来索引您的单词数组。

【讨论】:

  • 为什么要放array[0]=0?您不是随机选择这样做的第一个元素。
  • 你也可以把 F-Y 剪短。如果您只需要 10 项中的 4 项,则只需进行前 4 次迭代。
  • @Bob -- value = rand() % i 可以评估为零,所以是的,它确实随机选择第一个元素。
  • @LeeDanielCrocker -- 好点;人们很容易将其短路。
  • 我也完全有可能“过度简化”了一点。
猜你喜欢
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多