-.@~: gets a mask of duplicates, I. then their indices.
With them you can get a list of (index, value) pairs:
((],.{~) I.@:-.@~:) a
5 2
8 3
11 3
12 2
With 0 ({ (],.{~) I.@:-.@~:)) a you can 0-index into this list.
If you are only interested into the first duplicate of a value,
you could filter duplicate values:
(#~ [:~: {:"1)@((],.{~) I.@:-.@~:) a
5 2
8 3
On Wed Jan 26, 2022 at 7:37 PM CET, Pawel Jakubas wrote:
> Dear J enthusiasts,
>
> I wonder how to elegantly implement dyad f that takes as x=1,2,3... and
> y
> vector and returns nth duplicate value with index of that occurence:
>
> d=: 1 _1 2 3 4 2 5 6 3 8 10 3 2
> NB. the earliest first duplicate is for 2 and index 2
> 1 f d
> 2 2
> NB. the earliest second duplicate is for 3 for index 11
> 2 f d
> 3 11
>
> In Haskell for nth occurence I would just use accumulator as
> (Map with key being element and value the number of occurence of this
> element,
> current index count)
> and left fold that with starting accumulator (Map.empty, 0).
>
> Kindest regards,
> Pawel
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm