Xref: utzoo comp.sources.wanted:7425 alt.msdos.programmer:47 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!iuvax!watmath!watcgl!megauthier From: megauthier@watcgl.waterloo.edu (Marc E. Gauthier) Newsgroups: comp.sources.wanted,alt.msdos.programmer Subject: Re: Need algorithm to scramble order of array Message-ID: <9763@watcgl.waterloo.edu> Date: 17 May 89 21:21:52 GMT References: <3008@cps3xx.UUCP> Reply-To: megauthier@watcgl.waterloo.edu (Marc E. Gauthier) Organization: U. of Waterloo, Ontario Lines: 27 In article <3008@cps3xx.UUCP> reedp@frith.egr.msu.edu () writes: >I need a fast algorithm to randomly rearrange the order of elements in >an array. Right now I am just using a random number generator to form >a list of numbers that directly determines the order of the array [...] Here's a simple way to do it in C: Object t, a[SIZE]; int i, j; /* this works by filling (backwards) the array with elements * picked randomly from the remaining ones at start of array */ for (i=SIZE-1; i>0; i--) { j = random() % i; /* return indice between 0 and i-1 */ t = a[i]; a[i] = a[j]; a[j] = t; } Hope it helps. It's a simple solution I always use to shuffle cards, etc. Marc -- Marc E. Gauthier megauthier@watcgl.waterloo.edu University of Waterloo