2

int[3,3]在由所有值组成的二维整数数组(例如)中0,我想尽可能有效地n将数组的随机元素设置为该值。1我遇到的问题是数组中的第一个元素1比数组后面的其他元素更有可能具有 的值。

这是我的代码。在下面的示例中,我试图将 3x3 数组的 3 个随机选择的元素设置为 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;
            }
        }
    }
}
4

2 回答 2

4

您可以尝试以下方法。首先将矩阵初始化为所有 0 值,然后运行下面的代码。它将矩阵中的三个随机值设置为 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++;
    }
}
于 2013-01-26T16:01:06.773 回答
0
    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);

        }

    }
于 2013-01-26T16:19:53.493 回答