Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Union of overlapping numeric intervals

by atcroft (Abbot)
on Dec 30, 2013 at 22:50 UTC ( [id://1068782]=note: print w/replies, xml ) Need Help??


in reply to Union of overlapping numeric intervals

Here is a one-liner that provides an example of parsing of lists similar to those you provide into individual letter:number ranges:

perl -Mstrict -Mwarnings -le 'my @l = ( q{a:10-34 b:9-12 c:12-24 e: 1- +9}, q{a:1-8 a: 19-24 b:2-6}, q{a:7-11 d:9-23 e:12-23} ); foreach my $ +m ( @l ) { foreach my $n ( $m =~ m/([a-z]:\s*\d+(?:\s*-\s*\d+))/ig ) +{ $n =~ s/\s+//g; print $n; } }'

Here is a one-liner that provides an example of parsing a key and value or range to get the key, starting and ending values (or repeats the starting value as the ending value, if there is only one value present:

perl -Mstrict -Mwarnings -le 'my $str = q{a:1}; my %f; $str =~ m/([a-z +]):(\d+)(?:-(\d))?/; my ( $k, $starting, $ending ) = ( $1, $2, define +d $3 ? $3 : $2 ); print $k; print $starting; print $ending;'

Here is a one-liner that provides an example of filling in a hash with values in a range (the Data::Dumper code present only to verify that the values were set:

perl -Mstrict -Mwarnings -MData::Dumper -le '$Data::Dumper::Sortkeys = + 1; my %range = ( start => 1, end => 9, ); my %f; foreach my $i ( $ra +nge{start} .. $range{end} ) { $f{$i}++; } print Data::Dumper->Dump( [ + \%f, ], [ qw( *f ) ] );'

Here is a one-liner that takes a hash with values and loops through, to determine the consecutive ranges present:

perl -Mstrict -Mwarnings -le 'my %g = ( 1 => 1, 2 => 2, 3 => 2, 4 => 2 +, 6 => 1, 7 => 1, 8 => 1, 12 => 1, ); my @h = sort { $a <=> $b } keys + %g; my $sv; my $ev; while ( scalar @h ) { my $v = shift @h; if ( ! d +efined $sv ) { $sv = $v; } if ( ! defined $ev ) { $ev = $v; } my $i = + 1; while ( scalar @h and $h[0] == $sv + $i ) { $i++; $ev = shift @h; + } if ( $sv == $ev ) { print $sv; } else { print $sv, q{ - }, $ev; } +$sv = undef; $ev = undef; }'

With all of the examples above, there should be enough, with the addition of a small amount of code, to do what you desire. If not, then you might want to refocus your study of perl on the areas you still find yourself weakest in.

Please comment in the thread if you have any questions.

Hope that helps.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1068782]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2024-04-24 09:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found