Thanks Pascal. I only need the first nearest number, but yours may be handy
in the future

Raul, I wasn't sure how best to apply I., but that's where my head was at
too. My x would be sorted so it seems like an opportunity for special code
/ FLOS[1] to stop searching after the a value larger than the nearest value
is found

But as you said, it's probably not worth the extra code

NB. initial attempt

   6!:2 '(i.1e7) nearest 0'

0.246118



NB. pascal's


   6!:2 '(i.1e7) ( [ #~ [: (= <./)@:| -) 0'

0.206099


NB. using I.


   6!:2 '(i.1e7) I. 0'

0.0501746


So it seems like there would be a small amount of opportunity to speed it
up... maybe something like this that combines mine and I.


nearest3=: 4 : 0

NB. indices of value larger and one less

matches=:x ( (<: , ])@:I.) y

NB. filter out indices greater than length of x or less than 0

matches=. (#~ ((#x)&> *. _1&<)) matches

NB. find the closest match from the matches

closest=. (matches{x) ([ {~ {.@/: @: |@:-) y

)


   6!:2 '(i.1e7) nearest3 4'

0.0503515


Probably not worth it though


[1] -
http://www.jsoftware.com/jwiki/Vocabulary/SpecialCombinations#Searching_and_Matching_Items:_Fast_List_Operations_.28FLOs.29



On Mon, Jun 1, 2015 at 9:38 PM, Raul Miller <[email protected]> wrote:

> If you know that your values are sorted, you could use I. to get an
> initial approximation (a set of up to three values) and then use brute
> force to pick from them.
>
> This assumes also that you want a single value (or index).
>
> This also winds up being more code than the other proposals I've seen
> here. So I'm not sure if it's "worth it".
>
> --
> Raul
>
>
> On Mon, Jun 1, 2015 at 9:02 PM, Joe Bogner <[email protected]> wrote:
> > 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
>
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to