0

I'm using a piece of code taken from the website The Nature of Code - https://natureofcode.com/book/chapter-7-cellular-automata/ - the portion I used was from example 7.1. I'm trying to create a one-dimensional cellular automaton using the Processing IDE, but I keep getting an error saying that brackets are missing from particular locations.

Errors: -Missing curlry bracket "}", line 32 -Syntax error on "}", delete this, line 40

I've gone over it multiple times, but I can't see how this is wrong. Though I did try changing them as it says, only to get more errors. I thought maybe they were just in the wrong place, but I also can't see how that's the case. They seem to be correct as far as I can tell, but maybe I'm missing something. This is my first time using Processing, and it's been a long time since I last used Java. So maybe I'm mistaken.

class CA {
  int[] cells;
  int[] ruleset;
  int w = 10;
  // The CA should keep track of how
  // many generations.
  int generation = 0;
  CA() {
    cells = new int[width/w];
    ruleset = new int[]{0,1,0,1,1,0,1,0};
    cells[cells.length/2] = 1;
  }

  // Function to compute the next generation
  void generate() {
    int[] nextgen = new int[cells.length];
    for (int i = 1; i < cells.length-1; i++) {
      int left   = cells[i-1];
      int me     = cells[i];
      int right  = cells[i+1];
      nextgen[i] = rules(left, me, right);
    }
    cells = nextgen;
    // Increment the generation counter.
    generation++;
  }

  int rules(int a, int b, int c) {
    String s = "" + a + b + c;
    int index = Integer.parseInt(s,2);
    return ruleset[index];
  }

  for (int i = 0; i < cells.length; i++) {
    if (cells[i] == 1) fill(0);
    else               fill(255);
    // Set the y-location according to the generation.
    rect(i*w, generation*w, w, w);
  }
}

The program is supposed to print each generation of the one-dimensional CA on top of the next.

CrashBandicoot
  • 399
  • 2
  • 7
  • 21
  • Do you maybe need to have that for loop on line 34 within a method? Also, put curly braces on lines 35, after the '(cells[i] == 1)' and after the else. – CrashBandicoot Jan 23 '19 at 16:07
  • Curly braces around single-command code blocks such as the `fill(0);` and `fill(2555);` are not necessary. – hlg Jan 23 '19 at 16:37

1 Answers1

0

The for-loop in the end of the CA class is not supposed to be there. That is why you get the error: the parser expects either a method declaration or the end of the class, hence a curly bracket.

It looks like this loop is actually drawing the CA state, so you can try to wrap it in a void draw(){} method. Then it should be syntactically correct, not sure though whether it works as expected. Alternatively move the for-loop outside of the class and call fill based on the the cells state of an instance of the CA class.

In any case, will need some additional code that creates the CA instance and invokes the generate function.

hlg
  • 1,321
  • 13
  • 29