i. returns the index of the first occurrence of a value within an array.

So, when implementing an algorithm which needs the index of the second
occurrence of the value within a (large) array, we need to do some
additional work.

let's say that our array is A, the value is V

   F=: A i. V   NB. the index of the first occurrence of V

What's the most efficient way of finding the second occurrence?

One possibility is
   S=: (1+F) + ((1+F) }. A) i. V

Another possibility, assuming that V is numeric and not zero, would be
   S=: (0 F} A) i. V

But A is large, so perhaps a faster approach would be:
  S=: {{ while. V~:y{A do. y=. y+1 end. y }} F

(Which has me wishing that S=: A i.!.F V would do the job, though I'm
not sure that that's completely appropriate...)

But, we can probably eliminate the need to generate a copy of A with a
little extra work:

   A=: 0 F} A
  S=: A i. V
  A=: V F} A

It seems to me that this is probably going to be the fastest approach.

Can anyone think of a faster approach (or something with comparable
speed which isn't quite so unwieldy?)

Thanks,

-- 
Raul
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to