mercredi 7 avril 2021

Implementing a 1/3 chance of a variable being -1, 0, or 1 in C++ using rand [duplicate]

I need to generate a 1/3 chance of something using rand().

The reason why is because I want to generate a random dx and dy with 9 different outcomes:

//Stay in place
dx = 0, dy = 0, stay in place 

//Horizontal movement
dx = 1, dy = 0, so move right one cell
dx = -1, dy = 0, so move left one cell
 
//Vertical movement
dx = 0, dy = 1, so move up one cell
dx = 0, dy = -1, so move down one cell

//Diagonal movement
dx = 1, dy = 1, so move up right diagonally one cell
dx = 1, dy = -1, so move down right diagonally one cell
dx = -1, dy = -1, so move down left diagonally one cell 
dx = -1, dy = 1, so move up right left diagonally one cell

Notice that dx and dy take on one of three possible values: -1, 0, or 1

in my code I have

bool randomBool()
{
    return rand() > (RAND_MAX / 2);
}
//...
int main() 
{
    int dx = (randomBool()) ? 1 : -1;
    int dy = (randomBool()) ? 1 : -1;
    //...
}

which generates a 50/50 chance of dx or dy being -1 or 1. however, I want a 1/3 chance of dx and dy being either -1, 0, or 1. How would I accomplish this? I want to do this without using random_device or any other libraries, as I am trying to learn the basics (even though I know it's bad practice to use rand(), it is reminiscent of the Random class in Java, which I am familiar with and trying to apply previous knowledge to now)

Essentially, I want dx and dy to either be -1, 0, or 1.

I have tried accomplishing this by changing randomBool() to

bool randomBool()
{
    return rand() > (RAND_MAX / 3);
}

but now sure how to change dx and dy to account for this change.




Aucun commentaire:

Enregistrer un commentaire