How can I randomize a sequence of characters?
I want to write a function which randomizes the order of a sequence of alphabetic characters. For example, the sequence:
A B C D E F G . . .
...might be changed to:
Z L T A P ...
...which, if passed to the same function agai开发者_Go百科n could result in:
H R E I C ....
Any suggestions?
Have a look at the Fisher-Yates shuffle algorithm, and in particular the modern version of it.
This sounds like homework, but either way:
http://stanford.edu/~blp/writings/clc/shuffle.html
You mean randomise the alphabet? I wrote something similar in PHP a few days ago. The logic was the following:
- Let S1 be a string containing the alphabet characters "ABC...XYZ".
- Let S2 be an empty string.
- While strlen(S1) > 0, choose a random character C from S1. Append C to S2 and remove C from S1.
- Return S2.
The result is a randomly shuffled set of characters, created with minimal CPU load (if the string has 26 characters, the inner loop only needs 26 iterations).
精彩评论