"A man told his son that he would give him $1000 if he could accomplish the following task. The father gave his son ten envelopes and a thousand dollars, all in one dollar bills. He told his son, "Place the money in the envelopes in such a manner that no matter what number of dollars I ask for, you can give me one or more of the envelopes, containing the exact amount I asked for without having to open any of the envelopes. If you can do this, you will keep the $1000."
When the father asked for a sum of money, the son was able to give him envelopes containing the exact amount of money asked for. How did the son distribute the money among the ten envelopes?"
I've also read it as a guy at an auction buying a car, etc. Anyway, our assignment for class went a few steps further. We had to initialy take in any amount of money, place the cash in as few envelopes as possible, and exit if the initial amount is less than the amount of money asked for in return.
I no longer suffer myself to code in Pascal, and I thought this fun for Perl. Here's mine, dashed off while on a conference call today ... no doubt there are more efficient ways to accomplish this ... curious to see the mix of TIMTOWTDI.
UPDATE: THX to gaudior for pointing out that CarTalk did this as one of their puzzles a ways back ... I could not remember what put the bug in my bonnet about this. Also, feel free to golf this ... those of you who haven't yet.
#!/usr/bin/perl -w use strict; die "Too little money or you are too greedy!\n" if $ARGV[1] > $ARGV[0]; my $cash = $ARGV[0]; my $amount = $ARGV[1]; my @dispersal; # fill the envelopes while ( $cash > 0 ) { # what would be the next amount in geometric progression my $current = 2**($#dispersal + 1); # if our next number is more than the cash in hand, we'll stuff the +last # envelope with the remainder if ( $current > $cash ) { push @dispersal, $cash } # otherwise, take the progression and stuff that else { push @dispersal, $current } # deduct the cash in this envelope $cash -= $dispersal[$#dispersal]; } # perform a numeric sort versus ASCII my @envelope = sort { $a <=> $b } @dispersal; print $#envelope+1 . " are as few envelopes as I can use.\n"; for ( my $i = $#envelope + 1; $i >= 0; $i-- ) { if ( $envelope[$i-1] <= $amount ) { $amount -= $envelope[$i-1]; print "Envelope $i (\$$envelope[$i-1])\n\$$amount remaining\n"; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: 1,000 bucks
by merlyn (Sage) on May 17, 2001 at 23:48 UTC | |
by cforde (Monk) on May 18, 2001 at 01:05 UTC | |
by larryk (Friar) on May 24, 2001 at 00:12 UTC | |
|
Re: 1,000 bucks
by dailylemma (Scribe) on May 17, 2001 at 23:42 UTC | |
|
Re: 1,000 bucks
by tachyon (Chancellor) on May 20, 2001 at 10:05 UTC | |
by cforde (Monk) on May 22, 2001 at 20:34 UTC | |
|
Re: 1,000 bucks
by gaudior (Pilgrim) on May 18, 2001 at 22:35 UTC |