簡體   English   中英

二維數組中的加權隨機數-處理

[英]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.

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