Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# pylint:disable=unused-argument 

2 

3c"""source-before-namespace 

4#include <chrono> 

5#include <random> 

6""" 

7 

8c""" 

9static std::default_random_engine generator( 

10 std::chrono::system_clock::now().time_since_epoch().count()); 

11""" 

12 

13func random() -> f64: 

14 """Returns a pseudo random floating point number in the range [0.0, 

15 1.0] (inclusive). 

16 

17 """ 

18 

19 value: f64 = 0.0 

20 

21 c""" 

22 std::uniform_real_distribution<f64> distribution(0.0, 1.0); 

23 

24 value = distribution(generator) 

25 """ 

26 

27 return value 

28 

29func randint(minimum: i64, maximum: i64) -> i64: 

30 """Returns a pseudo random integer number in the range [minimum, 

31 maximum] (inclusive). 

32 

33 """ 

34 

35 value: i64 = 0 

36 

37 c""" 

38 std::uniform_int_distribution<i64> distribution(minimum, maximum); 

39 

40 value = distribution(generator) 

41 """ 

42 

43 return value 

44 

45func randfloat(minimum: f64, maximum: f64) -> f64: 

46 """Returns a pseudo random floating point number in the range 

47 [minimum, maximum] (inclusive). 

48 

49 """ 

50 

51 value: f64 = 0.0 

52 

53 c""" 

54 std::uniform_real_distribution<f64> distribution(minimum, maximum); 

55 

56 value = distribution(generator) 

57 """ 

58 

59 return value 

60 

61func randbytes(length: i64) -> bytes: 

62 """Returns given number of pseudo random bytes. 

63 

64 """ 

65 

66 value = b"" 

67 

68 for i in range(length): 

69 value += u8(randint(0, 255)) 

70 

71 return value 

72 

73@generic(T) 

74func shuffle(values: [T]): 

75 """Shuffle the values in place. 

76 

77 """ 

78 

79 length = values.length() 

80 

81 for current in range(length): 

82 other = randint(0, length - 1) 

83 value = values[current] 

84 values[current] = values[other] 

85 values[other] = value 

86 

87test random(): 

88 value = random() 

89 assert value >= 0.0 

90 assert value <= 1.0 

91 

92test randint(): 

93 value = randint(-1, 2) 

94 assert value >= -1 

95 assert value <= 2 

96 values: [i64] = [-1, 0, 1, 2] 

97 assert value in values 

98 

99test randfloat(): 

100 value = randfloat(-2.5, 2.0) 

101 assert value >= -2.51 

102 assert value <= 2.01 

103 

104test randbytes(): 

105 assert randbytes(0).length() == 0 

106 assert randbytes(5).length() == 5 

107 

108test shuffle(): 

109 values = [1, 2, 3] 

110 

111 while True: 

112 shuffle[i64](values) 

113 

114 if values != [1, 2, 3]: 

115 break