In a two-dimensional array of integers (e.g. int[3,3]), consisting of all 0 values, I'd like to set n random elements of the array to the value 1 as efficiently as possible. The problem that I am running into is that the first elements in the array are more likely to have a value of 1 than other elements later in the array.
Here is my code. In the example below I am attempting to set exactly 3 randomly-selected elements of the 3x3 array to 1.
int sum = 0;
private void MakeMatrix()
{
for (int i = 0; i < 3; i++)
{
for (int k = 0; k < 3; k++)
{
int n = _r.Next(2);
if (n != 1 && sum < 3)
{
matrix[i, k] = 1;
sum++;
}
else
{
matrix[i, k] = 0;
}
}
}
}