user2079392
user2079392

Reputation: 167

Joining intervals in perl

First let me show an example:

I have one set of intervals like

[1,4],[5,15],[16,20]

and the other one like

[2,3],[6,14]

and I want it become one set like

[1,2],[3,4],[5,6],[7,15],[16,20]

I am not sure what this operation is called though, forget me if the title was misleading. Is there a CPAN module with I can use or is it better to come up with my own solution? Is there a general well known algorithm?

Upvotes: 1

Views: 87

Answers (2)

Eugene K
Eugene K

Reputation: 3457

Step by step approach:

#!/usr/bin/perl
use Data::Dumper;

my @set1 = ([1,4],[5,15],[16,20]);
my @set2 = ([2,3],[6,14]);

# Make the tuples into an unsorted list
my @nums = ();
foreach my $tuple (@set1,@set2) {
    foreach my $num (@{$tuple}) {
        push @nums, $num;
    }
}

# Sort the list
my @sorted = sort {$a <=> $b} @nums;
print "@sorted\n";

# Retuple
my @finalset = ();
while(my @tuple = splice(@sorted,0,2)) {
    push @finalset, \@tuple;
}
print Dumper(\@finalset);

Upvotes: 0

Chris Charley
Chris Charley

Reputation: 6573

Using the pairs function from List::Util is a possible solution.

#!/usr/bin/perl
use strict;
use warnings;
use List::Util 'pairs';

my @a1 = ([1,4],[5,15],[16,20]);
my @a2 = ([2,3],[6,14]);

my @new = pairs sort {$a <=> $b} map {@$_} @a1, @a2;

use Data::Dumper; print Dumper \@new;

This prints

$VAR1 = [
          [
            1,
            2
          ],
          [
            3,
            4
          ],
          [
            5,
            6
          ],
          [
            14,
            15
          ],
          [
            16,
            20
          ]
        ];

Upvotes: 5

Related Questions