[英]Weighted random numbers in 2D Array - Processing
我想用值1,2,3填充3x3 2D数组。
我需要每个数字都显示给定的时间。
例如:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
我需要的是将这些数字存储在随机位置的数组中。
例如:
1,2,2
3,2,2
1,3,3
我已经使用一个计数器控制的两个不同数字以一种简单的方式完成了此操作。 因此,我遍历2D数组并应用数字1和2的随机值。我正在检查该值是否为1,并将其添加到计数器中,并与数字2相同。如果计数器之一超过了我拥有的数字设置为最大出现时间,然后继续并应用其他值。
有没有更好的方法来将3个数字填充到随机数组位置?
参见下面的代码:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
根据讨论,我终于做到了:
如何生成一定范围内的随机数,但排除一些随机数? ,使用一维数组进行测试,但它并不总是有效。 请参阅附件代码:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
我想用5,6或7的值填充1D数组。每个值都有一个特定的数字。 5号可以加14次。 数字6可加4次。 7号可以加10次。
上面的代码在大多数情况下都有效,但是某些方面却无效。 有什么想法请告诉我
这是您的问题的Octave / Matlab代码。
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
请注意,当仅使用一个索引寻址2D数组时,Matlab / Octave将使用Column-major order 。
有很多方法可以做到这一点。 由于您使用的是处理 ,一种方法是从要添加到数组中的所有数字创建一个IntList
,将其洗牌,然后将它们添加到数组中。 像这样:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
您还可以采用另一种方法:在数组中创建位置的ArrayList,将它们随机排列,然后将int添加到这些位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.