Skip to content

Instantly share code, notes, and snippets.

@kynan
Created October 15, 2012 20:56
Show Gist options
  • Save kynan/3895415 to your computer and use it in GitHub Desktop.
Save kynan/3895415 to your computer and use it in GitHub Desktop.
Game of Life with rule 24 in Coffee
DEAD = 0
ALIVE = 1
evolve_cell = (left, middle, right) ->
register = left*4+middle*2+right
#console.log left, middle, right, register
switch register
when 4 then ALIVE # from [ALIVE,DEAD,DEAD]
when 3 then ALIVE # from [DEAD,ALIVE,ALIVE]
else
DEAD
prev = (i,n) ->
if i is 0 then n-1
else
i-1
next = (i,n) ->
if i is n-1 then 0
else
i+1
evolve_state = (state) ->
state.map (value, i, array)->
n = array.length
evolve_cell array[prev i,n], array[i], array[next i,n]
describe 'utils', ->
it 'prev(0,4) should be 3', ->
expect(prev 0, 4).toBe 3
it 'next(3,4) should be 0', ->
expect(next 3, 4).toBe 0
describe 'single cell', ->
it 'next state from [DEAD,DEAD,DEAD] should be DEAD', ->
state=[DEAD,DEAD,DEAD]
expect(evolve_cell(state[0], state[1], state[2])).toBe DEAD
it 'next state from [ALIVE,ALIVE,ALIVE] should be DEAD', ->
state = [ALIVE,ALIVE,ALIVE]
expect(evolve_cell(state[0], state[1], state[2])).toBe DEAD
it 'next state from [ALIVE,DEAD,DEAD] should be ALIVE', ->
state = [ALIVE,DEAD,DEAD]
expect(evolve_cell(state[0], state[1], state[2])).toBe ALIVE
describe 'line of cells', ->
it 'next state from [ALIVE,ALIVE,ALIVE,DEAD] should be [ALIVE,DEAD,DEAD,DEAD]', ->
state = [ALIVE,ALIVE,ALIVE,DEAD]
next_state = evolve_state(state)
for i in [0..3]
expect(next_state[i]).toBe [ALIVE,DEAD,DEAD,DEAD][i]
it 'next state from [ALIVE,DEAD,DEAD,DEAD] should be [DEAD,ALIVE,DEAD,DEAD]', ->
state = [ALIVE,DEAD,DEAD,DEAD]
next_state = evolve_state(state)
for i in [0..3]
expect(next_state[i]).toBe [DEAD,ALIVE,DEAD,DEAD][i]
it 'next state from [DEAD,ALIVE,DEAD,DEAD] should be [DEAD,DEAD,ALIVE,DEAD]', ->
state = [DEAD,ALIVE,DEAD,DEAD]
next_state = evolve_state(state)
for i in [0..3]
expect(next_state[i]).toBe [DEAD,DEAD,ALIVE,DEAD][i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment