加倍矩阵 [英] Doubling a Matrix
问题描述
我创建了一个二维矩阵,并用随机数填充它。然后我把它打印出来了。我需要帮助创建第二个矩阵,其大小是第一个矩阵的两倍,并且填充了第一个矩阵(现在是2x2)。例如:
I've created a two dimensional matrix and populated it with random numbers. I've then printed it out. I need help creating a second matrix that is twice the size of the first, and is populated with the numbers from the first one (which are now 2x2). For example:
起始矩阵:
3 4
2 1
Doubled Matrix:
Doubled Matrix:
3 3 4 4
3 3 4 4
2 2 1 1
2 2 1 1
推荐答案
在Java 8中,您可以使用地图轻松处理收藏家。以下是一个完整的示例:
In Java 8 you can handle this pretty easily using maps and collectors. Here is a full example:
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);
}
}
这样可以避免事先知道列表的大小,并且也容忍矩阵的宽度和高度之间存在差异 - 只需将两个方向上的每个元素加倍。
This avoids needing to know the size of the list beforehand, and is also tolerant of there being a difference between the width and height of your matrix - simply doubling every element in both directions.
这篇关于加倍矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!