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.

Updated on: 24-Nov-2020

658 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements