--Apple-Mail-10--42713177 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII; format=flowed On Jun 11, 2006, at 2:22 PM, Phil Keller wrote: > > I have an application that I need to generate a random number > sequence for. Not just a random number, I know how to do that, > but an entire pseudo random sequence. You want a "shuffle" algorithm. With a similar problem some time ago, I came up with this framework (in C): The enclosed code in shuffle_lib.c will return a shuffled sequence of any number of items up to 65535, using only 6 bytes or less of storage. A pseudo-random number generator (PRNG) can be used to produce a non-repeating sequence of numbers, but the usual implementation will generate only a sequence of length 2^N-1 (for an N bit number.) That's not a problem, you can just filter out all the numbers that are outside the range of interest. The other problem with a PRN is that the sequence itself repeats; 12 always follows 232, or whatever. Since our PRNG is generating a larger range than we want anyway, this can be fixed by permuting the number somehow before filtering, using a separate permutation constant. This means that our final algorithm is something like: shufflednum(max) = filter(max, permute(prng(randreg), permuteconst)); The code example enclosed uses a standard shift-with-xor-feedback scheme for the PRNG, simple subtraction for the permutation, and a test against the maximum as the filter, making it quite fast. (however, it needs to be fast if the number of items to be shuffled is much smaller than the size of the PRNG. to get 10 items with a 16 bit PRN, you may end up filtering out 65525 numbers. This can be optimized by using a shorter PRN, of course.) Note that by changing the PRNG seed, you change the starting position of the shuffled list, but not the list itself, while changing the permutation constant results in dramatically different sequences. Enclosed files: shuffle_lib.c: library functions in hopefully machine-independent C code shuffle_test.c: demonstration program, written for unix, tested on Solaris shuffle_log.c: sample run, demonstrating effects of seed vs permutation constant changes --Apple-Mail-10--42713177 Content-Transfer-Encoding: base64 Content-Type: application/zip; x-mac-type=5A495020; x-unix-mode=0755; x-mac-creator=53495421; name="Shuffle.zip" Content-Disposition: attachment; filename=Shuffle.zip UEsDBBQAAAAIACy2uTAnbZBSHwIAAPwFAAAPAAAAc2h1ZmZsZV9sb2cudHh0hZRNj5swEIbv/hWj lXJjqW0wJJH20ktP/VDbW7WqWDABLbFTMO3uv69nEGZTleBIr8aeseN5ZvC3sm8vDgZX9E5XYA18 HzV8LF5BKhDZUSVH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set="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: inline -- http://www.piclist.com PIC/SX FAQ & list archive View/change your membership options at http://mailman.mit.edu/mailman/listinfo/piclist --Apple-Mail-10--42713177--