Dynamic Programming and Perl Arrays

Download Report

Transcript Dynamic Programming and Perl Arrays

Dynamic Programming
and
Perl Arrays
Ellen Walker
Bioinformatics
Hiram College
The Change Problem
• Given a set of coins
• Find the minimum number of coins to
make a given amount
Brute Force (Recursive)
Solution
Find_change (amt){
if ((amt) < 0) return infinity
else if (amt = 0) return 0
else
best = infinity
For each coin in the set
result = find_change(amt - coin)
if (result < best) best = result
return (best+1)
}
To write this in Perl
• We need to create an array of coins
– @coins = (1, 5, 10, 20, 25);
• To access a coin:
– $coin = $coins[2];
# gets 10
• To loop through all coins:
– foreach my $coin (@coins)
– Inside the loop, $coin is first $coins[0], then
$coins[1], etc.
Brute Force Coins in Perl
(main)
• my @coins = ( 1, 5, 10, 20, 25 );
• print brute_change( 99 );
• print "\n";
Subroutine to compute
change (Part 1)
sub brute_change
{
my $amt = shift(@_);
if ($amt == 0){
return 0;
}
if ($amt < 0){
return 99999999999999;
}
Subroutine to compute
change (Part 2)
my $best = 99999999999999;
foreach my $coin (@coins){
my $count = brute_change($amt - $coin);
print "coin is $coin , count is $count \n";
if ($best > $count) {
$best = $count;
}
}
return $best+1;
}
Why It Takes So Long
• For each value, we repeatedly compute
the same result numerous times.
• For 99: 74, 79, 89, 94, 98
• For 98: 73, 78, 88, 93, 97
• For 97: 72, 76, 87, 92, 96
• For 96: 71, 75, 86, 91, 95
• For 95: 70, 74, 85, 82, 94
Save Time by Expending
Space
• Instead of calling the function
recursively as we need it…
– Compute each amount from 1 to 99
– Save each result as we need it
– Instead of doing a recursive computation,
look up the value in the array of results
• This is called dynamic programming
Why it Works?
• By the order we’re computing in, we
know that we have every value less
than $amt covered when we get to
$amt.
• We never need a value larger than
$amt, so all the values we need are in
the table.
Dynamic Programming in
General
• Consider an impractical recursive solution
• Note which results are needed to compute a
new result
• Reorder the computions so the needed ones
are done first
• Save all results and look them up in the table
instead of doing a recursive computation
The Bottom Line for Making
Change
• Brute force solution considers every
sequence. Since longest sequence is
amt, this is O(coinsamt)
• Dynamic programming solution
considers every value from 1 to amt,
and for each amt, does a check for each
coin. This is O(coins*amt)