Skip to content

Instantly share code, notes, and snippets.

@harrytallbelt
Created May 18, 2016 15:44
Show Gist options
  • Save harrytallbelt/cc236e710c9edf858853c118bc38c9ad to your computer and use it in GitHub Desktop.
Save harrytallbelt/cc236e710c9edf858853c118bc38c9ad to your computer and use it in GitHub Desktop.
F# solution for water on land problem
let oneWayCapacity a =
let mutable max = 0
a |> List.map (fun e -> if e > max then max <- e; 0 else max - e)
let totalCapacity a =
let aL = a |> oneWayCapacity
let aR = a |> List.rev |> oneWayCapacity |> List.rev
List.map2 min aL aR |> List.sum
let test a =
a |> totalCapacity |>
printfn "totalCapacity %A = %i" a
let () =
[1; 2; 1; 3; 5; 3; 1; 2; 4; 1] |> test
[2; 5; 10; 7; 3; 8; 5; 2] |> test
[2; 5; 1; 2; 3; 4; 7; 7; 6] |> test
(* Task description
calculate how much water * will be left
on the land after the rain for any given array
_ _
|7 7|_
_ | 6|
|5|* * * *| |
| |* * *|4 |
_| |* *|3 |
2 |*|2 |
1
[2,5,1,2,3,4,7,7,6] gives answer of 10
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment