Java实现环形矩阵生成

0

环形矩阵如下:

环形矩阵

已经用箭头标记了生成的规律,从125,箭头的数量是5、4、4、3、3、2、2、1、1
矩阵可以看作x和y轴,坐标变换规律:x+y+x-y-的重复。所以代码如下:

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 环形矩阵
 */
public class DoubleMatrix {

	public static final void matrix(int num) {
		// 设置矩阵
//		int[][] matrix = new int[num][num];
		String[][] matrixProcess = new String[num][num];
		// 数组index:num -> 2 * (num - 1) -> 2 * (1):2n次
		// 矩阵index:x+1 -> y+1 -> x-1 -> y-1;
		AtomicInteger value = new AtomicInteger(0); // 当前所有
		AtomicInteger x = new AtomicInteger(-1); // x轴
		AtomicInteger y = new AtomicInteger(); // y轴
		AtomicInteger o = new AtomicInteger(0); // 次数
		for (int i = 2 * num; i > 0; i--) {
//			putMatrix(matrix, i / 2, x, y, o, value); // 数字
			putMatrix(matrixProcess, i / 2, x, y, o, value); // 变化规则
		}
	}

	public static final void putMatrix(int[][] matrix, int length, AtomicInteger x, AtomicInteger y, AtomicInteger o, AtomicInteger value) {
		for (int i = 0; i < length; i++) {
			value.incrementAndGet();
			if(o.get() % 4 == 0) {
				x.addAndGet(1);
				matrix[y.get()][x.get()] = value.get();
			} else if(o.get() % 4 == 1) {
				y.addAndGet(1);
				matrix[y.get()][x.get()] = value.get();
			} else if(o.get() % 4 == 2) {
				x.addAndGet(-1);
				matrix[y.get()][x.get()] = value.get();
			} else if(o.get() % 4 == 3) {
				y.addAndGet(-1);
				matrix[y.get()][x.get()] = value.get();
			}
		}
		printMatrix(matrix);
		o.incrementAndGet();
	}
	
	public static final void putMatrix(String[][] matrix, int length, AtomicInteger x, AtomicInteger y, AtomicInteger o, AtomicInteger value) {
		for (int i = 0; i < length; i++) {
			value.incrementAndGet();
			if(o.get() % 4 == 0) {
				x.addAndGet(1);
				matrix[y.get()][x.get()] = String.format("%04d", value.get()) + "→";
			} else if(o.get() % 4 == 1) {
				y.addAndGet(1);
				matrix[y.get()][x.get()] = String.format("%04d", value.get()) + "↓";
			} else if(o.get() % 4 == 2) {
				x.addAndGet(-1);
				matrix[y.get()][x.get()] = String.format("%04d", value.get()) + "←";
			} else if(o.get() % 4 == 3) {
				y.addAndGet(-1);
				matrix[y.get()][x.get()] = String.format("%04d", value.get()) + "↑";
			}
		}
		printMatrix(matrix);
		o.incrementAndGet();
	}
	
	public static final void printMatrix(int[][] matrix) {
		System.out.println("------------------");
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				System.out.print(String.format("%04d-", matrix[i][j]));
			}
			System.out.println();
		}
		System.out.println("------------------");
	}
	
	public static final void printMatrix(String[][] matrix) {
		System.out.println("------------------");
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[i].length; j++) {
				System.out.print(matrix[i][j]);
			}
			System.out.println();
		}
		System.out.println("------------------");
	}
	
	public static void main(String[] args) {
		matrix(5);
	}
	
}