Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#在随机位置仅更改数组的一部分_C#_Arrays_Random - Fatal编程技术网

C#在随机位置仅更改数组的一部分

C#在随机位置仅更改数组的一部分,c#,arrays,random,C#,Arrays,Random,我在控制台c#代码(7X3‘cells’)中有一个int的2D数组。我创建它的那一刻,它就被初始化为零 我只需要将5个“单元格”的值改为1,而不改变其他“单元格”的值。我知道这是一件基本的事情,但是,作为一名C#的新手,无论我使用什么细胞,我都无法让它工作。你能帮我吗 提前谢谢 (注意:由于我是一个经常使用/参与的用户,我知道这看起来像是一个经典的“做我的家庭作业”问题,我对此表示歉意,但由于我真的被困在这个很小的部分(我的项目的其余部分还可以),我非常感谢您的帮助) 所以您定义了一个多维数组(

我在控制台c#代码(7X3‘cells’)中有一个int的2D数组。我创建它的那一刻,它就被初始化为零

我只需要将5个“单元格”的值改为1,而不改变其他“单元格”的值。我知道这是一件基本的事情,但是,作为一名C#的新手,无论我使用什么细胞,我都无法让它工作。你能帮我吗

提前谢谢


(注意:由于我是一个经常使用/参与的用户,我知道这看起来像是一个经典的“做我的家庭作业”问题,我对此表示歉意,但由于我真的被困在这个很小的部分(我的项目的其余部分还可以),我非常感谢您的帮助)

所以您定义了一个多维数组(基本上是一个矩阵):

然后将所有值初始化为0

要更改值,您应该可以这样做,例如:

cells[3,2] = 1;
这就是你试过的吗?您是否收到任何异常或警告

如果您使用的是锯齿状数组(数组的数组),则可能如下所示:

int[][] cells = new int[7][3];
然后您可以设置值:

cells[3][2] = 1;

这里有两种方法来解决这个问题,第一种;名为
BruteForceRandomImplementation
的方法很容易实现和理解,但如果您试图用1标记大量位置,则速度会非常慢,因为它像蛮力一样使用
Random
,直到填满足够的位置

    /// <summary>
    /// This method uses a random based algorithm to create a two-dimensional array of [height, width] 
    /// with exactly locationsToFind locations set to 1. 
    /// </summary>
    /// <param name="height"></param>
    /// <param name="width"></param>
    /// <param name="locationsToFind"></param>
    /// <returns></returns>
    public int[,] BruteForceRandomImplementation(int height, int width, int locationsToFind)
    {
        var random = new Random();
        locationsToFind = LimitLocationsToFindToMaxLocations(height, width, locationsToFind);

        // Create our two-dimensional array.
        var map = new int[height, width];

        int locationsFound = 0;

        // Randomly set positons to 1 untill we have set locationsToFind locations to 1. 
        while (locationsFound < locationsToFind)
        {
            // Get a random Y location - limit the max value to our height - 1. 
            var randomY = random.Next(height);
            // Get a random X location - limit the max value to our width - 1. 
            var randomX = random.Next(width);

            // Find another random location if this location is already set to 1. 
            if (map[randomY, randomX] == 1)
                continue;

            // Otherwise set our location to 1 and increment the number of locations we've found.
            map[randomY, randomX] = 1;
            locationsFound += 1;
        }

        return map;
    }
我的第二个实现称为
ShuffleImplementation
,当您标记大量的唯一位置时,它的速度要快很多。它创建一个一维数组,填充足够的1以满足您的需要,然后使用Fisher-Yates shuffle对该数组进行洗牌,最终将该一维数组扩展为二维数组:

    /// <summary>
    /// This method uses a shuffle based algorithm to create a two-dimensional array of [height, width] 
    /// with exactly locationsToFind locations set to 1. 
    /// </summary>
    /// <param name="height"></param>
    /// <param name="width"></param>
    /// <param name="locationsToFind"></param>
    /// <returns></returns>
    public int[,] ShuffleImplementation(int height, int width, int locationsToFind)
    {
        locationsToFind = LimitLocationsToFindToMaxLocations(height, width, locationsToFind);
        // Create a 1 dimensional array large enough to contain all our values. 
        var array = new int[height * width];

        // Set locationToFind locations to 1. 
        for (int location = 0; location < locationsToFind; location++)
            array[location] = 1;

        // Shuffle our array.
        Shuffle(array);

        // Now let's create our two-dimensional array.
        var map = new int[height, width];

        int index = 0;

        // Expand our one-dimensional array into a two-dimensional one. 
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                map[y, x] = array[index];
                index++;
            }
        }

        return map;
    }

    /// <summary>
    /// Shuffles a one-dimensional array using the Fisher-Yates shuffle. 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="arr"></param>
    public static void Shuffle<T>(T[] array)
    {
        var random = new Random();

        for (int i = array.Length - 1; i > 0; i--)
        {
            int n = random.Next(i + 1);
            Swap(ref array[i], ref array[n]);
        }
    }

    /// <summary>
    /// Swaps two values around. 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="valueA"></param>
    /// <param name="valueB"></param>
    public static void Swap<T>(ref T valueA, ref T valueB)
    {
        T tempValue = valueA;
        valueA = valueB;
        valueB = tempValue;
    }
或:

取决于您要使用哪一个。要了解两者之间性能差异的一个好例子,请尝试:

        int width = 1000;
        int height = 1000;
        int locationsToFind = (width * height) - 1;

        var stopwatch = new Stopwatch();

        stopwatch.Start();
        BruteForceRandomImplementation(height, width, locationsToFind);
        stopwatch.Stop();

        Console.WriteLine(string.Format("BruteForceRandomImplementation took {0}ms", stopwatch.ElapsedMilliseconds));

        stopwatch.Restart();
        ShuffleImplementation(height, width, locationsToFind);
        stopwatch.Stop();

        Console.WriteLine(string.Format("ShuffleImplementation took {0}ms", stopwatch.ElapsedMilliseconds));
在我的笔记本电脑上,BruteForceRandomon的实现耗时1205毫秒,ShuffleiImplementation则耗时67毫秒,快了近18倍

var array = new int[7,3];

array[5,2] = 1;
array[3,2] = 1;

请记住,数组索引是从零开始的,因此int[7,3]的有效范围是[0..6,0..2]

请发布创建、初始化和“更改值”数组的代码。同意上述内容。告诉我们实际的问题是什么。@J.Kommer,我试过这样的方法,问题是,你的代码将整个数组更改为1,而不仅仅是5个随机单元格。注意,随机数和随机数的最大值分别为
height-1
width-1
,如果五次选择的随机数都相同,该怎么办?这不管用。@J.Kommer,我在一台新电脑和一个新项目上又试了一次,效果很好。非常感谢,我真的很沮丧,因为它以前不起作用。虽然我注意到,如果,比如说,数组中有1000个元素,你被要求随机填充其中997个,你可以等待很长时间,直到最后几个值被填充。随着随机选择的元素数量变大,您的算法无法很好地扩展。
    /// <summary>
    /// This method uses a shuffle based algorithm to create a two-dimensional array of [height, width] 
    /// with exactly locationsToFind locations set to 1. 
    /// </summary>
    /// <param name="height"></param>
    /// <param name="width"></param>
    /// <param name="locationsToFind"></param>
    /// <returns></returns>
    public int[,] ShuffleImplementation(int height, int width, int locationsToFind)
    {
        locationsToFind = LimitLocationsToFindToMaxLocations(height, width, locationsToFind);
        // Create a 1 dimensional array large enough to contain all our values. 
        var array = new int[height * width];

        // Set locationToFind locations to 1. 
        for (int location = 0; location < locationsToFind; location++)
            array[location] = 1;

        // Shuffle our array.
        Shuffle(array);

        // Now let's create our two-dimensional array.
        var map = new int[height, width];

        int index = 0;

        // Expand our one-dimensional array into a two-dimensional one. 
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                map[y, x] = array[index];
                index++;
            }
        }

        return map;
    }

    /// <summary>
    /// Shuffles a one-dimensional array using the Fisher-Yates shuffle. 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="arr"></param>
    public static void Shuffle<T>(T[] array)
    {
        var random = new Random();

        for (int i = array.Length - 1; i > 0; i--)
        {
            int n = random.Next(i + 1);
            Swap(ref array[i], ref array[n]);
        }
    }

    /// <summary>
    /// Swaps two values around. 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="valueA"></param>
    /// <param name="valueB"></param>
    public static void Swap<T>(ref T valueA, ref T valueB)
    {
        T tempValue = valueA;
        valueA = valueB;
        valueB = tempValue;
    }
var map = BruteForceRandomImplementation(7, 3, 5);
var map = ShuffleImplementation(7, 3, 5);
        int width = 1000;
        int height = 1000;
        int locationsToFind = (width * height) - 1;

        var stopwatch = new Stopwatch();

        stopwatch.Start();
        BruteForceRandomImplementation(height, width, locationsToFind);
        stopwatch.Stop();

        Console.WriteLine(string.Format("BruteForceRandomImplementation took {0}ms", stopwatch.ElapsedMilliseconds));

        stopwatch.Restart();
        ShuffleImplementation(height, width, locationsToFind);
        stopwatch.Stop();

        Console.WriteLine(string.Format("ShuffleImplementation took {0}ms", stopwatch.ElapsedMilliseconds));
var array = new int[7,3];

array[5,2] = 1;
array[3,2] = 1;