CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Calculation of median value

 



xyz
New User

Feb 22, 2010, 4:31 AM

Post #1 of 4 (931 views)
Calculation of median value Can't Post

Hello,
I would like to calculate a median value from array. I retrieve data for the array from the following file:

Code
  
8
4
7
3
1
7
4
6
3
7
5


However I would like to read three lines and put them to the array. After that I would like to get the median of the three values.

If it is not possible to retrieve three lines because they are only two than I would like get the median of the two values.

I have tried to do it, but I have got just the output of the file and the median values.

Code
use Data::Dumper; 
use Carp;

my @numArray = ();
my $count = 0;

open( my $input_fh, '<', "test/median.txt")
or croak("Can't open file $!.\n");

while (my $line = <$input_fh> ) {
print $line;
if ($count < 3) {
push(@numArray, $line);
$count += 1;
}
elsif ($count == 2) {
my($medianValue) = Math::NumberCruncher::Median(\@numArray);
print "Median " . $medianValue;
}
else {
#print Dumper(\%$numArray);
}
}


How could I improve the code.

Best regards,


(This post was edited by xyz on Feb 22, 2010, 4:34 AM)


7stud
Enthusiast

Feb 22, 2010, 6:06 AM

Post #2 of 4 (928 views)
Re: [xyz] Calculation of median value [In reply to] Can't Post


Code
use strict; 
use warnings;
use 5.010;

use List::MoreUtils qw {natatime};
use Math::NumberCruncher;

open my $DATA, '<', 'data1.txt';
chomp(my @values = <$DATA>);

my $stepper = natatime 3, @values;

while ( my @chunk = $stepper->() ) {
my $median = Math::NumberCruncher::Median \@chunk;
say $median;
}

--output:--
7
3
4
6



xyz
New User

Feb 25, 2010, 12:19 AM

Post #3 of 4 (912 views)
Re: [7stud] Calculation of median value [In reply to] Can't Post

Thank you it works. Is it possible no to read the complete file, because the file can be very big and therefore it is more memory usage.


7stud
Enthusiast

Feb 25, 2010, 6:59 AM

Post #4 of 4 (908 views)
Re: [xyz] Calculation of median value [In reply to] Can't Post

Yes. Use a while loop to read the lines of the file. Every time you read a line, store the value in an array. When the array length gets to 3, calculate the median and empty the array. After the while loop ends, you will have to check the array length. If it's greater than 0, calculate the median for the last couple of lines in the file.


(This post was edited by 7stud on Feb 25, 2010, 7:00 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives