加倍矩阵

我创建了一个二维矩阵,并用随机数填充它。 然后我把它打印出来了。 我需要帮助创建第二个矩阵,其大小是第一个矩阵的两倍,并且填充了第一个的数字(现在是2×2)。 例如:

起始矩阵:

3 4 2 1 

双矩阵:

 3 3 4 4 3 3 4 4 2 2 1 1 2 2 1 1 

 import java.util.Scanner; import java.util.Random; public class MatrixDoubler { public static void main(String[] arg) { Scanner keyboard = new Scanner(System.in); Random rand = new Random(); System.out.println("Enter the size of the matrix"); int size = keyboard.nextInt(); int A[][] = new int[size][size]; for (int row = 0; row < size; ++row) { for (int col = 0; col < size; ++col) { A[row][col] = rand.nextInt(10); } } System.out.println("Matrix A:"); printMatrix(A); int[][] B = doubleMatrix(A); System.out.println("Matrix B:"); printMatrix(B); } private static int[][] doubleMatrix(int[][] A) { int rows = A.length; assert(rows > 0); int cols = A[0].length; assert(cols > 0); int B[][] = new int[rows * 2][cols * 2]; for (int row = 0; row < rows * 2; ++row) { for (int col = 0; col < cols * 2; ++col) { B[row][col] = A[row / 2][col / 2]; } } return B; } private static void printMatrix(int[][] M) { for(int i = 0; i < M.length; i++) { for(int j = 0; j < M.length; j++) { System.out.print(M[i][j] + " "); } System.out.println(); } } } 

我不确定这是不是你想要的但试试这个:

 for (int i = 0; i < newMatrix.length; i++) { for (int j = 0; j < newMatrix.length; j++) { newMatrix[i][j] = matrix[i/size][j/size]; } } 

注意:这段代码肯定不是最好的解决方案,而是快速简单的解决方案。 它只适用于两个尺寸相同的尺寸,如果newMatrix不是matrix两倍,它将无法工作。 如果它总是只是“加倍”矩阵它应该工作正常。


输出:
如果您选择尺寸2而不是输出:

 Enter the size of the matrix 2 The Matrix is 3 5 5 2 The newMatrix is 3 3 5 5 3 3 5 5 5 5 2 2 5 5 2 2 

例如,对于大小3,它将是

 Enter the size of the matrix 3 The Matrix is 4 4 3 5 9 4 7 4 1 The newMatrix is 4 4 4 4 3 3 4 4 4 4 3 3 5 5 9 9 4 4 5 5 9 9 4 4 7 7 4 4 1 1 7 7 4 4 1 1 

目前尚不清楚你在问什么,但我希望这会有所帮助(:

在Java 8中,您可以使用地图和收集器轻松处理此问题。 这是一个完整的例子:

 public class DoubleMatrix { public static void main(String[] args) { List> startingMatrix = Arrays.asList( Arrays.asList(3, 4), Arrays.asList(2, 1) ); List> doubleMatrix = startingMatrix.stream() .map(innerList -> { //For each list List doubled = innerList.stream() .map(element -> Arrays.asList(element, element)) //Return a list doubling each element .flatMap(l -> l.stream()) //Flatten out/join all doubled lists .collect(Collectors.toList()); return Arrays.asList(doubled, doubled); //Double the list }) .flatMap(l -> l.stream()) .collect(Collectors.toList()); //Collect into a final list System.out.println(doubleMatrix); } } 

这避免了需要事先知道列表的大小,并且还容忍矩阵的宽度和高度之间存在差异 – 只需将两个方向上的每个元素加倍。