Algorithms and OOD (CSC 207 2014F) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] - [Learning Outcomes] [FAQ] [Teaching & Learning] [Grading] [Rubric] - [Calendar]
Current: [Assignment] [EBoard] [Lab] [Outline] [Reading]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines] [Readings]
Reference: [Student-Curated Resources] [Java 8 API] [Java 8 Tutorials] [Code Conventions]
Related Courses: [CSC 152 2006S (Rebelsky)] [CSC 207 2014S (Rebelsky)] [CSC 207 2014F (Walker)] [CSC 207 2011S (Weinman)]
Misc: [Submit Questions] - [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] - [Issue Tracker (Course)] [Issue Tracker (Textbook)]
Overview
You go to the post-office and you need to put together the number of stamps to pay for the weight.
Describing more formally
Example
Make as much process as is possible in 1 step.
while (haven't reached target)
add biggest possible stamp
This is fast.
Exercise: Take a few minutes with a partner and see if you can come up with a correct algorithm that is not necessarily efficient.
Issues with enumerative algorithms
Comparing the two strategies
Sequence
F0 F1 F2 F3 F4 F5 F6 F7 ... Fn
0 1 1 2 3 5 8 13 F(n-1)+F(n-2)
We might rephrase this as
F0 = 0
F1 = 1
Fn = Fn = F(n-1) + F(n-2) Inductive Step
Let's think of this as a function
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1)+fib(n-2)
Code
public static int fib(int n)
{
// Base case
if ((n == 0) || (n == 1))
return n;
// Recursive case
else
return fib(n-1) + fib(n-2)
} // fib(int)
Let's trace it (Sam's attempt to sketch it again on the eboard)
fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2)
/ \ / \
fib(2) fib(1)
/ \
fib(1) fib(0)
Wow! We had to do fifteen or so recursive calls. That seems like a lot. The problem: We repeat a lot of work! fib(5) calls fib(4) and fib(3). fib(4) calls fib(3) again and fib(2). Each of the fib(3)'s also calls fib(2).
Strategy: Memoize! Each time you compute something (e.g., fib(2)), remember it.
So, what did we achieve?
Is there is a way that we can do something that's a little more natural?
Five minutes with your partner: Think about these issues for another solution for Fibonacci.
Idea: Start with base cases and work your way up.
public static int fib(int n)
{
// Set up data structure
if (n == 0) return 0;
int[] fib = new int[n+1];
fib[0] = 0;
fib[1] = 1;
// Invariant: for j < i, fib[j] is the jth Fibonacci number
for (int i = 2; i <= n; i++)
{
fib[i] = fib[i-1] + fib[i-2];
} // for
return fib[n];
} // fib(int)
Can we do better than this?