Skip to content

Instantly share code, notes, and snippets.

@phil8192
Created November 2, 2018 19:10
Show Gist options
  • Select an option

  • Save phil8192/cf153ecee3540fbab4c2afa6d87fce1e to your computer and use it in GitHub Desktop.

Select an option

Save phil8192/cf153ecee3540fbab4c2afa6d87fce1e to your computer and use it in GitHub Desktop.
R solution to twitter waterflow problem
# 1 line
function(x) sum(head(tail(pmin(cummax(x),rev(cummax(rev(x))))-x,-1),-1))
# or with fancy ascii visualisation!
#
# > water(x)
# $water
# [1] 10
#
# $vis
# [,1]
# [1,] "XX"
# [2,] "XXXXX"
# [3,] "XOOOO"
# [4,] "XXOOO"
# [5,] "XXXOO"
# [6,] "XXXXO"
# [7,] "XXXXXXX"
# [8,] "XXXXXXX"
# [9,] "XXXXXX"
water <- function(x) {
pools <- head(tail(pmin(cummax(x),rev(cummax(rev(x))))-x,-1),-1)
p.vis <- matrix(do.call(paste0,lapply(list(list("X",x),list("O",c(0,pools,0))),function(x)do.call(function(s,x)lapply(x,function(x)paste0(rep(s,x),collapse="")),x))))
list(water=sum(pools), vis=p.vis)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment