       Re: need little help

• To: mathgroup at smc.vnet.net
• Subject: [mg23544] Re: [mg23530] need little help
• From: Ken Levasseur <Kenneth_Levasseur at uml.edu>
• Date: Sat, 20 May 2000 03:10:22 -0400 (EDT)
• Organization: UMass Lowell
• References: <200005170230.WAA22619@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```Wagner:

I've used a variation of the following function to illustrate pattern
matching in my Mathematica class.

In:=
m = {0.2, 0.4, 0.1, 0.3}

Out=
{0.2, 0.4, 0.1, 0.3}

In:=
RandomIndex[m_] :=
(m /. {{a__, b___} :> Length[{a}] /; Plus[a] >= #}) &[Random[]]

In:=
Count[Table[RandomIndex[m], {1000}], #] & /@ Range[1, 4]/1000.

Out=
{0.211, 0.397, 0.103, 0.273}

****Using an iMac DV *****
In:=
Timing[Table[RandomIndex[m], {1000}]] // First

Out=
0.3 Second

Ken Levasseur
UMass Lowell
Instructor: the online course Introduction to Mathematica
(http://www.uml.edu/dept/math/m419.html)  Starts May 21!

Wagner Truppel wrote:
>
> Howdy everyone,
>
> I have a list of probabilities (whose sum is 1.0), each associated
> with an index. I'd like to randomly choose an index based on those
> probabilities. For example, suppose
>
> m = {0.2, 0.4, 0.1, 0.3}
>
> which dictates that index 1 should be selected with prob 0.2, index 2
> with prob 0.4, index 3 with prob 0.1, and index 4 with prob 0.3.
>
> I've already written a function that works, but I think there should
> be a simpler, more elegant, and more efficient way of accomplishing
> this task.
>
> Here's my solution:
>
> randomIndexPick[ m_ ] :=
>      Module[ { r, s },
>        r = Random[];
>        s = Sort[ Thread[ { m, Range[ Length[m] ] } ] ];
>        s = Table[ { Sum[ s[[i, 1]], { i, 1, k } ], s[[k, 2]] },
>                   { k, 1, Length[m] } ];
>        s = Map[ ( { r * First[#], Last[#] } ) &, s ];
>        s = Select[ s, ( First[#] ) & ];
>        Return[ s[[1, 2]] ] ];
>
> Table[ randomIndexPick[ {0.2, 0.4, 0.1, 0.3} ], {20} ]
>
> {4, 4, 1, 2, 2, 4, 4, 1, 4, 4, 2, 3, 1, 2, 2, 2, 4, 3, 2, 3}
>
> Does anybody have a better solution?
>
> Thanks!
> Wagner

```

• Prev by Date: Re: need little help
• Next by Date: Re: need little help
• Previous by thread: need little help
• Next by thread: RE: need little help