[英]Rotate matrix elements for ArrayList<ArrayList<String>> in java
我已經做了很多搜索並得到了很多旋轉矩陣的解決方案,但它們都是2D arrays ,例如arr[][]
但就我而言,我的矩陣是ArrayList<ArrayList<String>>
。 所以它在行和列中可能不相等是很自然的。 例如,我的矩陣是 -
1-2-3
4-5-6-6 //Here column is 4 not 3 like the 1-2-3 or 7-8-9 rows
7-8-9
我的目標是使我的ArrayList<ArrayList<String>>
矩陣順時針或逆時針旋轉,並使其行和列大小相等。 例如-
1-2-3-0 1-4-7
4-5-6-6 ==> 2-5-8
7-8-9-0 3-6-9
0-6-0
如何最佳地達到這個目的?
假設您的原始列表元素總是與0
不同,您可以遍歷每一列並收集每一行的元素,並為任何大小短的行添加0
並在所有元素等於0
時停止。 就像是:
public static void main(String[] args) {
List<List<String>> matrix = List.of( List.of("1", "2", "3"),
List.of("4", "5", "6", "6"),
List.of("7", "8", "9"));
List<List<String>> rotated =
IntStream.iterate(0, i -> i + 1)
.mapToObj(i -> matrix.stream()
.map(sublist -> i < sublist.size() ? sublist.get(i) : "0")
.toList())
.takeWhile(list -> !list.stream().allMatch(e -> "0".equals(e)))
.toList();
rotated.forEach(System.out::println);
}
public List<List<String>> rotate(List<List<String>> matrix) {
int maxRowLength = matrix.stream().map(List::size)
.max(Comparator.naturalOrder()).orElse(0);
return IntStream.range(0, maxRowLength)
.mapToObj(i -> matrix.stream()
.map(l -> l.size() <= i ? "0" : l.get(i)).toList())
.toList();
}
這種方法首先獲取矩陣中最長行的長度:
matrix.stream().map(List::size).max(Comparator.naturalOrder()).orElse(0)
然后它創建一個流,遍歷所有可能的列表索引:0 和最大行長度之間的整數:
IntStream.range(0, maxRowLength)
對於該列表中的每個索引i
,它將索引映射到列表。 此列表的每個元素都是矩陣中相應列表的第i
個元素,如果該列表比i
短,則為“0”:
.mapToObj(i -> matrix.stream()
.map(l -> l.size() <= i ? "0" : l.get(i)).toList())
最后,它將流轉換為列表:
.toList();
這是一個“老狗”方法:
public static List<List<Integer>> rotate (List<List<Integer>> source) {
// find row with greatest number of columns
// there will be one row generated for each column
int max = 0;
for (int i = 0; i < source.size(); ++i) {
max = Math.max (source.get(i).size(), max);
}
List<List<Integer>> dest = new ArrayList<> (max);
// i indexes column in source, row in dest
for (int i = 0; i < max; ++i) {
List<Integer> line = new ArrayList<> (source.size());
// j indexes row in source, column in dest
for (int j = 0; j < source.size(); ++j) {
if (i >= source.get(j).size()) {
line.add (j,0);
} else {
line.add (j,source.get(j).get(i));
}
}
dest.add (line);
}
return dest;
}
測試方法:
public static void testRotate () {
Integer [][] arr = {{1,2,3},{4,5,6,10,11},{7,8,9}};
List<List<Integer>> list = new ArrayList<> ();
for (int i = 0; i < arr.length; ++i) {
List<Integer> row = Arrays.asList (arr[i]);
list.add(row);
}
List<List<Integer>> res = rotate (list);
for (int i = 0; i < res.size(); ++i) {
System.out.println ();
for (int j = 0; j < res.get(i).size(); ++j) {
System.out.print (res.get(i).get(j) + "\t");
}
}
System.out.println ("\n");
}
arr
中的空行 ( {}
) 將導致res
中的相應列全為零。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.