将整数分割为随机数字的总和

3

假设我们有一个整数16

是否有一个函数,可以返回随机数组的数字,组成其总和

例如7 1 2 4 1 1或1 5 2 3 6

我想知道在JavaScript中是否存在某种优雅的方法来实现这一点。


1
我怀疑这个功能没有库函数。你尝试过什么了吗? - doctorlove
你需要多随机呢?最简单的解决方案就是不断从范围 [1..n] 中获取一个数字,其中 n 是能够“完成”总和的数字,但这会导致数字分布不均匀。 - kviiri
https://dev59.com/CGsz5IYBdhLWcg3wmpBa将数字拆分成和的组件http://stackoverflow.com/questions/13720356/random-splitting-up-of-integer-value-in-javaJava中整数值的随机分割 - ngrashia
2个回答

5
没有现成的函数,但是可以使用以下方法:

没有现成的函数,但是可以使用以下方法:

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

a 包含数组。


谢谢。小错误 - sum 数组中有零。为了避免它们,我使用了 Math.round(Math.random() * (number - 1)) + 1; - Ilya Tereschuk

0

你也可以考虑这种方法

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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接