Skip to content

Instantly share code, notes, and snippets.

@dnavas77
Created January 22, 2020 04:09
Show Gist options
  • Save dnavas77/074d5fa95162552df47e8504d2954e4c to your computer and use it in GitHub Desktop.
Save dnavas77/074d5fa95162552df47e8504d2954e4c to your computer and use it in GitHub Desktop.
package practice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
class Result {
static private int totalLines = 0;
static private Map<String, SaleRecord> allsales = new HashMap<>();
static class SaleRecord {
private int unitsSold = 0;
private int maxBrandCount = 0;
private String maxBrand;
private Map<String, Integer> brandCount = new HashMap<>();
public SaleRecord(int qtySold, String brand) {
this.add(qtySold);
this.addBrand(brand);
}
public void add(int qty) {
this.unitsSold += qty;
}
public void addBrand(String brand) {
Integer s = brandCount.get(brand);
if (s == null) {
brandCount.put(brand, Integer.valueOf(1));
if (1 > maxBrandCount) {
maxBrandCount = 1;
maxBrand = brand;
}
} else {
int temp = s + 1;
if (temp > maxBrandCount) {
maxBrandCount = temp;
maxBrand = brand;
}
brandCount.put(brand, Integer.valueOf(temp));
}
}
public String getMaxBrand() {
return this.maxBrand;
}
public int getUnitsSold() {
return this.unitsSold;
}
}
public static void generateFiles(String filename) throws Exception {
Files.lines(Paths.get(filename)).forEach(Result::ProcessLine);
String[] out0 = new String[1];
String[] out1 = new String[1];
allsales.forEach((product, sr) -> {
out0[0] += product + "," + ((double)sr.getUnitsSold() / (double)totalLines) + "\n";
out1[0] += product + "," + sr.getMaxBrand() + "\n";
});
String _filename = filename.substring(0,filename.length()-4);
Files.write(Paths.get(_filename+"_0.csv"), out0[0].getBytes(), StandardOpenOption.CREATE);
Files.write(Paths.get(_filename+"_1.csv"), out1[0].getBytes(), StandardOpenOption.CREATE);
}
static private void ProcessLine(String line) {
totalLines += 1;
String[] tokens = line.split(",");
String product = tokens[2];
String brand = tokens[4];
int qtySold = Integer.parseInt(tokens[3]);
SaleRecord sr = allsales.get(product);
if (sr == null) {
allsales.put(product, new SaleRecord(qtySold, brand));
} else {
sr.add(qtySold);
sr.addBrand(brand);
allsales.put(product, sr);
}
}
}
public class ReadAndParseCSV {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String input_file;
input_file = bufferedReader.readLine();
Result.generateFiles(input_file);
bufferedReader.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment