首页 > 解决方案 > (C++) 制作一组数字 1-3 的随机序列

问题描述

我需要我的程序每次从 1-3 生成一个随机序列,但我不明白如何使用 rand() 以每个程序的不同顺序生成数字 1 到 3 的序列。它不能再次是相同的数字,所以我不知道我会做些什么来防止这种情况发生。一个示例运行将是

123第一,231第二,321等等第四

你会用什么来制作一个不重复数字的序列

标签: c++randomsequence

解决方案


生成序列的最简单方法是使用std::shuffle重新排序包含所需值的向量:

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

int main()
{
    std::random_device rd;
    std::mt19937 g(rd());
    std::vector<int> elements = { 1, 2, 3 };
    std::shuffle(elements.begin(), elements.end(), g);
    for (int i : elements)
    {
        std::cout << i << "\n";
    }
}

如果你真的必须使用rand()(它通常不是一个很好的随机数生成器)你也可以把它挤进去shuffle

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

struct RandDevice
{
    using result_type = uint32_t;
    static result_type max() { return static_cast<result_type>(RAND_MAX); };
    static result_type min() { return 0; };

    result_type operator()() {
        return static_cast<result_type>(rand());
    }
};

int main()
{
    std::vector<int> elements = { 1, 2, 3 };
    srand(time(0));
    std::shuffle(elements.begin(), elements.end(), RandDevice());
    for (int i : elements)
    {
        std::cout << i << "\n";
    }
}

推荐阅读