[Solved] How to split int in a 5 random numbers? [closed]


I hope you will still edit your question with some more criteria and what you have tried so far, however, following implementation follows:

  • No 0 numbers ;
  • The resulting array should be exactly the requested numbers long ;

It doesn’t check if the division is possible, theoretically, the targetNumber - totalSumNumbers >= 0 has to apply, if it doesn’t, you will get incorrect results, it should rather throw an error.

/**
 * @method createRandomSumNumbers
 * @param {int} the number that should be able to be summed
 * @param {int} the size of the array that should be left at the end
 * @returns {[int,...,totalSumNumbers]} an array containing up totalSumNumbers of integers
 */
function createRandomSumNumbers( targetNumber, totalSumNumbers ) {
  if (targetNumber - totalSumNumbers < 0) {
    throw "Cannot create the desired output if the targetNumber is smaller than the totalSumNumbers";
  }
  if (targetNumber <= 0 || totalSumNumbers <= 0) {
    throw "Inputted numbers should be greater than 0";
  }
  let result = [], rest = targetNumber;
  for (let i = 1; i < totalSumNumbers; i++) {
    // to make sure no 0s sneak in, the random pattern should be
    // the rest value minus the number of numbers that should be created + the current I step
    // and the +1 to exclude 0s
    let value = parseInt(Math.random() * ( rest - totalSumNumbers + i) ) + 1;
    result.push( value );
    rest -= value;
  }
  result.push( rest );
  return result;
}

console.log( createRandomSumNumbers( 10, 5 ) );

// this should always return [1,1,1,1,1]
console.log( createRandomSumNumbers( 5, 5 ) );

// throws an error
console.log( createRandomSumNumbers( 4, 5 ) );   

3

solved How to split int in a 5 random numbers? [closed]