我想生成许多矩阵并用随机数填充它



大家好,我想用随机数生成许多 5x5 的矩阵,但我制作的这段代码只一遍又一遍地打印相同的矩阵,有什么问题?(我正在学习C ++(,这段代码只是一遍又一遍地打印相同的矩阵,而不是每个矩阵中的不同数字

#include <iostream>
#include <string>
#include <sstream>
#include <ctime>
#include <iomanip>
#include <cstdlib>
using namespace std;

bool verif(int carton[5][5], int f, int c, int nume){
for(f=0;f<5;f++){
for(c=0;c<5;c++){
if(nume==carton[f][c]){
return false;
}
}
}
return true;
}
int i,cant,nume;
int main()
{
ingresa: 
int j,cant;
cout<< "type the number of bingo cards you want: ";
cin>>cant;
if(cant>100){ 
cout<<"ERROR the max number of bingo cards is 100:"<<endl;
goto ingresa;
}
for(i=1;i<=cant;i++){ 
cout<<endl;
cout<< "BINGO #"<<i<<endl;
int carton[5][5]; 
int f,c,nume; 
srand(time(NULL));
for(f=0;f<5;f++){
for(c=0;c<5;c++){
nume=1+rand()%25;
carton[f][c]=nume;
while(verif(carton,5,5,nume)==false){
nume=1+rand()%25;
}
carton[f][c]=nume;
}
}
for(f=0;f<5;f++){
for(c=0;c<5;c++){
cout<<setw(3)<<carton[f][c]<<" ";
}
cout<<endl; 
}
}
}

主要问题是您多次调用srand(),将随机数生成器的状态重置为相同的值(除非您很幸运并且时钟在迭代之间步进一秒(。您只应为伪随机数生成器设定种子一次

细节:

  • 填充数组的算法很昂贵。与其生成一个随机数并测试该数字是否已被采用,不如按顺序 (1-25( 生成数字,然后std::iota然后std::shuffle数组。

  • 不要使用srand()&rand()。标准库中有更好的随机生成器,例如std::mt19937

  • 不要使用goto.创建一个while(true)循环,并在用户输入有效数字时将其break

#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
int main() {
std::mt19937 prng(std::random_device{}()); // A seeded PRNG

int carton[5][5];
// fill the array with 1-25
std::iota(&carton[0][0], &carton[0][0] + 25, 1);
// make the order properly random
std::shuffle(&carton[0][0], &carton[0][0] + 25, prng);
// You can use the prng to generate a random number in the range [1,25]
// with the help from uniform_int_distribution:
std::uniform_int_distribution<int> dist(1, 25);
std::cout << "A random number 1-25: " << dist(prng) << 'n';
}

最新更新