C ++随机将var更改为不是本身的枚举

C++ Randomly change var to enum that is not itself

目前,我可以从一个枚举中随机选择并将其分配给我的变量:

(*itL).setDirection(static_cast<LadyDirection>(rand()% NUM_DIRECTIONS));

void Ladybug::setDirection(LadyDirection temp_direction)
{
    this->direction = temp_direction;
}

enum LadyDirection
{
    North,
    East,
    South,
    West,
    NUM_DIRECTIONS
};

我想做的是将此更改为随机枚举值,这不是当前的值。例如。如果方向==北,则随机设置为东、西或南。

我知道我可以用一些 if/elseif 语句来做到这一点,但我想知道是否有更好的方法。

谢谢。

将方向列表视为一个循环列表,在 1NUM_DIRECTIONS - 1 之间(包括)生成一个随机数,并将其用作移动到列表中的步骤数:

void LadyBug::setDirection(int nSteps)
{
    this->direction = static_cast<LadyDirection>(
                     (this->direction + nSteps) % NUM_DIRECTIONS
    );
}

(*itL).setDirection(1 + rand()%(NUM_DIRECTIONS - 1)));

您可以这样做而不是第一行代码

r = rand() % (NUM_DIRECTIONS - 1); // limit the random to 0..2
new_direction = (old_direction + r + 1) % NUM_DIRECTIONS;

could do this with a few if/elseif statements

我认为你高估了复杂性:只需使用 rand() % (NUM_DIRECTIONS - 2)(这样你就永远不会直接得到 West),如果你碰巧碰到当前方向,请使用 West取而代之的是:

LadyDirection dir = itL->getDirection();
itL->setDirection(static_cast<LadyDirection>(rand() % (NUM_DIRECTIONS - 2));
if (itL->getDirection() == dir)
    itL->setDirection(West);

作为成员函数会更简单