I misunderstood the question, but here is a way of getting the 2nd match of a 
list.

ia =. 4 : ' x } y'
   }.@:I.@:~:@:(~: ia  ] , (1,#) $ _1:) 2 # i.10 
1 3 5 7 9 11 13 15 17 19




----- Original Message -----
From: Marshall Lochbaum <[email protected]>
To: [email protected]
Cc: 
Sent: Thursday, June 12, 2014 1:17:12 PM
Subject: [Jprogramming] Get the first two of each item in a list

I came across this problem and was wondering if anyone could come up
with a solution that is both elegant and fast:

Given a list of positive integers, return a mask (or index list) which
selects the first two of each unique value in the list.

Of course ~: is the solution if you only want the first value. A fast
but ugly solution using ~: is

f1 =. (] +. ~:@:(*-.)) ~:

which relies on the fact that the list is always positive. A more
general solution using key, which returns an unordered list of indices,
is

f2 =. (2&{.)^:(2<#)(<@)/.(;@:) i.@#

which isn't exactly pretty, but at least allows you to change the number
of values you want. It's also much slower than f1:

   d =. 99 , 100 + 1e7?.@$10000
   (I.@:f1 -: /:~@:f2) d
1
   6!:2 'f1 d'
0.273576
   6!:2 'f2 d'
1.08829

Any other ideas?

Marshall
----------------------------------------------------------------------
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