Wednesday, November 5, 2008

A bit of code.

This being a blog about computer science, I'm surprised that we have yet to post any actual code. Well, that's about to change:

/*
* Form: if n(x) then set y
*/
private boolean checkSyntax(String s) {
  Scanner scan = new Scanner(s);
  if (!scan.next().equalsIgnoreCase("if"))
    return false;
  if (!scan.next().equalsIgnoreCase("n"))
    return false;
  if (scan.nextInt() < 0)
    return false;
  if (!scan.next().equalsIgnoreCase("then"))
    return false;
  if (!scan.next().equalsIgnoreCase("set"))
    return false;
  if (scan.nextInt() < 0)
    return false;
  return true;
}

I know, I know, not exactly awe inspiring. In fact, Something about this code just seems wrong. It's ugly, with way to many "ifs" in a row and way to many return statements. Not to mention that it only works for one particular case! I mean, what happens when I want a check the syntax of something more complicated (which would be just about anything). Well at least it's commented.

This method took about a minute to write, and despite it's apparent inelegance, I am rather happy with it. I would even go as far to say that it's a solid piece of code. I've run quite a few malformed statements through it and it handled them with no problems whatsoever (due to the handy scanner class), and it's easy to read. It only handles a very simple syntax, but that's all I need for now.

Right now I'm building a prototype of a program that will test out the ideas I presented in Stabilize This. Right now all I want it to do is read in a text file of rules and then execute them on a simple graph. I can then see if the algorithm (rules) stabilizes within a certain time frame.

The next step would be to generate random graphs and track how the algorithm performs on each one. Finally, I will create a program that generates, combines, and mutates the rules. Then I will be able to generate and test algorithms to my heart's desire.

Right now you are probably thinking, "But James, isn't using plain text as an intermediary data structure going to be far to slow to do any significant amount of testing?" Absolutely, which brings me back to my ugly little piece of code: once it has served it's purpose it will be discarded as quickly as it was written. For now it's handy to have so I can easily create test cases and visually check the output of and generator that I make.

James

No comments: