Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split integer into sum of random numbers

Assume we have an integer 16.

Is there a function, that returns random array of numbers, which compose its sum?

For example 7 1 2 4 1 1 or 1 5 2 3 6

I wonder if some elegant method of doing this in JavaScript exists.

like image 876
Ilya Tereschuk Avatar asked Mar 11 '26 09:03

Ilya Tereschuk


1 Answers

No there's not existing function, but e.g.:

var n = 16;
var a = [];
while (n > 0) {
  var s = Math.round(Math.random()*n);
  a.push(s);
  n -= s;
}

a contains the array.

like image 177
Samuli Hakoniemi Avatar answered Mar 12 '26 22:03

Samuli Hakoniemi