随机填充矢量矢量与固定数量的元素

时间:2014-12-11 00:44:10

标签: c++ random vector

我有一个项目,我必须随机填充一个网格(vector<vector<box>>),其中包含每个框中具有特定类型的元素。
 我们有4种特定类型:type1type2type3type4
用户设置每种类型的百分比 示例: Type1 33%,Type2 22%,Type3 22%,Type4 23%
我们可以有这样的网格:

\-----------
|1|1|3|3|4|2|
\-----------
|4|1|2|2|3|1|
\-----------
|4|4|2|1|1|3|
\------------

这是我的代码:

<vector<vector<box>> grid;
//createGrid is a function initializing a grid with elements with neutral type.
//in this example the number of lines is 3 and the number of columns is 6
createGrid(grid,3,6);
double numberOfType1 = round (3*6*percentOfType1/100);
//each number is calculated in the same way 
vector<string> types={"Type1","Type2","Type3","Type4"}
for(int i=0,i<grid.size(),i++){
   for(int j=0,j<grid[i].size(),j++){
      int choice = rand()%types.size();
      if(types[choice]=="Type1"){
        grid[i][j]=Element("Type1");
        numberOfType1--;
        if(numberOfType1==0){
          //a function that delete the element by its value in the vector
          delete(types,"Type1"); 
        }
      }else if(types[choice]=="Type2"){
        grid[i][j]=Element("Type2");
        numberOfType2--;
        if(numberOfType2==0){
          delete (types,"Type2");
        }
      } //and so on

我知道我可以使用开关盒,但这是第一稿。 所以我的问题是:

  1. 还有其他更好或更简单的方法吗?
  2. 如果没有,可以改进吗?

1 个答案:

答案 0 :(得分:0)

这是建议更好/更简单的方法(需要C ++ 11):

std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> d({3, 2, 2, 2});   //here determine discrete distribution

std::vector<int> v(10);   //or choose different size
std::generate(std::begin(v),std::end(v),[&](){return d(gen)+1;});

DEMO

生成包含

等元素的向量
4  2  1  2  3  3  2  1  3  1  

现在只需将其调整为您所写的所需类型。

相关问题