Java 以给定格式打印二维矩阵
//给定一个数字n,我想为它生成相应的二维矩阵。 //例如,对于n=1,我的二维矩阵应为 对于n=1 1 2 34 对于n=2Java 以给定格式打印二维矩阵,java,algorithm,Java,Algorithm,//给定一个数字n,我想为它生成相应的二维矩阵。 //例如,对于n=1,我的二维矩阵应为 对于n=1 1 2 34 对于n=2 1 2 5 6 3 4 7 8 9 10 13 14 11 12 15 16 对于n=3 1 2 5 6 17 18 21 22 3 4 7 8 19 20 23 24 9 10 13 14 25 26 29 30 11 12 15 16 27 28 31 32 33 34 37 38 49 50 53 54 35 36 39
1 2 5 6
3 4 7 8
9 10 13 14
11 12 15 16
对于n=3
1 2 5 6 17 18 21 22
3 4 7 8 19 20 23 24
9 10 13 14 25 26 29 30
11 12 15 16 27 28 31 32
33 34 37 38 49 50 53 54
35 36 39 40 51 52 55 56
41 42 45 46 57 58 61 62
43 44 47 48 59 60 63 64
这个问题可以用递归来解决。例如,下面的代码精确打印给定
n
所需的矩阵
import java.util.Scanner;
public class Main {
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
final int n = scanner.nextInt();
final int[][] matrix = create(1, (int) Math.pow(2, n));
print(matrix);
}
private static int[][] create(final int startValue, final int size) {
if (size == 1) {
return new int[][]{{startValue}};
} else {
final int half = size / 2;
final int step = half * half;
return combine(create(startValue, half), create(startValue + step, half),
create(startValue + 2 * step, half), create(startValue + 3 * step, half));
}
}
private static int[][] combine(final int[][] m1, final int[][] m2, final int[][] m3, final int[][] m4) {
final int initialSize = m1.length;
final int sizeOfResult = initialSize * 2;
final int[][] result = new int[sizeOfResult][sizeOfResult];
for (int row = 0; row < initialSize; row++) {
for (int col = 0; col < initialSize; col++) {
result[row][col] = m1[row][col];
result[row][col + initialSize] = m2[row][col];
result[row + initialSize][col] = m3[row][col];
result[row + initialSize][col + initialSize] = m4[row][col];
}
}
return result;
}
private static void print(final int[][] matrix) {
for (final int[] row : matrix) {
for (final int val : row) {
System.out.printf("%-5d", val);
}
System.out.println();
}
}
}
import java.util.Scanner;
公共班机{
公共静态void main(最终字符串[]args){
最终扫描仪=新扫描仪(System.in);
final int n=scanner.nextInt();
最终int[][]矩阵=创建(1,(int)Math.pow(2,n));
打印(矩阵);
}
私有静态int[][]创建(最终int起始值,最终int大小){
如果(大小==1){
返回新的int[][{{startValue}};
}否则{
最终整数的一半=尺寸/2;
最后一步整数=一半*一半;
返回联合收割机(创建(起始值,一半),创建(起始值+阶跃,一半),
创建(起始值+2*步,一半),创建(起始值+3*步,一半);
}
}
专用静态整数[][]组合(最终整数[][]m1、最终整数[]m2、最终整数[]m3、最终整数[]m4){
最终int initialSize=m1.length;
最终int-sizeOfResult=初始大小*2;
最终int[][]结果=新int[sizeOfResult][sizeOfResult];
对于(int row=0;row
很酷。随它去吧。一旦你尝试了什么并且有了一个实际的具体问题,请不要犹豫提问。你应该在这里解释更多以获得帮助,IFAIK,最大数字是4^n
,但我不知道如何基于n
的矩阵结构。