-2
int random(){
    double x = ((double) rand() / (RAND_MAX)); // this i tried but only 0
    return x;
} 

how I generate either 0 or 1 randomly for a tic tac toe player to play

rajdeep04
  • 17
  • 5

1 Answers1

0

If you have C++11 you can use the new standard <random> library. In particular the std::bernoulli_distribution distribution gives true or false results (default convertible to 1 and 0 respectively).

// returns true or false
bool randomly_true(double p = 0.5)
{
    thread_local static std::mt19937 mt{std::random_device{}()};
    thread_local static std::bernoulli_distribution d;
    return d(mt, std::bernoulli_distribution::param_type{p});
}

int main()
{
    for(int i = 0; i < 30; ++i)
        std::cout << randomly_true() << '\n';
}

Output: (sample)

0
0
0
1
0
1
1
1
0
1

If you always want 1 or 0 integer values rather than true or false bool values you can force the conversion by returning int from the function:

// returns 1 or 0
int randomly_true(double p = 0.5)
{
    thread_local static std::mt19937 mt{std::random_device{}()};
    thread_local static std::bernoulli_distribution d;
    return d(mt, std::bernoulli_distribution::param_type{p});
}

Note: You should use this library in preference to rand() as there is no guarantee of quality with rand() and may be very poorly implemented.

Galik
  • 47,303
  • 4
  • 80
  • 117
  • And generally you should use this library rather than C--style rand(), which is notorious for low quality implementations. – Malcolm McLean Sep 17 '17 at 13:40
  • It's worth noting that using the Mersenne Twister and its 2.5 KiB of state plus a Bernoulli distribution with its floating point calculations (when you could just take any bit of the MT output) to decide whether it's tic or tac it's ridicolous. Keeping a bit of the humblest of the LCGs (or, even better, of any member of the XorShift family) would be plenty good. No wonder that they say software keeps expanding to do the same things wasting the ever increasing hardware resources. – Matteo Italia Sep 17 '17 at 13:58
  • @MatteoItalia In a real application you would re-use the same random number generator for all your random needs and the distributions should only extract as many bits as they require for each call (they are stateful). Also the standard library also provides LCGs if that's all you require. – Galik Sep 17 '17 at 14:21
  • If you are picking a single bit from the RNG output, then avoid the least significant bit. Some RNGs have very non-random LSBs: 010101010101... Pick a bit somewhere in the middle of the return. – rossum Sep 17 '17 at 20:02