将多维数组的n个随机元素设置为值

时间:2013-01-26 15:54:08

标签: c# random

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

这是我的代码。在下面的示例中,我尝试将3x3数组的3个随机选择的元素设置为1。

1

2 个答案:

答案 0 :(得分: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++;
    }
}

答案 1 :(得分: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);

        }

    }