-> Actually I was thinking of using the length of the string passed to
-> determine the number of exchanges to make.
Yes. I seem to recall that the very similar routine that was posted here
a few weeks ago did exactly that. It did 2*N swaps, where N is the
number of characters in the string.
-> That it may "produce probabilities that are exceedingly close" is
-> good enough for me. I like the idea that it has that "randomness"
-> built in!
Well, it's true that a lot of practical randomizers aren't strictly
random, but *tend toward* randomness as some routine is iterated several
times. For example, the normal way of shuffling a deck of cards, by
splitting it into two roughly equal parts, then riffling the parts
together, produces results that are nowhere near random if the actions
are done just once. The card that was on the top of the deck will almost
certainly still be on the top or very close to it, and so on. Only by
repeating the splitting and riffling quite a large number of times, as
is done in practice, do the cards become really jumbled, so they would
satisfy practical tests of randomness.
And the same is true of your routine...
However, since BASIC comes with the built-in RND generator, which
satisfies just about every test for randomness and operates very
quickly, I feel that computer randomizing routines shouldn't depend on
tending towards randomness, but should use RND to achieve it very
quickly, And that's what my routine does.
-> DW>and swaps. I still prefer my routine, which produces a
-> theoretically DW>perfect result in just two swaps!
->
-> Yes but only when there are only 3 characters in the string. What
-> happens when there are more characters in the string?
It needs N-1 swaps, where there are N characters involved.
The swapping routine is:
FOR X = 1 TO N - 1
SWAP L$(X), L$(X + INT(RND * (N + 1 - X)))
NEXT X
So N - 1 swaps are done. If you figure out the expression in the second
L$(), when X=1, the swap can be done in N ways, involving any of the N
characters. When X=2, there are only N-1 possibilities in the swap. The
first element can't be involved. And so on. So the total number of
branches in the decision tree is N*(N-1)*(N-2)* ... *3*2, in other
words, N!, the exact same number as the number of possible permutations
of N characters. It's easy to show that every permutation is reachable
by just one branch, so the permutations are exactly equi-probable -
which is the goal of this kind of randomization routine.
I still far prefer it to any iteration method!
dow
--- PCBoard (R) v15.3 (OS/2) 5
---------------
* Origin: FidoNet: CAP/CANADA Support BBS : 416 287-0234 (1:250/710)
|