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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find the minimum value in a column of an array

Status
Not open for further replies.

Scifi9547

Technical User
May 6, 2010
10
US
Hi I have a file with data like this.

Code:
-1 2 ereu
1 2 rerer
2 2 rere
3 2 eee
3 2 wwwe
9 2 qqewew
9 2 vvvgf
-1 2 [URL unfurl="true"]wwwew[/URL]
4 3 wwew
-9 3 wwss
6 3 jjuu
7 3 kkii
7 3 ggtyu
8 3 ffder
1 4 rrtrr
1 4 rree

If the values in 2nd column are same, calculate the minimum value in the first column and print corresponding lines.

My desired output is;

Code:
-1 2 ereu
-1 2 [URL unfurl="true"]wwwew[/URL]
-9 3 wwss
1 4 rrtrr
1 4 rree

I wrote a code like this.

Code:
#! usr/bin/perl
use warnings;
use strict;
my @a = <> ;
my @b = ();
foreach (@a) {
 push (@b, split(/ /));
             }
my $i = 0;
my $j = 1;
my $min = $b[0];
my $x = 0;
while ($x++ < 150) { 
    $j = $j+3;
    $i = $i+3;
 
        if ($b[$j] = $b[$j+3]) { 

          if ($min > $b[$i]) {
                                   
                    $min = $b[$i] 
                             }
                         
                               }
                   }

 print "$min\n";

But the code ignores the condition if ($b[$j] = $b[$j+3]) and prints just the minimum value of first column. My idea was to use a regex involving the minimum value to print the corresponding lines.

Can experts help me please? thanks in advance.
 
You don't need a regex for this, just a queue that saves the lines with the current minimum value for the current group. If you can assume the lines are ordered, you could simplify the below logic, but the following will work.

Code:
#!/usr/bin/perl -w

use strict;
use warnings;

my @lines;
my $min;
my $group;

while (<DATA>) {
	my @data = split;
	
	if (@lines && $group ne $data[1]) {
		print @lines;
		@lines = ();
	}

	$group = $data[1];
	
	if (!@lines || $data[0] == $min) {
		push @lines, $_;
		$min = $data[0];
		
	} elsif ($data[0] < $min) {
		@lines = $_;
		$min = $data[0];
	}
}

print @lines;

__DATA__
-1 2 ereu
1 2 rerer
2 2 rere
3 2 eee
3 2 wwwe
9 2 qqewew
9 2 vvvgf
-1 2 [URL unfurl="true"]wwwew[/URL]
4 3 wwew
-9 3 wwss
6 3 jjuu
7 3 kkii
7 3 ggtyu
8 3 ffder
1 4 rrtrr
1 4 rree

- Miller
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top