我有一个任务,希望ne制作一个魔术方程序,你生成随机数1-9并将它们分配到2D数组,我无法弄清楚如何生成不重复的随机数,我我想知道是否有人可以帮助我做c ++。
提前谢谢你!
答案 0 :(得分:0)
在算法标题中查看std::random_shuffle。它应该适用于几乎所有的stl容器,假设这已经足够了。例如,您可以在具有整数1到9的向量上使用它,然后将其转换回数组。它不是最有效的方法,但它可以节省大部分编码工作。
希望这有帮助!
答案 1 :(得分:0)
#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的简单回答,但它并没有完全符合您的要求。
我发布的代码应该与您正在寻找的代码一致。