RosettaCodeData/Task/Wireworld/Pluto/wireworld.pluto
2026-04-30 12:34:36 -04:00

68 lines
1.6 KiB
Text

local fmt = require "fmt"
require "table2"
local rows, cols = 0, 0 -- extent of input configuration
local rx, cx = 0, 0 -- grid extent (includes border)
local mn = {} -- offsets of Moore neighborhood
local function gprint(grid)
print(string.rep("__", cols))
print()
for r = 1, rows do
for c = 1, cols do fmt.write(" %s", grid[r * cx + c + 1]) end
print()
end
end
local function step(dst, src)
for r = 1, rows do
for c = 1, cols do
local x = r * cx + c + 1
dst[x] = src[x]
if dst[x] == "H" then
dst[x] = "t"
elseif dst[x] == "t" then
dst[x] = "."
elseif dst[x] == "." then
local nn = 0
for mn as n do
if src[x + n] == "H" then nn += 1 end
end
if nn == 1 or nn == 2 then dst[x] = "H" end
end
end
end
end
local nl = os.platform == "windows" ? "\r\n" : "\n"
local src_rows = io.contents("ww.config"):rstrip():split(nl)
rows = #src_rows
for src_rows as r do
if #r > cols then cols = #r end
end
rx = rows + 2
cx = cols + 2
mn = {-cx - 1, -cx, -cx + 1, -1, 1, cx - 1, cx, cx + 1}
-- Allocate two grids and copy input into first grid.
local odd = table.rep(rx * cx, " ")
local even = table.rep(rx * cx, " ")
local ri = 0
for src_rows as r do
for i = 0, #r - 1 do
odd[(ri + 1) * cx + 2 + i] = r[i + 1]
end
ri += 1
end
-- Run.
while true do
gprint(odd)
step(even, odd)
io.read() -- wait for enter to be pressed
gprint(even)
step(odd, even)
io.read() -- ditto
end