#!/usr/bin/env perl use utf8; ############################################################################### # This program computes the median of a list of float values on STDIN. # # Copyright © 2021 Richard Lesh. All rights reserved. ############################################################################### use Error::Simple; use Nice::Try; use Utils; use strict; use warnings; MAIN: { my $line; my $d; my $count = 0; my $values = []; while ($line = ) { $line = Utils::trim($line); try { $d = Utils::stod($line); push(@{$values}, $d); ++$count; } catch (Error::Simple $ex) { if (length($line) > 0) { print "Can't parse input: ", $line, "\n"; } } } $values = [sort { $a <=> $b } @$values]; if ($count > 0) { my $median; if ($count % 2 == 1) { $median = $values->[int(($count - 1) / 2)]; } else { my $middle = int($count / 2); $median = ($values->[$middle] + $values->[$middle - 1]) / 2.0; } print Utils::messageFormat("\{0:g\}", $median), "\n"; } }