2.9 KiB
2.9 KiB
id, title, challengeType
id | title | challengeType |
---|---|---|
cf1111c1c12feddfaeb1bdef | Generate Random Whole Numbers with JavaScript | 1 |
Description
- Use
Math.random()
to generate a random decimal. - Multiply that random decimal by
20
. - Use another function,
Math.floor()
to round the number down to its nearest whole number.
Math.random()
can never quite return a 1
and, because we're rounding down, it's impossible to actually get 20
. This technique will give us a whole number between 0
and 19
.
Putting everything together, this is what our code looks like:
Math.floor(Math.random() * 20);
We are calling Math.random()
, multiplying the result by 20, then passing the value to Math.floor()
function to round the value down to the nearest whole number.
Instructions
0
and 9
.
Tests
- text: The result of <code>randomWholeNum</code> should be a whole number.
testString: 'assert(typeof randomWholeNum() === "number" && (function(){var r = randomWholeNum();return Math.floor(r) === r;})(), ''The result of <code>randomWholeNum</code> should be a whole number.'');'
- text: You should be using <code>Math.random</code> to generate a random number.
testString: 'assert(code.match(/Math.random/g).length > 1, ''You should be using <code>Math.random</code> to generate a random number.'');'
- text: You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.
testString: 'assert(code.match(/\s*?Math.random\s*?\(\s*?\)\s*?\*\s*?10[\D]\s*?/g) || code.match(/\s*?10\s*?\*\s*?Math.random\s*?\(\s*?\)\s*?/g), ''You should have multiplied the result of <code>Math.random</code> by 10 to make it a number that is between zero and nine.'');'
- text: You should use <code>Math.floor</code> to remove the decimal part of the number.
testString: 'assert(code.match(/Math.floor/g).length > 1, ''You should use <code>Math.floor</code> to remove the decimal part of the number.'');'
Challenge Seed
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
// Only change code below this line.
return Math.random();
}
After Test
console.info('after the test');
Solution
var randomNumberBetween0and19 = Math.floor(Math.random() * 20);
function randomWholeNum() {
return Math.floor(Math.random() * 10);
}