## ## Slide 0.12 - do the counting ## nrows <- 7 ncols <- 7 alive <- matrix(0, nrows+2, ncols+2) # "+2" is adding the gray border # add some "alive" cells - see question sheet for giving random entries alive[4,4:6] <- 1 alive[7:8,7] <- 1 # do the neighbour counting - only for the non-gray cells neebs <- matrix(0, nrows+2, ncols+2) for(i in 2:(nrows+1)){ for(j in 2:(ncols+1)){ neebs[i,j] <- alive[i-1,j-1] + alive[i-1,j ] + alive[i-1,j+1] + alive[i ,j-1] + alive[i ,j+1] + alive[i+1,j-1] + alive[i+1,j ] + alive[i+1,j+1] # adding over the 8 neighbors } # close j loop } # close i loop ## ## Slide 0.13 - Plotting status ## plot(0,0, type="n", xlab="", ylab="", axes=F, xlim=c(0.5,nrows+0.5), ylim=c(0.5,ncols+0.5), asp=1) for(i in 1:nrows){ for(j in 1:ncols){ rect(j-0.5,i-0.5,j+0.5,i+0.5, col=alive[i+1,j+1] + 1, border="cyan") } } ## ## Slide 0.15 - check your counting ## for(i in 1:nrows){ for(j in 1:ncols){ text(j,i, neebs[i+1,j+1], col="white") }} ## ## Slide 0.14 - update the "alive" status ## alive.new <- matrix(0, nrows+2, ncols+2) # note full of zeros for(i in 2:(nrows+1)){ for(j in 2:(ncols+1)){ if(alive[i,j]==1 & neebs[i,j]<2 ){ alive.new[i,j] <- 0 } if(alive[i,j]==1 & neebs[i,j]%in%2:3){ alive.new[i,j] <- 1 } if(alive[i,j]==1 & neebs[i,j]>3 ){ alive.new[i,j] <- 0 } if(alive[i,j]==0 & neebs[i,j]==3 ){ alive.new[i,j] <- 1 } } } alive <- alive.new