The following is a real bug that appeared in real code by yours truly. (Code which was written late at night under pressure. *ahem*)

I think that trying to see what causes a possible infinite loop in this code is rather instructive.

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; }
(Assume that the cur_balances are all positive numbers greater than 10,000, and their sum is under 2 billion.)

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.