Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Closest-value-in-list Golf!

by larryk (Friar)
on May 29, 2001 at 17:47 UTC ( #83923=perlmeditation: print w/ replies, xml ) Need Help??

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'.

1. sub must take 2 params:
  1) list (or listref) of _numerical_ data (minimum 1 element)
  2) a number - int/real/negative - whatever! as the "match-closest-to-this" number
not necessarily in that order.
2. the original order of the data must be maintained - you can't sort the data directly.
3. can't think of any more!

Update: 19:45 29/05/2001 (GMT)
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.


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)];

#!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
I can't believe I had to leave a space in!

"Argument is futile - you will be ignorralated!"

Server Error (Error ID 5233487a76259)

An error has occurred. The site administrators have been notified of the problem and will likely soon fix it. We thank you, for you're patients.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://83923]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (9)
As of 2015-03-29 23:51 GMT
Find Nodes?
    Voting Booth?

    When putting a smiley right before a closing parenthesis, do you:

    Results (632 votes), past polls