Sum a CSV Column
Problem
The first line is the CSV header (names separated by commas). The second line is the name of a column. Every next line is a data row with whole numbers or text, also separated by commas. Print the sum of the values in the named column. All values in that column are integers. If there are no data rows, print 0.
Constraints
- 1 <= columns <= 20
- 0 <= rows <= 10^4
- No quoted commas
Examples
Input
name,age,score score Asha,20,90 Ravi,25,85
Output
175
Solutions
CSV is just text. We find the index of the column in the header, and then read that index in every row. For real CSV files with quoted commas use a CSV library.
/*
* Problem : Sum a CSV column.
* Input : Header, a column name, data rows.
* Output : The sum.
* Approach: Find the column index first.
* Time : O(rows * columns)
* Space : O(columns)
* 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 long solve(String[] lines) {
// Step 1: The first line has the column names. Find the position of the wanted column.
String[] header = lines[0].split(",");
int column = java.util.Arrays.asList(header).indexOf(lines[1]);
// Step 2: Read every data row, take the value at that position and add it.
long sum = 0;
for (int i = 2; i < lines.length; i++) {
String[] cells = lines[i].split(",");
sum += Long.parseLong(cells[column].trim());
}
return sum;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(solve(lines));
}
}
Hints (1)
- How do you find the position of a column name?