如何切换2D阵列中元素的位置?

时间:2019-01-04 14:25:55

标签: c#

因此,我对C#还是比较陌生,我正在尝试制作一个图片拼图游戏,其中将图像分成多个块。我遇到的麻烦是找到一种方法来使2D数组的元素更改位置,这是允许我为游戏添加随机混洗和玩家控制。因此,例如,左上角是0,右下角是9,我希望它们交换位置。

int[,] grid = new int[4, 4];

        for (int y = 0; y < 4; y++)
        {
            Console.WriteLine("*********************");

            for (int x = 0; x < 4; x++)
            {
                grid[x, y] = x * y;

                Console.Write("|" + grid[x, y] + "| ");
            }

            Console.WriteLine();
        }

        Console.WriteLine("*********************");

        Console.ReadKey();

到目前为止,我已经将其工作到可以创建数组值网格的地步,我对如何使值转换位置的想法感到困惑。

2 个答案:

答案 0 :(得分:2)

我们可以为此提供帮助功能。它的工作方式是将一个现货的值存储在一个临时变量中,这样它就不会丢失,然后用另一个现货代替。然后,我们将临时变量的值推到另一个位置。

我们将int[,]作为ref传入,以便当您在网格上调用Swap时,实际的网格会在函数外部更改。

    public static void Swap(int x1, int y1, int x2, int y2, ref int[,] grid)
    {
        int temp = grid[x1, y1]; // store the value we're about to replace
        grid[x1, y1] = grid[x2, y2]; // replace the value
        grid[x2, y2] = temp; // push the stored value into the other spot
    }

使用示例:

        int[,] grid = new int[4, 4];
        grid[0, 0] = 5;
        grid[1, 1] = 7;
        Console.WriteLine(" " + grid[0, 0] + " | " + grid[1, 1]);
        Swap(0, 0, 1, 1, ref grid);
        Console.WriteLine(" " + grid[0, 0] + " | " + grid[1, 1]);

礼物:

 5 | 7
 7 | 5

答案 1 :(得分:1)

我使用@Nick Dechiara交换函数添加了随机洗牌。我正在使用GetLength来获取网格的大小

    static void Main(string[] args)
    {
        int[,] grid = new int[7, 4];

        for (int y = 0; y < grid.GetLength(1); y++)
        {
            for (int x = 0; x < grid.GetLength(0); x++)
            {
                grid[x, y] = x * y;
            }
        }

        PrintGrid(grid);

        int numberOfShuffles = 5;
        Random rand = new Random();
        for (int i = 0; i < numberOfShuffles; i++)
        {
            int x1 = rand.Next(0, grid.GetLength(0));
            int x2 = rand.Next(0, grid.GetLength(0));
            int y1 = rand.Next(0, grid.GetLength(1));
            int y2 = rand.Next(0, grid.GetLength(1));

            Console.WriteLine();
            Console.WriteLine("Swapping ({0},{1}) with ({2},{3})", x1,y1,x2,y2);

            Swap(x1,y1,x2,y2,ref grid);

            PrintGrid(grid);
        }
    }

    public static void Swap(int x1, int y1, int x2, int y2, ref int[,] grid)
    {
        int temp = grid[x1, y1]; // store the value we're about to replace
        grid[x1, y1] = grid[x2, y2]; // replace the value
        grid[x2, y2] = temp; // push the stored value into the other spot
    }

    private static void PrintGrid(int[,] grid)
    {
        Console.WriteLine("****************************");
        for (int y = 0; y < grid.GetLength(1); y++)
        {
            for (int x = 0; x < grid.GetLength(0); x++)
            {
                Console.Write("|" + grid[x, y] + "| ");
            }
            Console.WriteLine();
        }
    }