如何防止在随机数生成器中多次生成整数

时间:2019-05-18 17:35:43

标签: c++

我想在国际象棋棋盘中生成随机坐标,而不会多次生成坐标。我尝试使多个count变量跟踪每个坐标(例如a5,h7),但是我意识到为每64个坐标创建参数将花费一些时间。有没有更快的方法?

// Declarations:
string coordinates_x[8] = {"a", "b", "c", "d", "e", "f", "g", "h"};
string coordinates_y[8] = {"1", "2", "3", "4", "5", "6", "7", "8"};
vector<string> store;

// Storing coordinates in a vector:
for(int i = 0; i < 8; i++)
{
  for(int p = 0; p < 8; p++)
  {
    string temp = coordinates_x[p] + coordinates_y[i];
    store.push_back(temp);
  }
}

srand(time(NULL)); // integer generator intialization 

// Generating for white side of board:
for(int i = 0; i < w.size(); i++) // iterating based on the amt of chess pieces:
{
   int location_w = rand() % 31;
   cout << store[location_w] << endl;
   // Parameters to prevent the same location being outputted more than once
}

2 个答案:

答案 0 :(得分:2)

将它们放在std :: set中。独特的对象。如果不需要排序,甚至可以是unordered_set。

答案 1 :(得分:2)

@dyukha指出,一种解决方案是改组坐标池,最终可能看起来像:

#include <random>
#include <algorithm>
#include <iostream>

std::mt19937& get_generator()
{
    static std::random_device rd;
    static std::mt19937 g(rd());
    return g;
}

std::vector<std::string> get_random_coords(std::vector<std::string>& pool, int num_coords) 
{
    std::shuffle(pool.begin(), pool.end(), get_generator());
    return std::vector<std::string>
        (pool.begin(), pool.begin() + std::min(num_coords, (int)pool.size()));
}

int main() 
{
    int const board_width = 8;
    int const board_height = 8;
    std::vector<std::string> store;
    std::string coordinates_x[board_width] = {"a", "b", "c", "d", "e", "f", "g", "h"};
    std::string coordinates_y[board_height] = {"1", "2", "3", "4", "5", "6", "7", "8"};

    for(int y = 0; y < board_height; y++)
    {
        for(int x = 0; x < board_width; x++)
        {
            store.push_back(coordinates_x[x] + coordinates_y[y]);
        }
    }

    std::vector<std::string> random_pool(store.begin(), store.end());
    for(auto const& coord : get_random_coords(random_pool, 5))
    {
        std::cout << coord << '\n';
    }
 }