Created
July 13, 2017 18:54
-
-
Save Feuermurmel/47a1dc7a8034167e458fa48b5de52d35 to your computer and use it in GitHub Desktop.
Cellular Automaton in Lua 5.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- Create a rule function which calculates the next value of a single cell in | |
-- a cellular automaton | |
-- @param rule | |
-- Rule number. | |
-- @param neighbours | |
-- Number of neighbours in each direction which affect the next state of a | |
-- cell. With 0, a cell only affects itself. With 1, the two immediate | |
-- neighbours also affect the cell. | |
function wolfram_ca_rule_fn(rule, neighbours) | |
return function(get_cell_fn) | |
local neighbours_value = 0 | |
for i = -neighbours, neighbours do | |
neighbours_value = 2 * neighbours_value + get_cell_fn(i) | |
end | |
return math.floor(rule / 2 ^ neighbours_value) % 2 | |
end | |
end | |
--- Calculate the next step in a cellular automaton. | |
-- @param rule_fn | |
-- Function which takes arguments (get_cell) and returns the new state of | |
-- the current cell. get_cell is a function which takes an offset to the | |
-- current cell and returns its current state. | |
-- @param state | |
-- Current state of the cellular automaton as a list of cell states. | |
function wolfram_ca_step(rule_fn, state) | |
local new_state = {} | |
for i = 1, #state do | |
--- Get the cell at the specified position relative to the current one. | |
-- @param offset Offset from the current cell. | |
local function get_cell(offset) | |
return state[(i + offset - 1) % #state + 1] | |
end | |
new_state[i] = rule_fn(get_cell) | |
end | |
return new_state | |
end | |
function wolfram_ca(rule_fn, initial_state, steps) | |
local result = {initial_state} | |
local state = initial_state | |
for i = 2, steps do | |
state = wolfram_ca_step(rule_fn, state) | |
result[i] = state | |
end | |
return result | |
end | |
return _G |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local ca = require('ca') | |
local chars = {'.', 'o'} | |
local rule = ca.wolfram_ca_rule_fn(60, 1) | |
local initial_state = {} | |
for i = 1,40 do | |
initial_state[i] = 0 | |
end | |
initial_state[1] = 1 | |
local result = ca.wolfram_ca(rule, initial_state, 40) | |
for _, i in ipairs(result) do | |
for _, j in ipairs(i) do | |
io.write(chars[j + 1]) | |
end | |
print() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment