Elementary cellular automaton: Difference between revisions

jq
(jq)
Line 1,008:
# #### ### ## #
</pre>
 
=={{header|jq}}==
{{works with|jq|1.5}}
 
For simplicity we will use strings of 0s and 1s to represent the
automaton, its states, and the rules, except that the "automaton"
function will accept decimal rule specifications.
 
'''Helper functions'''
<lang jq># The ordinal value of the relevant states:
def states:
{"111": 1, "110": 2, "101": 3, "100": 4, "011": 5, "010": 6, "001": 7, "000": 8};
 
# Compute the next "state"
# input: a state ("111" or "110" ...)
# rule: the rule represented as a string of 0s and 1s
# output: the next state "0" or "1" depending on the rule
def next(rule):
states[.] as $n | rule[($n-1):$n] ;
 
# The state of cell $n, using 0-based indexing
def triple($n):
if $n == 0 then .[-1:] + .[0:2]
elif $n == (length-1) then .[-2:] + .[0:1]
else .[n-1:n+2]
end;
 
# input: non-negative decimal integer
# output: 0-1 binary string
def binary_digits:
if . == 0 then "0"
else [recurse( if . == 0 then empty else ./2 | floor end ) % 2 | tostring]
| reverse
| .[1:] # remove the leading 0
| join("")
end ;</lang>
 
'''Main function'''
<lang jq># "rule" can be given as a decimal or string of 0s and 1s:
def automaton(rule; steps):
 
# Compute the rule as a string of length 8
def tos:
if type == "number" then "0000000" + binary_digits else . end
| .[-8:];
 
# input: the current state of the automaton
# output: its next state
def update(rule):
. as $in
| reduce range(0; length) as $n ("";
. + ($in|triple($n)|next(rule)));
 
(rule | tos) as $rule
| limit(steps; while(true; update($rule) )) ;
 
# Example
 
"0000001000000" # initial state
| automaton($rule; $steps) # $rule and $steps are taken from the command line
| gsub("0"; ".") # pretty print
| gsub("1"; "#")
</lang>
 
 
'''Command-line Invocation'''
$ jq -r -n -f program.jq --argjson steps 10 --argjson rule 90
 
{{out}}
<pre>"......#......"
".....#.#....."
"....#...#...."
"...#.#.#.#..."
"..#.......#.."
".#.#.....#.#."
"#...#...#...#"
"##.#.#.#.#.##"
".#.........#."
"#.#.......#.#"</pre>
 
=={{header|Mathematica}}==
2,515

edits