Elementary cellular automaton/Infinite length: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 443: | Line 443: | ||
Looks like a [[Sierpinski_triangle|Sierpinski triangle]] |
Looks like a [[Sierpinski_triangle|Sierpinski triangle]] |
||
=={{header|jq}}== |
|||
'''Adapted from [[#Python|Python]]''' |
|||
{{works with|jq}} |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
'''Preliminaries''' |
|||
<lang jq> |
|||
def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .; |
|||
def lpad($len): lpad($len; " "); |
|||
# Like *ix `tr` but it is as though $to is padded with blanks |
|||
def tr($from;$to): |
|||
explode as $s |
|||
| ($from | explode) as $f |
|||
| ($to | explode) as $t |
|||
| reduce range(0;length) as $i ([]; |
|||
($f | index($s[$i])) as $ix |
|||
| if $ix then . + [$t[$ix] // " "] |
|||
else . + [$s[$i]] |
|||
end ) |
|||
| implode; |
|||
# Input: a non-negative integer |
|||
# Output: the corresponding stream of bits (0s and 1s), |
|||
# least significant digit first, with a final 0 |
|||
def stream: |
|||
recurse(if . > 0 then ./2|floor else empty end) | . % 2 ; |
|||
# input: an array, e.g. as produced by [7|stream] |
|||
# output: the corresponding binary string |
|||
def to_b: reverse | map(tostring) | join("") | sub("^0";"");</lang> |
|||
'''The Cellular Automaton''' |
|||
<lang jq># Output: an unbounded stream of the form [count, row] |
|||
# giving the rows produced by the eca defined by |
|||
# $cells (a string) and $rule (an integer) |
|||
def eca_infinite($cells; $rule): |
|||
def notcell: tr("01";"10") ; |
|||
def rule2hash($rule): |
|||
[$rule | stream] as $r |
|||
| reduce range(0;8) as $i ({}; |
|||
. + { ($i|[stream]|to_b|lpad(3;"0")): ($r[$i] // 0)}); |
|||
rule2hash($rule) as $neighbours2next |
|||
| [0, $cells], |
|||
foreach range(1; infinite) as $i ({c: $cells}; |
|||
.c = (.c[0:1]|notcell)*2 + .c + (.c[-1:]|notcell)*2 # Extend and pad the ends |
|||
| .c = ([range(1; .c|length - 1) as $i | $neighbours2next[.c[$i-1:$i+2] ]] | join("")); |
|||
[$i, .c] ) ; |
|||
</lang> |
|||
'''The Task''' |
|||
<lang jq># $lines specifies the number of lines to display for each eca |
|||
def main($lines): |
|||
(90, 30) as $rule |
|||
| "\nRule: \($rule)", |
|||
(limit($lines; eca_infinite("1"; $rule) |
|||
| .[0] as $line |
|||
| ($line|lpad(3)) + " " * ($lines - $line) + (.[1] | tr("01"; ".#") ))); |
|||
main(25)</lang> |
|||
{{out}} |
|||
As for [[#Python|Python]]. |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{trans|Python}} |
{{trans|Python}} |