vrecko
virtual reality framework
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
randomindex.h
Go to the documentation of this file.
1 #ifndef RANDOMINDEX_H_
2 #define RANDOMINDEX_H_
3 
4 #include <vector>
5 #include <cstdlib>
6 #include <ctime>
7 #include "configuration.h"
8 
9 using namespace boost::program_options;
10 
11 namespace AP_LSystem {
16 {
17 private:
18  std::vector<double> probabilities;
19  double sum;
20 public:
24  static void init()
25  {
26  const variable_value * seed = Configuration::get()->getProperty( "RandomSeed" );
27  if( seed )
28  {
29  srand( seed->as<unsigned int>() );
30  }
31  else
32  {
33  srand( time( NULL ) );
34  }
35  }
36 
41  {
42  sum = 0;
43  }
44 
49  void addProbability( double p )
50  {
51  probabilities.push_back( sum + p );
52  sum += p;
53  }
54 
59  unsigned int getRandomIndex()
60  {
61  double r = (static_cast<double>(rand() % 100)) * sum / 100.0f;
62 
63  for(std::vector<double>::iterator it = probabilities.begin(); it != probabilities.end()-1; it++)
64  {
65  if( *it >= r )
66  {
67  return it - probabilities.begin();
68  }
69  }
70 
71  return probabilities.size( ) - 1;
72  }
73 };
74 }
75 #endif // RANDOMINDEX_H