One-dimensional cellular automata: Difference between revisions

added C code
(added C code)
Line 240:
Generation 8 : __##________________
Generation 9 : __##________________</pre>
 
=={{header|C}}==
<c>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define SPACEDIM 20
#define GENERATION 10
 
#define ALIVE '#'
#define DEAD '_'
 
/* what happens out of the space: is the world a circle, or
it really ends? */
#define CCOND 0
 
char space[SPACEDIM];
char tspace[SPACEDIM];
 
int rrand(int l)
{
return (int)((double)l*(double)rand()/((double)RAND_MAX+1.0));
}
 
void initspace(char *s, int d)
{
int i;
char *tp = "_###_##_#_#_#_#__#__";
for(i=0; (i < strlen(tp)) && (i<d) ; i++)
{
s[i] = (tp[i] == ALIVE) ? 1 : 0;
}
}
 
void initspace_random(char *s, int d)
{
int i;
for (i=0; i<d; i++)
{
s[i] = rrand(2);
}
}
 
/*
count the Number of Alive in the Neighbourhood
two kind of "bound condition" can be choosen
at compile time
*/
int nalive(char *s, int i, int d)
{
switch ( CCOND )
{
case 0:
return ((i-1)<0 ? 0 : s[i-1]) + ((i+1)<d ? s[i+1] : 0 );
case 1:
return s[ (i+1)%d ] + s[ (i+d-1)%d ];
}
}
 
void evolve(char *from, char *to, int d)
{
int i;
for(i=0; i<d; i++)
{
if ( from[i] )
{ /* 0 neighbour is solitude, 2 are one too much; 1, he's a friend */
if ( nalive(from, i, d) == 1 )
{
to[i] = 1;
} else {
to[i] = 0;
}
} else {
if ( nalive(from, i, d) == 2 )
{ /* there must be two, to make a child ... */
to[i] = 1;
} else {
to[i] = 0;
}
}
}
}
 
void show(char *s, int d)
{
int i;
for(i=0; i<d; i++)
{
printf("%c", s[i] ? ALIVE : DEAD);
}
printf("\n");
}
 
 
int main()
{
int i;
char *from, *to, *t;
initspace(space, SPACEDIM);
from = space; to = tspace;
for(i=0; i<GENERATION; i++)
{
show(from, SPACEDIM);
evolve(from, to, SPACEDIM);
t = from; from = to; to = t;
}
printf("\n");
initspace_random(space, SPACEDIM);
from = space; to = tspace;
for(i=0; i<GENERATION; i++)
{
show(from, SPACEDIM);
evolve(from, to, SPACEDIM);
t = from; from = to; to = t;
}
return 0;
}
</c>
 
The output is:
 
<pre style="height:10pc;overflow:scroll">_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________
 
#_###__#_#_#_#####_#
_##_#___#_#_##___##_
_###_____#_###___##_
_#_#______##_#___##_
__#_______###____##_
__________#_#____##_
___________#_____##_
_________________##_
_________________##_
_________________##_
</pre>
 
 
=={{header|Fortran}}==