#' Title
#'
#' @param x
#' @param ...
#'
#' @return percolate method
#' @export
#'
#' @examples
percolate <- function(x, ...){
UseMethod("percolate")}
#' get_neighbors
#'
#' @param boardobj
#' @param i
#'
#' @return neighboring cells
#' @export
#'
#' @examples
get_neighbors = function(boardobj, i){
n = nrow(boardobj)
i2 = i - 1
col =as.integer((i2 / n)) + 1
row = i2 %% n + 1
res = c((i + 1)[row < n], (i - 1)[row > 1], (i + n)[col < n], (i - n)[col > 1] )
return(res[!(res %in% i)])
}
#' percolate
#'
#' @param start_board a board object to be percolated
#'
#' @return a list containing the field result: a T/F indicating whether or not the board percolated and
#' result_board: a board object after the percolation
#' @export
#'
#' @examples m = board(generate_board_mat(n = 100, p = 0.4)); plot(percolate(m)$result_board)
#'
#'
#' mat_example_list <- list(matrix(c(1,1,1,1,0,
#'0,0,0,1,0,
#'1,1,1,1,0,
#'0,1,0,0,0,
#'0,1,1,1,1), 5, 5),
#'matrix(c(1,1,1,1,0,
#' 0,0,0,1,0,
#' 0,1,1,1,0,
#' 0,1,0,0,0,
#' 0,1,1,1,1), 5, 5),
#'matrix(c(1,1,1,1,0,
#' 0,0,0,1,0,
#' 0,1,1,0,0,
#' 0,1,0,0,0,
#' 0,1,1,1,1), 5, 5))
#'
#'mat_boards = lapply(mat_example_list, FUN = board)
#'mat_perc_boards = lapply(mat_boards, FUN = function(b)(percolate(b)$result_board))
#'all = c(mat_boards, mat_perc_boards)
#'mat_plots = lapply(all, FUN = plot)
#'library(gridExtra)
#'grid.arrange(grobs = mat_plots, ncol = 3, nrow = 2)
#'
#'
#'
#'
#'
#'
#'
#'
#'
#'
percolate.board = function(start_board){
# set all empty cells in row 1 to full
n = nrow(start_board)
start_board[1,] = ifelse(start_board[1,] == 1, 2, 0)
wet_squares_ind = which(start_board == 2)
adj_squares_ind = get_neighbors(start_board, wet_squares_ind)
available_squares_ind =adj_squares_ind[start_board[adj_squares_ind] == 1]
while(length(available_squares_ind) > 0){
start_board[available_squares_ind] = 2
wet_squares_ind = which(start_board == 2)
adj_squares_ind = get_neighbors(start_board, wet_squares_ind)
available_squares_ind =adj_squares_ind[start_board[adj_squares_ind] == 1]
}
return(list(result_board = start_board,
result = any(start_board[nrow(start_board),] == 2)))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.