admin管理员组

文章数量:1418306

Assume we have an integer 16.

Is there a function, that returns random array of numbers, which pose 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.

Assume we have an integer 16.

Is there a function, that returns random array of numbers, which pose 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.

Share Improve this question asked Aug 14, 2014 at 10:35 nasytnyknasytnyk 1,2021 gold badge9 silver badges21 bronze badges 3
  • 1 I doubt there's a library function for this. Have you tried anything yet? – doctorlove Commented Aug 14, 2014 at 10:37
  • How random do you need? The most simple solution would be simply repeatedly getting a number from the range [1..n] where n is the number that would "plete" the sum, but that would result in an uneven distribution of numbers. – kviiri Commented Aug 14, 2014 at 10:38
  • stackoverflow./questions/7788135/…, stackoverflow./questions/13720356/… – ngrashia Commented Aug 14, 2014 at 10:39
Add a ment  | 

2 Answers 2

Reset to default 5

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.

you can consider this method too

function getRandomInt(max) {
    return Math.floor(Math.random() * max + 1);
}

const total = 100;
const max = 20;
const nbrounds = 9;
function fillWithRandom(max, total, len) {
    let arr = new Array();
    let sum = 0;
    newmax = max;


    do {
        newtotal = total - sum;

        //max depending on length
        console.log(arr.length,len);
        if (arr.length+1 == len) {
            arr.push(newtotal);
        } else {
            maxbylen = parseInt(newtotal / (len - arr.length));
          //  console.log('maxbylen', maxbylen, arr.length);
            if (max > maxbylen) {
                rndmax = max;
            } else {
                rndmax = maxbylen;
            }


            if (newtotal > max) {
                rnd = getRandomInt(rndmax);
            } else {
                rnd = getRandomInt(newtotal);
            }
            arr.push(rnd);
        }

        sum = arr.reduce((acc, val) => acc + val, 0);
      //  console.log('sum', sum, 'newtotal', newtotal, 'rnd', rnd, arr);


    } while (sum < total);
//   console.log(arr);
    //random order
    return arr.map((value) => ({value, sort: Math.random()})).sort((a, b) => a.sort - b.sort).map(({ value }) => value);
}
;



console.log(fillWithRandom(max, total, nbrounds));

本文标签: javascriptSplit integer into sum of random numbersStack Overflow