perlmeditation
larryk
Inspired by [neophyte]'s question in the chatter about parsing a list of numerical data for the nearest value to a given (number) value, I tee off timidly and prepare for an ass-whoopin'.
<p><b>Rules</b><br>
1. sub must take 2 params:<br>
1) list (or listref) of _numerical_ data (minimum 1 element)<br>
2) a number - int/real/negative - whatever! as the "match-closest-to-this" number<br>
not necessarily in that order.<br>
2. the original order of the data must be maintained - you can't sort the data directly.<br>
3. can't think of any more!
<p><b>Update: 19:45 29/05/2001 (GMT)</b><br>
Apologies if I did not make this clear: 2 things go into the sub - a number and a list. the order in which you pass these is up to you. the list can either go in as a strtaight list or as a reference to a list - your choice - just so long as the original isn't modified. and the return value from the sub should be either the value closest to the given number or the index in the original list.
<p>e.g.
<code>
sub g {blah}
print "Closest value is ",g(@list,$number);
# or
print "Closest value is ",g($number,@list);
# or
print "Closest value is ",g(\@list,$number);
# or
print "Closest value is ",g($number,\@list);
# OR
print "Closest value is ",$list[g(@list,$number)];
# or
print "Closest value is ",$list[g($number,@list)];
# or
print "Closest value is ",$list[g(\@list,$number)];
# or
print "Closest value is ",$list[g($number,\@list)];
</code>
<p><readmore>
<code>
#!perl -w
use strict;
chomp(my @list = <DATA>);
# FORE!!! 78 chars.
sub g {my%h=();my$n=pop;$h{abs($_-$n)}=$_ for@_;my@s=sort{$a<=>$b}keys%h;$h{shift@s};}
print g(@list,10);
__DATA__
17
1.4
18.2
7.9
12.2
12.5
1.1
7.8
18.3
20
6.7
6.9
18.1
1.5
17.7
16.6
1.2
1.3
17.5
</code>
I can't believe I had to leave a space in!
<p><FONT color=#330099 size=1>"Argument is futile - you will be ignorralated!"</FONT>