#!/usr/bin/perl


# $om = odd_median(\@array) computes the odd median of an array of
# numbers.
#
sub odd_median {
    my $arrayref = shift;
    my @array = sort @$arrayref;
    return $array[(@array - (0,0,1,0)[@array & 3]) / 2];
}

# $mode = mode(\@array) computes the mode of an array of numbers.
#
sub mode {
    my $arrayref = shift;
    my (%count, @result);

    # Use the %count hash to store how often each element occurs
    foreach (@$arrayref) { $count{$_}++ }

    # Sort the elements according to how often they occur,
    # and loop through the sorted list, keeping the modes.
    foreach (sort { $count{$b} <=> $count{$a} } keys %count) {
        last if @result && $count{$_} != $count{$result[0]};
        push(@result, $_);
    }

    # Uncomment the following line to return undef for nonunique modes.
    # return undef if @result > 1;

    # Return the odd median of the modes.
    return odd_median \@result;       # odd_median() is defined earlier.
}

@points = (10, 10, 31, 28, 46, 22, 27, 28, 42, 31, 8, 27, 45, 34, 6, 23);

print mode(\@points), "\n";


