How to resolve the algorithm One-dimensional cellular automata step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm One-dimensional cellular automata step by step in the R programming language

Table of Contents

Problem Statement

Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm One-dimensional cellular automata step by step in the R programming language

Source code in the r programming language

set.seed(15797, kind="Mersenne-Twister")

maxgenerations = 10
cellcount = 20
offendvalue = FALSE

## Cells are alive if TRUE, dead if FALSE
universe <- c(offendvalue,
              sample( c(TRUE, FALSE), cellcount, replace=TRUE),
              offendvalue)

## List of patterns in which the cell stays alive
stayingAlive <- lapply(list(c(1,1,0),
                            c(1,0,1),
                            c(0,1,0)), as.logical)

## x : length 3 logical vector
## map: list of length 3 logical vectors that map to patterns
##      in which x stays alive
deadOrAlive <- function(x, map) list(x) %in% map

cellularAutomata <- function(x, map) {
    c(x[1], apply(embed(x, 3), 1, deadOrAlive, map=map), x[length(x)])
}

deadOrAlive2string <- function(x) {
    paste(ifelse(x, '#', '_'), collapse="")
}

for (i in 1:maxgenerations) {
    universe <- cellularAutomata(universe, stayingAlive)
    cat(format(i, width=3), deadOrAlive2string(universe), "\n")
}


  

You may also check:How to resolve the algorithm Determine if a string has all the same characters step by step in the Ruby programming language
You may also check:How to resolve the algorithm Pick random element step by step in the TUSCRIPT programming language
You may also check:How to resolve the algorithm Ray-casting algorithm step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Draw a sphere step by step in the D programming language
You may also check:How to resolve the algorithm Sierpinski triangle step by step in the PicoLisp programming language