Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

you can consider this method too

functiongetRandomInt(max) {
    returnMath.floor(Math.random() * max + 1);
}

const total = 100;
const max = 20;
const nbrounds = 9;
functionfillWithRandom(max, total, len) {
    let arr = newArray();
    let sum = 0;
    newmax = max;


    do {
        newtotal = total - sum;

        //max depending on lengthconsole.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 orderreturn arr.map((value) => ({value, sort: Math.random()})).sort((a, b) => a.sort - b.sort).map(({ value }) => value);
}
;



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

Post a Comment for "Split Integer Into Sum Of Random Numbers"