R/utils.R

Defines functions generate_board_mat is_valid str_to_board read_boards

Documented in generate_board_mat is_valid read_boards

#' Generate Board Matrix
#'
#' @param n a positive integer of side length
#' @param p proportion of blocked cells
#' @import assertthat
#' @return matrix representing the board
#' @export
#'
#' @examples generate_board_mat()
#' @examples generate_board_mat(n = 8, p = 0.75)
generate_board_mat = function(n = 5,p = 0.25){
  assertthat::assert_that(length(n) == 1 && length(p) == 1 &&
                is.numeric(n) && is.numeric(p) &&
                n %% 1 == 0 && n > 0 &&
                p >= 0 && p <= 1)
  prop_blocked = n^2 * p
  board_vec = rep(1, n^2)
  block_locations = sample(1:n^2, prop_blocked, replace = FALSE)
  board_vec[block_locations] = 0
  mat = matrix(board_vec, nrow = n, ncol = n)
  return(mat)
}

#' is_valid
#'
#' @param mat a matrix to be used as a board
#' @import assertthat
#' @return T/F if the matrix is valid or not
#' @export
#' @import assertthat
#' @examples is_valid(mat)
is_valid = function(mat){
  assert_that(is.matrix(mat) && nrow(mat) == ncol(mat) &&
                all(mat == 0 | mat == 1 | mat == 2))
  return(TRUE)
}




str_to_board = function(v){ #helper fn for read_boards()
  if (is.na(as.integer(v[1]))) {return(NA)}
  num = as.integer(v[1])
  if (!(num > 0 && nchar(v[2]) == num^2)) {return(NA)}
  b_vec = strsplit(v[2],"")[[1]]
  if(!all(b_vec == "." | b_vec == "*")) {return(NA)}
  b_vec = ifelse(b_vec == "*", 0, 1)
  mat = matrix(b_vec, nrow = num, ncol = num, byrow = TRUE)
  b = board(mat = mat)
  return(b)
}

#' read_boards
#'
#' @param path path to filename or url
#' @import testthat
#' @return list of boards read in from the text in path
#' @export
#'
#' @examples read_boards("https://raw.githubusercontent.com/benjaminleroy/36-350-summer-data/master/Week5/percolation_write_example.txt")
read_boards = function(path){
  raw_text = readLines(path)
  expect_true(any(grepl("----", raw_text)))
  sep_inds = which(raw_text == "----")
  expect_true(1 %in% sep_inds && length(raw_text) %in% sep_inds, "file not formatted properly")
  text_str = paste(raw_text, collapse =  "\n")
  mat_str = strsplit(text_str, "----")[[1]]

  mat_str = lapply(mat_str, FUN = function(txt){strsplit(txt, "\n")[[1]][-1]}) #because each line begins with \n
  mat_str = mat_str[-1] #because file starts with ----
  mat_str = lapply(mat_str, FUN = function(v){return(c(v[1], paste(v[-1], collapse = "")))})
  a = lapply(mat_str, FUN = function(v){c(v[1], paste(strsplit(v[2], " ")[[1]],collapse = ""))})
  b_list = lapply(a, FUN = str_to_board)
  expect_true(length(b_list) == length(which(raw_text == "----")) -1, "file not formatted correctly")
  return(b_list)
}
Achowdh1/percolate documentation built on Oct. 30, 2019, 4:09 a.m.