0

I have a 2D array that I want to initialize with a b and c values, such that 50% of the cells are a, 25% b and 25% c. Can you please suggest me a way to do this ?

EDIT : I have found a solution for 1D array that I can adapt for a 2D array (I initialize deterministically then shuffle): Shuffle array in C

Is there a better way ?

Community
  • 1
  • 1

1 Answers1

0

First, you fill the 2D array with a, b, c according to the proportions, then shuffle the array.

int size_a = size * 50%;
int size_b = size * 25%;
int size_c = size * 25%;
int i;
for(i = 0; i < size_a; ++i)
{
    A[i/WIDTH][i%WIDTH] = a;
}
...

and the same for others. Then use the shuffle(in c++, we have std::shuffle) you get from the link while mapping the 2D array to 1D array.

jfly
  • 7,715
  • 3
  • 35
  • 65
  • That's what I plan to do, but I don't understand you when you write A[size_a / WIDTH][size_a % WIDTH] = a; ? – user3346223 Mar 31 '14 at 01:31
  • Because you are using a 2D array, for example, `A[3][2]`, when we map the 2D array to 1D array, `a[4] = A[4/2][4%2]`. – jfly Mar 31 '14 at 01:37
  • my mistake, it's `A[i/WIDTH][i%WIDTH] = a;`, so when you call the `shuffle()` for 1D array, the `array[j]` can be mapped to `A[j/WIDTH][j%WIDTH]` – jfly Mar 31 '14 at 01:50