最近小孩在小学数学培训,需要做一个完成幻方的做法
幻方的口诀
口诀:
1 居上行正中央,
依次斜填切莫忘,
上出框界往下写,
右出框时左边放,
重复便在下格填,
出角重复一个样。
附上java的实现
package com.sf.test;
public class huanfang {
public static void main(String[] args) {
try {
getHF(3,1,1);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* size为 自然数且为奇数,设置一个(2N+1)的幻方 begin 为开始数 ,步长为 step 的连续数,填写size*size的魔方
*
* @param args
*/
public static int[][] getHF(int size,int begin,int step) throws Exception{
if(size<0||size%2==0){
throw new Exception("size must be odd number ");
}
if(begin<=0){
throw new Exception("the first number must beyong zero ");
}
if(step<=0){
throw new Exception("the step number must beyong zero ");
}
int n = size/2;
int j = 0;
int k = 0;
int temp = 0;
int length = (2 * n + 1) * (2 * n + 1);
int array[][] = new int[2 * n + 1][2 * n + 1];
array[0][n] = begin;
j = 0;
k = n;
temp = begin;
for (int i = 0; i < length - 1; i++) {
int nextJ = j - 1;
int nextK = k + 1;
System.out.println(i + " the x " + nextJ + " the y " + nextK);
// 对角线出线
if (nextJ == -1 && nextK == 2 * n + 1) {
nextJ = 1;
nextK = 2 * n;
}
// 如果出现了J 出线的且不是对角线,则转到下个
if (nextJ < 0 && nextK != 2 * n + 1) {
nextJ = 2 * n;
}
// 如果出现了K 出线的且不是对角线,则转到下个
if (nextJ >= 0 && nextK == 2 * n + 1) {
nextK = 0;
}
// 如果右上角有数,则下移
if (nextJ >= 0 && nextK <= 2 * n) {
if (array[nextJ][nextK] != 0) {
nextJ = j + 1;
nextK = k;
}
}
System.out.println(i + " firt the x " + nextJ + " the y " + nextK);
array[nextJ][nextK] = temp + step;
System.out.println(i + " next the x " + nextJ + " the y " + nextK);
System.out.println(i + " next value " + array[nextJ][nextK]);
j = nextJ;
k = nextK;
temp = temp + step;
System.out.println("***********************************************");
for (int l = 0; l < (2 * n + 1); l++) {
for (int m = 0; m < (2 * n + 1); m++) {
System.out.print((array[l][m] < 10 ? "0" : "")+ array[l][m] + ",");
}
System.out.println();
}
System.out.println("***********************************************");
}
return array;
}
}