Caves Travel Diving Graphics Mizar Texts Cuisine Lemkov Contact Map RSS Polski
Trybiks' Dive Texts R Conway's Game of Life... in R YAC Software
  Back

List

Charsets

Charts

DBExpress

Delphi

HTML

Intraweb

MSTest

PHP

Programming

R

Rhino Mocks

Software

Testing

UI Testing

VB.NET

VCL

WPF

Conway's Game of Life... in R
Just playing with matrices in R. :-)



Not that it's difficult or anything, just wanted to practice coding in R. And the code can be made quite compact and readable at the same time:
  calculate.neighbors <- function(board)
  {
    shifted.up <- shift.up(board)
    shifted.down <- shift.down(board)
  
    neighbors <-
      shift.left(shifted.up) + shifted.up + shift.right(shifted.up) +
      shift.left(board) + shift.right(board) +
      shift.left(shifted.down) + shifted.down + shift.right(shifted.down)
  }
  
  calculate.generation <- function(board)
  {
    neighbors <- calculate.neighbors(board)
  
    remaining <- neighbors == 2
    creating <- neighbors == 3
  
    (board * remaining) + creating
  }
In the code above, board is an R matrix, with values equal to 0 (empty cell) and 1 (occupied cell).

I especially like the last expression that returns the next generation... :-)
(Remember that * in R is matrix multiplication element by element, not the linear algebra matrix multiplication. That combined with R's handling of TRUE/FALSE values (1 and 0 respectively) allows for the final expression to work as expected.)

The above assumes that you have the shift.up/down/left/right functions defined for matrices; for instance, the matrixcalc package gives you that. I preferred to code simplified versions of those functions myself - again, mainly as an exercise (and thanks to that Life calculations are about 7% quicker, too).

Anyway, if you want to view or play with the source code, it's available on GitHub.

Top

Comments
Alas!
No comments yet...

Top

Add a comment (fields with an asterisk are required)
Name / nick *
Mail (will remain hidden) *
Your website
Comment (no tags) *
Enter the text displayed below *
 

Top

Tags

R