公司有个同事提出了一个问题,就是用程序来输出一个正方形矩阵,如:
1 2 5 7
3 5 8 13
4 9 12 14
10 11 15 16
分析过程如下:
其中的+-号是代表排序。写下这些文字,思路立刻出现,剩下的只是敲键盘。
-1
填充[0,0],
+2
填充[0,1]
填充[1,0]
-3
填充[2,0]
填充[1,1]
填充[0,2]
+4
填充[0,3]
填充[1,2]
填充[2,1]
填充[3,0]
-3(对应第一个3)
填充[3,1]
填充[2,2]
填充[1,3]
+2(对应第一个2)
填充[2,3]
填充[3,2]
-1(对应第一个1)
填充[3,3]
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
程序代码
using System;
namespace Matrix
{
class Program
{
static void Main(string[] args)
{
int strat = 1;
int max = 4;
bool direction = true;
if (args != null)
{
if (args.Length >= 1)
{
strat = int.Parse(args[0]);
}
if (args.Length >= 2)
{
max = int.Parse(args[1]);
}
if (args.Length >= 3)
{
direction = bool.Parse(args[2]);
}
}
PrintLabel();
PrintCreateMatrix(strat, max, direction);
}
/// <summary>
/// 创建矩阵
/// </summary>
/// <param name="strat"></param>
/// <param name="max"></param>
/// <param name="direction"></param>
/// <returns></returns>
static int[,] CreateMatrix(int strat, int max, bool direction)
{
if (max < 0) return null;
int[,] matrix = new int[max, max];
if (max == 1)
{
matrix[0, 0] = 0;
return matrix;
}
int cu = strat;
//正三角!
for (int i = 0; i < max; i++)
{
if (direction)
{
for (int j = i, n = 0; j >= 0; j--, n++, cu++)
{
matrix[j, n] = cu;
}
}
else
{
for (int j = 0, n = i; j <= i; j++, n--, cu++)
{
matrix[j, n] = cu;
}
}
direction = !direction;
}
//反三角!
int maxIndex = max - 1;
for (int i = max - 2; i >= 0; i--)
{
if (direction)
{
for (int j = i, n = 0; j >= 0; j--, n++, cu++)
{
matrix[maxIndex - n, maxIndex - j] = cu;
}
}
else
{
for (int j = 0, n = i; j <= i; j++, n--, cu++)
{
matrix[maxIndex - n, maxIndex - j] = cu;
}
}
direction = !direction;
}
return matrix;
}
/// <summary>
/// 打印矩阵
/// </summary>
/// <param name="strat"></param>
/// <param name="max"></param>
/// <param name="direction"></param>
static void PrintCreateMatrix(int strat, int max, bool direction)
{
int[,] matrix = CreateMatrix(strat, max, direction);
for (int i = 0; i < max; i++)
{
for (int j = 0; j < max; j++)
{
if (j == max - 1)
Console.WriteLine(matrix[i, j]);
else
Console.Write(matrix[i, j].ToString() + " ");
}
}
Console.ReadKey();
}
static void PrintLabel()
{
Console.WriteLine("/* ***************************************");
Console.WriteLine("/* 公 司:浙江新能量科技有限公司");
Console.WriteLine("/* 功能名称:矩阵算法");
Console.WriteLine("/* 作 者:李中华 2008年7月31日");
Console.WriteLine("*************************************** */");
Console.WriteLine(string.Empty);
}
}
}
调用表达式:
Matrix.exe [strat] [max] [direction]
strat:起始值,默认为1;
max:最大的维数,默认为4;
direction:排序的方向,true为先横后竖,false反之,默认为ture。
使用步骤:
在运行中输入:
路径\Matrix.exe 1,4,true
或者是:
路径\Matrix.exe 1,4
或者是:
路径\Matrix.exe 1
或者是:
路径\Matrix.exe
或者直接双击Matrix.exe。