将 x 分成 y 部分的随机数,最大值为 n
Split x into y parts of random numbers with a max value of n
谁能提供一种方法,将一个数字分成 x 个具有最大值的随机部分?
即
要拆分的总数 = 50
要拆分的部分数 = 10
每个部分的最大 val = 10
will return something like
3,7,4,6,9,1,2,8,5,5
每个部分在一定程度上是随机的。没有制服只需要 y 个随机数,它们加起来等于 x,每个部分都有最大 val。
我已经找到了
var n = 16;
var a = [];
while (n > 0) {
var s = Math.round(Math.random() * (n- 1)) + 1;
a.push(s);
n -= s;
}
console.log(a);
但这不会给出 x 个零件。这是一个随机数量的部分...
这是一种方法。首先创建一个均匀分配的数组以获得 "parts, and then loop trough it and for each " 部分的正确数量”,您向其中添加一个随机数,同时从另一个随机索引中删除相同的数字。
var n = 160;
var a = [];
var x = 10;
var b = n/x;
for(var i=0; i<x; i++){
a.push(b);//create an array of 10 parts with the same value
}
for(var i=0; i<x; i++){
var s = Math.round((Math.random()*b)) ;
var index = Math.round((Math.random()*x))-1 ;
a[i] += s;
a[index] -=s;
}
console.log(a);
var n = 16;
var a = [];
var parts = 10;
var maxValuePerPart = 10;
for(let i = 0; i < parts; i++){
let max = (maxValuePerPart < n) ? maxValuePerPart : n;
let min = 1;
var s = Math.floor(Math.random() * (max - min)) + min;
a[i] = s;
n -= s;
}
console.log(a);
如果这不是您要找的,请告诉我
谁能提供一种方法,将一个数字分成 x 个具有最大值的随机部分?
即 要拆分的总数 = 50 要拆分的部分数 = 10 每个部分的最大 val = 10
will return something like
3,7,4,6,9,1,2,8,5,5
每个部分在一定程度上是随机的。没有制服只需要 y 个随机数,它们加起来等于 x,每个部分都有最大 val。
我已经找到了
var n = 16;
var a = [];
while (n > 0) {
var s = Math.round(Math.random() * (n- 1)) + 1;
a.push(s);
n -= s;
}
console.log(a);
但这不会给出 x 个零件。这是一个随机数量的部分...
这是一种方法。首先创建一个均匀分配的数组以获得 "parts, and then loop trough it and for each " 部分的正确数量”,您向其中添加一个随机数,同时从另一个随机索引中删除相同的数字。
var n = 160;
var a = [];
var x = 10;
var b = n/x;
for(var i=0; i<x; i++){
a.push(b);//create an array of 10 parts with the same value
}
for(var i=0; i<x; i++){
var s = Math.round((Math.random()*b)) ;
var index = Math.round((Math.random()*x))-1 ;
a[i] += s;
a[index] -=s;
}
console.log(a);
var n = 16;
var a = [];
var parts = 10;
var maxValuePerPart = 10;
for(let i = 0; i < parts; i++){
let max = (maxValuePerPart < n) ? maxValuePerPart : n;
let min = 1;
var s = Math.floor(Math.random() * (max - min)) + min;
a[i] = s;
n -= s;
}
console.log(a);
如果这不是您要找的,请告诉我