Page 1 of 1

Simple cellular automata doesn't seem right

Posted: Mon May 01, 2017 8:29 am
by leNoah
Hello,
I was experimenting with cellular automata and read some stuff here, here, and a bunch of other sites. Currently, my createMap() function looks like this:

Code: Select all

function createMap(width, height, iterations)
  -- empty table
  map = {}
  for h = 1, height do
    -- create another empty table inside each table address
    map[h] = {}
    -- in the second table , 45% chance is land.
    for w = 1, width do
      if love.math.random(1, 100) <= 45 then
        map[h][w] = 3
      else
        map[h][w] = 1
      end
    end
    
    for i = 1, iterations do
      for h, value1 in pairs(map) do
        for w, value2 in pairs(map[h]) do
          neighbours = 0
          
          -- check left and right
          neighbours = neighbours + check(map[h][w - 1])
          neighbours = neighbours + check(map[h][w + 1])
          
          -- if it's the top row all the above count as land
          if h == 1 then
            neighbours = neighbours + 3
          else
            -- check above row
            neighbours = neighbours + check(map[h - 1][w - 1])
            neighbours = neighbours + check(map[h - 1][w])
            neighbours = neighbours + check(map[h - 1][w + 1])
          end
          -- if it's the bottom row sim.
          if h == table.getn(map) then
            neighbours = neighbours + 3
          else
            -- check below row
            neighbours = neighbours + check(map[h + 1][w - 1])
            neighbours = neighbours + check(map[h + 1][w])
            neighbours = neighbours + check(map[h + 1][w + 1])
          end
          
          if neighbours > 5 then
            map[h][w] = 3
          elseif neighbours < 3 then
            map[h][w] = 1
          end
        end
      end
    end
  end
  
And, when iterations is set to anything except 0, it outputs something near-identical to the screenshot I attached at the bottom.

Not sure what I'm doing wrong, whether it's some dumb typo (I did check) or something else, but any help would be appreciated.
Thanks in advance,
Noah ^^

Re: Simple cellular automata doesn't seem right

Posted: Mon May 01, 2017 6:20 pm
by airstruck
Try doing it in two passes. In the first pass, store the next value for each cell, but don't update the actual value yet. In the second pass, update the actual value from the "next value" you stored on the previous pass.