Deriving Random10() function from Random7() in JavaScript


Problem

const random7 = () => Math.ceil(Math.random() * 7);

Suppose we have the above fat arrow function. This function yields a random number between 0 (exclusive) and 7 (inclusive) everytime we make a call to it.

We are required to write a similar random10() JavaScript function that takes no argument and makes no use of the JavaScript library or any third party library. And only making use of this random7() function, our function should return random number between 0 (exclusive) and 10(inclusive).

Example

The code for this will be −

 Live Demo

const random7 = () => Math.ceil(Math.random() * 7);
const random10 = () => {
   let sum;
   for(let i = 0; i < 50; i++){
      sum += random7();
   }
   return (sum % 10) + 1;
};
console.log(random10());

Code Explanation

Here, we just generated a random sum as uniform as possible, adding a few numbers (50 in our case, however the number can be different) with the rand7() function and used the sum to generate a number in Base 10.

Output

And the output in the console will be −

NaN

Updated on: 04-Mar-2021

148 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements