- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split number into 4 random numbers in JavaScript
We are required to write a JavaScript function that takes in a number as the first input and a maximum number as the second input.
The function should generate four random numbers, which when summed should equal the number provided to function as the first input and neither of those four numbers should exceed the number given as the second input.
For example − If the arguments to the function are −
const n = 10; const max = 4;
Then,
const output = [3, 2, 3, 2];
is a valid combination.
Note that repetition of numbers is allowed.
Example
The code for this will be −
const total = 10; const max = 4; const fillWithRandom = (max, total, len = 4) => { let arr = new Array(len); let sum = 0; do { for (let i = 0; i < len; i++) { arr[i] = Math.random(); } sum = arr.reduce((acc, val) => acc + val, 0); const scale = (total − len) / sum; arr = arr.map(val => Math.min(max, Math.round(val * scale) + 1)); sum = arr.reduce((acc, val) => acc + val, 0); } while (sum − total); return arr; }; console.log(fillWithRandom(max, total));
Output
And the output in the console will be −
[ 3, 3, 2, 2 ]
The output is expected to differ in each run.
- Related Articles
- Number Split into individual digits in JavaScript
- Split number into n length array - JavaScript
- How to split JavaScript Number into individual digits?
- Split string into groups - JavaScript
- Split string into equal parts JavaScript
- Inserting random numbers into a table in MySQL?
- Return 5 random numbers in range, first number cannot be zero - JavaScript
- Can split array into consecutive subsequences in JavaScript
- How to split a number into digits in R?
- Generate random characters and numbers in JavaScript?
- Split Array of items into N Arrays in JavaScript
- How to generate random numbers between two numbers in JavaScript?
- Generating Random Prime Number in JavaScript
- Split keys and values into separate objects - JavaScript
- Insert a number into a sorted array of numbers JavaScript

Advertisements