Algorithms and OOD (CSC 207 2014S) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [FAQ] [Teaching & Learning] [Grading] [Rubric] - [Calendar]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines] [Partners] [Readings]
Reference: [Java 7 API] [Java Code Conventions] [GNU Code Conventions]
Related Courses: [CSC 152 2006S (Rebelsky)] [CSC 207 2013F (Rebelsky)] [CSC 207 2013S (Walker)] [CSC 207 2011S (Weinman)]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] [Issue Tracker (Course)] [Issue Tracker (Textbook)]
Overview
Question: How do you solve this?
Greed is Good
EM
UM
Why do we care? (other than that it's cooly recursive)
Direct translation
public static BigInteger fib(int n)
{
if (n < 2)
return new BigInteger(n);
else
return fib(n-1).add(fib(n-2));
} // fib(int)
Solution: Keep track of the past values
BigInteger FIB[]; // Cached results. If a value in here is non-null
// it's the nth Fibonacci number
public static BigInteger fib(int n)
{
if (FIB == null)
{
FIB = new BigInteger[n+1];
FIB[0] = 0;
FIB[1] = 1;
} // if we don't have the array
if (FIB[n] != null)
return FIB[n];
else
{
FIB[n] = fib(n-1).add(fib(n-2));
return FIB[n];
} // else
Caching has turned an exponential algortihm into a linear algorithm
We could also use the closed form of the Fibonacci numbers.
We could also build the array iteratively
public static BigInteger fib(int n)
{
BigInteger FIB[n+1];
FIB[0] = 0;
FIB[1] = 1;
for (int i = 2; i <= n; i++)
FIB[i] = FIB[i-1].add(FIB[i-2]);
return FIB[n];
} // fib(int)
Sam thinks of the key ideas of dynamic programming as: "Cache in an array, and build from bottom up."
Cache and build from bottom up
Reminder:
Running time: O(t*n) - Essentially linear.
Nope, we didn't get this far.
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [FAQ] [Teaching & Learning] [Grading] [Rubric] - [Calendar]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines] [Partners] [Readings]
Reference: [Java 7 API] [Java Code Conventions] [GNU Code Conventions]
Related Courses: [CSC 152 2006S (Rebelsky)] [CSC 207 2013F (Rebelsky)] [CSC 207 2013S (Walker)] [CSC 207 2011S (Weinman)]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] [Issue Tracker (Course)] [Issue Tracker (Textbook)]
Copyright (c) 2013-14 Samuel A. Rebelsky.

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this
license, visit http://creativecommons.org/licenses/by/3.0/
or send a letter to Creative Commons, 543 Howard Street, 5th Floor,
San Francisco, California, 94105, USA.