MathGroup Archive 2001

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Random Sampling Without Replacement?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg26650] Re: [mg26586] Random Sampling Without Replacement?
  • From: "Allan Hayes" <hay at haystack.demon.co.uk>
  • Date: Sat, 13 Jan 2001 22:36:23 -0500 (EST)
  • References: <200101090652.BAA00242@smc.vnet.net> <H5z76.38$nn4.14271@ralph.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Daniel,
I'd like to be able to use your technique on an unnamed list, but we  have

SetAttributes[deal, HoldFirst]
deal[deck_, start_, end_] :=
  Module[{len = Length[deck], rand}, Do[rand = Random[Integer, {j, len}];
      deck[[{j, rand}]] = deck[[{rand, j}]], {j, start, end}];
    Take[deck, {start, end}]]

deal[{1, 2, 3, 4, 5, 6}, 1, 3]

Set::setps:
   {1, 2, 3, 4, 5, 6} in assignment of part is not a
     symbol.

To get this functionality we can drop the attribute HoldFirst and use

deal2[deck_, start_, end_] :=
  Module[{len = Length[deck], rand, dk = deck},
    Do[rand = Random[Integer, {j, len}];
      dk[[{j, rand}]] = dk[[{rand, j}]], {j, start, end}];
    Take[dk, {start, end}]]

Thus

deal2[{1, 2, 3, 4, 5, 6}, 1, 3]

{2, 3, 5}


--
Allan
---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565

"Daniel Lichtblau" <danl at wolfram.com> wrote in message
news:H5z76.38$nn4.14271 at ralph.vnet.net...
> "A. E. Siegman" wrote:
> >
> > Looking for neat compact way to extract three distinct (i.e., nonequal)
> > randomly selected integers k1, k2, k3 from the range 1 to N (N > 3) --
> > in other words, random sampling without replacement -- ???
>
> A general efficient way to sample without replacement may be implemented
> as a shuffling algorithm that iteratively swaps first element with a
> random element between start and end, then swaps second with a random
> element between second and end, and so on. In essence we shuffle as we
> deal (don't try this in Las Vegas).
>
> SetAttributes[deal, HoldFirst]
> deal[deck_, start_, end_] := Module[
> {len=Length[deck], rand},
> Do [
> rand = Random[Integer,{j,len}];
> deck[[{j,rand}]] = deck[[{rand,j}]],
> {j,start,end}];
> Take[deck, {start,end}]
> ]
>
> deck = Range[52];
>
> Let's pick four.
>
> In[178]:= deal[deck, 1, 4]
> Out[178]= {44, 18, 7, 9}
>
> Now we can pick some more, say seven.
>
> In[179]:= deal[deck, 5, 11]
> Out[179]= {36, 34, 11, 45, 8, 2, 46}
>
>
> Daniel Lichtblau
> Wolfram Research
>
>




  • Prev by Date: Summary: Random Sampling Without Replacement
  • Next by Date: Re: calling function in a DLL from Mathematica
  • Previous by thread: Re: Random Sampling Without Replacement?
  • Next by thread: Re: Random Sampling Without Replacement?