c++ - (C++) 制作一组数字 1-3 的随机序列
问题描述
我需要我的程序每次从 1-3 生成一个随机序列,但我不明白如何使用 rand() 以每个程序的不同顺序生成数字 1 到 3 的序列。它不能再次是相同的数字,所以我不知道我会做些什么来防止这种情况发生。一个示例运行将是
123第一,231第二,321等等第四
你会用什么来制作一个不重复数字的序列
解决方案
生成序列的最简单方法是使用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";
}
}
推荐阅读
- android - 我想让这个日期选择器透明
- sql - 从 Excel 文件中的数据生成 SQL INSERT
- node.js - 如何使用 Chrome DevTools 在 goormIDE 中调试 Node.js 应用程序?
- ios - 获取 UITextField 安全文本的宽度
- javascript - 在文件上传器 Javascript 上检测损坏的文件
- python-3.x - 是否可以在 Python (Spyder) 中更新内联图?
- java - 使用自定义比较器会导致排序不一致
- android - Main Activity toolbar not showing after hiding when attaching fragment
- echarts - 如何使用 Echarts 在散点图上绘制圆形图层
- hibernate - 如何选择部分实体,然后使用实体更新数据库中的实体?