design-underground-system.dart (1772B)
1 //This theoretically has an issue, but in 2 //reality the issue is with the question and not my implementation 3 //thus I consider this correct as it does what is expected 4 //which is tracking entry and exit and finding the average time 5 //for a single hop between the two. 6 7 //To solve this I created a trip class which just stores where 8 //a given user started and at what time. This is placed as the value 9 //for the key which is the user's id. 10 //Then from here when the user leaves you take the end time - start time 11 //and add it to the total time to travel from one station to another along with 12 //iterating the total number of trips by 1 to be able to find the mean. 13 14 class UndergroundSystem { 15 Map<int, Trip> travelling_users = {}; 16 Map<String, List<int>> trip_times = {}; 17 18 void checkIn(int id, String stationName, int t) { 19 if(travelling_users.containsKey(id)){ 20 return; 21 } 22 travelling_users[id] = new Trip( stationName,t); 23 } 24 25 void checkOut(int id, String stationName, int t) { 26 Trip current_trip = (travelling_users[id] ?? new Trip('',0)); 27 String locations = current_trip.start_name + " " + stationName; 28 List<int> this_trip_time = (trip_times[locations] ?? [0,0]); 29 this_trip_time[0] += 1; 30 this_trip_time[1] += t - current_trip.start_time; 31 trip_times[locations] = this_trip_time; 32 } 33 34 double getAverageTime(String startStation, String endStation) { 35 List<int> spec_trip = (trip_times[startStation + " " + endStation] ?? []); 36 double average = spec_trip[1] / spec_trip[0]; 37 return average; 38 } 39 } 40 41 42 class Trip{ 43 String start_name = ""; 44 int start_time = 0; 45 Trip(String _start_name, int _start_time){ 46 start_name = _start_name; 47 start_time = _start_time; 48 } 49 50 }