【问题标题】:Non repeating elements from array [duplicate]数组中的非重复元素[重复]
【发布时间】:2018-07-02 18:18:04
【问题描述】:
#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{
    srand(time(NULL)); //initialize the random seed

    while (true) {
        const char arrayNum[4] = { '1', '3', '7', '9' };
        int RandIndex = rand() % 4; //generates a random number between 0 and 3
        cout << arrayNum[RandIndex];
    }
}

当生成这些数字时,其中一些是重复的,我不想要这个。这是一种方法吗?

【问题讨论】:

  • 好吧...当您只从 4 个中选择时,您不能有一个无限循环不断打印不同的数字。您真正想要什么?
  • 请注意,消除重复会使您的序列不那么随机,而不是更随机。
  • 让我们提议我有一个重复 10 次的 for
  • 我不希望数字重复
  • 我不清楚您是要避免连续数字重复,还是希望整个序列中的每个数字都是唯一的。

标签: c++ arrays loops random


【解决方案1】:

您可以创建一个布尔数组来指示索引是否已被使用。

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;


int main()
{
    srand(time(NULL)); //initialize the random seed
    const char arrayNum[4] = { '1', '3', '7', '9' };
    bool taken[4] = { false };
    int RandIndex;
    for(int i = 0; i < 4; i++){
        do{
             RandIndex = rand() % 4;
        }while(taken[RandIndex]);
        taken[RandIndex] = true;
        cout << arrayNum[RandIndex];
    }
}

【讨论】:

  • 此解决方案有效,但(平均而言)每个后续数字需要越来越多的工作。并且使用幻数使其容易出错。
  • @FrançoisAndrieux 我同意
  • 这项工作,谢谢你
猜你喜欢
  • 2015-03-13
  • 2017-08-18
  • 1970-01-01
  • 2012-08-04
  • 2014-05-26
  • 1970-01-01
  • 2013-03-23
  • 2013-05-20
相关资源
最近更新 更多