c++如何排除已经尝试过的随机数
c++ how to exclude random numbers that have already been tried
我正在编写一个程序,让原子在晶格中移动,它通过选择与某个方向(其中有八个)相关的随机数来实现这一点,测试该方向是否可行,以及是否不选择新的随机数。
我想知道是否有一种方法可以将该随机数从可以选择的随机数池中排除,这样程序就不会重复尝试选择相同的随机数
我目前正在使用一个看起来有点像这样的开关(不包括整个功能,因为目前它相当大…
int a = rand()%8;
switch (a)
{case 0:
...
case 1:
...
and so forth
}
使用一个包含数字1到8的int向量,然后在每次迭代后随机洗牌,怎么样?类似:
std::vector<int> vOneToEight;
for (int i=1; i<9; ++i) vOneToEight.push_back(i); // {1, 2, 3, 4, 5, 6, 7, 8}.
std::random_shuffle(vOneToEight.begin(), vOneToEight.end()); // 1 to 8 with random order.
for (size_t i=0; i<vOneToEight.size(); ++i)
your_func(vOneToEight[i]); // Use the outcome in whatever way.
std::random_shuffle(vOneToEight.begin(), vOneToEight.end()); // Re-shuffle.
for (size_t i=0; i<vOneToEight.size(); ++i)
your_func(vOneToEight[i]); // Keep going if needed..
类似的东西?
下面的代码是用记事本写的,速度极快。如果您发现错误,请留言评论,谢谢
/* main.cpp */
#include <vector>
#include <iterator>
typedef std::vector<int> NumberList;
int main()
{
NumberList list;
int Last = 0;
for(int i=0;i<5;i++)
{
// Prevent using it two times in a row
while( ( x = rand()%mod ) != last ){ }
// Prevent adding the same number two times in the list
bool alreadyIn == false;
for( std::vector<int>::iterator it = list.begin();
it != list.end(); it->next() )
{
if( *it == x )
alreadyIn = true;
}
if( !alreadyIn )
list.push_back(x);
// Do stuff with x
switch(x)
{
// ...
}
// Keep track of x
last = x;
}
return 0;
}
此代码可能会生成一个列表:
{1,0,2,4,9}
这意味着0将不会成为第一项
要修复此问题,请使用int Last = -1;
**假设rand()返回正整数。
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- 函数何时会在c++中包含stack_Unwind_Resume调用
- Python中的for循环与C++有何不同
- if数组上的随机数
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 半随机数生成C++
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- 具有随机数的二维数组不会更改
- 随机数未达到限制
- 我想生成许多矩阵并用随机数填充它
- <random>在实践中应该实际使用哪个随机数引擎? std::mt19937?
- 在C++中释放内存期间,迭代器与指针有何不同
- 制作具有平均值的随机数生成器
- C++:如何在从给定缓存中排除数字的同时生成随机数
- c++如何排除已经尝试过的随机数
- 如何生成8位(伪)随机数,以便排除某些已知数字
- C++排除范围内的随机数