G'day nanophd,

Here's my take on a solution:

#!/usr/bin/env perl -l use strict; use warnings; use List::Util qw{max}; my %data = ( -4 => 0, -3.9 => 0, -3.8 => 0, -3.7 => 1, -3.6 => 0, -3.5 => 1, -3 +.4 => 0, -3.3 => 0, -3.2 => 5, -3.1 => 19, -3 => 23, -2.9 => 50, -2.8 => 43 +, -2.7 => 28, -2.6 => 72, -2.5 => 165, -2.4 => 302, -2.3 => 168, -2. +2 => 260, -2.1 => 151, -2 => 13, -1.9 => 1, -1.8 => 0, -1.7 => 0, -1.6 => 0, -1.5 => 0, -1.4 => 0, -1.3 => 0, -1.2 => 0, -1.1 => 0, -1 => 0, ); my $max_value = max values %data; my $max_key = { reverse %data }->{$max_value}; my $half = $max_value / 2; my @closest; my $side = 0; for my $key (sort { $a <=> $b } keys %data) { if ($key == $max_key) { $closest[$side] = [$max_key, $max_value] unless defined $close +st[$side]; $side = 1; next; } my $diff = abs $half - $data{$key}; if (! defined $closest[$side]) { $closest[$side] = [$key, $diff]; next; } $closest[$side] = [$key, $diff] if $closest[$side]->[1] > $diff; } print "max_key = $max_key; max_value = $max_value"; print "half = $half"; print "closest: BEFORE = $closest[0]->[0] AFTER = $closest[1]->[0]";

Output:

max_key = -2.4; max_value = 302 half = 151 closest: BEFORE = -2.5 AFTER = -2.1

-- Ken


In reply to Re: Finding hash key related to closest value by kcott
in thread Finding hash key related to closest value by nanophd

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.