I like Pascal's method as it's easy to adapt to return the indexes of the
nearest values, which may be more useful than returning the values
themselves:
nearestIxs=: [: I. [: (] = <./) [: | -
1 5 7 8 9 7 5 nearestIxs 6
1 2 5 6
On Mon, Jun 1, 2015 at 9:12 PM, 'Pascal Jasmin' via Programming <
[email protected]> wrote:
> there is
>
> 1 5 7 8 9 ( [ #~ [: (= <./)@:| -) 6
> 5 7
>
>
> which returns all items that are nearest.
>
>
> ----- Original Message -----
> From: Joe Bogner <[email protected]>
> To: [email protected]
> Cc:
> Sent: Monday, June 1, 2015 9:02 PM
> Subject: [Jprogramming] Find nearest number in a list
>
> Is there a more efficient, idiomatic method of finding the nearest
> (absolute difference) x to y?
>
> nearest=:([ {~ {.@/: @: |@:-)
>
> 1 5 8 9 nearest 4
> 5
>
> 1 5 8 9 nearest 6
> 5
>
> 1 5 8 9 nearest 5
> 5
>
> 1 5 8 9 nearest 2
> 1
>
> This seems to work fine but was curious if there is a more common solution
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
>
--
Devon McCormick, CFA
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm