c++如何排除已经尝试过的随机数

c++ how to exclude random numbers that have already been tried

本文关键字:随机数 何排除 排除 c++      更新时间:2023-10-16

我正在编写一个程序,让原子在晶格中移动,它通过选择与某个方向(其中有八个)相关的随机数来实现这一点,测试该方向是否可行,以及是否不选择新的随机数。

我想知道是否有一种方法可以将该随机数从可以选择的随机数池中排除,这样程序就不会重复尝试选择相同的随机数

我目前正在使用一个看起来有点像这样的开关(不包括整个功能,因为目前它相当大…

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()返回正整数。