Re: need little help
- To: mathgroup at smc.vnet.net
- Subject: [mg23549] Re: [mg23530] need little help
- From: BobHanlon at aol.com
- Date: Sat, 20 May 2000 03:10:26 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
In a message dated 5/16/2000 10:56:25 PM, wtruppel at uci.edu writes:
>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?
randomIndexPick[m_List] :=
Module[{cdf = FoldList[Plus, First[m], Rest[m]], r = Random[]},
Count[cdf, _?(# < r &)] + 1] /; (Plus @@ m) == 1
Bob
BobHanlon at aol.com