On this page:
Fibonacci
Sequences
8.6

Assignment 10: Fibonacci

Goals: Practice working with state.

You should submit one .java file containing the solution to this problem.

Be sure to properly test your code and write purpose statements for your methods. A lack of tests and documentation will result in a lower grade! Remember that testing requires you to make some examples of data in an examples class.

Fibonacci

The Fibonacci sequence, whose first 10 elements are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, is recursively defined as:

Create a class Fibonacci which has a get method that, when called for the nth time on the same object, returns the nth element in the Fibonacci sequence (the first time it is called it should return 0). This class should only have a default (i.e. 0-argument) constructor. Additionally, create a static method which takes in an integer n, and returns the nth element of the Fibonacci sequence. Be sure to include purpose statements and effect statements where appropriate, and note that your non-static method should not need to rely on your static method (the latter is just an exercise in recursion).

Sequences

Consider the following interface:

interface ISequence<X>{
// returns the current element in the sequence // EFFECT: updates the state to the next element in the sequence X get();
}

We can now easily represent infinite sequences without taking up infinite memory!

Make sure your Fibonacci class can implement this interface (what should <X> be set to?). Then, create a GenericSequence<X> class which implements ISequence<X> and takes in some initial value for the sequence and a function object that given the current state will produce the next one. Note that the function given should be a proper function, i.e. should have no side effects. Use this to produce the sequence of strings "", "a", "aa", "aaa", "aaaa", etc. Feel free to come up with a sequence of your own!