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 <random> 

5""" 

6 

7c""" 

8static std::random_device device; 

9""" 

10 

11func random() -> f64: 

12 """Returns a cryptographically safe random floating point number in 

13 the range [0.0, 1.0] (inclusive). 

14 

15 """ 

16 

17 value: f64 = 0.0 

18 

19 c""" 

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

21 

22 value = distribution(device) 

23 """ 

24 

25 return value 

26 

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

28 """Returns a cryptographically safe random integer number in the range 

29 [minimum, maximum] (inclusive). 

30 

31 """ 

32 

33 value: i64 = 0 

34 

35 c""" 

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

37 

38 value = distribution(device) 

39 """ 

40 

41 return value 

42 

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

44 """Returns a cryptographically safe random floating point number in 

45 the range [minimum, maximum] (inclusive). 

46 

47 """ 

48 

49 value: f64 = 0.0 

50 

51 c""" 

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

53 

54 value = distribution(device) 

55 """ 

56 

57 return value 

58 

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

60 """Returns given number of cryptographically safe random bytes. 

61 

62 """ 

63 

64 value = b"" 

65 

66 for i in range(length): 

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

68 

69 return value 

70 

71@generic(T) 

72func shuffle(values: [T]): 

73 """Shuffle the values in place. 

74 

75 """ 

76 

77 length = values.length() 

78 

79 for current in range(length): 

80 other = randint(0, length - 1) 

81 value = values[current] 

82 values[current] = values[other] 

83 values[other] = value 

84 

85test random(): 

86 value = random() 

87 assert value >= 0.0 

88 assert value <= 1.0 

89 

90test randint(): 

91 value = randint(-1, 2) 

92 assert value >= -1 

93 assert value <= 2 

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

95 assert value in values 

96 

97test randfloat(): 

98 value = randfloat(-2.5, 2.0) 

99 assert value >= -2.51 

100 assert value <= 2.01 

101 

102test randbytes(): 

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

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

105 

106test shuffle(): 

107 values = [1, 2, 3] 

108 

109 while True: 

110 shuffle[i64](values) 

111 

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

113 break