Dan -

we must be on the same wavelength lately - I looked into this a couple of
weeks ago and here's what I came up with:

   pickFrom=: ] {~ [ ?@$ [: # ]
   #results =. 4e5 pickFrom 5 10 25 60#/i.4
400000
   1 round 100*(#results)%~+/results =/ i.4
5 10 25 60

It's simple and it's oriented toward working on a vector of items though
it's easy to adapt to indexes as seen here.  It wouldn't scale well for
extremely large selections but was fine for the few tens or hundreds of
thousands of items I was generating.

Regards,

Devon

On Fri, May 27, 2011 at 12:37 PM, Dan Bron <[email protected]> wrote:

> What's a clear, short verb to select random items in a weighted fashion?
> Something like ? only:
>
>        #0  Ranks 1 0 1
>        #1  y=.vector of weights (proportional to their total)
>        #2  x=.number of trials
>        #3  the monad is the dyad with a fixed left arg of 1, i.e.   1&$: :
> ( ... )
>        #4  result is x indexes into y  (i.e. results e. i.#y)  , selected
> at random, weighted by the index's proportion of the total
>
> Something like:
>
>           require'stats numeric'
>           wProb  =: 1&$: :( discreterand@:(;~ ] ,:~ i.@# ) )"1 0 1
>
>
>           ] results =. 4e5 wProb Y=.5 10 25 60
>        3 0 3 2 2 3 2 1 3 3 3 3 3 2 3 3 1 2 3 3 3 2 3 3 3 2 0 3 3 3 3 3 3
> ...
>           Y ,:~ (1 round 100 * #/.~ % #) (i.n=.#Y) , results
>        5 10 25 60
>        5 10 25 60
>
> Only discreterand seems a little heavyweight.  Is there a simpler way?
>
> -Dan
>
>
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
>



-- 
Devon McCormick, CFA
^me^ at acm.
org is my
preferred e-mail
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to