Re: need little help - no longer!
- To: mathgroup at smc.vnet.net
- Subject: [mg23619] Re: [mg23530] need little help - no longer!
- From: Mark Fisher <mefisher at bellsouth.net>
- Date: Wed, 24 May 2000 02:16:20 -0400 (EDT)
- References: <8g9nm8$mmd@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Following up on Andrzej's point, Ken's solution is indeed elegant, but Ted Ersek's solution can be compiled. Here is Ted's solution (slightly modified): With[{x = Random[]}, Which[x < .2, 1, x < .6, 2, x < .7, 3, x < 1., 4] Here's a function that takes a list and returns a CompiledFuntion: compileRandomIndex[list_List/; Plus @@ list == 1] := Block[{x, y}, Compile @@ (Hold[{}, With[{x = Random[]}, y], {{Which[__], _Integer}}] /. y -> Which @@ (Flatten @ Transpose[{Thread[x < Rest @ FoldList[Plus, 0, list]], Range[Length[list]]}]))] The Hold is used to make an inert container that facilitates the construction of the arguments to Compile. The idea is to insert the evaluated Which expression into the Hold container without evaluating the call to Random, and only then slap on the Compile head. (The third argument to Compile alerts Compile to the fact that the Which expression returns an Integer.) Here is the usage: m = {0.2, 0.4, 0.1, 0.3} ran = compileRandomIndex[m] ran[] It runs faster than Ken's solution, with the advantage growing with the length of the list. --Mark.