Let's say I have a list of ratios in percents.
Map<Integer, Integer> ratio = new HashMap<Integer, Integer>();
ratio.put(0, 10);
ratio.put(1, 50);
ratio.put(3, 40);
Then I have a two dimensional array.
int[][] arr = new int[50][50];
Now I want to randomly, but evenly, distribute the defined values 0, 1 and 3 with their respective ratio of 10, 50 and 40 in that array.
How do I do that?
Fill an 1D array with first zeros, second 1 and then 3.
Something like:
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
}
Than take a Shuffle algorithm and suffle your 1D array. Finally fill up your 2D array.
for(int i = 0,k = 0; i < N; i++)
for(int j = 0; j < M; j++,k++)
arr[i][j] = array[k];
Since your 2D array have 2500 position (50^2), in the finally you should have 250 '0' (0.10 * 50^2), 1250 '1' (0.50 * 50^2) and 1000 '3' (0.4 * 50^2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With