0

I am trying to create a Cellular Automaton based on this. I have managed to do it in a simple way that would follow only rule 90 but when I changed it to accept any rule I did something wrong.

This is how the result should look. http://natureofcode.com/book/imgs/chapter07/ch07_12.png

This is my code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *myFile = fopen ( "input.txt" , "r" );
    int i, j, cell, iterations=100, current[80], previous[80], ruleCase, rule=90;
    for(i=0;i<80;i++){
        fscanf(myFile, "%1d", &previous[i]);
        if(previous[i]==0)printf("%c",176);
        else printf("%c",178);
    }
    for(i=0;i<=iterations;i++){
        for(cell=0;cell<80;cell++)
        {
            if((cell>0) && (cell<79))
            {
                ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[cell+1];
            }
            else if(cell==0)
            {
                ruleCase=1*previous[79]+2*previous[cell]+3*previous[cell+1];
            }
            else if(cell==79)
            {
                ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[0];
            }
            if(rule & (128 >> ruleCase))
            {
                current[cell]=1;
                printf("%c",178);
            }
            else
            {
                current[cell]=0;
                printf("%c",176);
            }
        }
        for(j=0;j<80;j++){
            previous[j]=current[j];
        }
    }
    return 0;
}

with the following input.txt 00000000000000000000000000000000000000100000000000000000000000000000000000000000

Thank you!

Community
  • 1
  • 1
Alexandru Cimpanu
  • 1,029
  • 2
  • 14
  • 38

2 Answers2

1

The fault is with this line:

ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[cell+1];

When I change the 3 to a 4 the program produces the Sierpinski triangles.

ruleCase=1*previous[cell-1]+2*previous[cell]+4*previous[cell+1];

and the other two similar lines.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
1

You appear to be computing ruleCase incorrectly. For example, in the general case you do ...

ruleCase=1*previous[cell-1]+2*previous[cell]+3*previous[cell+1]

... but you are trying to interpret the cell values as binary digits. Therefore, the coefficients should be powers of 2:

ruleCase=1*previous[cell-1]+2*previous[cell]+4*previous[cell+1]

Likewise for the special cases.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157