![](/img/trans.png)
[英]How do I sum the values in the row of a 2D array separately, and sum the values in the column separately? (Java)
[英]Java 2D array (matrix). Sum of each row separately
我知道如何掃描如何打印矩陣。 我也知道如何得到每一行的總和。
我的任務是掃描矩陣,然后分別計算每一行的總和,然后制作新矩陣並排除總和最小的行。
嘗試這個。
public static void main(String[] args) {
int[][] matrix = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8}};
int minRowSum = Stream.of(matrix)
.mapToInt(row -> IntStream.of(row).sum())
.min().getAsInt();
int[][] result = Stream.of(matrix)
.filter(row -> IntStream.of(row).sum() > minRowSum)
.toArray(int[][]::new);
for (int[] row : result)
System.out.println(Arrays.toString(row));
}
output:
[3, 4, 5]
[6, 7, 8]
如果只需要刪除總和最小的第一行,則可能需要找到最小行的索引。
此外,在第二遍中不計算行總和。
public static int[][] removeMinRow(int[][] data) {
int indexOfMinRow = IntStream.range(0, data.length)
.boxed()
.min(Comparator.comparingInt(i -> Arrays.stream(data[i]).sum()))
.orElse(-1);
if (indexOfMinRow == -1) {
return data; // nothing to delete from
}
int[][] result = new int[data.length - 1][];
for (int i = 0, j = 0; i < data.length; i++) {
if (i != indexOfMinRow) {
result[j++] = data[i]; // reassigning references to rows
}
}
return result;
}
測試:
int[][] data = {
{3, 4, 5},
{0, 2, 1},
{6, 7, 8},
{0, 1, 2},
};
System.out.println(Arrays.deepToString(removeMinRow(data)));
Output(僅刪除索引 1 處的行):
[[3, 4, 5], [6, 7, 8], [0, 1, 2]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.