On 02/12/2011 06:24, [email protected] wrote:
Hi All
I have following code set of code which will have a subroutine which
has 2 parameters. The first parameter (VALUES) is a reference to an
array of non-sorted, hex strings. The second parameter (RANGES) is a
reference to an array that is empty. The subroutine should fill the
RANGES array with consecutive ranges built from the VALUES array.
The subroutine should return the number of ranges built .
Example:
@array = ("0A0", "005", "001", "004", "0BC", "004", "002", "001");
$numRanges = buildRanges(VALUES => \@array, REF_RANGES=>\@ranges);
The array @ranges should be filled as follows:
@ranges = ("001:002", "004:005", "0A0", "0BC"); ==> I am not getting all the
values in the array . I am getting only ranges in array .
And $numRanges should be 2.
============================
#!/usr/bin/perl
use strict;
my @array = ("0A0", "005", "001", "0A1","004", "0BC", "002" );
my @ranges = ();
my $numRanges = buildranges(VALUE => \@array , REF_RANGES=>\@ranges);
print "No of ranges exist in array : $numRanges .\n";
sub buildranges{
my ($value , $ref_array , $range , $ref_range)= @_;
my @array = @$ref_array;
my @ranges = @$ref_range;
my ($int1,$int2);
for (my $i=0;$i< @array;$i++){
my $int1 = hex($array[$i]);
for (my $j=1;$j< @array; $j++){
$int2 = hex($array[$j]);
if ($int2 == ($int1 + 1)){
push(@ranges,"$array[$i]:$array[$j]");
}
elsif ($int2 == ($int1 - 1)){
push(@ranges,"$array[$j]:$array[$i]");
}
else {
next;
}
}
}
my %hash_ranges = map {$_ => 1 } @ranges;
@ranges = keys %hash_ranges;
my $numRanges = \@ranges;
return $numRanges;
}
=================================
What changes I should make in my program .
The problem is that you don't push anything onto @ranges if the value
is out of sequence. The program below does what you need.
HTH,
Rob
use strict;
use warnings;
my @array = qw(0A0 005 001 004 0BC 004 002 001);
my @ranges;
my $numRanges = buildranges(VALUES => \@array, RANGES=>\@ranges);
print "No of ranges exist in array : $numRanges\n";
print "@ranges\n";
sub buildranges {
my %params = @_;
my @data = sort {$a <=> $b} map hex, @{$params{VALUES}};
my $ranges = $params{RANGES};
my $num_ranges = 0;
my ($beg, $end);
$beg = $end = shift @data;
foreach my $val (@data, -1) {
if ($val == $end + 1) {
$end = $val;
}
elsif ($val != $end) {
my $range;
if ($beg == $end) {
$range = sprintf '%03X', $beg;
}
else {
$range = sprintf '%03X:%03X', $beg, $end;
$num_ranges++;
}
push @$ranges, $range;
$beg = $end = $val;
}
}
return $num_ranges;
}
**OUTPUT**
No of ranges exist in array : 2
001:002 004:005 0A0 0BC
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/