我创建了一个二维矩阵并用随机数填充它。然后我打印出来了。我需要帮助创建第二个矩阵,其大小是第一个矩阵的两倍,并且用第一个矩阵(现在是2×2)中的数字填充。例如:加倍矩阵
起始基体:
3 4
2 1
一倍矩阵:
3 3 4 4
3 3 4 4
2 2 1 1
2 2 1 1
我创建了一个二维矩阵并用随机数填充它。然后我打印出来了。我需要帮助创建第二个矩阵,其大小是第一个矩阵的两倍,并且用第一个矩阵(现在是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<List<Integer>> startingMatrix = Arrays.asList(
Arrays.asList(3, 4),
Arrays.asList(2, 1)
);
List<List<Integer>> doubleMatrix
= startingMatrix.stream()
.map(innerList -> { //For each list
List<Integer> 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);
}
}
这避免了需要知道的名单事先的大小,也是宽容的存在是你的矩阵的宽度和高度之间的差异 - 只需在两个方向上加倍的每一个元素。
指定问题 – Rao