Round 3 - Data Parsing
unknown
plain_text
4 years ago
3.4 kB
8
Indexable
/* Your manager has asked you to devise a quick program that will parse an input file containing usage data for your service and output information of the user with the most usage for a provided time period. In particular he is interested in the human-friendly name, the unique id, and the total usage of that user in the time period. The file format is:
Name,ID,Usage,Year,Month,Day
e.g.
Bob Wiley,123456789,90.0,2021,10,03
Frodo Baggins,987654321,50.0,2021,10,05
Frodo Baggins,987654321,50.0,2021,10,06
If your program would run with a time range of 2021-10-01 to 2021-10-05, it would return information about the Bob user who had the most usage. However, if you ran your program for a time range of 2021-10-01 to 2021-10-06, it would return information about the Frodo user.
Invalid Records:
Bob Wiley,90.0,2021,10,03
Frodo Baggins,987654321,50.0,2023,10,06
*/
import java.util.Date;
public class Person {
String name;
String id;
public Person(String name, String id) {
this.name = name;
this.id = id;
}
}
public class Record {
Person person;
double usage;
public Record(Person person, double usage) {
this.person = person;
this.usage = usage;
}
}
public class Main {
Map<Date, List<Record>> recordsByDate;
public Main(){
this.recordsByDate = new HashMap<>();
}
// Assumption: All records are valid
public void parseRecords(List<String> records) {
for (String record: records) {
List<String> entries = record.split(",");
Date date = toTimestamp(entries.getItem(3), entries.getItem(4), entries.getItem(5));
Person person = new Person(entries.getItem(0), entries.getItem(1));
Record parsedRecord = new Record(person, entries.getItem(2));
List<Record> currentRecords = recordsByDate.getOrDefault(date, new ArrayList<>());
currentRecords.add(parsedRecord);
recordsByDate.put(date, currentRecords);
}
}
public Date toTimestamp(int year, int month, int day) {
Date date = new Date(year, month, day);
return date;
}
public Person mostUsage(Date startDate, Date endDate) {
int startDays = startDate.getDay(); // number days
int endDays = endDate.getDay();
int numberOfDays = startDays - endDays;
Map<Person, Double> usageMap = new HashMap<>();
for (int i = startDays; i <= endDays; i++) {
Date day = new Date(startDays); // Assumption: constructor takes in day to convert number of days to Date
List<Record> records = recordsByDate.getOrDefault(day, new ArrayList<>());
for (Record record:records) {
Double usage = usageMap.getOrDefault(record.person, 0);
usage += record.usage;
usageMap.put(record.person, usage);
}
}
Double max = 0.0;
Person person;
for (MapEntry<Person, Double> entry : usageMap.keySet()) {
double currentUsage = entry.value;
Person currentPerson = entry.key;
if (currentUsage > max) {
max = currentUsage;
person = currentPerson;
}
}
return person;
}
}Editor is loading...