C# 打印对角线阵列
如果数组的数目为C# 打印对角线阵列,c#,arrays,matrix,multidimensional-array,C#,Arrays,Matrix,Multidimensional Array,如果数组的数目为 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13, 14,15,16,17, 18,19,20,21, 22,23,24,25 } 这个代码的输出是 1,2,6,3,7,11,4,6,12,16,5,9,13,17,21,10,14,18,21,15,19,23,20,24,25 我想修改一下我的密码,让它成为我的行乞对象 21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 203 9 15
{
1, 2, 3, 4, 5,
6, 7, 8, 9,
10,11,12,13,
14,15,16,17,
18,19,20,21,
22,23,24,25
}
这个代码的输出是
1,2,6,3,7,11,4,6,12,16,5,9,13,17,21,10,14,18,21,15,19,23,20,24,25
我想修改一下我的密码,让它成为我的行乞对象
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 203 9 15 4 10 5
这是我的密码
int[,]p=新的int[5,5];
整数和=1;
对于(inti=1;i这比你想象的要复杂得多
要遍历此矩阵的对角线:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
从左下角开始,穿过每个对角线,如图中所示:
我编写了一个名为DiagonalIndices()
的助手方法,对于给定的最大索引(对于5x5矩阵,它将是4),它将以正确的顺序生成一系列(行、列)索引,以遍历所有对角线
请注意,输入数组必须是方形的-我假设您的数据就是这样!它显然适用于5x5矩阵
以下程序的输出为
2116221171723618241713191925248120391154105
代码如下:
using System;
using System.Collections.Generic;
namespace ConsoleApplication4
{
public sealed class Index
{
public Index(int row, int col)
{
Row = row;
Col = col;
}
public readonly int Row;
public readonly int Col;
}
public static class Program
{
private static void Main()
{
int [,] p = new int[5, 5];
for (int i = 0, n = 1; i < 5; ++i)
for (int j = 0; j < 5; ++j, ++n)
p[i, j] = n;
// This is the bit you will use in your program.
// Replace the Console.WriteLine() with your custom code
// that uses p[index.Row, index.Col]
int maxIndex = p.GetUpperBound(1);
foreach (var index in DiagonalIndices(maxIndex))
Console.Write(p[index.Row, index.Col] + " ");
Console.WriteLine();
}
public static IEnumerable<Index> DiagonalIndices(int maxIndex)
{
for (int i = 0; i <= maxIndex; ++i)
for (int j = 0; j <= i; ++j)
yield return new Index(maxIndex-i+j, j);
for (int i = 0; i < maxIndex; ++i)
for (int j = 0; j < maxIndex-i; ++j)
yield return new Index(j, i+j+1);
}
}
}
使用系统;
使用System.Collections.Generic;
命名空间控制台应用程序4
{
公开密封等级索引
{
公共索引(整数行,整数列)
{
行=行;
Col=Col;
}
公共只读int行;
公共只读int Col;
}
公共静态类程序
{
私有静态void Main()
{
int[,]p=新的int[5,5];
对于(int i=0,n=1;i<5;++i)
对于(int j=0;j<5;++j,++n)
p[i,j]=n;
//这是您将在程序中使用的位。
//用自定义代码替换Console.WriteLine()
//使用p[index.Row,index.Col]
int maxIndex=p.GetUpperBound(1);
foreach(对角化中的var指数(maxIndex))
Console.Write(p[index.Row,index.Col]+“”);
Console.WriteLine();
}
公共静态IEnumerable对角化(int maxIndex)
{
对于(int i=0;i而言,仅在矩阵的正方向上打印对角线值更有效。
int [,] p = new int [5,5]
{
{1, 2, 3, 4,5},
{6, 7, 8, 9},
{10,11,12,13},
{14,15,16,17},
{18,19,20,21},
{22,23,24,25}
};
for (int i = 4, j = 4; i >= 0 && j > = 0; i--, j--)
{
Console.Writeline(p[ i, j ]);
}
你说的“对角线”到底是什么意思?
int [,] p = new int [5,5]
{
{1, 2, 3, 4,5},
{6, 7, 8, 9},
{10,11,12,13},
{14,15,16,17},
{18,19,20,21},
{22,23,24,25}
};
for (int i = 4, j = 4; i >= 0 && j > = 0; i--, j--)
{
Console.Writeline(p[ i, j ]);
}