Re: Algorithm Questions
- To: mathgroup at smc.vnet.net
- Subject: [mg29402] Re: Algorithm Questions
- From: Mark Fisher <mark at markfisher.net>
- Date: Sat, 16 Jun 2001 22:43:50 -0400 (EDT)
- References: <9gf01l$7lj$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Try this: SetAttributes[RandomWithoutReplacement, HoldFirst] RandomWithoutReplacement[ran_, n_Integer?Positive] := Module[{list = {}, r}, While[Length[list] < n, If[FreeQ[list, r = ran], AppendTo[list, r]]]; list ] Needs["DiscreteMath`Permutations`"] RandomWithoutReplacement[RandomPartition[100], 100] --Mark. Hu Zhe wrote: > > Hi, > I am wondering that if Mathematica has lazy-evaluation features. Say I > am going to extract 100 lists from the permutation lists of {1, > 2,...,100} (Permutation[Range[100]]) randomly. > > If I program like this: > > largeList = Permutation[Range[100]]; > > indx = Table[Random[Integer, {1, 100!}], {100}]; > > Part[largeList, indx] > > the program is very slow, since it works out all the 100! elements for > the largeList, while I only need 100 items from it. > > Can I program like this ? Say, > > take 100 (somePermutationFunction 100) > > so that the permutation stops after 100 lists were taken. (I learned > that it's called lazy-evaluation from Haskell.) > > The second question is that: > > I want the 100 lists randomly taken to be all different. > > So I program this way: > > While[Length[a] != 100, > a = (Table[Random[Integer, {1, n!}], {100}] // Union)]; > > there must be more efficient solutions, especially to combine the > solution with the first question? > > So my slow program is like this, deeply welcome suggestions to improve > it: > > randomList[n_, k_] := > Module[{a}, > While[Length[a] != k, > a = (Table[Random[Integer, {1, n!}], {k}] // Union)]; > Part[Permutations[Range[n]], a]] > > Sincerely, > Hu Zhe