transform-entropy-results.mdx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. ---
  2. title: Transform Entropy Results
  3. description: Best practices for transforming entropy results in your applications
  4. icon: Book
  5. ---
  6. ## Generating random values within a specific range
  7. 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).
  8. Here is a simple example of how to map a random number provided by Entropy into a range between `minRange` and `maxRange` (inclusive).
  9. ```solidity copy
  10. // Maps a random number into a range between minRange and maxRange (inclusive)
  11. function mapRandomNumber(
  12. bytes32 randomNumber,
  13. int256 minRange,
  14. int256 maxRange
  15. ) internal pure returns (int256) {
  16. require(minRange <= maxRange, "Invalid range");
  17. uint256 range = uint256(maxRange - minRange + 1);
  18. uint256 randomUint = uint256(randomNumber);
  19. return minRange + int256(randomUint % range);
  20. }
  21. ```
  22. Notice that using the modulo operator can distort the distribution of random numbers if it's not a power of 2. This is
  23. negligible for small and medium ranges, but it can be noticeable for large ranges.
  24. For example, if you want to generate a random number between 1 and 52, the probability of having value 5 is approximately
  25. `10^-77` higher than the probability of having value 50 which is infinitesimal.
  26. ## Generating multiple random values in a single transaction
  27. If you need to generate multiple random values in a single transaction, you can hash the random input provided by Entropy with a unique identifier for each random number.
  28. In the following example, `mapRandomNumber` is used to generate 6 random attributes for a character.
  29. ```solidity copy
  30. function generateAttributes(bytes32 randomNumber) internal {
  31. int256 strength = mapRandomNumber(
  32. keccak256(abi.encodePacked(randomNumber, "strength")),
  33. 15,
  34. 20
  35. );
  36. int256 stamina = mapRandomNumber(
  37. keccak256(abi.encodePacked(randomNumber, "stamina")),
  38. 10,
  39. 15
  40. );
  41. int256 agility = mapRandomNumber(
  42. keccak256(abi.encodePacked(randomNumber, "agility")),
  43. 5,
  44. 15
  45. );
  46. int256 stealth = mapRandomNumber(
  47. keccak256(abi.encodePacked(randomNumber, "stealth")),
  48. 0,
  49. 5
  50. );
  51. int256 positionX = mapRandomNumber(
  52. keccak256(abi.encodePacked(randomNumber, "positionX")),
  53. -100,
  54. 100
  55. );
  56. int256 positionY = mapRandomNumber(
  57. keccak256(abi.encodePacked(randomNumber, "positionY")),
  58. -100,
  59. 100
  60. );
  61. }
  62. ```