Row Sums and Column Sums
Problem
Read a matrix. Print two lines. The first line is rows: followed by the sum of each row. The second line is columns: followed by the sum of each column.
Constraints
- 1 <= r, c <= 100
Examples
Input
2 3 1 2 3 4 5 6
Output
rows: 6 15 columns: 5 7 9
Solutions
A single pass over all elements fills both sum arrays: element (i, j) adds to row i and to column j.
/*
* Problem : Process a matrix.
* Input : r and c, then r rows of c integers.
* Output : Two lines.
* Approach: One pass for both sums.
* Time : O(r * c)
* Space : O(r + c)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(int[][] m) {
int rows = m.length;
int cols = m[0].length;
// Step 1: One sum for each row and one sum for each column.
long[] rowSums = new long[rows];
long[] colSums = new long[cols];
// Step 2: Add every element to its row sum and to its column sum.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rowSums[i] += m[i][j];
colSums[j] += m[i][j];
}
}
// Step 3: Make the two output lines.
StringBuilder first = new StringBuilder("rows:");
for (long sum : rowSums) {
first.append(" ").append(sum);
}
StringBuilder second = new StringBuilder("columns:");
for (long sum : colSums) {
second.append(" ").append(sum);
}
return new String[] {first.toString(), second.toString()};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = scanner.nextInt();
}
}
System.out.println(String.join("\n", solve(m)));
}
}
Hints (1)
- To which two sums does element (i, j) belong?