For a school assignment, we have to create a memorized fibonacci function that reuses the recursive implementation of computing the fibonacci.
What is a good way to design our memorized function such that it takes advantage of an already existing function? This is my implementation so far:
Base class:
public int computeFibonacci(int position) {
assertPosition(position);
if (position < 2) {
return 1;
}
return computeFibonacci(position - 1) + computeFibonacci(position - 2);
}
Inherited class:
public int computeFibonacci(int position) {
assertPosition(position);
if (position < 2) {
return 1;
}
if (this.memoizedList.containsKey(position)) {
return this.memoizedList.get(position);
}
int result = super.computeFibonacci(position - 1) + super.computeFibonacci(position - 2);
this.memoizedList.put(position, result);
return result;
}
superimplementation. If you callsuperimplementation then you won't be able to make use of memoized values.