简体   繁体   English

以不同的顺序读取多维数组

[英]Reading a multi-dimensional array in a different order

So I have a number array like this 所以我有一个像这样的数字数组

0 1 2 3 0 1 2 3

4 5 6 7 4 5 6 7

8 9 10 11 8 9 10 11

12 13 14 15 12 13 14 15

And know what I want to know is how to make it read the number 7 after the number 3, and number 8 after number 4. And so on, like this: 知道我想知道的是如何让它读取3号之后的7号和4号之后的8号。依此类推:

0 -> 1 -> 2 -> 3
               |
               \/
4 <- 5 <- 6 <- 7
|
\/
8 -> 9 -> 10 -> 11
                  |
                  \/
12 <- 13 <- 14 <- 15

However if I use nested incremental for it will read in normal sequential order. 但是,如果我使用嵌套增量式for它将以正常的顺序读取。

I have no idea how to make it read from 3 to 7, 4 to 8 and so on... 我不知道如何使它从3到7、4到8等读取...

How can I achieve that? 我该如何实现?

You can store a flag indicating if the next iteration is going to start on the left or right. 您可以存储一个标志,指示下一次迭代是在左侧还是在右侧开始。 So... 所以...

static void Main(string[] args)
{
    // initializing values
    int[,] arr = new int[4, 4];
    int n = 0;

    for (int i = 0; i < 4; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            arr[i, j] = n++;
        }
    }

    n = 0;
    // initialization end

    // starts from the left
    bool left = true;
    // go line by line
    for (int i = 0; i < 4; i++)
    {
        // if it starts from the left, set start point a index 0
        // otherwise start from max index
        for (int j = left ? 0 : 3; left ? j < 4 : j >= 0; )
        {
            arr[i, j] = n++;

            // increment/decrements depending on the direction
            j = left ? j + 1 : j - 1;
        }

        // if it started from the left, the next iteration will
        // start from the right
        left = !left;
    }
}

Results: 结果:

Initialized: 初始化:

 0  1  2  3

 4  5  6  7

 8  9 10 11

12 13 14 15

After navigating on it: 导航之后:

 0  1  2  3

 7  6  5  4

 8  9 10 11

15 14 13 12

If you have: 如果你有:

_arr = new int[,] { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 }, { 12, 13, 14, 15 } };

Then try: 然后尝试:

    public void PrintArr()
    {
        for (int i = 0; i < 4; i++)
        {
            if (i % 2 == 0)
            {
                for (int j = 0; j < 4; j++)
                    Console.Write(_arr[i, j] + " ");
                Console.WriteLine();
            }
            else
            {
                for (int j = 3; j >= 0; j--)
                    Console.Write(_arr[i, j] + " ");
                Console.WriteLine();

            }
        }
    }

Here's a short, simple solution: 这是一个简短的简单解决方案:

int h = array.GetLength(0), w = array.GetLength(1);
for(int i = 0, j = 0, c = 1; i < h; i++, c = -c, j += c)
{
    for(int k = 0; k < w; k++, j += c)
    {
        Console.WriteLine(array[i, j]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM