LeetCode 1396. Design Underground System in F#
URL
Design Underground System - LeetCode
Code
type UnderGroundSystem =
{
checkIns : Map<int, (string * int)>
times: Map<(string * string), (int * int)>
}
static member init() : UnderGroundSystem =
{
checkIns = Map.empty; times = Map.empty
}
static member checkIn (id: int) (stationName: string) (t: int) (u: UnderGroundSystem) : UnderGroundSystem =
let checkIns' = Map.add id (stationName, t) u.checkIns
{ u with checkIns = checkIns'}
static member checkOut(id :int) (stationName: string) (t: int) (u: UnderGroundSystem) : UnderGroundSystem =
match Map.tryFind id u.checkIns with
| None -> failwith "never reach here"
| Some((startStation, startTime)) ->
let checkIns' = Map.remove id u.checkIns
let key = (startStation, stationName)
let diff = t - startTime
let times = match Map.tryFind key u.times with
| Some((numbers, total)) ->
Map.add key (numbers + 1, total + diff) u.times
| None ->
Map.add key (1, diff) u.times
{ checkIns = checkIns'; times = times }
static member getAverageTime(startStation: string) (endStation: string) (u: UnderGroundSystem) : double =
match Map.tryFind (startStation, endStation) u.times with
| Some((count, total)) ->
(double total) / (double count)
| None ->
match Map.tryFind (endStation, startStation) u.times with
| Some((count, total)) ->
(double total) / (double count)
| None ->
failwith "never reach here"