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.
In reply to Instructive bug by tilly
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |