Advertisement
Guest User

Untitled

a guest
Apr 16th, 2018
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. 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),
  2. 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),
  3. 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))
  4.  
  5. percolate.board = function(mat) {
  6. assert_that(is.valid(mat))
  7. assert_that(onlyZerosandOnes(mat))
  8. #top row of matrix with empty cells is filled with 'water'
  9. for (i in 1:ncol(mat)) {
  10. if (mat[1,i] == 1) mat[1,i] = 2
  11. }
  12. while (TRUE) {
  13. #check to see if the matrix changes at all
  14. oldMat = mat
  15. #keeps track of all the indices where a 1 appears
  16. onesIndex = list()
  17. #returns a matrix with TRUEs and FALSEs
  18. onesMatrix = (mat == 1)
  19. index = 1
  20. for (r in 1:nrow(onesMatrix)) {
  21. for (c in 1:ncol(onesMatrix)) {
  22. if (onesMatrix[r,c]) {
  23. onesIndex[[index]] = c(r,c)
  24. index = index + 1
  25. }
  26. }
  27. }
  28. if (length(onesIndex) == 0) break
  29. #loop over the list containing the indices of the 1s
  30. for (i in 1:length(onesIndex)) {
  31. row = onesIndex[[i]][1]
  32. col = onesIndex[[i]][2]
  33. left = col - 1
  34. right = col + 1
  35. top = row - 1
  36. bottom = row + 1
  37.  
  38. if (1 <= left & left <= ncol(mat)) {
  39. if (mat[row, left] == 2) mat[row, col] = 2
  40. }
  41. if (1 <= right & right <= ncol(mat)) {
  42. if (mat[row, right] == 2) mat[row, col] = 2
  43. }
  44. if (1 <= top & top <= nrow(mat)) {
  45. if (mat[top, col] == 2) mat[row, col] = 2
  46. }
  47. if (1 <= bottom & bottom <= nrow(mat)) {
  48. if (mat[bottom, col] == 2) mat[row, col] = 2
  49. }
  50. }
  51.  
  52. if (all(mat == oldMat)) break
  53. }
  54. result = FALSE
  55. #check if matrix percolated or not
  56. for (i in 1:ncol(mat)) {
  57. if (mat[nrow(mat),i] == 2) result = TRUE
  58. }
  59.  
  60. return(list(result.mat = mat, result = result))
  61. }
  62.  
  63. par(mfrow = c(2,3))
  64.  
  65. for (i in 1:3) {
  66. plot.board(mat.example.list[[i]])
  67. plot.board(percolate.board(mat.example.list[[i]])[["result.mat"]])
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement