Download Recursion, Fixed Schedule - Lecture Slides | CMSC 433 and more Study Guides, Projects, Research Programming Languages in PDF only on Docsity!
Recursion
CMSC 433
Bill Pugh and
Nelson Padua-Perez
Fixed schedule
Project 5 - Dense bags and Markov text
Due next Thursday, April 6th
2nd Midterm, Monday, April 10th
Readings from now to midterm:
Chapter 7: Recursion
Section 8.1: Tree terminology
How many ways are there to
order the numbers 1..n?
permutation(1) = 1
permutation(n) =
n different numbers that could occur first
remaining elements could appear in permutation(n-1) different orders
thus, permutation(n) = n * permutation(n-1)
= n!
Iteration/Recursion
Iteration over a list/sequence is very similar to using recursion to combine the result from the first element with the result from the rest of the list - int countVowels(String s) { if (s.length() == 0) return 0; int tailResult = countVowels(s.substring(1)); switch (s.charAt(1)) { case ‘a’: case ‘e’: case ‘i’: case ‘o’: case ‘u’: return tailResult+1; default: return tailResult; }}
Boring recursion
Using recursion where iteration would work
just as well isn’t that exciting
sometimes, a little to think about it as a recursive problem
In Java, it isn’t particularly efficient for long lists or deep recursion
In some languages (such as Scheme) that support tail recursion, it is as efficient as iteration. In fact, it can be the only/preferred way to implement iteration - has to be a special kind of recursion, called tail recursion
Some interesting recursion
Binary search
Quicksort
Mergesort
recursive permutation
generation
Define a function calculatePermutations(int [] a)
that generates each permutation of a and calls handlePermutation(int [] a)
with each generated permutation
Hint: define a recursive helper function calculatePermutations(int [] a, int k)
permutes the values in a[k ... a.length-1]
Change making
We’ve been asked to help devise a new set of coins for a country ruled by a mathematician.
Our task is to figure out what the denominations of the coins should be. - For example, in the US, the coins have denominations (in pennies) of: 1, 5, 10, 25 (we'll ignore half dollars for now)
Assume we want to have only three coins.
What values should the coins have so as to minimize the average number of coins needed to make any number of cents from 0 to 99.