You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
## Generating random values within a specific range
7
9
8
10
You can map the random number provided by Entropy into a smaller range using the solidity [modulo operator](https://docs.soliditylang.org/en/latest/types.html#modulo).
9
11
Here is a simple example of how to map a random number provided by Entropy into a range between `minRange` and `maxRange` (inclusive).
10
12
11
-
```solidity
13
+
<DynamicCodeBlocklang="solidity"code={`\
12
14
// Maps a random number into a range between minRange and maxRange (inclusive)
13
15
function mapRandomNumber(
14
16
bytes32 randomNumber,
@@ -21,8 +23,9 @@ function mapRandomNumber(
21
23
uint256 randomUint = uint256(randomNumber);
22
24
23
25
return minRange + int256(randomUint % range);
26
+
24
27
}
25
-
```
28
+
`} />
26
29
27
30
Notice that using the modulo operator can distort the distribution of random numbers if it's not a power of 2. This is
28
31
negligible for small and medium ranges, but it can be noticeable for large ranges.
@@ -35,7 +38,9 @@ If you need to generate multiple random values in a single transaction, you can
35
38
36
39
In the following example, `mapRandomNumber` is used to generate 6 random attributes for a character.
37
40
38
-
```solidity
41
+
<DynamicCodeBlock
42
+
lang="solidity"
43
+
code={`\
39
44
function generateAttributes(bytes32 randomNumber) internal {
0 commit comments