random.cpp

(plain text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
#include <climits>
#include <ctime>

#if !defined(__GNUC__) || __GNUC__ > 3
#  include <limits>
namespace eloi { using std::numeric_limits; }

#else
namespace eloi {
  template <typename T> struct numeric_limits { enum { is_integer = false }; };
#  define SFASOFOASDHF_20021024T1734(T) template <> struct numeric_limits<T> { enum { is_integer = true }; };
  SFASOFOASDHF_20021024T1734(char); 
  SFASOFOASDHF_20021024T1734(signed char);      SFASOFOASDHF_20021024T1734(unsigned char);
  SFASOFOASDHF_20021024T1734(signed short);     SFASOFOASDHF_20021024T1734(unsigned short);
  SFASOFOASDHF_20021024T1734(signed int);       SFASOFOASDHF_20021024T1734(unsigned int);
  SFASOFOASDHF_20021024T1734(signed long);      SFASOFOASDHF_20021024T1734(unsigned long);
#  ifdef LLONG_MAX
  SFASOFOASDHF_20021024T1734(signed long long); SFASOFOASDHF_20021024T1734(unsigned long long);
#  endif
#undef SFASOFOASDHF_20021024T1734
}
#endif

template <typename T>
T random (T low, T high, bool inclusive = false) {
  return static_cast<T>(std::rand() / (1.0L + RAND_MAX)
			* (high - low + (eloi::numeric_limits<T>::is_integer && inclusive))
			+ low);
}

int main () {
  std::srand(std::time(0));

  for (int i = 0; i < 10; ++i) {
    std::cout << random(0.3, 0.9, 1) << std::endl;
  }
}