hx3d  1
2D/3D Simple Game Framework
random.cpp
1 /*
2  Random functions.
3  Copyright (C) 2015 Denis BOURGE
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Lesser General Public
7  License as published by the Free Software Foundation; either
8  version 2.1 of the License, or (at your option) any later version.
9 
10  This library is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public
16  License along with this library; if not, write to the Free Software
17  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
18  USA
19 */
20 
21 #include "hx3d/math/random.hpp"
22 #include "hx3d/utils/algorithm.hpp"
23 #include "hx3d/utils/log.hpp"
24 
25 #include <cstdlib>
26 
27 namespace hx3d {
28 namespace math {
29 
30 WeightedRandom::WeightedRandom() {}
31 
32 void WeightedRandom::define(int i, int weight, std::function<void()> f) {
33  if (_weights.find(i) == _weights.end()) {
34  _vec.push_back(i);
35  _weights[i] = weight;
36  _map[i] = f;
37  } else {
38  Log.Error("WeightedRandom: Already defined '%d'", i);
39  }
40 }
41 
43  int n = get_number(math::random(0, total_count() - 1));
44  _map[n]();
45 
46  return n;
47 }
48 
49 int WeightedRandom::get_number(int gen) {
50  int curr = 0;
51 
52  for (auto n: _vec) {
53  for (int i = 0; i < _weights[n]; ++i) {
54  if (gen == curr)
55  return n;
56 
57  ++curr;
58  }
59  }
60 
61  return -1;
62 }
63 
64 int WeightedRandom::total_count() {
65  return algo::reduce(_vec, 0, [this](int res, int val){ return res + _weights[val]; });
66 }
67 
69 
70 float randfloat() {
71  return (float)rand() / (RAND_MAX + 1.f);
72 }
73 
74 int random(int min, int max) {
75  return rand() % (max-min + 1) + min;
76 }
77 
78 bool flip_coin() {
79  return random(0, 1) == 0;
80 }
81 
82 } /* math */
83 } /* hx3d */
hx3d framework namespace
Definition: audio.hpp:26
float randfloat()
Generate a random float between 0.0 and 1.0.
Definition: random.cpp:70
Type reduce(Container &container, Type init)
Apply a simple reduce.
int random()
Choose a random number and execute the callback.
Definition: random.cpp:42
void Error(const std::string fmt,...)
Write an error message.
Definition: log.cpp:72
static hx3d::LogImpl Log
Current log implementation.
Definition: log.hpp:91
void define(int i, int weight, std::function< void()> f)
Define a value with a weight and a callback.
Definition: random.cpp:32
int random(int min, int max)
Generate a random integer between min and max.
Definition: random.cpp:74
bool flip_coin()
Generate a random boolean.
Definition: random.cpp:78