topic:
Write a function to generate magic array. The parameter of the function is the order of the generated magic array, and the returned value is the generated magic array.
(The N-order magic array is an N*N matrix composed of natural numbers between 1 and N*N, where N is an odd number. The sum of each row, column and diagonal is equal.)
Code:
#include <iostream>
using namespace std;
void function(int n);
int main()
{
cout << "生成一个魔阵" << endl << endl;
int n;
cout << "请输入生成的魔阵的阶数:(必须为奇数)";
cin >> n;
function(n);
system("pause");
return 0;
}
void function(int n)
{
if (n % 2 == 0) cout << endl << "错误!" << n << "为偶数!" << endl << endl;
else
{
int **a, i = 0, j, k;
a = new int *[n];
for (i = 0; i < n; ++i) a[i] = new int[n];
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
a[i][j] = 0;
}
}
//填写方法:
j = (n - 1) / 2;
a[0][j] = 1; //1.第一个元素放在第一行中间一列
for (k = 2; k <= n*n; ++k)
{
//注意从除法的角度理解下面的特殊情况
//2.下一个元素存放在当前元素的上一行、下一列
if (a[(i - 1 + n) % n][(j + 1) % n] == 0)
{
i = (i - 1 + n) % n;
j = (j + 1) % n;
a[i][j] = k;
}
//3.若上一行、下一列已经有内容,则下一个元素的存放位置为当前列的下一行
else
{
i = (i + 1) % n;
a[i][j] = k;
}
}
cout << endl << n << "阶魔阵为:";
for (i = 0; i < n; ++i)
{
cout << endl;
for (j = 0; j < n; ++j)
{
if ((a[i][j] >= 1) & (a[i][j] <= 9)) cout << " ";
cout << a[i][j] << " ";
}
}
cout << endl << endl;
}
}