|
| 1 | +# Introduction |
| 2 | + |
| 3 | +Many programs need (apparently) random values to simulate real-world events. |
| 4 | + |
| 5 | +Common, familiar examples include: |
| 6 | + |
| 7 | + - A coin toss: a random value from ('H', 'T'). |
| 8 | + - The roll of a die: a random integer from 1 to 6. |
| 9 | + - Shuffling a deck of cards: a random ordering of a card list. |
| 10 | + - The creation of trees and bushes in a 3-D graphics simulation. |
| 11 | + |
| 12 | +Generating truly random values with a computer is a [surprisingly difficult technical challenge][why-randomness-is-hard], so you may see these results referred to as "pseudorandom". |
| 13 | +## Generating random numbers |
| 14 | +In Javascript, you can generate psuedorandom numbers using the [`Math.random()`][Math.random] function. |
| 15 | +It will return a psuedorandom floating-point number between 0 (inclusive), and 1 (exclusive). |
| 16 | + |
| 17 | +To get a random number between _min_ (inclusive) and _max_ (exclusive) you can use a function something like this: |
| 18 | +```javascript |
| 19 | +function getRandomInRange(min, max) { |
| 20 | + return min + Math.random() * (max - min) ; |
| 21 | +} |
| 22 | +getRandomInRange(4, 10) |
| 23 | +// => 5.72 |
| 24 | +``` |
| 25 | +## Generating random integers |
| 26 | +To generate a random integer, you can use `Math.floor()` or `Math.ceil()` to turn a randomly generated number into an integer. |
| 27 | +~~~~exercism/caution |
| 28 | +
|
| 29 | +The `Math.random()` function should NOT be used for security and cryptographic applications!! |
| 30 | +
|
| 31 | +Instead, you can use the Web Crypto API, which provides various cryptographic functions. |
| 32 | +~~~~ |
| 33 | + |
| 34 | +[why-randomness-is-hard]: https://www.malwarebytes.com/blog/news/2013/09/in-computers-are-random-numbers-really-random |
| 35 | +[Math.random]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random |
0 commit comments