Perl Weekly Challenge # 50: Merge Intervals and Noble Numbers
These are some answers to the Week 50 of the Perl Weekly Challenge organized by Mohammad S. Anwar.
Task 1: Merge Intervals
Write a script to merge the given intervals where ever possible.
[2,7], [3,9], [10,12], [15,19], [18,22]
The script should merge [2, 7] and [3, 9] together to return [2, 9].
Similarly it should also merge [15, 19] and [18, 22] together to return [15, 22].
The final result should be something like below:
[2, 9], [10, 12], [15, 22]
The example shows that intervals should be merged only if they overlap, but not if they are contiguous (in the example, [2,9] is not merged with [10, 12]).
Merge Intervals in Perl
For each interval except the first one, we check whether it overlaps with the previous one (stored in the $current variable); if it does overlap, we build a new interval merging it with $current.