魔方阵,奇数阵。输入一个奇数,产生一个魔方阵

package com.test.dailyTest.doSome;

import java.util.Scanner;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

public class Njie {
	public static void main(String[] args) throws Exception {
		System.out.println("n阶举证-奇数");
		System.out.println("*****输入一个奇数*****");
		System.out.println("*********************");
		while (true) {
			Scanner cin = new Scanner(System.in);
			String num = cin.nextLine();
			if (StringUtils.isEmpty(num)) {
				num = "aa";
			}
			Pattern pattern = Pattern.compile("[0-9]*");
			if (pattern.matcher(num).matches()) {
				int Num = Integer.valueOf(num);
				int[][] numArr = getArr(Num);
				// 打印输出
				for (int i = 0; i < numArr[0].length; i++) {// 列长度
					for (int j = 0; j < numArr.length; j++) {// 行长度
						System.out.print(numArr[i][j] + "  ");
					}
					System.out.println();
				}
			} else {
				System.out.println("您输入的不是数字");
			}
		}

	}

	private static int[][] getArr(int Num) {
		int sum = Num * Num;

		int[][] numArr = new int[Num][Num];
		int firstIndex = (numArr.length - 1) / 2;
		numArr[0][firstIndex] = 1;
		int currentX = 0;
		int currentY = firstIndex;
		// 寻找下一个点
		for (int i = 2; i <= sum; i++) {
			int nextX = currentX - 1;
			int nextY = currentY - 1;
			if (nextX < 0 && nextY < 0) {
				nextX = currentX + 1;
				nextY = currentY;
			} else {
				if (nextX < 0) {
					nextX = nextX + Num;
				}
				if (nextY < 0) {
					nextY = nextY + Num;
				}
			}
			if (numArr[nextX][nextY] == 0) {
				numArr[nextX][nextY] = i;
			} else {
				nextX = currentX + 1;
				nextY = currentY;
				numArr[nextX][nextY] = i;
			}
			currentX = nextX;
			currentY = nextY;
		}
		return numArr;
	}
}

  

效果图如下

n阶举证-奇数
*****输入一个奇数*****
*********************
5
15 8 1 24 17
16 14 7 5 23
22 20 13 6 4
3 21 19 12 10
9 2 25 18 11

posted @ 2016-05-03 17:06  小祥工作室  阅读(468)  评论(0编辑  收藏  举报