Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to extract Min and Max value from multiple rows

Status
Not open for further replies.

amili

Programmer
Nov 9, 2010
18
0
0
CA
Hi,

i am very new to PERL. I need to find Min and Max values for different ID (4,5,6) in multiple rows. eg:


13976 14249 4
14306 14416 4
15094 15651 4
16111 16236 5
16367 16643 5
19092 19624 5
19683 20561 5
21204 22151 6
22217 22765 6

This data is in data.dat file. The result should be:

Min 13976 and Max 15651 for ID 4
Min 16111 and Max 20561 for ID 5
Min 21204 and Max 22765 for ID 6

How to do this in PERL?

thanks


 
Hi,

Here is my attempt:

Code:
#/usr/bin/perl
use strict;
use warnings;

my %hash;

while (my $line = <DATA>) {
	my @row = split /\s+/, $line;

	$hash{$row[2]}{min} = 	  (!defined $hash{$row[2]}{min}) ? $row[0]
				: ($row[0] < $hash{$row[2]}{min}) ? $row[0]
				: $hash{$row[2]}{min}
				;
	$hash{$row[2]}{min} = 	  (!defined $hash{$row[2]}{min}) ? $row[1]
				: ($row[1] < $hash{$row[2]}{min}) ? $row[1]
				: $hash{$row[2]}{min}
				;
	$hash{$row[2]}{max} = 	  (!defined $hash{$row[2]}{max}) ? $row[0]
				: ($row[0] < $hash{$row[2]}{max}) ? $row[0]
				: $hash{$row[2]}{max}
				;
	$hash{$row[2]}{max} = 	  (!defined $hash{$row[2]}{max}) ? $row[1]
				: ($row[1] > $hash{$row[2]}{max}) ? $row[1]
				: $hash{$row[2]}{max}
				;
}

print "Min $hash{$_}{min} and Max $hash{$_}{max} for ID $_\n" foreach (sort keys %hash);

__DATA__
13976    14249    4
14306    14416    4
15094    15651    4
16111    16236    5
16367    16643    5
19092    19624    5
19683    20561    5
21204    22151    6
22217    22765    6

Chris
 
This would be a bit simpler and faster:
Code:
while(<DATA){
  ($min,$max,$key)=split;
  if(exists$hash{$key}){
    $hash{$key}[0]=$min if$min<$hash{$key}[0];
    $hash{$key}[1]=$max if$max>$hash{$key}[1];
  }else{
    $hash{$key}[0]=$min;
    $hash{$key}[1]=$max;
  }
}
print"Min $hash{$_}[0] and Max $hash{$_}[1] for ID $_\n"for(sort{$a<=>$b}keys%hash);
The sorting is adapted for numerical ID's.

Franco
: Online engineering calculations
: Magnetic brakes for fun rides
: Air bearing pads
 
Much cleaner prex.

To note the key difference, besides the improved code, mine will look for the min and max across both columns, whilst prex's uses the 1st column for min and the 2nd column for max. I suppose prex's method is what the O/P was intending, I wasn't sure. Anyhow, it would be very easy to adjust prex's the code if need be.

Chris
 
Hi both,

sorry for replying late. yess...your script had solved my problem. Thanks a million..
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top