1

I am trying to choose one of two numbers randomly: 2 or -2. Is there a way to do it? I am trying to implement an algorithm to create a maze.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • This might help: https://stackoverflow.com/questions/33060893/whats-a-simple-way-to-generate-a-random-bool-in-c – Mickael B. Feb 01 '20 at 15:20

3 Answers3

2

You have rand() from the C standard library, which returns a pseudo-random integer in the range [0, RAND_MAX]. You can use this function and choose one of the two numbers checking if the value returned is above or below RAND_MAX/2.

First, use srand() to initialize the pseudo-random number generator with some seed. It's common to use time() to do this as it returns a different value each time.

srand(time(NULL));

int rnd = rand();
int result = (rnd > RAND_MAX/2) ? 2 : -2;

Alternatively you could use the least significant bit of the value returned by rand(), as suggested in this other answer, since half the values returned are odd and half are even:

int result = (rnd & 1) ? 2 : -2;
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
1

There are many ways to do this, my favorite is:

a + rand() % 2 * (b - a);

but it isn't clear what does it do and it doesn't contribute on efficiency either (well if you would make it into a macro/inline function and never used with variables, modern compilers should evaluate the numbers at the compile-time), so the most elegant way to do this would be to use some kind of condition, here's an example with ternary operator:

(rand() % 2)? a: b;

BTW: There are many ways to chose between 0/1, I used rand()%2 because it's most the used technique, but if you happened to be doing this for 6502 architecture where there's no modulo/division you can do it with bitwise-and operator like this rand() & ANY_POWER_OF_TWO or like this rand() > HALF_MAX_RAND

WENDYN
  • 650
  • 7
  • 15
0

You can use this. It uses bitwise operations to generate either 2 or -2 without branching:

-((rand() & 1) << 2) + 2

I note that you should use srand() to seed the random number generator before using it; I commonly use srand(time(NULL)).

Step-by-step:

  • (rand() & 1) generates a random number: either 0 or 1.

  • << 2 multiplies the previous result by 4, and the - in front of -((rand() & 1) << 2) negates that, so the result is either 0 or -4.

  • + 2 adds 2, so the result is either 2 or -2.

If you'd like to see a more arithmetic-like approach that may be easier to follow, here it is:

rand % 2 * -4 + 2
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76