Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate true or false values using normal distribution in c++

I want to do that without using boost and "strange" things, I want to fill a board randomly for the game of life.

like image 544
freinn Avatar asked Feb 25 '12 19:02

freinn


2 Answers

C++11 and do it with the following

#include <random>
#include <vector>

int main()
{
    std::mt19937 gen;
    std::bernoulli_distribution     dist;

    std::vector<bool> bv;
    bv.reserve(100);

    for(unsigned i=0; i!=100; ++i)
            bv.push_back( dist(gen));

    return 0;
}

Also I don't really see what the difference between uniform and normal distribution would be for a bool.

see here for C++ random numbers. http://en.cppreference.com/w/cpp/numeric/random

like image 128
111111 Avatar answered Sep 28 '22 02:09

111111


Just use stlib's rand():

#include <stdlib.h>
#include <time.h>

bool randomBool() {
  return rand() % 2 == 1;
}

int main ()
{
 /* initialize random seed: */
  srand ( time(NULL) );

/* fill up your game board here */

}

Just be aware that it will not yield perfectly uniform results. In order to achieve that, you'll probably have to implement something yourself. For non-cryptographic purposes, you're probably ok anyway.

like image 23
jupp0r Avatar answered Sep 28 '22 02:09

jupp0r