开发者

How can I randomize a sequence of characters?

开发者 https://www.devze.com 2023-01-04 23:54 出处:网络
I want to write a function which randomizes the order of a sequence of alphabetic characters. For example, the sequence:

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:

  1. Let S1 be a string containing the alphabet characters "ABC...XYZ".
  2. Let S2 be an empty string.
  3. While strlen(S1) > 0, choose a random character C from S1. Append C to S2 and remove C from S1.
  4. 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).

0

精彩评论

暂无评论...
验证码 换一张
取 消