Finding diagonal in 2D array and replacing with 0 above it

瘦欲@ 提交于 2019-12-24 15:19:00

问题


So the start is:

        Random r = new Random();
        int[,] mas = new int[4, 5];
        for (int i = 0; i < mas.GetLength(0); i++)
        {
            for (int j = 0; j < mas.GetLength(1); j++)
            {
                mas[i, j] = r.Next(1, 10);
                Console.Write("{0}\t", mas[i, j]);
            }

            Console.WriteLine();
        }

        Console.WriteLine();

Looks something like

4 3 5 6 2

3 5 6 7 4

2 3 4 5 5

2 3 4 5 6

What i i need is to get 0 above the diagonal.

4 0 0 0 0

3 5 0 0 0

2 3 4 0 0

2 3 4 5 0

This is what i've got so far, no what i need , but atleast got some diagonal and some 0's.

  for (int i = 0; i < mas.GetLength(0); i++)
        {
            for (int j = i; j < mas.GetLength(1); j++)
            {
                mas[i, j] = 0;
                Console.Write("{0}\t", mas[i, j]);
            }

            Console.WriteLine();
        }

回答1:


If you want to do everything in one go, you could do this:

    Random r = new Random();
    int[,] mas = new int[4, 5];
    for (int i = 0; i < mas.GetLength(0); i++)
    {
        for (int j = 0; j < mas.GetLength(1); j++)
        {
            mas[i, j] = j > i ? 0 : r.Next(1, 10);
            Console.Write("{0}\t", mas[i, j]);
        }

        Console.WriteLine();
    }

    Console.WriteLine();

Otherwise, your second section needs to be:

    for (int i = 0; i < mas.GetLength(0); i++)
    {
        for (int j = i; j < mas.GetLength(1); j++)
        {
            if(j > i) mas[i, j] = 0;
            Console.Write("{0}\t", mas[i, j]);
        }

        Console.WriteLine();
    }



回答2:


try this one (inside the inner loop):

if(j > i ) mas[i, j] = 0; // column number > row number, above diagonal

or the (better) alternative (inside the outer loop):

for (int j = i+1; j < mas.GetLength(1); j++)
{
    mas[i, j] = 0;
    Console.Write("{0}\t", mas[i, j]);
}



回答3:


Using Linq

Random r = new Random();
            //int[,] mas = new int[4, 5];

            int[][] mas = new int[4][];


            for (int i = 0; i < mas.Length; i++)
            {
                mas[i] = new int[5];

                for (int j = 0; j < mas[i].Length; j++)
                {
                    mas[i][j] = r.Next(1, 10);
                    Console.Write("{0}\t", mas[i][j]);
                }

                Console.WriteLine();
            }

            for (int i = 0; i < mas.Length; i++)
            {
                mas[i] = mas[i].Select((c, ind) =>
                {
                    if (ind > i)
                        c = 0;

                    return c;

                }).ToArray();
            }


来源:https://stackoverflow.com/questions/27530303/finding-diagonal-in-2d-array-and-replacing-with-0-above-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!