SimpleAI
 All Classes Namespaces Files Functions Variables Typedefs Macros Groups Pages
Random.h
Go to the documentation of this file.
1 
4 #pragma once
5 
15 #include <chrono>
16 #include <random>
17 #include <algorithm>
18 #include <iterator>
19 #include <stdlib.h>
20 #include "common/Thread.h"
21 
22 namespace ai {
23 
24 inline std::default_random_engine& randomEngine() {
25  AI_THREAD_LOCAL std::default_random_engine engine;
26  return engine;
27 }
28 
29 inline void randomSeed (unsigned int seed) {
30  randomEngine().seed(seed);
31 }
32 
33 inline float randomf (float max = 1.0f) {
34  std::uniform_real_distribution<float> distribution(0.0, max);
35  return distribution(randomEngine());
36 }
37 
38 inline int random (int min, int max) {
39  std::uniform_int_distribution<int> distribution(min, max);
40  return distribution(randomEngine());
41 }
42 
43 inline float randomBinomial (float max = 1.0f) {
44  return randomf(max) - randomf(max);
45 }
46 
47 template<typename I>
48 inline I randomElement(I begin, I end) {
49  const int n = static_cast<int>(std::distance(begin, end));
50  std::uniform_int_distribution<> dis(0, n - 1);
51  std::advance(begin, dis(randomEngine()));
52  return begin;
53 }
54 
58 template<typename T>
59 inline void randomElements(std::vector<T>& vec, int n) {
60  if (n >= (int)vec.size()) {
61  return;
62  }
63  std::shuffle(vec.begin(), vec.end(), randomEngine());
64  vec.resize(n);
65 }
66 
67 template<typename I>
68 inline void shuffle(I begin, I end) {
69  std::shuffle(begin, end, randomEngine());
70 }
71 
72 }
73