# 1396. Design Underground System
###### tags: `Hash`, `Implementation`, `OOP`, `Bloomberg`
Description:
An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.
Implement the `UndergroundSystem` class:
* `void checkIn(int id, string stationName, int t)`
* A customer with a card ID equal to `id`, checks in at the station `stationName` at time `t`.
* A customer can only be checked into one place at a time.
* `void checkOut(int id, string stationName, int t)`
* A customer with a card ID equal to id, checks out from the station stationName at time t.
* `double getAverageTime(string startStation, string endStation)`
* Returns the average time it takes to travel from `startStation` to `endStation`.
* The average time is computed from all the previous traveling times from `startStation` to `endStation` that happened **directly**, meaning a check in at `startStation` followed by a check out from `endStation`.
* The time it takes to travel from `startStation` to `endStation` **may be different** from the time it takes to travel from endStation to `startStation`.
* There will be at least one customer that has traveled from `startStation` to `endStation` before getAverageTime is called.
You may assume all calls to the `checkIn` and `checkOut` methods are consistent. If a customer checks in at time `t1` then checks out at time `t2`, then `t1 < t2`. All events happen in chronological order.
Solution:
```java=
class Customer {
String startStation;
String endStation;
int startTime;
int endTime;
public Customer(String startStation, int startTime) {
this.startStation = startStation;
this.startTime = startTime;
}
public void checkout(String endStation, int endTime) {
this.endStation = endStation;
this.endTime = endTime;
}
}
class Route {
int count;
int totalTime;
public Route() {
this.count = 0;
this.totalTime = 0;
}
public void update(int time) {
count++;
totalTime += time;
}
public double getAvg() {
return (double)totalTime / count;
}
}
class UndergroundSystem {
Map<Integer, Customer> cusInSystem;
Map<String, Route> routeRecord;
public UndergroundSystem() {
this.cusInSystem = new HashMap<>();
this.routeRecord = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
cusInSystem.put(id, new Customer(stationName, t));
}
public void checkOut(int id, String stationName, int t) {
Customer c = cusInSystem.get(id);
c.checkout(stationName, t);
updateRouteRecord(c);
cusInSystem.remove(id);
}
private void updateRouteRecord(Customer c) {
String route = c.startStation + "-" + c.endStation;
if (!routeRecord.containsKey(route)) {
routeRecord.put(route, new Route());
}
Route r = routeRecord.get(route);
r.update(c.endTime - c.startTime);
}
public double getAverageTime(String startStation, String endStation){
String route = startStation + "-" + endStation;
return routeRecord.get(route).getAvg();
}
}
```