Sunday, 3 June 2012

NXT Fibonacci

I have just received my Lego NXT Mindstorm! I immediatley flashed LeJOS on the brick, and before I got to work on some AI, I decided to create a little program which represented the Fibonacci sequence terms as bursts of the motors.
import lejos.nxt.*;

public class fib {
 
 public static void main (String[] args) {
  
  //Limit the sequence.
  int fib[] = new int[100];
  
  //First two terms in sequence are 1
  fib[0] = fib[1] = 1;
  
  for (int i = 2; i < fib.length; i++) {
   //Calculate, and print next value in Fibonacci sequence
   fib[i] = fib[i - 1] + fib[i - 2];
   LCD.clear();
   LCD.drawInt(fib[i], 6, 4);
   
   //Move forward for the length of the Fibonacci number
   Motor.C.forward();
   Motor.A.forward();
   try{
    Thread.sleep(fib[i]); 
   } catch (Exception e) {}
   
   //Sleep for a tenth of a second.
   Motor.C.stop();
   Motor.A.stop();
   try{
    Thread.sleep(100);
   } catch (Exception e) {}
  }
 }
}

No comments:

Post a Comment