user319824
user319824

Reputation:

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 again could result in:

H R E I C ....

Any suggestions?

Upvotes: 1

Views: 471

Answers (3)

Mark Byers
Mark Byers

Reputation: 837926

Have a look at the Fisher-Yates shuffle algorithm, and in particular the modern version of it.

Upvotes: 2

mingos
mingos

Reputation: 24502

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).

Upvotes: 0

David
David

Reputation: 218798

This sounds like homework, but either way:

http://stanford.edu/~blp/writings/clc/shuffle.html

Upvotes: 0

Related Questions