Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
5
Task/One-dimensional-cellular-automata/00-META.yaml
Normal file
5
Task/One-dimensional-cellular-automata/00-META.yaml
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
category:
|
||||
- Cellular automata
|
||||
from: http://rosettacode.org/wiki/One-dimensional_cellular_automata
|
||||
note: Games
|
||||
16
Task/One-dimensional-cellular-automata/00-TASK.txt
Normal file
16
Task/One-dimensional-cellular-automata/00-TASK.txt
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
Assume an array of cells with an initial distribution of live and dead cells,
|
||||
and imaginary cells off the end of the array having fixed values.
|
||||
|
||||
Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation.
|
||||
|
||||
If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table:
|
||||
|
||||
0'''0'''0 -> 0 #
|
||||
0'''0'''1 -> 0 #
|
||||
0'''1'''0 -> 0 # Dies without enough neighbours
|
||||
0'''1'''1 -> 1 # Needs one neighbour to survive
|
||||
1'''0'''0 -> 0 #
|
||||
1'''0'''1 -> 1 # Two neighbours giving birth
|
||||
1'''1'''0 -> 1 # Needs one neighbour to survive
|
||||
1'''1'''1 -> 0 # Starved to death.
|
||||
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
V gen = ‘_###_##_#_#_#_#__#__’.map(ch -> Int(ch == ‘#’))
|
||||
L(n) 10
|
||||
print(gen.map(cell -> (I cell != 0 {‘#’} E ‘_’)).join(‘’))
|
||||
gen = [0] [+] gen [+] [0]
|
||||
gen = (0 .< gen.len - 2).map(m -> Int(sum(:gen[m .+ 3]) == 2))
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
\ one-dimensional automaton
|
||||
|
||||
\ direct map of input state to output state:
|
||||
{
|
||||
" " : 32,
|
||||
" #" : 32,
|
||||
" # " : 32,
|
||||
" ##" : 35,
|
||||
"# " : 32,
|
||||
"# #" : 35,
|
||||
"## " : 35,
|
||||
"###" : 32,
|
||||
} var, lifemap
|
||||
|
||||
: transition \ s ix (r:s') -- (r:s')
|
||||
>r dup r@ n:1- 3 s:slice
|
||||
lifemap @ swap caseof
|
||||
r> swap r@ -rot s:! >r ;
|
||||
|
||||
\ run over 'state' and generate new state
|
||||
: gen \ s -- s'
|
||||
clone >r
|
||||
dup s:len 2 n:-
|
||||
' transition 1 rot loop
|
||||
drop r> ;
|
||||
|
||||
: life \ s -- s'
|
||||
dup . cr gen ;
|
||||
|
||||
" ### ## # # # # # " ' life 10 times
|
||||
bye
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
(defun rc-step-r (cells)
|
||||
(if (endp (rest cells))
|
||||
nil
|
||||
(cons (if (second cells)
|
||||
(xor (first cells) (third cells))
|
||||
(and (first cells) (third cells)))
|
||||
(rc-step-r (rest cells)))))
|
||||
|
||||
(defun rc-step (cells)
|
||||
(cons (and (first cells) (second cells))
|
||||
(rc-step-r cells)))
|
||||
|
||||
(defun rc-steps-r (cells n prev)
|
||||
(declare (xargs :measure (nfix n)))
|
||||
(if (or (zp n) (equal cells prev))
|
||||
nil
|
||||
(let ((new (rc-step cells)))
|
||||
(cons new (rc-steps-r new (1- n) cells)))))
|
||||
|
||||
(defun rc-steps (cells n)
|
||||
(cons cells (rc-steps-r cells n nil)))
|
||||
|
||||
(defun pretty-row (row)
|
||||
(if (endp row)
|
||||
(cw "~%")
|
||||
(prog2$ (cw (if (first row) "#" "-"))
|
||||
(pretty-row (rest row)))))
|
||||
|
||||
(defun pretty-output (out)
|
||||
(if (endp out)
|
||||
nil
|
||||
(prog2$ (pretty-row (first out))
|
||||
(pretty-output (rest out)))))
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
INT stop generation = 9;
|
||||
INT universe width = 20;
|
||||
FORMAT alive or dead = $b("#","_")$;
|
||||
|
||||
BITS universe := 2r01110110101010100100;
|
||||
# universe := BIN ( ENTIER ( random * max int ) ); #
|
||||
INT upb universe = bits width;
|
||||
INT lwb universe = bits width - universe width + 1;
|
||||
|
||||
PROC couple = (BITS parent, INT lwb, upb)BOOL: (
|
||||
SHORT INT sum := 0;
|
||||
FOR bit FROM lwb TO upb DO
|
||||
sum +:= ABS (bit ELEM parent)
|
||||
OD;
|
||||
sum = 2
|
||||
);
|
||||
|
||||
FOR generation FROM 0 WHILE
|
||||
printf(($"Generation "d": "$, generation,
|
||||
$f(alive or dead)$, []BOOL(universe)[lwb universe:upb universe],
|
||||
$l$));
|
||||
# WHILE # generation < stop generation DO
|
||||
BITS next universe := 2r0;
|
||||
|
||||
# process the first event horizon manually #
|
||||
IF couple(universe,lwb universe,lwb universe + 1) THEN
|
||||
next universe := 2r10
|
||||
FI;
|
||||
|
||||
# process the middle kingdom in a loop #
|
||||
FOR bit FROM lwb universe + 1 TO upb universe - 1 DO
|
||||
IF couple(universe,bit-1,bit+1) THEN
|
||||
next universe := next universe OR 2r1
|
||||
FI;
|
||||
next universe := next universe SHL 1
|
||||
OD;
|
||||
|
||||
# process the last event horizon manually #
|
||||
IF couple(universe, upb universe - 1, upb universe) THEN
|
||||
next universe := next universe OR 2r1
|
||||
FI;
|
||||
universe := next universe
|
||||
OD
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
INT stop generation = 9;
|
||||
INT upb universe = 20;
|
||||
FORMAT alive or dead = $b("#","_")$;
|
||||
|
||||
BITS bits universe := 2r01110110101010100100;
|
||||
# bits universe := BIN ( ENTIER ( random * max int ) ); #
|
||||
[upb universe] BOOL universe := []BOOL(bits universe)[bits width - upb universe + 1:];
|
||||
|
||||
PROC couple = (REF[]BOOL parent)BOOL: (
|
||||
SHORT INT sum := 0;
|
||||
FOR bit FROM LWB parent TO UPB parent DO
|
||||
sum +:= ABS (parent[bit])
|
||||
OD;
|
||||
sum = 2
|
||||
);
|
||||
|
||||
FOR generation FROM 0 WHILE
|
||||
printf(($"Generation "d": "$, generation,
|
||||
$f(alive or dead)$, universe,
|
||||
$l$));
|
||||
# WHILE # generation < stop generation DO
|
||||
[UPB universe]BOOL next universe;
|
||||
|
||||
# process the first event horizon manually #
|
||||
next universe[1] := couple(universe[:2]);
|
||||
|
||||
# process the middle kingdom in a loop #
|
||||
FOR bit FROM LWB universe + 1 TO UPB universe - 1 DO
|
||||
next universe[bit] := couple(universe[bit-1:bit+1])
|
||||
OD;
|
||||
|
||||
# process the last event horizon manually #
|
||||
next universe[UPB universe] := couple(universe[UPB universe - 1: ]);
|
||||
universe := next universe
|
||||
OD
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
begin
|
||||
string(20) state;
|
||||
string(20) nextState;
|
||||
integer generation;
|
||||
generation := 0;
|
||||
state := "_###_##_#_#_#_#__#__";
|
||||
while begin
|
||||
write( i_w := 1, s_w := 1, "Generation ", generation, state );
|
||||
nextState := "____________________";
|
||||
for cPos := 1 until 18 do begin
|
||||
string(3) curr;
|
||||
curr := state( cPos - 1 // 3 );
|
||||
nextState( cPos // 1 ) := if curr = "_##" or curr = "#_#" or curr = "##_" then "#" else "_"
|
||||
end for_cPos ;
|
||||
( state not = nextState )
|
||||
end do begin
|
||||
state := nextState;
|
||||
generation := generation + 1
|
||||
end while_not_finished
|
||||
end.
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
#!/usr/bin/awk -f
|
||||
BEGIN {
|
||||
edge = 1
|
||||
ruleNum = 104 # 01101000
|
||||
maxGen = 9
|
||||
mark = "@"
|
||||
space = "."
|
||||
initialState = ".@@@.@@.@.@.@.@..@.."
|
||||
width = length(initialState)
|
||||
delete rules
|
||||
delete state
|
||||
|
||||
initRules(ruleNum)
|
||||
initState(initialState, mark)
|
||||
for (g = 0; g < maxGen; g++) {
|
||||
showState(g, mark, space)
|
||||
nextState()
|
||||
}
|
||||
showState(g, mark, space)
|
||||
}
|
||||
|
||||
function nextState( newState, i, n) {
|
||||
delete newState
|
||||
for (i = 1; i < width - 1; i++) {
|
||||
n = getRuleNum(i)
|
||||
newState[i] = rules[n]
|
||||
}
|
||||
for (i = 0; i < width; i++) { # copy, can't assign arrays
|
||||
state[i] = newState[i]
|
||||
}
|
||||
}
|
||||
|
||||
# Convert a three cell neighborhood from binary to decimal
|
||||
function getRuleNum(i, rn, j, p) {
|
||||
rn = 0
|
||||
for (j = -1; j < 2; j++) {
|
||||
p = i + j
|
||||
rn = rn * 2 + (p < 0 || p > width ? edge : state[p])
|
||||
}
|
||||
return rn
|
||||
}
|
||||
|
||||
function showState(gen, mark, space, i) {
|
||||
printf("%3d: ", gen)
|
||||
for (i = 1; i <= width; i++) {
|
||||
printf(" %s", (state[i] ? mark : space))
|
||||
}
|
||||
print ""
|
||||
}
|
||||
|
||||
# Make state transition lookup table from rule number.
|
||||
function initRules(ruleNum, i, r) {
|
||||
delete rules;
|
||||
r = ruleNum
|
||||
for (i = 0; i < 8; i++) {
|
||||
rules[i] = r % 2
|
||||
r = int(r / 2)
|
||||
}
|
||||
}
|
||||
|
||||
function initState(init, mark, i) {
|
||||
delete state
|
||||
srand()
|
||||
for (i = 0; i < width; i++) {
|
||||
state[i] = (substr(init, i, 1) == mark ? 1 : 0) # Given an initial string.
|
||||
# state[int(width/2)] = '@' # middle cell
|
||||
# state[i] = int(rand() * 100) < 30 ? 1 : 0 # 30% of cells
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
Another new solution (twice size as previous solution) :
|
||||
cat automata.awk :
|
||||
|
||||
#!/usr/local/bin/gawk -f
|
||||
|
||||
# User defined functions
|
||||
function ASCII_to_Binary(str_) {
|
||||
gsub("_","0",str_); gsub("@","1",str_)
|
||||
return str_
|
||||
}
|
||||
|
||||
function Binary_to_ASCII(bit_) {
|
||||
gsub("0","_",bit_); gsub("1","@",bit_)
|
||||
return bit_
|
||||
}
|
||||
|
||||
function automate(b1,b2,b3) {
|
||||
a = and(b1,b2,b3)
|
||||
b = or(b1,b2,b3)
|
||||
c = xor(b1,b2,b3)
|
||||
d = a + b + c
|
||||
return d == 1 ? 1 : 0
|
||||
}
|
||||
|
||||
# For each line in input do
|
||||
{
|
||||
str_ = $0
|
||||
gen = 0
|
||||
taille = length(str_)
|
||||
print "0: " str_
|
||||
do {
|
||||
gen ? str_previous = str_ : str_previous = ""
|
||||
gen += 1
|
||||
str_ = ASCII_to_Binary(str_)
|
||||
split(str_,tab,"")
|
||||
str_ = and(tab[1],tab[2])
|
||||
for (i=1; i<=taille-2; i++) {
|
||||
str_ = str_ automate(tab[i],tab[i+1],tab[i+2])
|
||||
}
|
||||
str_ = str_ and(tab[taille-1],tab[taille])
|
||||
print gen ": " Binary_to_ASCII(str_)
|
||||
} while (str_ != str_previous)
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
CHAR FUNC CalcCell(CHAR prev,curr,next)
|
||||
IF prev='. AND curr='# AND next='# THEN
|
||||
RETURN ('#)
|
||||
ELSEIF prev='# AND curr='. AND next='# THEN
|
||||
RETURN ('#)
|
||||
ELSEIF prev='# AND curr='# AND next='. THEN
|
||||
RETURN ('#)
|
||||
FI
|
||||
RETURN ('.)
|
||||
|
||||
PROC NextGeneration(CHAR ARRAY s)
|
||||
BYTE i
|
||||
CHAR prev,curr,next
|
||||
|
||||
IF s(0)<4 THEN RETURN FI
|
||||
prev=s(1) curr=s(2) next=s(3)
|
||||
i=2
|
||||
DO
|
||||
s(i)=CalcCell(prev,curr,next)
|
||||
i==+1
|
||||
IF i=s(0) THEN EXIT FI
|
||||
prev=curr curr=next next=s(i+1)
|
||||
OD
|
||||
RETURN
|
||||
|
||||
PROC Main()
|
||||
DEFINE MAXGEN="9"
|
||||
CHAR ARRAY s=".###.##.#.#.#.#..#.."
|
||||
BYTE i
|
||||
|
||||
FOR i=0 TO MAXGEN
|
||||
DO
|
||||
PrintF("Generation %I: %S%E",i,s)
|
||||
IF i<MAXGEN THEN
|
||||
NextGeneration(s)
|
||||
FI
|
||||
OD
|
||||
RETURN
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
|
||||
procedure Cellular_Automata is
|
||||
type Petri_Dish is array (Positive range <>) of Boolean;
|
||||
|
||||
procedure Step (Culture : in out Petri_Dish) is
|
||||
Left : Boolean := False;
|
||||
This : Boolean;
|
||||
Right : Boolean;
|
||||
begin
|
||||
for Index in Culture'First..Culture'Last - 1 loop
|
||||
Right := Culture (Index + 1);
|
||||
This := Culture (Index);
|
||||
Culture (Index) := (This and (Left xor Right)) or (not This and Left and Right);
|
||||
Left := This;
|
||||
end loop;
|
||||
Culture (Culture'Last) := Culture (Culture'Last) and not Left;
|
||||
end Step;
|
||||
|
||||
procedure Put (Culture : Petri_Dish) is
|
||||
begin
|
||||
for Index in Culture'Range loop
|
||||
if Culture (Index) then
|
||||
Put ('#');
|
||||
else
|
||||
Put ('_');
|
||||
end if;
|
||||
end loop;
|
||||
end Put;
|
||||
|
||||
Culture : Petri_Dish :=
|
||||
( False, True, True, True, False, True, True, False, True, False, True,
|
||||
False, True, False, True, False, False, True, False, False
|
||||
);
|
||||
begin
|
||||
for Generation in 0..9 loop
|
||||
Put ("Generation" & Integer'Image (Generation) & ' ');
|
||||
Put (Culture);
|
||||
New_Line;
|
||||
Step (Culture);
|
||||
end loop;
|
||||
end Cellular_Automata;
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
100 HOME
|
||||
110 n = 10
|
||||
120 READ w : DIM x(w+1),x2(w+1) : FOR i = 1 TO w : READ x(i) : NEXT
|
||||
130 FOR k = 1 TO n
|
||||
140 FOR j = 1 TO w
|
||||
150 IF x(j) THEN PRINT "#";
|
||||
155 IF NOT x(j) THEN PRINT "_";
|
||||
160 IF x(j-1)+x(j)+x(j+1) = 2 THEN x2(j) = 1
|
||||
165 IF x(j-1)+x(j)+x(j+1) <> 2 THEN x2(j) = 0
|
||||
170 NEXT : PRINT
|
||||
180 FOR j = 1 TO w : x(j) = x2(j) : NEXT
|
||||
190 NEXT
|
||||
200 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
evolve: function [arr][
|
||||
ary: [0] ++ arr ++ [0]
|
||||
ret: new []
|
||||
loop 1..(size ary)-2 'i [
|
||||
a: ary\[i-1]
|
||||
b: ary\[i]
|
||||
c: ary\[i+1]
|
||||
|
||||
if? 2 = a+b+c -> 'ret ++ 1
|
||||
else -> 'ret ++ 0
|
||||
]
|
||||
ret
|
||||
]
|
||||
|
||||
printIt: function [arr][
|
||||
print replace replace join map arr 'n -> to :string n "0" "_" "1" "#"
|
||||
]
|
||||
|
||||
arr: [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]
|
||||
printIt arr
|
||||
|
||||
newGen: evolve arr
|
||||
while [newGen <> arr][
|
||||
arr: newGen
|
||||
newGen: evolve arr
|
||||
printIt newGen
|
||||
]
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
n := 22, n1 := n+1, v0 := v%n1% := 0 ; set grid dimensions, and fixed cells
|
||||
|
||||
Loop % n { ; draw a line of checkboxes
|
||||
v%A_Index% := 0
|
||||
Gui Add, CheckBox, % "y10 w17 h17 gCheck x" A_Index*17-5 " vv" A_Index
|
||||
}
|
||||
Gui Add, Button, x+5 y6, step ; button to step to next generation
|
||||
Gui Show
|
||||
Return
|
||||
|
||||
Check:
|
||||
GuiControlGet %A_GuiControl% ; set cells by the mouse
|
||||
Return
|
||||
|
||||
ButtonStep: ; move to next generation
|
||||
Loop % n
|
||||
i := A_Index-1, j := i+2, w%A_Index% := v%i%+v%A_Index%+v%j% = 2
|
||||
Loop % n
|
||||
GuiControl,,v%A_Index%, % v%A_Index% := w%A_Index%
|
||||
Return
|
||||
|
||||
GuiClose: ; exit when GUI is closed
|
||||
ExitApp
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
DECLARE FUNCTION life$ (lastGen$)
|
||||
DECLARE FUNCTION getNeighbors! (group$)
|
||||
CLS
|
||||
start$ = "_###_##_#_#_#_#__#__"
|
||||
numGens = 10
|
||||
FOR i = 0 TO numGens - 1
|
||||
PRINT "Generation"; i; ": "; start$
|
||||
start$ = life$(start$)
|
||||
NEXT i
|
||||
|
||||
FUNCTION getNeighbors (group$)
|
||||
ans = 0
|
||||
IF (MID$(group$, 1, 1) = "#") THEN ans = ans + 1
|
||||
IF (MID$(group$, 3, 1) = "#") THEN ans = ans + 1
|
||||
getNeighbors = ans
|
||||
END FUNCTION
|
||||
|
||||
FUNCTION life$ (lastGen$)
|
||||
newGen$ = ""
|
||||
FOR i = 1 TO LEN(lastGen$)
|
||||
neighbors = 0
|
||||
IF (i = 1) THEN 'left edge
|
||||
IF MID$(lastGen$, 2, 1) = "#" THEN
|
||||
neighbors = 1
|
||||
ELSE
|
||||
neighbors = 0
|
||||
END IF
|
||||
ELSEIF (i = LEN(lastGen$)) THEN 'right edge
|
||||
IF MID$(lastGen$, LEN(lastGen$) - 1, 1) = "#" THEN
|
||||
neighbors = 1
|
||||
ELSE
|
||||
neighbors = 0
|
||||
END IF
|
||||
ELSE 'middle
|
||||
neighbors = getNeighbors(MID$(lastGen$, i - 1, 3))
|
||||
END IF
|
||||
|
||||
IF (neighbors = 0) THEN 'dies or stays dead with no neighbors
|
||||
newGen$ = newGen$ + "_"
|
||||
END IF
|
||||
IF (neighbors = 1) THEN 'stays with one neighbor
|
||||
newGen$ = newGen$ + MID$(lastGen$, i, 1)
|
||||
END IF
|
||||
IF (neighbors = 2) THEN 'flips with two neighbors
|
||||
IF MID$(lastGen$, i, 1) = "#" THEN
|
||||
newGen$ = newGen$ + "_"
|
||||
ELSE
|
||||
newGen$ = newGen$ + "#"
|
||||
END IF
|
||||
END IF
|
||||
NEXT i
|
||||
life$ = newGen$
|
||||
END FUNCTION
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
arraybase 1
|
||||
dim start = {0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0}
|
||||
dim sgtes(start[?]+1)
|
||||
|
||||
for k = 0 to 9
|
||||
print "Generation "; k; ": ";
|
||||
for j = 0 to start[?]-1
|
||||
|
||||
if start[j] then print "#"; else print "_";
|
||||
if start[j-1] + start[j] + start[j+1] = 2 then sgtes[j] = 1 else sgtes[j] = 0
|
||||
next j
|
||||
print
|
||||
for j = 0 to start[?]-1
|
||||
start[j] = sgtes[j]
|
||||
next j
|
||||
next k
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
DIM rule$(7)
|
||||
rule$() = "0", "0", "0", "1", "0", "1", "1", "0"
|
||||
|
||||
now$ = "01110110101010100100"
|
||||
|
||||
FOR generation% = 0 TO 9
|
||||
PRINT "Generation " ; generation% ":", now$
|
||||
next$ = ""
|
||||
FOR cell% = 1 TO LEN(now$)
|
||||
next$ += rule$(EVAL("%"+MID$("0"+now$+"0", cell%, 3)))
|
||||
NEXT cell%
|
||||
SWAP now$, next$
|
||||
NEXT generation%
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
@echo off
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
::THE MAIN THING
|
||||
call :one-dca __###__##_#_##_###__######_###_#####_#__##_____#_#_#######__
|
||||
pause>nul
|
||||
exit /b
|
||||
::/THE MAIN THING
|
||||
|
||||
::THE PROCESSOR
|
||||
:one-dca
|
||||
echo.&set numchars=0&set proc=%1
|
||||
|
||||
::COUNT THE NUMBER OF CHARS
|
||||
set bef=%proc:_=_,%
|
||||
set bef=%bef:#=#,%
|
||||
set bef=%bef:~0,-1%
|
||||
for %%x in (%bef%) do set /a numchars+=1
|
||||
|
||||
set /a endchar=%numchars%-1
|
||||
:nextgen
|
||||
echo. ^| %proc% ^|
|
||||
set currnum=0
|
||||
set newgen=
|
||||
:editeachchar
|
||||
set neigh=0
|
||||
set /a testnum2=%currnum%+1
|
||||
set /a testnum1=%currnum%-1
|
||||
if %currnum%==%endchar% (
|
||||
set testchar=!proc:~%testnum1%,1!
|
||||
if !testchar!==# (set neigh=1)
|
||||
) else (
|
||||
if %currnum%==0 (
|
||||
set testchar=%proc:~1,1%
|
||||
if !testchar!==# (set neigh=1)
|
||||
) else (
|
||||
set testchar1=!proc:~%testnum1%,1!
|
||||
set testchar2=!proc:~%testnum2%,1!
|
||||
if !testchar1!==# (set /a neigh+=1)
|
||||
if !testchar2!==# (set /a neigh+=1)
|
||||
)
|
||||
)
|
||||
if %neigh%==0 (set newgen=%newgen%_)
|
||||
if %neigh%==1 (
|
||||
set testchar=!proc:~%currnum%,1!
|
||||
set newgen=%newgen%!testchar!
|
||||
)
|
||||
if %neigh%==2 (
|
||||
set testchar=!proc:~%currnum%,1!
|
||||
if !testchar!==# (set newgen=%newgen%_) else (set newgen=%newgen%#)
|
||||
)
|
||||
if %currnum%==%endchar% (goto :cond) else (set /a currnum+=1&goto :editeachchar)
|
||||
|
||||
:cond
|
||||
if %proc%==%newgen% (echo.&echo ...The sample is now stable.&goto :EOF)
|
||||
set proc=%newgen%
|
||||
goto :nextgen
|
||||
::/THE (LLLLLLOOOOOOOOOOOOONNNNNNNNGGGGGG.....) PROCESSOR
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
v
|
||||
" !!! !! ! ! ! ! ! " ,*25 <v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
|
||||
v$< @,*25,,,,,,,,,,,,,,,,,,,,<
|
||||
>110p3>:1-10gg" "-4* \:10gg" "-2* \:1+10gg" "-\:54*1+`#v_20p++ :2`#v_ >:4`#v_> >$" "v
|
||||
>:3`#^_v>:6`|
|
||||
^ >$$$$320p10g1+:9`v > >$"!"> 20g10g1+p 20g1+:20p
|
||||
^ v_10p10g
|
||||
> ^
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
( ( evolve
|
||||
= n z
|
||||
. @( !arg
|
||||
: %?n ? @?z
|
||||
: ?
|
||||
( ( ( 000
|
||||
| 001
|
||||
| 010
|
||||
| 100
|
||||
| 111
|
||||
)
|
||||
& 0 !n:?n
|
||||
| (011|101|110)
|
||||
& 1 !n:?n
|
||||
)
|
||||
& ~`
|
||||
)
|
||||
?
|
||||
)
|
||||
| rev$(str$(!z !n))
|
||||
)
|
||||
& 11101101010101001001:?S
|
||||
& :?seen
|
||||
& whl
|
||||
' ( ~(!seen:? !S ?)
|
||||
& out$!S
|
||||
& !S !seen:?seen
|
||||
& evolve$!S:?S
|
||||
)
|
||||
);
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
#include <iostream>
|
||||
#include <bitset>
|
||||
#include <string>
|
||||
|
||||
const int ArraySize = 20;
|
||||
const int NumGenerations = 10;
|
||||
const std::string Initial = "0011101101010101001000";
|
||||
|
||||
int main()
|
||||
{
|
||||
// + 2 for the fixed ends of the array
|
||||
std::bitset<ArraySize + 2> array(Initial);
|
||||
|
||||
for(int j = 0; j < NumGenerations; ++j)
|
||||
{
|
||||
std::bitset<ArraySize + 2> tmpArray(array);
|
||||
for(int i = ArraySize; i >= 1 ; --i)
|
||||
{
|
||||
if(array[i])
|
||||
std::cout << "#";
|
||||
else
|
||||
std::cout << "_";
|
||||
int val = (int)array[i-1] << 2 | (int)array[i] << 1 | (int)array[i+1];
|
||||
tmpArray[i] = (val == 3 || val == 5 || val == 6);
|
||||
}
|
||||
array = tmpArray;
|
||||
std::cout << std::endl;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace prog
|
||||
{
|
||||
class MainClass
|
||||
{
|
||||
const int n_iter = 10;
|
||||
static int[] f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 };
|
||||
|
||||
public static void Main (string[] args)
|
||||
{
|
||||
for( int i=0; i<f.Length; i++ )
|
||||
Console.Write( f[i]==0 ? "-" : "#" );
|
||||
Console.WriteLine("");
|
||||
|
||||
int[] g = new int[f.Length];
|
||||
for( int n=n_iter; n!=0; n-- )
|
||||
{
|
||||
for( int i=1; i<f.Length-1; i++ )
|
||||
{
|
||||
if ( (f[i-1] ^ f[i+1]) == 1 ) g[i] = f[i];
|
||||
else if ( f[i] == 0 && (f[i-1] & f[i+1]) == 1 ) g[i] = 1;
|
||||
else g[i] = 0;
|
||||
}
|
||||
g[0] = ( (f[0] & f[1]) == 1 ) ? 1 : 0;
|
||||
g[g.Length-1] = ( (f[f.Length-1] & f[f.Length-2]) == 1 ) ? 1 : 0;
|
||||
|
||||
int[] tmp = f;
|
||||
f = g;
|
||||
g = tmp;
|
||||
|
||||
for( int i=0; i<f.Length; i++ )
|
||||
Console.Write( f[i]==0 ? "-" : "#" );
|
||||
Console.WriteLine("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
char trans[] = "___#_##_";
|
||||
|
||||
#define v(i) (cell[i] != '_')
|
||||
int evolve(char cell[], char backup[], int len)
|
||||
{
|
||||
int i, diff = 0;
|
||||
|
||||
for (i = 0; i < len; i++) {
|
||||
/* use left, self, right as binary number bits for table index */
|
||||
backup[i] = trans[ v(i-1) * 4 + v(i) * 2 + v(i + 1) ];
|
||||
diff += (backup[i] != cell[i]);
|
||||
}
|
||||
|
||||
strcpy(cell, backup);
|
||||
return diff;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
char c[] = "_###_##_#_#_#_#__#__\n",
|
||||
b[] = "____________________\n";
|
||||
|
||||
do { printf(c + 1); } while (evolve(c + 1, b + 1, sizeof(c) - 3));
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
#include <stdio.h>
|
||||
|
||||
char trans[] = "___#_##_";
|
||||
|
||||
int evolve(char c[], int len)
|
||||
{
|
||||
int i, diff = 0;
|
||||
# define v(i) ((c[i] & 15) == 1)
|
||||
# define each for (i = 0; i < len; i++)
|
||||
|
||||
each c[i] = (c[i] == '#');
|
||||
each c[i] |= (trans[(v(i-1)*4 + v(i)*2 + v(i+1))] == '#') << 4;
|
||||
each diff += (c[i] & 0xf) ^ (c[i] >> 4);
|
||||
each c[i] = (c[i] >> 4) ? '#' : '_';
|
||||
|
||||
# undef each
|
||||
# undef v
|
||||
return diff;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
char c[] = "_###_##_#_#_#_#__#__\n";
|
||||
|
||||
do { printf(c + 1); } while (evolve(c + 1, sizeof(c) - 3));
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
Identification division.
|
||||
Program-id. rc-1d-cell.
|
||||
|
||||
Data division.
|
||||
Working-storage section.
|
||||
|
||||
*> "Constants."
|
||||
01 max-gens pic 999 value 9.
|
||||
01 state-width pic 99 value 20.
|
||||
01 state-table-init pic x(20) value ".@@@.@@.@.@.@.@..@..".
|
||||
01 alive pic x value "@".
|
||||
01 dead pic x value ".".
|
||||
|
||||
*> The current state.
|
||||
01 state-gen pic 999 value 0.
|
||||
01 state-row.
|
||||
05 state-row-gen pic zz9.
|
||||
05 filler pic xx value ": ".
|
||||
05 state-table.
|
||||
10 state-cells pic x occurs 20 times.
|
||||
|
||||
*> The new state.
|
||||
01 new-state-table.
|
||||
05 new-state-cells pic x occurs 20 times.
|
||||
|
||||
*> Pointer into cell table during generational production.
|
||||
01 cell-index pic 99.
|
||||
88 at-beginning value 1.
|
||||
88 is-inside values 2 thru 19.
|
||||
88 at-end value 20.
|
||||
|
||||
*> The cell's neighborhood.
|
||||
01 neighbor-count-def.
|
||||
03 neighbor-count pic 9.
|
||||
88 is-comfy value 1.
|
||||
88 is-ripe value 2.
|
||||
|
||||
Procedure division.
|
||||
Perform Init-state-table.
|
||||
Perform max-gens times
|
||||
perform Display-row
|
||||
perform Next-state
|
||||
end-perform.
|
||||
Perform Display-row.
|
||||
Stop run.
|
||||
|
||||
Display-row.
|
||||
Move state-gen to state-row-gen.
|
||||
Display state-row.
|
||||
|
||||
*> Determine who lives and who dies.
|
||||
Next-state.
|
||||
Add 1 to state-gen.
|
||||
Move state-table to new-state-table.
|
||||
|
||||
Perform with test after
|
||||
varying cell-index from 1 by 1
|
||||
until at-end
|
||||
perform Count-neighbors
|
||||
perform Die-off
|
||||
perform New-births
|
||||
end-perform
|
||||
|
||||
move new-state-table to state-table.
|
||||
|
||||
*> Living cell with wrong number of neighbors...
|
||||
Die-off.
|
||||
if state-cells(cell-index) =
|
||||
alive and not is-comfy
|
||||
then move dead to new-state-cells(cell-index)
|
||||
end-if
|
||||
.
|
||||
|
||||
*> Empty cell with exactly two neighbors are...
|
||||
New-births.
|
||||
if state-cells(cell-index) = dead and is-ripe
|
||||
then move alive to new-state-cells(cell-index)
|
||||
end-if
|
||||
.
|
||||
*> How many living neighbors does a cell have?
|
||||
Count-neighbors.
|
||||
Move 0 to neighbor-count
|
||||
if at-beginning or at-end then
|
||||
add 1 to neighbor-count
|
||||
else
|
||||
if is-inside and state-cells(cell-index - 1) = alive
|
||||
then
|
||||
add 1 to neighbor-count
|
||||
end-if
|
||||
if is-inside and state-cells(cell-index + 1) = alive
|
||||
then
|
||||
add 1 to neighbor-count
|
||||
end-if
|
||||
end-if
|
||||
.
|
||||
|
||||
*> String is easier to enter, but table is easier to work with,
|
||||
*> so move each character of the initialization string to the
|
||||
*> state table.
|
||||
|
||||
Init-state-table.
|
||||
Perform with test after
|
||||
varying cell-index from 1 by 1
|
||||
until at-end
|
||||
move state-table-init(cell-index:1)
|
||||
to state-cells(cell-index)
|
||||
end-perform
|
||||
.
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
# We could cheat and count the bits, but let's keep this general.
|
||||
# . = dead, # = alive, middle cells survives iff one of the configurations
|
||||
# below is satisified.
|
||||
survival_scenarios = [
|
||||
'.##' # happy neighbors
|
||||
'#.#' # birth
|
||||
'##.' # happy neighbors
|
||||
]
|
||||
|
||||
b2c = (b) -> if b then '#' else '.'
|
||||
|
||||
cell_next_gen = (left_alive, me_alive, right_alive) ->
|
||||
fingerprint = b2c(left_alive) + b2c(me_alive) + b2c(right_alive)
|
||||
fingerprint in survival_scenarios
|
||||
|
||||
cells_for_next_gen = (cells) ->
|
||||
# This function assumes a finite array, i.e. cells can't be born outside
|
||||
# the original array.
|
||||
(cell_next_gen(cells[i-1], cells[i], cells[i+1]) for i in [0...cells.length])
|
||||
|
||||
display = (cells) ->
|
||||
(b2c(is_alive) for is_alive in cells).join ''
|
||||
|
||||
simulate = (cells) ->
|
||||
while true
|
||||
console.log display cells
|
||||
new_cells = cells_for_next_gen cells
|
||||
break if display(cells) == display(new_cells)
|
||||
cells = new_cells
|
||||
console.log "equilibrium achieved"
|
||||
|
||||
simulate (c == '#' for c in ".###.##.#.#.#.#..#..")
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
shared abstract class Cell(character) of alive | dead {
|
||||
shared Character character;
|
||||
string => character.string;
|
||||
shared formal Cell opposite;
|
||||
}
|
||||
|
||||
shared object alive extends Cell('#') {
|
||||
opposite => dead;
|
||||
}
|
||||
shared object dead extends Cell('_') {
|
||||
opposite => alive;
|
||||
}
|
||||
|
||||
shared Map<Character, Cell> cellsByCharacter = map { for (cell in `Cell`.caseValues) cell.character->cell };
|
||||
|
||||
shared class Automata1D({Cell*} initialCells) {
|
||||
|
||||
|
||||
value permanentFirstCell = initialCells.first else dead;
|
||||
value permanentLastCell = initialCells.last else dead;
|
||||
|
||||
value cells = Array { *initialCells.rest.exceptLast };
|
||||
|
||||
shared Boolean evolve() {
|
||||
|
||||
value newCells = Array {
|
||||
for (index->cell in cells.indexed)
|
||||
let (left = cells[index - 1] else permanentFirstCell,
|
||||
right = cells[index + 1] else permanentLastCell,
|
||||
neighbours = [left, right],
|
||||
bothAlive = neighbours.every(alive.equals),
|
||||
bothDead = neighbours.every(dead.equals))
|
||||
if (bothAlive)
|
||||
then cell.opposite
|
||||
else if (cell == alive && bothDead)
|
||||
then dead
|
||||
else cell
|
||||
};
|
||||
|
||||
if (newCells == cells) {
|
||||
return false;
|
||||
}
|
||||
|
||||
newCells.copyTo(cells);
|
||||
return true;
|
||||
}
|
||||
|
||||
string => permanentFirstCell.string + "".join(cells) + permanentLastCell.string;
|
||||
}
|
||||
|
||||
shared Automata1D? automata1d(String string) =>
|
||||
let (cells = string.map((Character element) => cellsByCharacter[element]))
|
||||
if (cells.every((Cell? element) => element exists))
|
||||
then Automata1D(cells.coalesced)
|
||||
else null;
|
||||
|
||||
shared void run() {
|
||||
|
||||
assert (exists automata = automata1d("__###__##_#_##_###__######_###_#####_#__##_____#_#_#######__"));
|
||||
|
||||
variable value generation = 0;
|
||||
print("generation ``generation`` ``automata``");
|
||||
while (automata.evolve() && generation<10) {
|
||||
print("generation `` ++generation `` ``automata``");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
100 CLS
|
||||
110 LET n = 10
|
||||
120 READ w
|
||||
121 DIM x(w+1): DIM x2(w+1)
|
||||
122 FOR i = 1 TO w : READ x(i) : NEXT i
|
||||
130 FOR k = 1 TO n
|
||||
140 FOR j = 1 TO w
|
||||
150 IF x(j) THEN PRINT "#"; ELSE PRINT "_";
|
||||
160 IF x(j-1)+x(j)+x(j+1) = 2 THEN LET x2(j) = 1 ELSE LET x2(j) = 0
|
||||
170 NEXT j
|
||||
171 PRINT
|
||||
180 FOR j = 1 TO w : LET x(j) = x2(j) : NEXT j
|
||||
190 NEXT k
|
||||
200 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0
|
||||
210 END
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
(ns one-dimensional-cellular-automata
|
||||
(:require (clojure.contrib (string :as s))))
|
||||
|
||||
(defn next-gen [cells]
|
||||
(loop [cs cells ncs (s/take 1 cells)]
|
||||
(let [f3 (s/take 3 cs)]
|
||||
(if (= 3 (count f3))
|
||||
(recur (s/drop 1 cs)
|
||||
(str ncs (if (= 2 (count (filter #(= \# %) f3))) "#" "_")))
|
||||
(str ncs (s/drop 1 cs))))))
|
||||
|
||||
(defn generate [n cells]
|
||||
(if (= n 0)
|
||||
'()
|
||||
(cons cells (generate (dec n) (next-gen cells)))))
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
one-dimensional-cellular-automata> (doseq [cells (generate 9 "_###_##_#_#_#_#__#__")]
|
||||
(println cells))
|
||||
_###_##_#_#_#_#__#__
|
||||
_#_#####_#_#_#______
|
||||
__##___##_#_#_______
|
||||
__##___###_#________
|
||||
__##___#_##_________
|
||||
__##____###_________
|
||||
__##____#_#_________
|
||||
__##_____#__________
|
||||
__##________________
|
||||
nil
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
#!/usr/bin/env lein-exec
|
||||
|
||||
(require '[clojure.string :as str])
|
||||
|
||||
(def first-genr "_###_##_#_#_#_#__#__")
|
||||
|
||||
(def hospitable #{"_##"
|
||||
"##_"
|
||||
"#_#"})
|
||||
|
||||
(defn compute-next-genr
|
||||
[genr]
|
||||
(let [genr (str "_" genr "_")
|
||||
groups (map str/join (partition 3 1 genr))
|
||||
next-genr (for [g groups]
|
||||
(if (hospitable g) \# \_))]
|
||||
(str/join next-genr)))
|
||||
|
||||
;; ---------------- main -----------------
|
||||
(loop [g first-genr
|
||||
i 0]
|
||||
(if (not= i 10)
|
||||
(do (println g)
|
||||
(recur (compute-next-genr g)
|
||||
(inc i)))))
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
(def rules
|
||||
{
|
||||
[0 0 0] 0
|
||||
[0 0 1] 0
|
||||
[0 1 0] 0
|
||||
[0 1 1] 1
|
||||
[1 0 0] 0
|
||||
[1 0 1] 1
|
||||
[1 1 0] 1
|
||||
[1 1 1] 0
|
||||
})
|
||||
|
||||
(defn nextgen [gen]
|
||||
(concat [0]
|
||||
(->> gen
|
||||
(partition 3 1)
|
||||
(map vec)
|
||||
(map rules))
|
||||
[0]))
|
||||
|
||||
; Output time!
|
||||
(doseq [g (take 10 (iterate nextgen [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]))]
|
||||
(println g))
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
(defun value (x)
|
||||
(assert (> (length x) 1))
|
||||
(coerce x 'simple-bit-vector))
|
||||
|
||||
(defun count-neighbors-and-self (value i)
|
||||
(flet ((ref (i)
|
||||
(if (array-in-bounds-p value i)
|
||||
(bit value i)
|
||||
0)))
|
||||
(declare (inline ref))
|
||||
(+ (ref (1- i))
|
||||
(ref i)
|
||||
(ref (1+ i)))))
|
||||
|
||||
(defun next-cycle (value)
|
||||
(let ((new-value (make-array (length value) :element-type 'bit)))
|
||||
(loop for i below (length value)
|
||||
do (setf (bit new-value i)
|
||||
(if (= 2 (count-neighbors-and-self value i))
|
||||
1
|
||||
0)))
|
||||
new-value))
|
||||
|
||||
(defun print-world (value &optional (stream *standard-output*))
|
||||
(loop for i below (length value)
|
||||
do (princ (if (zerop (bit value i)) #\. #\#)
|
||||
stream))
|
||||
(terpri stream))
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
CL-USER> (loop for previous-value = nil then value
|
||||
for value = #*01110110101010100100 then (next-cycle value)
|
||||
until (equalp value previous-value)
|
||||
do (print-world value))
|
||||
.###.##.#.#.#.#..#..
|
||||
.#.#####.#.#.#......
|
||||
..##...##.#.#.......
|
||||
..##...###.#........
|
||||
..##...#.##.........
|
||||
..##....###.........
|
||||
..##....#.#.........
|
||||
..##.....#..........
|
||||
..##................
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
void main() {
|
||||
import std.stdio, std.algorithm;
|
||||
|
||||
enum nGenerations = 10;
|
||||
enum initial = "0011101101010101001000";
|
||||
enum table = "00010110";
|
||||
|
||||
char[initial.length + 2] A = '0', B = '0';
|
||||
A[1 .. $-1] = initial;
|
||||
foreach (immutable _; 0 .. nGenerations) {
|
||||
foreach (immutable i; 1 .. A.length - 1) {
|
||||
write(A[i] == '0' ? '_' : '#');
|
||||
const val = (A[i-1]-'0' << 2) | (A[i]-'0' << 1) | (A[i+1]-'0');
|
||||
B[i] = table[val];
|
||||
}
|
||||
A.swap(B);
|
||||
writeln;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
void main() {
|
||||
import std.stdio, std.algorithm, std.range;
|
||||
|
||||
auto A = "_###_##_#_#_#_#__#__".map!q{a == '#'}.array;
|
||||
auto B = A.dup;
|
||||
|
||||
do {
|
||||
A.map!q{ "_#"[a] }.writeln;
|
||||
A.zip(A.cycle.drop(1), A.cycle.drop(A.length - 1))
|
||||
.map!(t => [t[]].sum == 2).copy(B);
|
||||
A.swap(B);
|
||||
} while (A != B);
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
void main() {
|
||||
import std.stdio, std.algorithm, std.range, std.bitmanip;
|
||||
|
||||
immutable initial = "__###_##_#_#_#_#__#___";
|
||||
enum nGenerations = 10;
|
||||
BitArray A, B;
|
||||
A.init(initial.map!(c => c == '#').array);
|
||||
B.length = initial.length;
|
||||
|
||||
foreach (immutable _; 0 .. nGenerations) {
|
||||
//A.map!(b => b ? '#' : '_').writeln;
|
||||
//foreach (immutable i, immutable b; A) {
|
||||
foreach (immutable i; 1 .. A.length - 1) {
|
||||
"_#"[A[i]].write;
|
||||
immutable val = (uint(A[i - 1]) << 2) |
|
||||
(uint(A[i]) << 1) |
|
||||
uint(A[i + 1]);
|
||||
B[i] = val == 3 || val == 5 || val == 6;
|
||||
}
|
||||
|
||||
writeln;
|
||||
A.swap(B);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
const ngenerations = 10;
|
||||
const table = [0, 0, 0, 1, 0, 1, 1, 0];
|
||||
|
||||
var a := [0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0];
|
||||
var b := a;
|
||||
|
||||
var i, j : Integer;
|
||||
for i := 1 to ngenerations do begin
|
||||
for j := a.low+1 to a.high-1 do begin
|
||||
if a[j] = 0 then
|
||||
Print('_')
|
||||
else Print('#');
|
||||
var val := (a[j-1] shl 2) or (a[j] shl 1) or a[j+1];
|
||||
b[j] := table[val];
|
||||
end;
|
||||
var tmp := a;
|
||||
a := b;
|
||||
b := tmp;
|
||||
PrintLn('');
|
||||
end;
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
type TGame = string[20];
|
||||
type TPattern = string[3];
|
||||
|
||||
function GetSubPattern(Game: TGame; Inx: integer): TPattern;
|
||||
{Get the pattern of three cells adjacent to Inx}
|
||||
var I: integer;
|
||||
begin
|
||||
Result:='';
|
||||
{Cells off the ends of the array are consider empty}
|
||||
for I:=Inx-1 to Inx+1 do
|
||||
if (I<1) or (I>Length(Game)) then Result:=Result+' '
|
||||
else Result:=Result+Game[I];
|
||||
end;
|
||||
|
||||
function GetNewValue(P: TPattern): char;
|
||||
{Calculate the new value for a cell based}
|
||||
{the pattern of neighboring cells}
|
||||
begin
|
||||
if P=' ' then Result:=' ' { No change}
|
||||
else if P=' #' then Result:=' ' { No change}
|
||||
else if P=' # ' then Result:=' ' { Dies without enough neighbours}
|
||||
else if P=' ##' then Result:='#' { Needs one neighbour to survive}
|
||||
else if P='# ' then Result:=' ' { No change}
|
||||
else if P='# #' then Result:='#' { Two neighbours giving birth}
|
||||
else if P='## ' then Result:='#' { Needs one neighbour to survive}
|
||||
else if P='###' then Result:=' '; { Starved to death.}
|
||||
end;
|
||||
|
||||
|
||||
procedure CellularlAutoGame(Memo: TMemo);
|
||||
{Iterate through steps of evolution of cellular automaton}
|
||||
var GameArray,NextArray: TGame;
|
||||
var P: string [3];
|
||||
var I,G: integer;
|
||||
begin
|
||||
{Start arrangement}
|
||||
GameArray:=' ### ## # # # # # ';
|
||||
for G:=1 to 10 do
|
||||
begin
|
||||
{Display current game situation}
|
||||
Memo.Lines.Add(GameArray);
|
||||
{Evolve each cell in the array}
|
||||
for I:=1 to Length(GameArray) do
|
||||
begin
|
||||
P:=GetSubPattern(GameArray,I);
|
||||
NextArray[I]:=GetNewValue(P);
|
||||
end;
|
||||
GameArray:=NextArray;
|
||||
end;
|
||||
end;
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
def step(state, rule) {
|
||||
var result := state(0, 1) # fixed left cell
|
||||
for i in 1..(state.size() - 2) {
|
||||
# Rule function receives the substring which is the neighborhood
|
||||
result += E.toString(rule(state(i-1, i+2)))
|
||||
}
|
||||
result += state(state.size() - 1) # fixed right cell
|
||||
return result
|
||||
}
|
||||
|
||||
def play(var state, rule, count, out) {
|
||||
out.print(`0 | $state$\n`)
|
||||
for i in 1..count {
|
||||
state := step(state, rosettaRule)
|
||||
out.print(`$i | $state$\n`)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
def rosettaRule := [
|
||||
" " => " ",
|
||||
" #" => " ",
|
||||
" # " => " ",
|
||||
" ##" => "#",
|
||||
"# " => " ",
|
||||
"# #" => "#",
|
||||
"## " => "#",
|
||||
"###" => " ",
|
||||
].get
|
||||
|
||||
? play(" ### ## # # # # # ", rosettaRule, 9, stdout)
|
||||
0 | ### ## # # # # #
|
||||
1 | # ##### # # #
|
||||
2 | ## ## # #
|
||||
3 | ## ### #
|
||||
4 | ## # ##
|
||||
5 | ## ###
|
||||
6 | ## # #
|
||||
7 | ## #
|
||||
8 | ##
|
||||
9 | ##
|
||||
# value: " ## "
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
PROGRAM ONEDIM_AUTOMATA
|
||||
|
||||
! for rosettacode.org
|
||||
!
|
||||
|
||||
!VAR I,J,N,W,K
|
||||
|
||||
!$DYNAMIC
|
||||
DIM X[0],X2[0]
|
||||
|
||||
BEGIN
|
||||
|
||||
DATA(20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0)
|
||||
|
||||
PRINT(CHR$(12);)
|
||||
N=20 ! number of generation required
|
||||
READ(W)
|
||||
!$DIM X[W+1],X2[W+1]
|
||||
FOR I=1 TO W DO
|
||||
READ(X[I])
|
||||
END FOR
|
||||
FOR K=1 TO N DO
|
||||
PRINT("Generation";K;TAB(16);)
|
||||
FOR J=1 TO W DO
|
||||
IF X[J]=1 THEN PRINT("#";) ELSE PRINT("_";) END IF
|
||||
IF X[J-1]+X[J]+X[J+1]=2 THEN X2[J]=1 ELSE X2[J]=0 END IF
|
||||
END FOR
|
||||
PRINT
|
||||
FOR J=1 TO W DO
|
||||
X[J]=X2[J]
|
||||
END FOR
|
||||
END FOR
|
||||
END PROGRAM
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
class
|
||||
APPLICATION
|
||||
|
||||
create
|
||||
make
|
||||
|
||||
feature
|
||||
|
||||
make
|
||||
-- First 10 states of the cellular automata.
|
||||
local
|
||||
r: RANDOM
|
||||
automata: STRING
|
||||
do
|
||||
create r.make
|
||||
create automata.make_empty
|
||||
across
|
||||
1 |..| 10 as c
|
||||
loop
|
||||
if r.double_item < 0.5 then
|
||||
automata.append ("0")
|
||||
else
|
||||
automata.append ("1")
|
||||
end
|
||||
r.forth
|
||||
end
|
||||
across
|
||||
1 |..| 10 as c
|
||||
loop
|
||||
io.put_string (automata + "%N")
|
||||
automata := update (automata)
|
||||
end
|
||||
end
|
||||
|
||||
update (s: STRING): STRING
|
||||
-- Next state of the cellular automata 's'.
|
||||
require
|
||||
enough_states: s.count > 1
|
||||
local
|
||||
i: INTEGER
|
||||
do
|
||||
create Result.make_empty
|
||||
-- Dealing with the left border.
|
||||
if s [1] = '1' and s [2] = '1' then
|
||||
Result.append ("1")
|
||||
else
|
||||
Result.append ("0")
|
||||
end
|
||||
-- Dealing with the middle cells.
|
||||
from
|
||||
i := 2
|
||||
until
|
||||
i = s.count
|
||||
loop
|
||||
if (s [i] = '0' and (s [i - 1] = '0' or (s [i - 1] = '1' and s [i + 1] = '0'))) or ((s [i] = '1') and ((s [i - 1] = '1' and s [i + 1] = '1') or (s [i - 1] = '0' and s [i + 1] = '0'))) then
|
||||
Result.append ("0")
|
||||
else
|
||||
Result.append ("1")
|
||||
end
|
||||
i := i + 1
|
||||
end
|
||||
-- Dealing with the right border.
|
||||
if s [s.count] = '1' and s [s.count - 1] = '1' then
|
||||
Result.append ("1")
|
||||
else
|
||||
Result.append ("0")
|
||||
end
|
||||
ensure
|
||||
has_same_length: s.count = Result.count
|
||||
end
|
||||
|
||||
end
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
defmodule RC do
|
||||
def run(list, gen \\ 0) do
|
||||
print(list, gen)
|
||||
next = evolve(list)
|
||||
if next == list, do: print(next, gen+1), else: run(next, gen+1)
|
||||
end
|
||||
|
||||
defp evolve(list), do: evolve(Enum.concat([[0], list, [0]]), [])
|
||||
|
||||
defp evolve([a,b,c], next), do: Enum.reverse([life(a,b,c) | next])
|
||||
defp evolve([a,b,c|rest], next), do: evolve([b,c|rest], [life(a,b,c) | next])
|
||||
|
||||
defp life(a,b,c), do: (if a+b+c == 2, do: 1, else: 0)
|
||||
|
||||
defp print(list, gen) do
|
||||
str = "Generation #{gen}: "
|
||||
IO.puts Enum.reduce(list, str, fn x,s -> s <> if x==0, do: ".", else: "#" end)
|
||||
end
|
||||
end
|
||||
|
||||
RC.run([0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0])
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
import Maybe exposing (withDefault)
|
||||
import List exposing (length, tail, reverse, concat, head, append, map3)
|
||||
import Html exposing (Html, div, h1, text)
|
||||
import String exposing (join)
|
||||
import Svg exposing (svg)
|
||||
import Svg.Attributes exposing (version, width, height, viewBox,cx,cy, fill, r)
|
||||
import Html.App exposing (program)
|
||||
import Random exposing (step, initialSeed, bool, list)
|
||||
import Matrix exposing (fromList, mapWithLocation, flatten) -- chendrix/elm-matrix
|
||||
import Time exposing (Time, second, every)
|
||||
|
||||
type alias Model = { history : List (List Bool)
|
||||
, cols : Int
|
||||
, rows : Int
|
||||
}
|
||||
|
||||
view : Model -> Html Msg
|
||||
view model =
|
||||
let
|
||||
circleInBox (row,col) value =
|
||||
if value
|
||||
then [ Svg.circle [ r "0.3"
|
||||
, fill ("purple")
|
||||
, cx (toString (toFloat col + 0.5))
|
||||
, cy (toString (toFloat row + 0.5))
|
||||
]
|
||||
[]
|
||||
]
|
||||
else []
|
||||
|
||||
showHistory model =
|
||||
model.history
|
||||
|> reverse
|
||||
|> fromList
|
||||
|> mapWithLocation circleInBox
|
||||
|> flatten
|
||||
|> concat
|
||||
in
|
||||
div []
|
||||
[ h1 [] [text "One Dimensional Cellular Automata"]
|
||||
, svg [ version "1.1"
|
||||
, width "700"
|
||||
, height "700"
|
||||
, viewBox (join " "
|
||||
[ 0 |> toString
|
||||
, 0 |> toString
|
||||
, model.cols |> toString
|
||||
, model.rows |> toString
|
||||
]
|
||||
)
|
||||
]
|
||||
(showHistory model)
|
||||
]
|
||||
|
||||
update : Msg -> Model -> (Model, Cmd Msg)
|
||||
update msg model =
|
||||
if length model.history == model.rows
|
||||
then (model, Cmd.none)
|
||||
else
|
||||
let s1 = model.history |> head |> withDefault []
|
||||
s0 = False :: s1
|
||||
s2 = append (tail s1 |> withDefault []) [False]
|
||||
|
||||
gen d0 d1 d2 =
|
||||
case (d0,d1,d2) of
|
||||
(False, True, True) -> True
|
||||
( True, False, True) -> True
|
||||
( True, True, False) -> True
|
||||
_ -> False
|
||||
|
||||
updatedHistory = map3 gen s0 s1 s2 :: model.history
|
||||
updatedModel = {model | history = updatedHistory}
|
||||
in (updatedModel, Cmd.none)
|
||||
|
||||
|
||||
init : Int -> (Model, Cmd Msg)
|
||||
init n =
|
||||
let gen1 = fst (step (list n bool) (initialSeed 34))
|
||||
in ({ history = [gen1], rows = n, cols= n }, Cmd.none)
|
||||
|
||||
type Msg = Tick Time
|
||||
|
||||
subscriptions model = every (0.2 * second) Tick
|
||||
|
||||
main = program
|
||||
{ init = init 40
|
||||
, view = view
|
||||
, update = update
|
||||
, subscriptions = subscriptions
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
-module(ca).
|
||||
-compile(export_all).
|
||||
|
||||
run(N,G) ->
|
||||
run(N,G,0).
|
||||
|
||||
run(GN,G,GN) ->
|
||||
io:fwrite("~B: ",[GN]),
|
||||
print(G);
|
||||
run(N,G,GN) ->
|
||||
io:fwrite("~B: ",[GN]),
|
||||
print(G),
|
||||
run(N,next(G),GN+1).
|
||||
|
||||
print([]) ->
|
||||
io:fwrite("~n");
|
||||
print([0|T]) ->
|
||||
io:fwrite("_"),
|
||||
print(T);
|
||||
print([1|T]) ->
|
||||
io:fwrite("#"),
|
||||
print(T).
|
||||
|
||||
next([]) ->
|
||||
[];
|
||||
next([_]) ->
|
||||
[0];
|
||||
next([H,1|_]=G) ->
|
||||
next(G,[H]);
|
||||
next([_|_]=G) ->
|
||||
next(G,[0]).
|
||||
|
||||
next([],Acc) ->
|
||||
lists:reverse(Acc);
|
||||
next([0,_],Acc) ->
|
||||
next([],[0|Acc]);
|
||||
next([1,X],Acc) ->
|
||||
next([],[X|Acc]);
|
||||
next([0,X,0|T],Acc) ->
|
||||
next([X,0|T],[0|Acc]);
|
||||
next([1,X,0|T],Acc) ->
|
||||
next([X,0|T],[X|Acc]);
|
||||
next([0,X,1|T],Acc) ->
|
||||
next([X,1|T],[X|Acc]);
|
||||
next([1,0,1|T],Acc) ->
|
||||
next([0,1|T],[1|Acc]);
|
||||
next([1,1,1|T],Acc) ->
|
||||
next([1,1|T],[0|Acc]).
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
44> ca:run(9,[0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0]).
|
||||
0: __###_##_#_#_#_#__#___
|
||||
1: __#_#####_#_#_#_______
|
||||
2: ___##___##_#_#________
|
||||
3: ___##___###_#_________
|
||||
4: ___##___#_##__________
|
||||
5: ___##____###__________
|
||||
6: ___##____#_#__________
|
||||
7: ___##_____#___________
|
||||
8: ___##_________________
|
||||
9: ___##_________________
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
include machine.e
|
||||
|
||||
function rules(integer tri)
|
||||
return tri = 3 or tri = 5 or tri = 6
|
||||
end function
|
||||
|
||||
function next_gen(atom gen)
|
||||
atom new, bit
|
||||
new = rules(and_bits(gen,3)*2) -- work with the first bit separately
|
||||
bit = 2
|
||||
while gen > 0 do
|
||||
new += bit*rules(and_bits(gen,7))
|
||||
gen = floor(gen/2) -- shift right
|
||||
bit *= 2 -- shift left
|
||||
end while
|
||||
return new
|
||||
end function
|
||||
|
||||
constant char_clear = '_', char_filled = '#'
|
||||
|
||||
procedure print_gen(atom gen)
|
||||
puts(1, int_to_bits(gen,32) * (char_filled - char_clear) + char_clear)
|
||||
puts(1,'\n')
|
||||
end procedure
|
||||
|
||||
function s_to_gen(sequence s)
|
||||
s -= char_clear
|
||||
return bits_to_int(s)
|
||||
end function
|
||||
|
||||
atom gen, prev
|
||||
integer n
|
||||
|
||||
n = 0
|
||||
prev = 0
|
||||
gen = bits_to_int(rand(repeat(2,32))-1)
|
||||
while gen != prev do
|
||||
printf(1,"Generation %d: ",n)
|
||||
print_gen(gen)
|
||||
prev = gen
|
||||
gen = next_gen(gen)
|
||||
n += 1
|
||||
end while
|
||||
|
||||
printf(1,"Generation %d: ",n)
|
||||
print_gen(gen)
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
1.1 S OLD(2)=1; S OLD(3)=1; S OLD(4)=1; S OLD(6)=1; S OLD(7)=1
|
||||
1.2 S OLD(9)=1; S OLD(11)=1; S OLD(13)=1; S OLD(15)=1; S OLD(18)=1
|
||||
1.3 F N=1,10; D 2
|
||||
1.4 Q
|
||||
|
||||
2.1 F X=1,20; D 3
|
||||
2.2 F X=1,20; D 6
|
||||
2.3 F X=1,20; S OLD(X)=NEW(X)
|
||||
2.4 T !
|
||||
|
||||
3.1 I (OLD(X-1)+OLD(X)+OLD(X+1)-2)4.1,5.1,4.1
|
||||
|
||||
4.1 S NEW(X)=0
|
||||
|
||||
5.1 S NEW(X)=1
|
||||
|
||||
6.1 I (-OLD(X))7.1,8.1,8.1
|
||||
|
||||
7.1 T "#"
|
||||
|
||||
8.1 T "."
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
USING: bit-arrays io kernel locals math sequences ;
|
||||
IN: cellular
|
||||
|
||||
: bool-sum ( bool1 bool2 -- sum )
|
||||
[ [ 2 ] [ 1 ] if ]
|
||||
[ [ 1 ] [ 0 ] if ] if ;
|
||||
:: neighbours ( index world -- # )
|
||||
index [ 1 - ] [ 1 + ] bi [ world ?nth ] bi@ bool-sum ;
|
||||
: count-neighbours ( world -- neighbours )
|
||||
[ length iota ] keep [ neighbours ] curry map ;
|
||||
|
||||
: life-law ( alive? neighbours -- alive? )
|
||||
swap [ 1 = ] [ 2 = ] if ;
|
||||
: step ( world -- world' )
|
||||
dup count-neighbours [ life-law ] ?{ } 2map-as ;
|
||||
: print-cellular ( world -- )
|
||||
[ CHAR: # CHAR: _ ? ] "" map-as print ;
|
||||
: main-cellular ( -- )
|
||||
?{ f t t t f t t f t f t f t f t f f t f f }
|
||||
10 [ dup print-cellular step ] times print-cellular ;
|
||||
MAIN: main-cellular
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
class Automaton
|
||||
{
|
||||
static Int[] evolve (Int[] array)
|
||||
{
|
||||
return array.map |Int x, Int i -> Int|
|
||||
{
|
||||
if (i == 0)
|
||||
return ( (x + array[1] == 2) ? 1 : 0)
|
||||
else if (i == array.size-1)
|
||||
return ( (x + array[-2] == 2) ? 1 : 0)
|
||||
else if (x + array[i-1] + array[i+1] == 2)
|
||||
return 1
|
||||
else
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
public static Void main ()
|
||||
{
|
||||
Int[] array := [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]
|
||||
echo (array.join(""))
|
||||
Int[] newArray := evolve(array)
|
||||
while (newArray != array)
|
||||
{
|
||||
echo (newArray.join(""))
|
||||
array = newArray
|
||||
newArray = evolve(array)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
: init ( bits count -- )
|
||||
0 do dup 1 and c, 2/ loop drop ;
|
||||
|
||||
20 constant size
|
||||
create state $2556e size init 0 c,
|
||||
|
||||
: .state
|
||||
cr size 0 do
|
||||
state i + c@ if ." #" else space then
|
||||
loop ;
|
||||
|
||||
: ctable create does> + c@ ;
|
||||
ctable rules $68 8 init
|
||||
|
||||
: gen
|
||||
state c@ ( window )
|
||||
size 0 do
|
||||
2* state i + 1+ c@ or 7 and
|
||||
dup rules state i + c!
|
||||
loop drop ;
|
||||
|
||||
: life1d ( n -- )
|
||||
.state 1 do gen .state loop ;
|
||||
|
||||
10 life1d
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
### ## # # # # #
|
||||
# ##### # # #
|
||||
## ## # #
|
||||
## ### #
|
||||
## # ##
|
||||
## ###
|
||||
## # #
|
||||
## #
|
||||
##
|
||||
## ok
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
PROGRAM LIFE_1D
|
||||
|
||||
IMPLICIT NONE
|
||||
|
||||
LOGICAL :: cells(20) = (/ .FALSE., .TRUE., .TRUE., .TRUE., .FALSE., .TRUE., .TRUE., .FALSE., .TRUE., .FALSE., &
|
||||
.TRUE., .FALSE., .TRUE., .FALSE., .TRUE., .FALSE., .FALSE., .TRUE., .FALSE., .FALSE. /)
|
||||
INTEGER :: i
|
||||
|
||||
DO i = 0, 9
|
||||
WRITE(*, "(A,I0,A)", ADVANCE = "NO") "Generation ", i, ": "
|
||||
CALL Drawgen(cells)
|
||||
CALL Nextgen(cells)
|
||||
END DO
|
||||
|
||||
CONTAINS
|
||||
|
||||
SUBROUTINE Nextgen(cells)
|
||||
LOGICAL, INTENT (IN OUT) :: cells(:)
|
||||
LOGICAL :: left, centre, right
|
||||
INTEGER :: i
|
||||
|
||||
left = .FALSE.
|
||||
DO i = 1, SIZE(cells)-1
|
||||
centre = cells(i)
|
||||
right = cells(i+1)
|
||||
IF (left .AND. right) THEN
|
||||
cells(i) = .NOT. cells(i)
|
||||
ELSE IF (.NOT. left .AND. .NOT. right) THEN
|
||||
cells(i) = .FALSE.
|
||||
END IF
|
||||
left = centre
|
||||
END DO
|
||||
cells(SIZE(cells)) = left .AND. right
|
||||
END SUBROUTINE Nextgen
|
||||
|
||||
SUBROUTINE Drawgen(cells)
|
||||
LOGICAL, INTENT (IN OUT) :: cells(:)
|
||||
INTEGER :: i
|
||||
|
||||
DO i = 1, SIZE(cells)
|
||||
IF (cells(i)) THEN
|
||||
WRITE(*, "(A)", ADVANCE = "NO") "#"
|
||||
ELSE
|
||||
WRITE(*, "(A)", ADVANCE = "NO") "_"
|
||||
END IF
|
||||
END DO
|
||||
WRITE(*,*)
|
||||
END SUBROUTINE Drawgen
|
||||
|
||||
END PROGRAM LIFE_1D
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
#define SIZE 640
|
||||
|
||||
randomize timer
|
||||
|
||||
dim as ubyte arr(0 to SIZE-1, 0 to 1)
|
||||
dim as uinteger i
|
||||
for i = 0 to SIZE - 1 'initialise array with zeroes and ones
|
||||
arr(i, 0)=int(rnd+0.5)
|
||||
next i
|
||||
|
||||
screen 12 'display graphically
|
||||
|
||||
dim as string ch=" "
|
||||
dim as uinteger j = 0, cur = 0, nxt, prv, neigh
|
||||
while not ch = "q" or ch = "Q"
|
||||
for i = 0 to SIZE - 1
|
||||
pset(i, j), 8+7*arr(i,cur) 'print off cells as grey, on cells as bright white
|
||||
nxt = (i + 1) mod SIZE
|
||||
prv = (i - 1)
|
||||
if prv < 0 then prv = SIZE - 1 'let's have a wrap-around array for fun
|
||||
neigh = arr(prv, cur) + arr(nxt, cur)
|
||||
if arr(i, cur) = 0 then 'evolution rules
|
||||
if neigh = 2 then
|
||||
arr(i, 1-cur) = 1
|
||||
else
|
||||
arr(i, 1-cur) = 0
|
||||
end if
|
||||
else
|
||||
if neigh = 0 or neigh = 2 then
|
||||
arr(i, 1-cur) = 0
|
||||
else
|
||||
arr(i, 1-cur) = 1
|
||||
end if
|
||||
end if
|
||||
next i
|
||||
j = j + 1
|
||||
cur = 1 - cur
|
||||
do
|
||||
ch = inkey
|
||||
if ch <> "" then exit do 'press any key to advance the sim
|
||||
'or Q to exit
|
||||
loop
|
||||
wend
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
'
|
||||
' One Dimensional Cellular Automaton
|
||||
'
|
||||
start$="01110110101010100100"
|
||||
max_cycles%=20 ! give a maximum depth
|
||||
'
|
||||
' Global variables hold the world, with two rows
|
||||
' world! is set up with 2 extra cells width, so there is a FALSE on either side
|
||||
' cur% gives the row for current world,
|
||||
' new% gives the row for the next world.
|
||||
'
|
||||
size%=LEN(start$)
|
||||
DIM world!(size%+2,2)
|
||||
cur%=0
|
||||
new%=1
|
||||
clock%=0
|
||||
'
|
||||
@setup_world(start$)
|
||||
OPENW 1
|
||||
CLEARW 1
|
||||
DO
|
||||
@display_world
|
||||
@update_world
|
||||
EXIT IF @same_state
|
||||
clock%=clock%+1
|
||||
EXIT IF clock%>max_cycles% ! safety net
|
||||
LOOP
|
||||
~INP(2)
|
||||
CLOSEW 1
|
||||
'
|
||||
' parse given string to set up initial states in world
|
||||
' -- assumes world! is of correct size
|
||||
'
|
||||
PROCEDURE setup_world(defn$)
|
||||
LOCAL i%
|
||||
' clear out the array
|
||||
ARRAYFILL world!(),FALSE
|
||||
' for each 1 in string, set cell to true
|
||||
FOR i%=1 TO LEN(defn$)
|
||||
IF MID$(defn$,i%,1)="1"
|
||||
world!(i%,0)=TRUE
|
||||
ENDIF
|
||||
NEXT i%
|
||||
' set references to cur and new
|
||||
cur%=0
|
||||
new%=1
|
||||
RETURN
|
||||
'
|
||||
' Display the world
|
||||
'
|
||||
PROCEDURE display_world
|
||||
LOCAL i%
|
||||
FOR i%=1 TO size%
|
||||
IF world!(i%,cur%)
|
||||
PRINT "#";
|
||||
ELSE
|
||||
PRINT ".";
|
||||
ENDIF
|
||||
NEXT i%
|
||||
PRINT ""
|
||||
RETURN
|
||||
'
|
||||
' Create new version of world
|
||||
'
|
||||
PROCEDURE update_world
|
||||
LOCAL i%
|
||||
FOR i%=1 TO size%
|
||||
world!(i%,new%)=@new_state(@get_value(i%))
|
||||
NEXT i%
|
||||
' reverse cur/new
|
||||
cur%=1-cur%
|
||||
new%=1-new%
|
||||
RETURN
|
||||
'
|
||||
' Test if cur/new states are the same
|
||||
'
|
||||
FUNCTION same_state
|
||||
LOCAL i%
|
||||
FOR i%=1 TO size%
|
||||
IF world!(i%,cur%)<>world!(i%,new%)
|
||||
RETURN FALSE
|
||||
ENDIF
|
||||
NEXT i%
|
||||
RETURN TRUE
|
||||
ENDFUNC
|
||||
'
|
||||
' Return new state of cell given value
|
||||
'
|
||||
FUNCTION new_state(value%)
|
||||
SELECT value%
|
||||
CASE 0,1,2,4,7
|
||||
RETURN FALSE
|
||||
CASE 3,5,6
|
||||
RETURN TRUE
|
||||
ENDSELECT
|
||||
ENDFUNC
|
||||
'
|
||||
' Compute value for cell + neighbours
|
||||
'
|
||||
FUNCTION get_value(cell%)
|
||||
LOCAL result%
|
||||
result%=0
|
||||
IF world!(cell%-1,cur%)
|
||||
result%=result%+4
|
||||
ENDIF
|
||||
IF world!(cell%,cur%)
|
||||
result%=result%+2
|
||||
ENDIF
|
||||
IF world!(cell%+1,cur%)
|
||||
result%=result%+1
|
||||
ENDIF
|
||||
RETURN result%
|
||||
ENDFUNC
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
start = "_###_##_#_#_#_#__#__"
|
||||
offLeft = '_'
|
||||
offRight = '_'
|
||||
dead = '_'
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(start)
|
||||
g := newGenerator(start, offLeft, offRight, dead)
|
||||
for i := 0; i < 10; i++ {
|
||||
fmt.Println(g())
|
||||
}
|
||||
}
|
||||
|
||||
func newGenerator(start string, offLeft, offRight, dead byte) func() string {
|
||||
g0 := string(offLeft) + start + string(offRight)
|
||||
g1 := []byte(g0)
|
||||
last := len(g0) - 1
|
||||
return func() string {
|
||||
for i := 1; i < last; i++ {
|
||||
switch l := g0[i-1]; {
|
||||
case l != g0[i+1]:
|
||||
g1[i] = g0[i]
|
||||
case g0[i] == dead:
|
||||
g1[i] = l
|
||||
default:
|
||||
g1[i] = dead
|
||||
}
|
||||
}
|
||||
g0 = string(g1)
|
||||
return g0[1:last]
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const (
|
||||
start = "_###_##_#_#_#_#__#__"
|
||||
offLeft = '_'
|
||||
offRight = '_'
|
||||
dead = '_'
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(start)
|
||||
a := make([]byte, len(start)+2)
|
||||
a[0] = offLeft
|
||||
copy(a[1:], start)
|
||||
a[len(a)-1] = offRight
|
||||
var read, write sync.WaitGroup
|
||||
read.Add(len(start) + 1)
|
||||
for i := 1; i <= len(start); i++ {
|
||||
go cell(a[i-1:i+2], &read, &write)
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
write.Add(len(start) + 1)
|
||||
read.Done()
|
||||
read.Wait()
|
||||
read.Add(len(start) + 1)
|
||||
write.Done()
|
||||
write.Wait()
|
||||
fmt.Println(string(a[1 : len(a)-1]))
|
||||
}
|
||||
}
|
||||
|
||||
func cell(kernel []byte, read, write *sync.WaitGroup) {
|
||||
var next byte
|
||||
for {
|
||||
l, v, r := kernel[0], kernel[1], kernel[2]
|
||||
read.Done()
|
||||
switch {
|
||||
case l != r:
|
||||
next = v
|
||||
case v == dead:
|
||||
next = l
|
||||
default:
|
||||
next = dead
|
||||
}
|
||||
read.Wait()
|
||||
kernel[1] = next
|
||||
write.Done()
|
||||
write.Wait()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
def life1D = { self ->
|
||||
def right = self[1..-1] + [false]
|
||||
def left = [false] + self[0..-2]
|
||||
[left, self, right].transpose().collect { hood -> hood.count { it } == 2 }
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
def cells = ('_###_##_#_#_#_#__#__' as List).collect { it == '#' }
|
||||
println "Generation 0: ${cells.collect { g -> g ? '#' : '_' }.join()}"
|
||||
(1..9).each {
|
||||
cells = life1D(cells)
|
||||
println "Generation ${it}: ${cells.collect { g -> g ? '#' : '_' }.join()}"
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
import Data.List (unfoldr)
|
||||
import System.Random (newStdGen, randomRs)
|
||||
|
||||
bnd :: String -> Char
|
||||
bnd "_##" = '#'
|
||||
bnd "#_#" = '#'
|
||||
bnd "##_" = '#'
|
||||
bnd _ = '_'
|
||||
|
||||
nxt :: String -> String
|
||||
nxt = unfoldr go . ('_' :) . (<> "_")
|
||||
where
|
||||
go [_, _] = Nothing
|
||||
go xs = Just (bnd $ take 3 xs, drop 1 xs)
|
||||
|
||||
lahmahgaan :: String -> [String]
|
||||
lahmahgaan xs =
|
||||
init
|
||||
. until
|
||||
((==) . last <*> last . init)
|
||||
((<>) <*> pure . nxt . last)
|
||||
$ [xs, nxt xs]
|
||||
|
||||
main :: IO ()
|
||||
main =
|
||||
newStdGen
|
||||
>>= ( mapM_ putStrLn . lahmahgaan
|
||||
. map ("_#" !!)
|
||||
. take 36
|
||||
. randomRs (0, 1)
|
||||
)
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
# One dimensional Cellular automaton
|
||||
record Automaton(size, cells)
|
||||
|
||||
procedure make_automaton (size, items)
|
||||
automaton := Automaton (size, items)
|
||||
while (*items < size) do push (automaton.cells, 0)
|
||||
return automaton
|
||||
end
|
||||
|
||||
procedure automaton_display (automaton)
|
||||
every (write ! automaton.cells)
|
||||
end
|
||||
|
||||
procedure automaton_evolve (automaton)
|
||||
revised := make_automaton (automaton.size, [])
|
||||
# do the left-most cell
|
||||
if ((automaton.cells[1] + automaton.cells[2]) = 2) then
|
||||
revised.cells[1] := 1
|
||||
# do the right-most cell
|
||||
if ((automaton.cells[automaton.size] + automaton.cells[automaton.size-1]) = 2) then
|
||||
revised.cells[revised.size] := 1
|
||||
# do the intermediate cells
|
||||
every (i := 2 to (automaton.size-1)) do {
|
||||
if ((automaton.cells[i-1] + automaton.cells[i] + automaton.cells[i+1]) = 2) then
|
||||
revised.cells[i] := 1
|
||||
}
|
||||
return revised
|
||||
end
|
||||
|
||||
procedure main ()
|
||||
automaton := make_automaton (20, [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0])
|
||||
every (1 to 10) do { # generations
|
||||
automaton_display (automaton)
|
||||
automaton := automaton_evolve (automaton)
|
||||
}
|
||||
end
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
procedure main(A)
|
||||
A := if *A = 0 then ["01110110101010100100"]
|
||||
CA := show("0"||A[1]||"0") # add always dead border cells
|
||||
every CA := show(|evolve(CA)\10) # limit to max of 10 generations
|
||||
end
|
||||
|
||||
procedure show(ca)
|
||||
write(ca[2:-1]) # omit border cells
|
||||
return ca
|
||||
end
|
||||
|
||||
procedure evolve(CA)
|
||||
newCA := repl("0",*CA)
|
||||
every newCA[i := 2 to (*CA-1)] := (CA[i-1]+CA[i]+CA[i+1] = 2, "1")
|
||||
return CA ~== newCA # fail if no change
|
||||
end
|
||||
|
|
@ -0,0 +1 @@
|
|||
life1d=: '_#'{~ (2 = 3+/\ 0,],0:)^:a:
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
life1d ? 20 # 2
|
||||
_###_##_#_#_#_#__#__
|
||||
_#_#####_#_#_#______
|
||||
__##___##_#_#_______
|
||||
__##___###_#________
|
||||
__##___#_##_________
|
||||
__##____###_________
|
||||
__##____#_#_________
|
||||
__##_____#__________
|
||||
__##________________
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
Rule=:2 :0 NB. , m: number of generations, n: rule number
|
||||
'_#'{~ (3 ((|.n#:~8#2) {~ #.)\ 0,],0:)^:(i.m)
|
||||
)
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
9 Rule 104 '#'='_###_##_#_#_#_#__#__'
|
||||
_###_##_#_#_#_#__#__
|
||||
_#_#####_#_#_#______
|
||||
__##___##_#_#_______
|
||||
__##___###_#________
|
||||
__##___#_##_________
|
||||
__##____###_________
|
||||
__##____#_#_________
|
||||
__##_____#__________
|
||||
__##________________
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
public class Life{
|
||||
public static void main(String[] args) throws Exception{
|
||||
String start= "_###_##_#_#_#_#__#__";
|
||||
int numGens = 10;
|
||||
for(int i= 0; i < numGens; i++){
|
||||
System.out.println("Generation " + i + ": " + start);
|
||||
start= life(start);
|
||||
}
|
||||
}
|
||||
|
||||
public static String life(String lastGen){
|
||||
String newGen= "";
|
||||
for(int i= 0; i < lastGen.length(); i++){
|
||||
int neighbors= 0;
|
||||
if (i == 0){//left edge
|
||||
neighbors= lastGen.charAt(1) == '#' ? 1 : 0;
|
||||
} else if (i == lastGen.length() - 1){//right edge
|
||||
neighbors= lastGen.charAt(i - 1) == '#' ? 1 : 0;
|
||||
} else{//middle
|
||||
neighbors= getNeighbors(lastGen.substring(i - 1, i + 2));
|
||||
}
|
||||
|
||||
if (neighbors == 0){//dies or stays dead with no neighbors
|
||||
newGen+= "_";
|
||||
}
|
||||
if (neighbors == 1){//stays with one neighbor
|
||||
newGen+= lastGen.charAt(i);
|
||||
}
|
||||
if (neighbors == 2){//flips with two neighbors
|
||||
newGen+= lastGen.charAt(i) == '#' ? "_" : "#";
|
||||
}
|
||||
}
|
||||
return newGen;
|
||||
}
|
||||
|
||||
public static int getNeighbors(String group){
|
||||
int ans= 0;
|
||||
if (group.charAt(0) == '#') ans++;
|
||||
if (group.charAt(2) == '#') ans++;
|
||||
return ans;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
public class Life{
|
||||
private static char[] trans = "___#_##_".toCharArray();
|
||||
|
||||
private static int v(StringBuilder cell, int i){
|
||||
return (cell.charAt(i) != '_') ? 1 : 0;
|
||||
}
|
||||
|
||||
public static boolean evolve(StringBuilder cell){
|
||||
boolean diff = false;
|
||||
StringBuilder backup = new StringBuilder(cell.toString());
|
||||
|
||||
for(int i = 1; i < cell.length() - 3; i++){
|
||||
/* use left, self, right as binary number bits for table index */
|
||||
backup.setCharAt(i, trans[v(cell, i - 1) * 4 + v(cell, i) * 2
|
||||
+ v(cell, i + 1)]);
|
||||
diff = diff || (backup.charAt(i) != cell.charAt(i));
|
||||
}
|
||||
|
||||
cell.delete(0, cell.length());//clear the buffer
|
||||
cell.append(backup);//replace it with the new generation
|
||||
return diff;
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
StringBuilder c = new StringBuilder("_###_##_#_#_#_#__#__\n");
|
||||
|
||||
do{
|
||||
System.out.printf(c.substring(1));
|
||||
}while(evolve(c));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
function caStep(old) {
|
||||
var old = [0].concat(old, [0]); // Surround with dead cells.
|
||||
var state = []; // The new state.
|
||||
|
||||
for (var i=1; i<old.length-1; i++) {
|
||||
switch (old[i-1] + old[i+1]) {
|
||||
case 0: state[i-1] = 0; break;
|
||||
case 1: state[i-1] = (old[i] == 1) ? 1 : 0; break;
|
||||
case 2: state[i-1] = (old[i] == 1) ? 0 : 1; break;
|
||||
}
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
alert(caStep([0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]));
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
# The 1-d cellular automaton:
|
||||
def next:
|
||||
# Conveniently, jq treats null as 0 when it comes to addition
|
||||
# so there is no need to fiddle with the boundaries
|
||||
. as $old
|
||||
| reduce range(0; length) as $i
|
||||
([];
|
||||
($old[$i-1] + $old[$i+1]) as $s
|
||||
| if $s == 0 then .[$i] = 0
|
||||
elif $s == 1 then .[$i] = (if $old[$i] == 1 then 1 else 0 end)
|
||||
else .[$i] = (if $old[$i] == 1 then 0 else 1 end)
|
||||
end);
|
||||
|
||||
|
||||
# pretty-print an array:
|
||||
def pp: reduce .[] as $i (""; . + (if $i == 0 then " " else "*" end));
|
||||
|
||||
# continue until quiescence:
|
||||
def go: recurse(. as $prev | next | if . == $prev then empty else . end) | pp;
|
||||
|
||||
# Example:
|
||||
[0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0] | go
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
$ jq -c -r -n -f One-dimensional_cellular_automata.jq
|
||||
*** ** * * * * *
|
||||
* ***** * * *
|
||||
** ** * *
|
||||
** *** *
|
||||
** * **
|
||||
** ***
|
||||
** * *
|
||||
** *
|
||||
**
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
function next_gen(a::BitArray{1}, isperiodic=false)
|
||||
b = copy(a)
|
||||
if isperiodic
|
||||
ncnt = prepend!(a[1:end-1], [a[end]]) + append!(a[2:end], [a[1]])
|
||||
else
|
||||
ncnt = prepend!(a[1:end-1], [false]) + append!(a[2:end], [false])
|
||||
end
|
||||
b[ncnt .== 0] = false
|
||||
b[ncnt .== 2] = ~b[ncnt .== 2]
|
||||
return b
|
||||
end
|
||||
|
||||
function show_gen(a::BitArray{1})
|
||||
s = join([i ? "\u2588" : " " for i in a], "")
|
||||
s = "\u25ba"*s*"\u25c4"
|
||||
end
|
||||
|
||||
hi = 70
|
||||
a = bitrand(hi)
|
||||
b = falses(hi)
|
||||
println("A 1D Cellular Atomaton with ", hi, " cells and empty bounds.")
|
||||
while any(a) && any(a .!= b)
|
||||
println(" ", show_gen(a))
|
||||
b = copy(a)
|
||||
a = next_gen(a)
|
||||
end
|
||||
a = bitrand(hi)
|
||||
b = falses(hi)
|
||||
println()
|
||||
println("A 1D Cellular Atomaton with ", hi, " cells and periodic bounds.")
|
||||
while any(a) && any(a .!= b)
|
||||
println(" ", show_gen(a))
|
||||
b = copy(a)
|
||||
a = next_gen(a, true)
|
||||
end
|
||||
|
|
@ -0,0 +1 @@
|
|||
f:{2=+/(0,x,0)@(!#x)+/:!3}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
`0:"_X"@f\0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0
|
||||
_XXX_XX_X_X_X_X__X__
|
||||
_X_XXXXX_X_X_X______
|
||||
__XX___XX_X_X_______
|
||||
__XX___XXX_X________
|
||||
__XX___X_XX_________
|
||||
__XX____XXX_________
|
||||
__XX____X_X_________
|
||||
__XX_____X__________
|
||||
__XX________________
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
// version 1.1.4-3
|
||||
|
||||
val trans = "___#_##_"
|
||||
|
||||
fun v(cell: StringBuilder, i: Int) = if (cell[i] != '_') 1 else 0
|
||||
|
||||
fun evolve(cell: StringBuilder, backup: StringBuilder): Boolean {
|
||||
val len = cell.length - 2
|
||||
var diff = 0
|
||||
for (i in 1 until len) {
|
||||
/* use left, self, right as binary number bits for table index */
|
||||
backup[i] = trans[v(cell, i - 1) * 4 + v(cell, i) * 2 + v(cell, i + 1)]
|
||||
diff += if (backup[i] != cell[i]) 1 else 0
|
||||
}
|
||||
cell.setLength(0)
|
||||
cell.append(backup)
|
||||
return diff != 0
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val c = StringBuilder("_###_##_#_#_#_#__#__")
|
||||
val b = StringBuilder("____________________")
|
||||
do {
|
||||
println(c.substring(1))
|
||||
}
|
||||
while (evolve(c,b))
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
' [RC] 'One-dimensional cellular automata'
|
||||
|
||||
' does not wrap so fails for some rules
|
||||
rule$ ="00010110" ' Rule 22 decimal
|
||||
|
||||
state$ ="0011101101010101001000"
|
||||
|
||||
for j =1 to 20
|
||||
print state$
|
||||
oldState$ =state$
|
||||
state$ ="0"
|
||||
for k =2 to len( oldState$) -1
|
||||
NHood$ =mid$( oldState$, k -1, 3) ' pick 3 char neighbourhood and turn binary string to decimal
|
||||
vNHood =0
|
||||
for kk =3 to 1 step -1
|
||||
vNHood =vNHood +val( mid$( NHood$, kk, 1)) *2^( 3 -kk)
|
||||
next kk
|
||||
' .... & use it to index into rule$ to find appropriate new value
|
||||
state$ =state$ +mid$( rule$, vNHood +1, 1)
|
||||
next k
|
||||
state$ =state$ +"0"
|
||||
|
||||
next j
|
||||
|
||||
end
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
10 MODE 1:n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT
|
||||
20 FOR k=1 TO n
|
||||
30 FOR j=1 TO w
|
||||
40 IF x(j) THEN PRINT "#"; ELSE PRINT "_";
|
||||
50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0
|
||||
60 NEXT:PRINT
|
||||
70 FOR j=1 TO w:x(j)=x2(j):NEXT
|
||||
80 NEXT
|
||||
90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
make "cell_list [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]
|
||||
make "generations 9
|
||||
|
||||
to evolve :n
|
||||
ifelse :n=1 [make "nminus1 item :cell_count :cell_list][make "nminus1 item :n-1 :cell_list]
|
||||
ifelse :n=:cell_count[make "nplus1 item 1 :cell_list][make "nplus1 item :n+1 :cell_list]
|
||||
ifelse ((item :n :cell_list)=0) [
|
||||
ifelse (and (:nminus1=1) (:nplus1=1)) [output 1][output (item :n :cell_list)]
|
||||
][
|
||||
ifelse (and (:nminus1=1) (:nplus1=1)) [output 0][
|
||||
ifelse and (:nminus1=0) (:nplus1=0) [output 0][output (item :n :cell_list)]]
|
||||
]
|
||||
end
|
||||
|
||||
to CA_1D :cell_list :generations
|
||||
make "cell_count count :cell_list
|
||||
(print ")
|
||||
make "printout "
|
||||
repeat :cell_count [
|
||||
make "printout word :printout ifelse (item repcount :cell_list)=1 ["#]["_]
|
||||
]
|
||||
(print "Generation "0: :printout)
|
||||
|
||||
repeat :generations [
|
||||
(make "cell_list_temp [])
|
||||
repeat :cell_count[
|
||||
(make "cell_list_temp (lput (evolve repcount) :cell_list_temp))
|
||||
]
|
||||
make "cell_list :cell_list_temp
|
||||
make "printout "
|
||||
repeat :cell_count [
|
||||
make "printout word :printout ifelse (item repcount :cell_list)=1 ["#]["_]
|
||||
]
|
||||
(print "Generation word repcount ": :printout)
|
||||
]
|
||||
end
|
||||
|
||||
CA_1D :cell_list :generations
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
num_iterations = 9
|
||||
f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 }
|
||||
|
||||
function Output( f, l )
|
||||
io.write( l, ": " )
|
||||
for i = 1, #f do
|
||||
local c
|
||||
if f[i] == 1 then c = '#' else c = '_' end
|
||||
io.write( c )
|
||||
end
|
||||
print ""
|
||||
end
|
||||
|
||||
Output( f, 0 )
|
||||
|
||||
for l = 1, num_iterations do
|
||||
local g = {}
|
||||
for i = 2, #f-1 do
|
||||
if f[i-1] + f[i+1] == 1 then
|
||||
g[i] = f[i]
|
||||
elseif f[i] == 0 and f[i-1] + f[i+1] == 2 then
|
||||
g[i] = 1
|
||||
else
|
||||
g[i] = 0
|
||||
end
|
||||
end
|
||||
if f[1] == 1 and f[2] == 1 then g[1] = 1 else g[1] = 0 end
|
||||
if f[#f] == 1 and f[#f-1] == 1 then g[#f] = 1 else g[#f] = 0 end
|
||||
f, g = g, f
|
||||
|
||||
Output( f, l )
|
||||
end
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
divert(-1)
|
||||
define(`set',`define(`$1[$2]',`$3')')
|
||||
define(`get',`defn(`$1[$2]')')
|
||||
define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1,
|
||||
incr($2),shift(shift(shift($@))))')')
|
||||
|
||||
dnl throw in sentinels at each end (0 and size+1) to make counting easy
|
||||
define(`new',`set($1,size,eval($#-1))`'setrange($1,1,
|
||||
shift($@))`'set($1,0,0)`'set($1,$#,0)')
|
||||
|
||||
define(`for',
|
||||
`ifelse($#,0,``$0'',
|
||||
`ifelse(eval($2<=$3),1,
|
||||
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
|
||||
define(`show',
|
||||
`for(`k',1,get($1,size),`get($1,k) ')')
|
||||
|
||||
dnl swap(`a',a,`b') using arg stack for temp
|
||||
define(`swap',`define(`$1',$3)`'define(`$3',$2)')
|
||||
define(`nalive',
|
||||
`eval(get($1,decr($2))+get($1,incr($2)))')
|
||||
setrange(`live',0,0,1,0)
|
||||
setrange(`dead',0,0,0,1)
|
||||
define(`nv',
|
||||
`ifelse(get($1,z),0,`get(dead,$3)',`get(live,$3)')')
|
||||
define(`evolve',
|
||||
`for(`z',1,get($1,size),
|
||||
`set($2,z,nv($1,z,nalive($1,z)))')')
|
||||
new(`a',0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0)
|
||||
set(`b',size,get(`a',size))`'set(`b',0,0)`'set(`b',incr(get(`a',size)),0)
|
||||
define(`x',`a')
|
||||
define(`y',`b')
|
||||
divert
|
||||
for(`j',1,10,
|
||||
`show(x)`'evolve(`x',`y')`'swap(`x',x,`y')
|
||||
')`'show(x)
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
function one_dim_cell_automata(v,n)
|
||||
V='_#';
|
||||
while n>=0;
|
||||
disp(V(v+1));
|
||||
n = n-1;
|
||||
v = filter([1,1,1],1,[0,v,0]);
|
||||
v = v(3:end)==2;
|
||||
end;
|
||||
end
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
CellularAutomaton[{{0,0,_}->0,{0,1,0}->0,{0,1,1}->1,{1,0,0}->0,{1,0,1}->1,{1,1,0}->1,{1,1,1}->0},{{1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1},0},12]
|
||||
Print @@@ (% /. {1 -> "#", 0 -> "."});
|
||||
|
|
@ -0,0 +1 @@
|
|||
CellularAutomaton[2^^01101000 (* == 104 *), {{1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1}, 0}, 12];
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
###.##.#.#.#.#..#
|
||||
#.#####.#.#.#....
|
||||
.##...##.#.#.....
|
||||
.##...###.#......
|
||||
.##...#.##.......
|
||||
.##....###.......
|
||||
.##....#.#.......
|
||||
.##.....#........
|
||||
.##..............
|
||||
.##..............
|
||||
.##..............
|
||||
.##..............
|
||||
.##..............
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
MODULE Cell EXPORTS Main;
|
||||
|
||||
IMPORT IO, Fmt, Word;
|
||||
|
||||
VAR culture := ARRAY [0..19] OF INTEGER {0, 1, 1, 1,
|
||||
0, 1, 1, 0,
|
||||
1, 0, 1, 0,
|
||||
1, 0, 1, 0,
|
||||
0, 1, 0, 0};
|
||||
|
||||
PROCEDURE Step(VAR culture: ARRAY OF INTEGER) =
|
||||
VAR left: INTEGER := 0;
|
||||
this, right: INTEGER;
|
||||
BEGIN
|
||||
FOR i := FIRST(culture) TO LAST(culture) - 1 DO
|
||||
right := culture[i + 1];
|
||||
this := culture[i];
|
||||
culture[i] :=
|
||||
Word.Or(Word.And(this, Word.Xor(left, right)), Word.And(Word.Not(this), Word.And(left, right)));
|
||||
left := this;
|
||||
END;
|
||||
culture[LAST(culture)] := Word.And(culture[LAST(culture)], Word.Not(left));
|
||||
END Step;
|
||||
|
||||
PROCEDURE Put(VAR culture: ARRAY OF INTEGER) =
|
||||
BEGIN
|
||||
FOR i := FIRST(culture) TO LAST(culture) DO
|
||||
IF culture[i] = 1 THEN
|
||||
IO.PutChar('#');
|
||||
ELSE
|
||||
IO.PutChar('_');
|
||||
END;
|
||||
END;
|
||||
END Put;
|
||||
|
||||
BEGIN
|
||||
FOR i := 0 TO 9 DO
|
||||
IO.Put("Generation " & Fmt.Int(i) & " ");
|
||||
Put(culture);
|
||||
IO.Put("\n");
|
||||
Step(culture);
|
||||
END;
|
||||
END Cell.
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
30 VAR length .
|
||||
35 VAR height .
|
||||
FOR length 0 ENDFOR 1 0 ARR VAR list .
|
||||
length 1 - VAR topLen .
|
||||
FOR topLen 0 ENDFOR 1 ARR VAR topLst .
|
||||
|
||||
DEF getNeighbors
|
||||
1 - VAR tempIndex .
|
||||
GET tempIndex SWAP
|
||||
tempIndex 1 + VAR tempIndex .
|
||||
GET tempIndex SWAP
|
||||
tempIndex 1 + VAR tempIndex .
|
||||
GET tempIndex SWAP .
|
||||
FOR 3 TOSTR ROT ENDFOR
|
||||
FOR 2 SWAP + ENDFOR
|
||||
ENDDEF
|
||||
|
||||
DEF printArr
|
||||
LEN 1 - VAR stLen .
|
||||
0 VAR j .
|
||||
FOR stLen
|
||||
GET j
|
||||
TOSTR OUT .
|
||||
j 1 + VAR j .
|
||||
ENDFOR
|
||||
|| PRINT .
|
||||
ENDDEF
|
||||
|
||||
FOR height
|
||||
FOR length 0 ENDFOR ARR VAR next .
|
||||
1 VAR i .
|
||||
FOR length
|
||||
list i getNeighbors VAR last .
|
||||
i 1 - VAR ind .
|
||||
last |111| ==
|
||||
IF : .
|
||||
next 0 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |110| ==
|
||||
IF : .
|
||||
next 1 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |101| ==
|
||||
IF : .
|
||||
next 1 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |100| ==
|
||||
IF : .
|
||||
next 0 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |011| ==
|
||||
IF : .
|
||||
next 1 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |010| ==
|
||||
IF : .
|
||||
next 1 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |001| ==
|
||||
IF : .
|
||||
next 1 INSERT ind
|
||||
ENDIF
|
||||
|
||||
last |000| ==
|
||||
IF : .
|
||||
next 0 INSERT ind
|
||||
ENDIF
|
||||
clear
|
||||
i 1 + VAR i .
|
||||
ENDFOR
|
||||
next printArr .
|
||||
next 0 ADD APPEND . VAR list .
|
||||
ENDFOR
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
% we need a way to write a values and pass the same back
|
||||
wi is rest link [write, pass]
|
||||
% calculate the neighbors by rotating the array left and right and joining them
|
||||
neighbors is pack [pass, sum [-1 rotate, 1 rotate]]
|
||||
% calculate the individual birth and death of a single array element
|
||||
igen is fork [ = [ + [first, second], 3 first], 0 first, = [ + [first, second], 2 first], 1 first, 0 first ]
|
||||
% apply that to the array
|
||||
nextgen is each igen neighbors
|
||||
% 42
|
||||
life is fork [ > [sum pass, 0 first], life nextgen wi, pass ]
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
|loaddefs 'life.nial'
|
||||
|I := [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]
|
||||
|life I
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import random
|
||||
|
||||
|
||||
type
|
||||
BoolArray = array[30, bool]
|
||||
Symbols = array[bool, char]
|
||||
|
||||
|
||||
proc neighbours(map: BoolArray, i: int): int =
|
||||
if i > 0: inc(result, int(map[i - 1]))
|
||||
if i + 1 < len(map): inc(result, int(map[i + 1]))
|
||||
|
||||
proc print(map: BoolArray, symbols: Symbols) =
|
||||
for i in map: write(stdout, symbols[i])
|
||||
write(stdout, "\l")
|
||||
|
||||
proc randomMap: BoolArray =
|
||||
randomize()
|
||||
for i in mitems(result): i = sample([true, false])
|
||||
|
||||
|
||||
const
|
||||
num_turns = 20
|
||||
symbols = ['_', '#']
|
||||
|
||||
T = true
|
||||
F = false
|
||||
|
||||
var map =
|
||||
[F, T, T, T, F, T, T, F, T, F, T, F, T, F, T,
|
||||
F, F, T, F, F, F, F, F, F, F, F, F, F, F, F]
|
||||
|
||||
# map = randomMap() # uncomment for random start
|
||||
|
||||
print(map, symbols)
|
||||
|
||||
for _ in 0 ..< num_turns:
|
||||
var map2 = map
|
||||
|
||||
for i, v in pairs(map):
|
||||
map2[i] =
|
||||
if v: neighbours(map, i) == 1
|
||||
else: neighbours(map, i) == 2
|
||||
|
||||
print(map2, symbols)
|
||||
|
||||
if map2 == map: break
|
||||
map = map2
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import strutils
|
||||
|
||||
const
|
||||
s_init: string = "_###_##_#_#_#_#__#__"
|
||||
arrLen: int = 20
|
||||
|
||||
var q0: string = s_init & repeat('_',arrLen-20)
|
||||
var q1: string = q0
|
||||
|
||||
proc life(s:string): char =
|
||||
var str: string = s
|
||||
if len(normalize(str)) == 2: # normalize eliminates underscores
|
||||
return '#'
|
||||
return '_'
|
||||
|
||||
proc evolve(q: string): string =
|
||||
result = repeat('_',arrLen)
|
||||
#result[0] = '_'
|
||||
for i in 1 .. q.len-1:
|
||||
result[i] = life(substr(q & '_',i-1,i+1))
|
||||
|
||||
echo(q1)
|
||||
q1 = evolve(q0)
|
||||
echo(q1)
|
||||
while q1 != q0:
|
||||
q0 = q1
|
||||
q1 = evolve(q0)
|
||||
echo(q1)
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
proc cellAutomata =
|
||||
proc evolveInto(x, t : var string) =
|
||||
for i in x.low..x.high:
|
||||
let
|
||||
alive = x[i] == 'o'
|
||||
left = if i == x.low: false else: x[i - 1] == 'o'
|
||||
right = if i == x.high: false else: x[i + 1] == 'o'
|
||||
t[i] =
|
||||
if alive: (if left xor right: 'o' else: '.')
|
||||
else: (if left and right: 'o' else: '.')
|
||||
|
||||
var
|
||||
x = ".ooo.oo.o.o.o.o..o.."
|
||||
t = x
|
||||
|
||||
for i in 1..10:
|
||||
x.echo
|
||||
x.evolveInto t
|
||||
swap t, x
|
||||
|
||||
cellAutomata()
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
let get g i =
|
||||
try g.(i)
|
||||
with _ -> 0
|
||||
|
||||
let next_cell g i =
|
||||
match get g (i-1), get g (i), get g (i+1) with
|
||||
| 0, 0, 0 -> 0
|
||||
| 0, 0, 1 -> 0
|
||||
| 0, 1, 0 -> 0
|
||||
| 0, 1, 1 -> 1
|
||||
| 1, 0, 0 -> 0
|
||||
| 1, 0, 1 -> 1
|
||||
| 1, 1, 0 -> 1
|
||||
| 1, 1, 1 -> 0
|
||||
| _ -> assert(false)
|
||||
|
||||
let next g =
|
||||
let old_g = Array.copy g in
|
||||
for i = 0 to pred(Array.length g) do
|
||||
g.(i) <- (next_cell old_g i)
|
||||
done
|
||||
|
||||
let print_g g =
|
||||
for i = 0 to pred(Array.length g) do
|
||||
if g.(i) = 0
|
||||
then print_char '_'
|
||||
else print_char '#'
|
||||
done;
|
||||
print_newline()
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
: nextGen( l )
|
||||
| i s |
|
||||
l byteSize dup ->s String newSize
|
||||
s loop: i [
|
||||
i 1 if=: [ 0 ] else: [ i 1- l byteAt '#' = ]
|
||||
i l byteAt '#' = +
|
||||
i s if=: [ 0 ] else: [ i 1+ l byteAt '#' = ] +
|
||||
2 if=: [ '#' ] else: [ '_' ] over add
|
||||
]
|
||||
;
|
||||
|
||||
: gen( l n -- )
|
||||
l dup .cr #[ nextGen dup .cr ] times( n ) drop ;
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
declare
|
||||
A0 = {List.toTuple unit "_###_##_#_#_#_#__#__"}
|
||||
|
||||
MaxGenerations = 9
|
||||
|
||||
Rules = unit('___':&_
|
||||
'__#':&_
|
||||
'_#_':&_
|
||||
'_##':&#
|
||||
'#__':&_
|
||||
'#_#':&#
|
||||
'##_':&#
|
||||
'###':&_)
|
||||
|
||||
fun {Evolve A}
|
||||
{Record.mapInd A
|
||||
fun {$ I V}
|
||||
Left = {CondSelect A I-1 &_}
|
||||
Right = {CondSelect A I+1 &_}
|
||||
Env = {String.toAtom [Left V Right]}
|
||||
in
|
||||
Rules.Env
|
||||
end
|
||||
}
|
||||
end
|
||||
|
||||
fun lazy {Iterate X F}
|
||||
X|{Iterate {F X} F}
|
||||
end
|
||||
in
|
||||
for
|
||||
I in 0..MaxGenerations
|
||||
A in {Iterate A0 Evolve}
|
||||
do
|
||||
{System.showInfo "Gen. "#I#": "#{Record.toList A}}
|
||||
end
|
||||
|
|
@ -0,0 +1 @@
|
|||
step(v)=my(u=vector(#v),k);u[1]=v[1]&v[2];u[#u]=v[#v]&v[#v-1];for(i=2,#v-1,k=v[i-1]+v[i+1];u[i]=if(v[i],k==1,k==2));u;
|
||||
|
|
@ -0,0 +1 @@
|
|||
cur = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]; for(n=0, 9, print(cur); cur = step(cur));
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
[0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0]
|
||||
[0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue