Sorting 2D array of integers by column

后端 未结 2 838
攒了一身酷
攒了一身酷 2021-01-23 08:03

I need to build a method in Java where the input is a 2D array of integers and get as a result a 2D array of integers where each element makes reference to a position of an elem

2条回答
  •  死守一世寂寞
    2021-01-23 08:19

    Sorting the indexes of matrix elements by columns is sorting the indexes of elements by the rows of a transposed matrix:

    int m = 5;
    int n = 6;
    int[][] arr1 = new int[][]{
            {124, 188, 24, 254, 339, 3},
            {0, 7, 77, 145, 159, 1},
            {206, 340, 280, 523, 433, 5},
            {310, 265, 151, 411, 398, 4},
            {24, 104, 0, 183, 198, 2}};
    
    int[][] arr2 = IntStream
            // iterate over the indices
            // of the rows of the array
            .range(0, n)
            .mapToObj(i -> IntStream
                    // iterate over the
                    // indices of the columns
                    .range(0, m)
                    .boxed()
                    // sort indices of the elements of the
                    // columns by its values in the array
                    .sorted(Comparator.comparingInt(j -> arr1[j][i]))
                    .mapToInt(Integer::intValue)
                    // sorted column of indices is
                    // a row in the new array
                    .toArray())
            // return sorted array of indices
            .toArray(int[][]::new);
    
    // transpose the array of indices
    int[][] arr3 = new int[m][n];
    IntStream.range(0, m).forEach(i ->
            IntStream.range(0, n).forEach(j ->
                    arr3[i][j] = arr2[j][i]));
    
    // output
    Arrays.stream(arr3).map(Arrays::toString).forEach(System.out::println);
    

    Output:

    [1, 1, 4, 1, 1, 1]
    [4, 4, 0, 4, 4, 4]
    [0, 0, 1, 0, 0, 0]
    [2, 3, 3, 3, 3, 3]
    [3, 2, 2, 2, 2, 2]
    

提交回复
热议问题