Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: (Golf) Nearest Neighbors

by jmcnamara (Monsignor)
on Apr 04, 2001 at 13:36 UTC ( #69595=note: print w/replies, xml ) Need Help??

in reply to (Golf) Nearest Neighbors

Omitting leading whitespace this is 97 chars:
sub nn_single { @_=sort{$a<=>$b}@_; $_{abs$_[$_]-$_[$_-1]}=[$_-1,$_]for 1..$#_; @_[@{$_{(sort{$a<=>$b}keys%_)[0]}}] }
I worked on this without looking at your solutions but it is very similar to your nn3. Great minds?
If the list contains duplicates then the following will work. Omitting leading whitespace this is 114 chars.
sub nn_dup { my$s=sub{sort{$a<=>$b}keys%_}; @_{@_}=0; @_=&$s; %_=(); $_{abs$_[$_]-$_[$_-1]}=[$_-1,$_]for 1..$#_; @_[@{$_{(&$s)[0]}}] }
Update: I've updated this for a numerical sort and included snowcrash's %_ hack. danger, as usual, looks like the one to beat.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://69595]
[Discipulus]: nice Perl dreams, folks.. shower->Dumas->bed
[erix]: pere ou fils?
[Lady_Aleena]: Discipulus, good night.
[Discipulus]: pere, le vicomte de bragelonne.. wonderfull
[erix]: I'll keep that in mind (haven't read), buona notte :)
[Discipulus]: oh erix but is the fourth of cycle;read them in order
[erix]: hm, perhaps I can just read it here
Discipulus zzz...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2017-05-23 20:01 GMT
Find Nodes?
    Voting Booth?