I think that trying to see what causes a possible infinite loop in this code is rather instructive.
(Assume that the cur_balances are all positive numbers greater than 10,000, and their sum is under 2 billion.)sub init_selections { my $self = shift; my $slice_count = shift; my $cur_balances = $self->{cur_balances}; my $balance = 0; $balance += $_ foreach @$cur_balances; my @selections; my $select = 0; my $cur_balance = $cur_balances->[0]; foreach my $i (1..$slice_count) { # Move move selected forward until we are at the current # position. while ($cur_balance < ($balance * $i / $slice_count)) { $cur_balance += $cur_balances->[++$select]; } push @selections, $select; } return $self->{selections} = \@selections; }
UPDATE
Oops, forgot to ask. Please hide answers as described in How to present spoilers :-). Thanks.
UPDATE 2
mdillon pointed out to me that I should mention that "billion" here is the US billion, ie 10**9. Also the slice count may be assumed to be an integer in the range 5-100.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Instructive bug
by mpeppler (Vicar) on Mar 05, 2002 at 16:39 UTC | |
by perrin (Chancellor) on Mar 05, 2002 at 16:41 UTC | |
by tilly (Archbishop) on Mar 05, 2002 at 17:36 UTC | |
by ChemBoy (Priest) on Mar 05, 2002 at 18:19 UTC | |
by mdillon (Priest) on Mar 05, 2002 at 17:48 UTC | |
by tilly (Archbishop) on Mar 05, 2002 at 18:15 UTC | |
by mdillon (Priest) on Mar 05, 2002 at 18:23 UTC | |
by mdillon (Priest) on Mar 05, 2002 at 16:48 UTC | |
|
Re: Instructive bug
by japhy (Canon) on Mar 05, 2002 at 17:14 UTC | |
|
Re: Instructive bug
by mdillon (Priest) on Mar 05, 2002 at 21:24 UTC | |
|
Re: Instructive bug
by hakkr (Chaplain) on Mar 05, 2002 at 17:06 UTC |