簡體   English   中英

將整數拆分為隨機數的總和

[英]Split integer into sum of random numbers

假設我們有一個整數16

有沒有一個函數,它返回組成它的和的隨機數字數組?

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

我想知道是否存在一些在 JavaScript 中執行此操作的優雅方法。

不,沒有現有功能,但例如:

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

a包含數組。

你也可以考慮這個方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM