以一定的比率均匀分布二维数组中的随机值



假设我有一个百分比比率列表。

Map<Integer, Integer> ratio = new HashMap<Integer, Integer>();
ratio.put(0, 10);
ratio.put(1, 50);
ratio.put(3, 40);

然后我有一个二维数组。

int[][] arr = new int[50][50];

现在我想随机但均匀地将定义的值分布在013,以及它们在该数组中各自的105040比率。

我该怎么做?

用第一个零、第二个 1 和 3 填充一维数组。

像这样:

int arr[N][M] = //;
int array[N*M] = //;
int total_array_2D_size = N * M;
int j = 0;
Set<Map.Entry<Integer, Integer>> set = ratio.entrySet();  
for (Map.Entry<Integer, Integer> entry : set)
{
    int k = entry.getKey();        // Take the number
    int ratio = entry.getValue();  // Take the ratio
    int N = (total_array_2D_size * ratio) / 100; // The number of times 'k' should
                                                 // appear on the finally 2D array
    for(int i = 0; i < N; i++,j++) array[j] = k; // Fill the 1D array
}

然后采用随机算法并掐击您的 1D 数组。最后填满您的 2D 阵列。

for(int i = 0,k = 0; i < N; i++)
  for(int j = 0; j < M; j++,k++)
     arr[i][j] = array[k];
由于您的 2D 数组有 2500 个位置 (50^2),最后您应该有 250 '0' (0.10 * 50^2)、1250 '1' (0.50 * 50^2

) 和 1000 '3' (0.4 * 50^2)。

最新更新