Created
November 2, 2018 19:10
-
-
Save phil8192/cf153ecee3540fbab4c2afa6d87fce1e to your computer and use it in GitHub Desktop.
R solution to twitter waterflow problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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