Jump to content

Elementary cellular automaton: Difference between revisions

imported>Maxima enthusiast
No edit summary
Line 2,208:
=={{header|Julia}}==
<syntaxhighlight lang="julia">
struct Automaton
const lines = 10
g₀::Vector{Bool}
const start = ".........#........."
rule::Function
const rules = [90, 30, 14]
Automaton(n::Int) = new(
rule2poss(rule) = [rule & (1 << (i - 1))[c !== 0'#' for ic in 1:8".........#........."],
i -> isone.(digits(n; base = 2, pad = 8))[i])
cells2bools(cells) = [cells[i] == '#' for i in 1:length(cells)]
bools2cells(bset) = prod([bset[i] ? "#" : "." for i in 1:length(bset)])
function transform(bset, ruleposs)
newbset = map(x->ruleposs[x],
[bset[i - 1] * 4 + bset[i] * 2 + bset[i + 1] + 1
for i in 2:length(bset)-1])
vcat(newbset[end], newbset, newbset[1])
end
 
Base.iterate(a::Automaton, g = a.g₀) =
const startset = cells2bools(start)
g, @. a.rule(4*[g[end];g[1:end-1]] + 2*g + [g[2:end];g[1]] + 1)
 
for rul in rules
Base.show(io::IO, a::Automaton) =
println("\nUsing Rule $rul:")
for g in Iterators.take(a, 10)
bset = vcat(startset[end], startset, startset[1]) # wrap ends
println(io, join(c ? '#' : '.' for c ∈ g))
rp = rule2poss(rul)
for _ in 1:lines
println(bools2cells(bset[2:end-1])) # unwrap ends
bset = transform(bset, rp)
end
end
</syntaxhighlight> {{output}} <pre>
Using Rule 90:
.........#.........
........#.#........
.......#...#.......
......#.#.#.#......
.....#.......#.....
....#.#.....#.#....
...#...#...#...#...
..#.#.#.#.#.#.#.#..
.#...............#.
#.#.............#.#
 
for n ∈ [90, 30, 14]
Using Rule 30:
println("rule $n:")
.........#.........
show(Automaton(n))
........###........
println()
.......##..#.......
end</syntaxhighlight> {{output}}
......##.####......
<pre>
.....##..#...#.....
rule 90:
....##.####.###....
...##..#....#..#.......
..##.####.....#.#####........
.##......#...###.....#..
......#.#.####.##..#...###.
.....#.......#.....
....#.#.....#.#....
...#...#...#...#...
..#.#.#.#.#.#.#.#..
.#...............#.
#.#.............#.#
 
rule 30:
.........#.........
........###........
.......##..#.......
......##.####......
.....##..#...#.....
....##.####.###....
...##..#....#..#...
..##.####..######..
.##..#...###.....#.
##.####.##..#...###
 
rule 14:
.........#.........
........##.........
.......##..........
......##...........
.....##............
....##.............
...##..............
..##...............
.##................
##.................
 
Using Rule 14:
.........#.........
........##.........
.......##..........
......##...........
.....##............
....##.............
...##..............
..##...............
.##................
##.................
</pre>
 
39

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.