如何在C ++中使用随机数生成的应用程序中重复编号?

时间:2012-02-02 13:29:18

标签: c++

我有一个应用程序会显示Lotto Max数字,我需要让我的应用程序生成随机数,但我需要数字不重复。我完成了我的代码,并希望尽可能地改变一下。但任何帮助都会很棒!

    #include <iostream> 
    #include <iomanip>
    #include <cstdlib>
    using namespace std;

    int main()
    {

    {
cout << "*** LOTTO  MAX  INSTA  PICK ***" << endl;
cout<< " " << endl << endl;
    }

     {
 cout << "Your Insta Pick Numbers" << endl;
 cout<< " " << endl << endl;
     }
 for (int counter = 1; counter <= 21; ++ counter)
{

cout << setw(1) << (1 + rand() % 49) << " ";


if (counter % 7 == 0)
        cout << endl;
}
{
    cout<< " " << endl << endl;
}


{
cout << "Your Tag Numbers" << endl;
cout<< " " << endl << endl;
    }
for (int counter = 1; counter <= 9; ++ counter)
{

cout << setw(1) << (0 + rand() % 9)<< " ";


if (counter % 9 == 0)
        cout << endl;

}
{
    cout<< " " << endl << endl;
}
{
    cout << "Thank you for playing!! please check ticket\n a year minus a day            from date of purchase" <<endl;
}
    };

7 个答案:

答案 0 :(得分:3)

如果这是一个家庭作业,我不打算发布一个完整的解决方案。

但是,作为建议,您可以将已提取的数字存储在某处(例如,在排序的[*] std::vectorstd::map中),然后,当您提取新数字时,您可以检查容器中是否已存在该号码。如果是这样,您尝试提取一个新数字,直到在容器中找不到提取的数字。

[*]向量排序的事实允许快速二进制搜索(我不知道你要添加多少个数字;如果这个数量很少,那么简单 O(N)线性搜索就可以了;对于更大的计数, O(log(N))二进制搜索可以提供更好的性能。

答案 1 :(得分:1)

在使用rand函数之前,您需要使用唯一值为生成器设定种子。这是通过srand函数完成的。通常,唯一编号是time返回的当前时间:

srand(time(0));

除非您设法在一秒钟内多次运行应用程序,否则每次运行应用程序时结果都是唯一的。

答案 2 :(得分:1)

您需要一个存储已绘制数字的数据结构。当您生成一个数字时,您在该数据结构中查找它,如果它已经存在,则重绘,否则,您添加该数字。 std::set<int>是适合此的数据结构。

答案 3 :(得分:1)

我会填充一个向量来选择数字并用最后一个数字替换该向量中的所选数字,这样每次你选择时,你都可以得到一个唯一的数字。

答案 4 :(得分:0)

基本上当我们使用任何rand函数时,它并不会认为它总是会生成一个唯一的数字。所以只有一个解决方案存在使数据结构(例如数组)存储随机数并检查新创建的随机数带有数组的数字。如果存在,则再次调用随机生成函数。

答案 5 :(得分:0)

假设您的应用将返回49个号码中的一个,让我们存储所有可能的号码:

int numbers[49];

初始化它们:

for( int i = 0; i < 49; i++){
    numbers[i] = i+1;
}

存储您可以获得的最大数量:

int max = 49;

现在猜测算法:

int index = rand()%max; // Get just number inside the boundaries
int result = numbers[index]; // Store the number
max--; // Decrease maximum number you can get
numbers[index] = numbers[max]; // Move last number to place of just guessed number
numbers[max] = 0; // Erase last number

内部发生的事情(5个数字):

  • 假设您有这5个数字:[1 2 3 4 5]
  • rand()%5将输出2,即numbers[2],即数字3(结果)
  • 我们不能再使用3了,但是我们可以使用数字5并将列表缩短1,所以将5移到第3位,这样你的数组就会像:[1 2 5 4 5]
  • 从末尾删除5 [1 2 5 4 0]
  • 降低最大值,所以我们猜测只有索引0-3和数组似乎是[1 2 5 4]

个人注意事项:您也可以使用std::容器,但这就像用火焰喷射器狩猎

答案 6 :(得分:0)

如果你正在使用gcc,你可以利用一些lib来生成数字容器,加扰它们,然后从容器中弹出数字,一次一个:

#include <algorithm>
#include <ext/numeric>
#include <vector>
#include <iostream>


int main(int argc,const char** argv)
{
  std::vector<int>  v(21);

  __gnu_cxx::iota(v.begin(),v.end(),0);
  std::random_shuffle(v.begin(),v.end());
  while( !v.empty() ) {
    std::cout << v.back() << std::endl;
    v.pop_back();
  }
  return( 0 );
}

如果你没有使用gcc,iota可能是“数字”(而不是“ext / numeric”),在命名空间标准中。