# 如何根据列的总和来组织二维数组的列？

go评论53阅读模式

How to organize columns of 2D array based on sum of columns?

# 问题

I would like to organize a 2D array in descending order of each columns sum. For example:

``````3 1 1
2 6 5
5 4 2
``````

The sum of column 1 would be 10, column 2 would be 11, column 3 would be 8. Columns 2 and 1 would need to switch to be sorted in descending order. The updated 2D array would be:

``````1 3 1
6 2 5
4 5 2
``````

I'm aware of `Collections.reverseOrder()`, but that only works on sorting 1D arrays in descending order.

Here is the code I am using to get the sum of each column:

``````int tempSum = 0;
for (int i = 0; i &lt; columns; i++) {
for (int j = 0; j &lt; rows; j++) {
tempSum = array[i][j]
}
//reset tempSum
tempSum = 0;
}
``````

I am currently not doing anything with the tempSum of each column. Any guidance would be great.

# 答案1

``````int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] transposed = new int[cols][rows];
for (int r = 0; r < rows; ++r)
for (int c = 0; c < cols; ++c)
transposed[c][r] = matrix[r][c];
return transposed;
}

int[][] m = {
{3, 1, 1, 9},
{2, 6, 5, 4},
{5, 4, 2, 6}};
m = transpose(m);
Arrays.sort(m, Collections.reverseOrder(Comparator.comparingInt(row -> IntStream.of(row).sum())));
m = transpose(m);
for (int[] row : m)
System.out.println("\t" + Arrays.toString(row));
``````

``````	[9, 1, 3, 1]
[4, 6, 2, 5]
[6, 4, 5, 2]
``````

``````m = transpose(m);
m = Arrays.stream(m)
.map(row -> new Object() {
int sum = IntStream.of(row).sum();
int[] origin = row;
})
.sorted((a, b) -> Integer.compare(b.sum, a.sum))
.map(obj -> obj.origin)
.toArray(int[][]::new);
m = transpose(m);
``````

Try this.

``````int[][] transpose(int[][] matrix) {
int rows = matrix.length, cols = matrix[0].length;
int[][] transposed = new int[cols][rows];
for (int r = 0; r &lt; rows; ++r)
for (int c = 0; c &lt; cols; ++c)
transposed[c][r] = matrix[r][c];
return transposed;
}
``````

And

``````int[][] m = {
{3, 1, 1, 9},
{2, 6, 5, 4},
{5, 4, 2, 6}};
m = transpose(m);
Arrays.sort(m, Collections.reverseOrder(Comparator.comparingInt(row -&gt; IntStream.of(row).sum())));
m = transpose(m);
for (int[] row : m)
System.out.println(&quot;\t&quot; + Arrays.toString(row));
``````

output

``````[9, 1, 3, 1]
[4, 6, 2, 5]
[6, 4, 5, 2]
``````

Or if you need more performance

``````m = transpose(m);
m = Arrays.stream(m)
.map(row -&gt; new Object() {
int sum = IntStream.of(row).sum();
int[] origin = row;
})
.sorted((a, b) -&gt; Integer.compare(b.sum, a.sum))
.map(obj -&gt; obj.origin)
.toArray(int[][]::new);
m = transpose(m);
``````

• 本文由 发表于 2020年7月28日 09:54:12
• 转载请务必保留本文链接：https://go.coder-hub.com/63125933.html
• arrays
• java
• multidimensional-array
• sorting

go 68

go 54

go 65

go 49