Article View: comp.theory
Article #1865Re: Generating a Random Permutation
From: Michael Fischer
Date: Tue, 26 Jan 1993 17:01
Date: Tue, 26 Jan 1993 17:01
36 lines
2434 bytes
2434 bytes
Stephen Bloch (sbloch@silver.cs.umanitoba.ca) wrote: : sumner@math.scarolina.edu (David Sumner) writes: : >> In an earlier post I wrote that an easy way to generate a : >> random permutation of the integers 1-n was: : >> > ++++++++++++++ : >> > Initialize A[n] as the array [1, 2, 3, 4,..., n] : >> > for i=1 to n : >> > z = random(n) : >> > t = a[i] : >> > a[i] = a[z] : >> > a[z] = t : >> > next i : >> > ++++++++++++++ : >> There is a typo in this. The line 'z = random(n)' should : >> be 'z = random(i)' : I THINK (but am not sure) the : corrected one is also incorrect, for the reasons Thomas states. The corrected algorithm can be seen to be correct by a simple inductive argument. Namely, after the i-th iteration, A[1]...A[i] contains a random permutation of 1,...,i, and A[i+1]...A[n] contains the numbers (i+1),...,n in sequence. The next iteration swaps A[i+1] = (i+1) with a randomly-chosen A[z], where 1 <= z <= i+1. Thus, (i+1) is equally likely to go into any of the first i+1 slots, and the remaining positions end up being filled with a random permutation of 1,...,i. This results in a random permutation of 1,...,i+1 as desired. Since the induction hypothesis is obviously true for i=0, it holds for all i<=n by induction. Thus, after the last iteration, A[1],...,A[n] contains a random permutation of 1,...,n. ================================================== | Michael Fischer <fischer-michael@cs.yale.edu> | ==================================================
Technical Details
Message-ID:
<1993Jan26.170151.9146@cs.yale.edu>Path:
arc1-ca.pugleaf.net!sparky!uunet!mcsun!sunic!ericom!exucom.exu.ericsson.se!texsun!cronkite.Central.Sun.COM!news2me.EBay.Sun.COM!sun-barr!cs.utexas.edu!zaphod.mps.ohio-state.edu!howland.reston.ans.net!spool.mu.edu!yale.edu!cs.yale.edu!ginkgo.theory.cs.yale.edu!fischerReferences:
<C1FpMw.4Ip@ccu.umanitoba.ca>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!sparky!uunet!mcsun!sunic!ericom!exucom.exu.ericsson.se!texsun!cronkite.Central.Sun.COM!news2me.EBay.Sun.COM!sun-barr!cs.utexas.edu!zaphod.mps.ohio-state.edu!howland.reston.ans.net!spool.mu.edu!yale.edu!cs.yale.edu!ginkgo.theory.cs.yale.edu!fischer From: fischer-michael@cs.yale.edu (Michael Fischer) Newsgroups: comp.theory,sci.crypt,rec.puzzles Subject: Re: Generating a Random Permutation Message-ID: <1993Jan26.170151.9146@cs.yale.edu> Date: 26 Jan 93 17:01:51 GMT References: <C1FpMw.4Ip@ccu.umanitoba.ca> Sender: news@cs.yale.edu (Usenet News) Reply-To: fischer-michael@cs.yale.edu (Michael Fischer) Followup-To: comp.theory,sci.crypt,rec.puzzles Organization: Yale University Computer Science Dept., New Haven, CT 06520-2158 Lines: 36 Nntp-Posting-Host: ginkgo.theory.cs.yale.edu X-Newsreader: TIN [version 1.1az (for az) PL8]