生成 9 个随机数而不重复
Generating 9 random numbers without repeating
我有一个作业,希望 ne 制作一个魔方程序,您可以在其中生成随机数 1-9 并将它们分配给 2D 数组,我不知道如何生成不重复的随机数,我想知道是否有人可以帮助我它是 c++。
提前谢谢!
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
// Returns true if the item is in the list, otherwise false
bool checkInList(std::vector<int> &list, int value)
{
for (int i = 0; i < list.size(); ++i)
{
if (list.at(i) == value)
{
return true;
}
}
return false;
}
// min inclusive, max exclusive
// make sure to set a new seed before using to help make results more random. (std::srand)
int randomInt(int min, int max)
{
return rand() % (max - min) + min;
}
int main()
{
std::vector<int> list;
std::srand(std::time(0));
while (list.size() < 9)
{
int num = randomInt(1, 10);
if (!checkInList(list, num))
{
list.push_back(num);
}
}
for (int i = 0; i < list.size(); ++i)
{
std::cout << list.at(i) << std::endl;
}
return 0;
}
我喜欢 sabreitweiser的简单答案,但它并没有完全满足您的要求。
我发布的代码应该与您正在寻找的代码一致。
看看算法标头中的 std::random_shuffle。它应该适用于几乎所有的 stl 容器,假设这已经足够了。例如,您可以在整数为 1 到 9 的向量上使用它,然后将其转换回数组。这不是最有效的方法,但它可以节省大部分编码工作。
希望这有帮助!
相关文章:
- 半随机数生成C++
- 随机数生成函数说明
- C++RNG(随机数生成)优化
- C++ 11 随机数生成不起作用
- 有偏差的随机数生成
- 如何根据用户输入"weighted"随机数生成,使某些数字优先于其他数字?
- 0-1之间的随机数生成以填充容器
- Visual Studio C++ 2012 和 2017 在随机数生成中表现出不同的行为?
- 随机数生成缺少同一种子的模式
- C 伪随机数生成平台依赖关系
- Diffie-Hellman密钥交换的C GMP随机数生成
- 我简单的 c++ 文本游戏不起作用。我正在使用随机数生成,我很困惑
- 随机数生成:相同的C++代码,两种不同的行为
- c++中使用GMP的随机数生成
- 二项式随机数生成
- c++:用于随机数生成的通用函数
- 两个区间[a,b]之间的二重随机数生成
- 随机数生成与并行化c++/Qt
- rand()随机数生成C++
- 基本C++伪随机数生成