Wednesday, May 5, 2021

Javascript Practice 36: JS Hero - Random numbers

 
Question: 

Write a function dice that returns like a dice a random number between 1 and 6.




Answer: 

function dice () {

return (Math.floor(Math.random() * 6)) + 1;

}; 

> function dice has to return a random number between 1 and 6 
> random numbers can be generated using the Math.random method
> Math.random returns a floating-point, pseudo-random number
> random number is usually between 0 (inclusive) and 1 (exclusive)
> let me repeat - random number generated will be between 0 & 1
> 0 will be inclusive & 1 will be exclusive
> 0 will be included and 1 will not be included 
> we shall be generating numbers with decimal points (real numbers) and not a whole number
> for eg 0.75 or 0.89 or 0.9998898988898552 etc
> but we need to get a random whole number between two values i.e. 1 and 6 
> so first we need to use Math.random() to generate a number between 0 & 1
> we then multiply that with 6 like this: (Math.random() * 6)
> (Math.random() * 6) will generate random real numbers (not whole numbers) btw 0 & 6
> 0 will be included and 6 will not be included
> for eg 0.256, 1.536, 3.589 or 5.99958565
> then we wrap the result of (Math.random()*6) inside the Math.floor function to round it 
> like this: Math.floor(Math.random() * 6)
> Math.floor will round the number down to the closest whole number 
> this will generate whole numbers from 0 to 5 
> in order to ensure that our random numbers fall between 1 and 6 we simply add 1 
> like this: (Math.floor(Math.random()*6)) + 1; 
> the resulting numbers will always be between 1 and 6 

No comments:

Post a Comment