In a two-dimensional array of integers (eg 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;
}
}
}
}
You might try something like the following. First initialize your matrix to all 0 values, then run the code below. It will set three random values in the matrix to 1.
int count = 0;
while (count < 3)
{
int x = r.Next(0, 3);
int y = r.Next(0, 3);
if (matrix[x, y] != 1)
{
matrix[x, y] = 1;
count++;
}
}
static int sum = 0;
private static readonly int[,] matrix = new int[3,3];
private static readonly Random _r = new Random();
private static void MakeMatrix()
{
//by default all the element in the matrix will be zero, so setting to zero is not a issue
// now we need to fill 3 random places with numbers between 1-3 i guess ?
//an array of int[3] to remember which places are already used for random num
int[] used = new int[3];
int pos;
for (int i = 0; i < 3; i++)
{
pos = _r.Next(0, 8);
var x = Array.IndexOf(used, pos);
while (x != -1)
{
pos = _r.Next(0, 8);
}
used[i] = pos;
matrix[pos/3, pos%3] = _r.Next(1, 3);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.