freeCodeCamp/curriculum/challenges/english/02-javascript-algorithms-an.../basic-javascript/generate-random-whole-numbe...

103 lines
2.3 KiB
Markdown

---
id: cf1111c1c12feddfaeb2bdef
title: Generate Random Whole Numbers within a Range
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm83yu6'
forumTopicId: 18187
dashedName: generate-random-whole-numbers-within-a-range
---
# --description--
Instead of generating a random whole number between zero and a given number like we did before, we can generate a random whole number that falls within a range of two specific numbers.
To do this, we'll define a minimum number `min` and a maximum number `max`.
Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:
```js
Math.floor(Math.random() * (max - min + 1)) + min
```
# --instructions--
Create a function called `randomRange` that takes a range `myMin` and `myMax` and returns a random whole number that's greater than or equal to `myMin`, and is less than or equal to `myMax`, inclusive.
# --hints--
The lowest random number that can be generated by `randomRange` should be equal to your minimum number, `myMin`.
```js
assert(calcMin === 5);
```
The highest random number that can be generated by `randomRange` should be equal to your maximum number, `myMax`.
```js
assert(calcMax === 15);
```
The random number generated by `randomRange` should be an integer, not a decimal.
```js
assert(randomRange(0, 1) % 1 === 0);
```
`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.
```js
assert(
(function () {
if (
code.match(/myMax/g).length > 1 &&
code.match(/myMin/g).length > 2 &&
code.match(/Math.floor/g) &&
code.match(/Math.random/g)
) {
return true;
} else {
return false;
}
})()
);
```
# --seed--
## --after-user-code--
```js
var calcMin = 100;
var calcMax = -100;
for(var i = 0; i < 100; i++) {
var result = randomRange(5,15);
calcMin = Math.min(calcMin, result);
calcMax = Math.max(calcMax, result);
}
(function(){
if(typeof myRandom === 'number') {
return "myRandom = " + myRandom;
} else {
return "myRandom undefined";
}
})()
```
## --seed-contents--
```js
function randomRange(myMin, myMax) {
// Only change code below this line
return 0;
// Only change code above this line
}
```
# --solutions--
```js
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}
```