Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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))
- percolate.board = function(mat) {
- assert_that(is.valid(mat))
- assert_that(onlyZerosandOnes(mat))
- #top row of matrix with empty cells is filled with 'water'
- for (i in 1:ncol(mat)) {
- if (mat[1,i] == 1) mat[1,i] = 2
- }
- while (TRUE) {
- #check to see if the matrix changes at all
- oldMat = mat
- #keeps track of all the indices where a 1 appears
- onesIndex = list()
- #returns a matrix with TRUEs and FALSEs
- onesMatrix = (mat == 1)
- index = 1
- for (r in 1:nrow(onesMatrix)) {
- for (c in 1:ncol(onesMatrix)) {
- if (onesMatrix[r,c]) {
- onesIndex[[index]] = c(r,c)
- index = index + 1
- }
- }
- }
- if (length(onesIndex) == 0) break
- #loop over the list containing the indices of the 1s
- for (i in 1:length(onesIndex)) {
- row = onesIndex[[i]][1]
- col = onesIndex[[i]][2]
- left = col - 1
- right = col + 1
- top = row - 1
- bottom = row + 1
- if (1 <= left & left <= ncol(mat)) {
- if (mat[row, left] == 2) mat[row, col] = 2
- }
- if (1 <= right & right <= ncol(mat)) {
- if (mat[row, right] == 2) mat[row, col] = 2
- }
- if (1 <= top & top <= nrow(mat)) {
- if (mat[top, col] == 2) mat[row, col] = 2
- }
- if (1 <= bottom & bottom <= nrow(mat)) {
- if (mat[bottom, col] == 2) mat[row, col] = 2
- }
- }
- if (all(mat == oldMat)) break
- }
- result = FALSE
- #check if matrix percolated or not
- for (i in 1:ncol(mat)) {
- if (mat[nrow(mat),i] == 2) result = TRUE
- }
- return(list(result.mat = mat, result = result))
- }
- par(mfrow = c(2,3))
- for (i in 1:3) {
- plot.board(mat.example.list[[i]])
- plot.board(percolate.board(mat.example.list[[i]])[["result.mat"]])
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement