在2D阵列查找对角线和它上面0替换(Finding diagonal in 2D array and

2019-10-21 10:45发布

所以一开始是:

        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();

看起来像

4 3 5 6 2

3 5 6 7 4

2 3 4 5 5

2 3 4 5 6

二是什么是需要在对角线上方得到0。

4 0 0 0 0

3 5 0 0 0

2 3 4 0 0

2 3 4 5 0

这就是我这么远,不,我需要什么,但ATLEAST得到了一些对角和一些0。

  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();
        }

Answer 1:

如果你想一次做的一切,你可以这样做:

    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();

否则,你的第二个部分必须是:

    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();
    }


Answer 2:

试试这个(内环内):

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

或(更好)替代(外环内):

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


Answer 3:

使用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();
            }


文章来源: Finding diagonal in 2D array and replacing with 0 above it
标签: c# diagonal