将唯一随机数插入向量

时间:2017-01-10 04:02:09

标签: c++ vector random

作为特定游戏的代码的一部分,我想在向量中生成4个唯一的随机数。

此代码适用于一些重复播放,然后是应用程序崩溃(不响应窗口)。

虽然我理解if-condition阻止for循环将相同的数字插入到向量中,但是这个for循环在通过rand()函数生成唯一数字之前需要多长时间? srand(time(NULL))rand()如何根据系统时间完全协同创建随机值?

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

using namespace std;

//plays bulls and cows


int main() {
srand(time(NULL));
string play="yes";
int nums=4;       // number of values in an answer (must NOT exceed 10)
vector<int> answer;


while (play=="yes" || play=="YES" || play=="Y" || play=="Yes" || play=="y") { //plays the game

answer.push_back(rand()%10+1);
  do {                              //fills vector with unique random numbers
    for (int i=1; i<nums; i++) {
      answer.push_back(rand()%10+1);
      if (answer[i]==answer[i-1]) {
        i=i-1;
        continue;
        }
      }
  } while (answer.size()!=nums);

for (int i=0; i<nums; i++) {
  cout<<answer[i];
}

  cout<<"Do you want to play again?"<<'\n';
  cin>>play;
  answer.clear();
} //game ends


if (play=="no" || play=="n" || play=="No" || play=="NO" || play=="N") { //terminates and checks for exceptions
  cout<<"Thank you for playing!"<<'\n';
  return 0;
} else {
  cerr<<"Error: wrong input. Terminating."<<'\n';
  return 0;
}

    return 0; //safety return
}

3 个答案:

答案 0 :(得分:0)

为什么要将新的try添加到answer而不是临时变量。如果变量有效,则将其添加到答案中。在您的情况下,i始终保持1;

while (play=="yes" || play=="YES" || play=="Y" || play=="Yes" || play=="y") { //plays the game

    int last_try=rand()%10+1;
    answer.push_back(last_try);
    do { //fills vector with unique random numbers
            int new_try=rand()%10+1;

            if (last_try!=new_try)
            {
                answer.push_back(new_try);
                last_try=new_try;
            }
    } while (answer.size()!=nums);


    for (int i=0; i<nums; i++)
    {
        cout<<answer[i]<<"\n";
    }

    cout<<"Do you want to play again?"<<'\n';
    cin>>play;
    answer.clear();
} //game ends

答案 1 :(得分:0)

假设您必须使用std::vector(而不是std::set)。用随机数填充向量的最简单方法是检查数字是否已经被&#34;看到&#34; - 如果没有,则将其添加到矢量中。

这可以通过使用bool数组作为助手来确定数字是否已被看到来实现:

#include <vector>
#include <iostream>
#include <cstdlib>

int main()
{
    std::vector<int> answer;
    int num = 4;

    // 10 numbers
    bool seen[10] = {false};

    // keeps track of numbers added
    int numsAdded = 0;
    while (numsAdded < num)
    {
       int numRand = rand()%10;
       if ( !seen[numRand] )
       {
         // not seen, so add it to vector and update bool array and
         // numsAdded
         answer.push_back(numRand + 1);
         seen[num] = true;
         ++numsAdded;
       }
    }
    for (size_t i = 0; i < num; ++i)
       std::cout << answer[i] << " ";
}

Live Example

答案 2 :(得分:-1)

问题是你在检查它是否有效之前总是推回向量中的随机值。我们假设您的程序按顺序生成这些随机值:

2,6,6,7,9,10

你会插入2(i == 2),6(i == 3),6(i == 4),然后实现6重复两次,所以你回去一次迭代(i == 3),但你的六个人仍在你的向量中。所以现在你将添加7(i == 4),你将退出for循环中的5个值。

然后当你评估你的do-while条件时,你的answer.size()不会等于4,因为它已经等于5.你现在陷入无限循环,你的应用程序崩溃了消耗你的载体中无限增长的所有可用内存。

此外,您的逻辑似乎有错误。为了确保你没有重复的值(并且你被卡住了),你不仅要验证最后插入的值而且要验证整个向量。像这样:

#include <algorithm>

if ( std::find(vector.begin(), vector.end(), item) != vector.end() )
   do_this();
else
   do that();
相关问题