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

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

转载于:https://www.cnblogs.com/wangxiangstudy/p/5455689.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值