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]
wheren
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
2 Answers
Reset to default 5No 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
版权声明:本文标题:javascript - Split integer into sum of random numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745283328a2651554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论