in reply to Re: Overlapping portions of sub strings
in thread Overlapping portions of sub strings

No, this code will loop infinitely on many inputs, e.g. my @range3 = ([0, 10], [5, 20]); To fix that, you need redo if $j < @range;

But it is also buggy for contained intervals. The input my @range4 = ([0, 20], [5, 8]); will give the output interval ([0, 8]). Here is the complete correct code:

for (my $i = 0; $i < @range; $i++) { my $e = $range[$i][1]; for(my $j = $i+1; $j < @range; $j++) { unless($range[$j][0] > $e) { if ($range[$j][1] > $e) { $e = $range[$i][1] = $range[$j][1]; } splice @range, $j, 1; redo if $j < @range; } } }

Replies are listed 'Best First'.
Re: Re: Re: Overlapping portions of sub strings
by bart (Canon) on Jan 15, 2003 at 21:54 UTC
    Apparently you're right on both accounts. That of the nested range is a stupid mistake of mine, thinking that the end of the second range would always be the larger one because its start is. In fact, what I had in my head before I wrote anything down, was using max():
    use List::Util qw(max); $e = $range[$i][1] = max($e, $range[$j][1]);
    But in fact, your code is simpler, thus, better.

    But that of the infinite loop surprised me, a lot. I had assumed that the condition, the second expression in the for(;;) line, was being tested before any attempt at running the loop body, for each loop.

    But apparently, something goes wrong if you do a redo: