英文:
How to organize columns of 2D array based on sum of columns?
问题
我想要按每列的和降序排列一个2D数组。例如:
列1的总和是10,列2的总和是11,列3的总和是8。需要将列2和列1按降序排序。更新后的2D数组如下:
这是我用来获取每列总和的代码:
我目前还没有对每列的tempSum进行任何操作。希望能提供一些指导。
英文:
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 < columns; i++) {
for (int j = 0; j < 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
得分: 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 < rows; ++r)
for (int c = 0; c < 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 -> IntStream.of(row).sum())));
m = transpose(m);
for (int[] row : m)
System.out.println("\t" + 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 -> 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论