简体   繁体   English

旋转 ArrayList 的矩阵元素<arraylist<string> &gt; 在爪哇</arraylist<string>

[英]Rotate matrix elements for ArrayList<ArrayList<String>> in java

I already did search a lot and got a lot of solutions for the rotate matrix but all of them are 2D arrays , for example arr[][] but for my case, my matrix is ArrayList<ArrayList<String>> .我已经做了很多搜索并得到了很多旋转矩阵的解决方案,但它们都是2D arrays ,例如arr[][]但就我而言,我的矩阵是ArrayList<ArrayList<String>> So it is natural that it might not be equal in row and column.所以它在行和列中可能不相等是很自然的。 For example, my matrix is -例如,我的矩阵是 -

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

My target is to make my ArrayList<ArrayList<String>> matrix rotate into a clockwise or anti-clockwise and make it equal in a row and column size.我的目标是使我的ArrayList<ArrayList<String>>矩阵顺时针逆时针旋转,并使其行和列大小相等。 For example-例如-

1-2-3-0         1-4-7
4-5-6-6   ==>   2-5-8
7-8-9-0         3-6-9
                0-6-0

How to optimally achieve this purpose?如何最佳地达到这个目的?

Assuming your original list elemnts are always different from 0 you could iterate over each column and collect the elemnts of each row and add 0 for any row which size is to short and stop when all elemnts equal 0 .假设您的原始列表元素总是与0不同,您可以遍历每一列并收集每一行的元素,并为任何大小短的行添加0并在所有元素等于0时停止。 Something like:就像是:

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();
}

Explanation解释

This approach starts by getting the length of the longest row in the matrix:这种方法首先获取矩阵中最长行的长度:

matrix.stream().map(List::size).max(Comparator.naturalOrder()).orElse(0)

It then creates a stream which iterates through all possible list indexes: the ints between 0 and the max row length:然后它创建一个流,遍历所有可能的列表索引:0 和最大行长度之间的整数:

IntStream.range(0, maxRowLength)

For each index i in that list, it maps the index to a list.对于该列表中的每个索引i ,它将索引映射到列表。 Each element of this list is the i th element of the corresponding list in the matrix, or "0" if that list is shorter than i :此列表的每个元素都是矩阵中相应列表的第i个元素,如果该列表比i短,则为“0”:

.mapToObj(i -> matrix.stream()
        .map(l -> l.size() <= i ? "0" : l.get(i)).toList())

Finally, it converts the stream to a list:最后,它将流转换为列表:

.toList();

Here is a "Old Dog" approach:这是一个“老狗”方法:

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;    
 }

Test method:测试方法:

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");
}

An empty row ( {} ) in arr will result in a corresponding column in res having all zero. arr中的空行 ( {} ) 将导致res中的相应列全为零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM