java - 二维数组中的加权随机数 - 处理

标签 java multidimensional-array processing random

我想用值 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

我已经通过简单的方式做到了这一点,仅使用由计数器控制的 2 个不同的数字。因此,我循环遍历 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;
        }
      }
    }
<小时/>

我最终根据这个讨论做到了这一点:

How can I generate a random number within a range but exclude some? ,用一维数组进行测试,但并不总是有效。 请参阅附件代码:

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 的值填充一维数组。每个值都是一个特定的数字。数字 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 .

关于java - 二维数组中的加权随机数 - 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403017/

相关文章:

java - mt4j 和处理库 : clean image resources

java - android应用程序中的堆空间

R:随机排列选定维度的数组元素

javascript - 处理图像时的 Web 导出?

c++ - 可以采用不同维度数组的函数

c++ - 用指针初始化 C++ 数组,大小为 8

java - 如何确保加工过程中圆心保持静止?

java - 查看 System.out.println 的内部代码想了解它是如何工作的?

java - 如何动态添加 JLabels 到 JPanel?

数组列表的java数组列表