Skip to content

Instantly share code, notes, and snippets.

@shangaslammi
Last active December 28, 2015 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shangaslammi/7412058 to your computer and use it in GitHub Desktop.
Save shangaslammi/7412058 to your computer and use it in GitHub Desktop.
Recursive, single-pass, constant space solution to the watershed problem.
import Data.Array
waterVolume :: Array Int Int -> Int
waterVolume arr = go 0 minB maxB where
(minB,maxB) = bounds arr
go !acc lpos rpos
| lpos >= rpos = acc
| leftHeight < rightHeight = segment leftHeight 1 acc lpos contLeft
| otherwise = segment rightHeight (-1) acc rpos contRight
where
leftHeight = arr ! lpos
rightHeight = arr ! rpos
contLeft acc' pos' = go acc' pos' rpos
contRight acc' pos' = go acc' lpos pos'
segment limit move !acc' !pos cont
| delta <= 0 = cont acc' pos'
| otherwise = segment limit move (acc' + delta) pos' cont
where
delta = limit - arr ! pos'
pos' = pos + move
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment