Java Fibonacci Word

Fibonacci-word

Fibonacci Word means the next word is concatenated up by the two words before it.

Sn = S(n-1) · S(n-2)

0
01
010
01001

Question

Write a program FibonacciWord.java that prints the Fibonacci word of order 0 through 10. f(0) = "a", f(1) = "b", f(2) = "ba", f(3) = "bab", f(4) = "babba", and in general f(n) = f(n-1) followed by f(n-2). Use string concatenation.

Implementing Steps

First of all, we are going to define two base words 0 and 01, and pass a length n as the parameter. Then, we can use a for loop to go through each word and use a temp variable as a swap place to help to forward the two variables of base words.

Here the goes the key steps:

  1. There two variables wordN, wordN_1 for S(n) and S(n-1)
  2. There a variable temp for exchanging values
  3. Loop N times
  4. Return the last value

Solution


/******************************************************************************
 *  Compilation:  javac FibonacciWord.java
 *  Execution:    java FibonacciWord n
 *
 *  Prints the Fibonacci word of f(n) = f(n-1) followed by f(n-2).
 *
 *  % java FibonacciWord 3
 *  01001
 *  % java FibonacciWord 4
 *  01001010
 *
 ******************************************************************************/

public class FibonacciWord {
    private static String fibWord(int n) {
        String wordN = "01";
        String wordN_1 = "0";
        String temp;

        for (int i = 2; i <= n; i++) {
            temp = wordN;
            wordN += wordN_1;
            wordN_1 = temp;
        }

        return wordN;
    }

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        System.out.println(fibWord(n));
    }
}

Output

-> javac FibonacciWord.java
-> java FibonacciWord 2
010
-> java FibonacciWord 3
01001
-> java FibonacciWord 4
01001010