
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Derive 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 −
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
Advertisements