We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Randomizing the characters of a String
Page Index Toggle Pages: 1
Randomizing the characters of a String? (Read 273 times)
Randomizing the characters of a String?
Dec 16th, 2008, 9:05pm
 
I would like to take a String, such as "How Do You Do?" and randomize it so my output would be something like this: "oD?DYo H ou wo".  It would have to be the same output every time, (seeded).

What's the best way to handle this?  I think I'd be using some of the methods of the String class? but I'm not sure how to go about structuring this.
Re: Randomizing the characters of a String?
Reply #1 - Dec 16th, 2008, 9:41pm
 
knuth shuffle, O(n)

seed random generator
for each letter in the string
 pick a random letter anywhere* in the string
 swap them
the end

* can also be the same position leaving the letter in the same place.

use StringBuffer rather than String, allows you to insert letters mid-string. charAt(), setCharAt()

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html
Re: Randomizing the characters of a String?
Reply #2 - Dec 16th, 2008, 10:02pm
 
oops

http://dev.netcetera.org/blog/2007/08/24/good-knuth-bad-knuth/

you should only pick letters from the currently unshuffled bit and, like he says, this is easier if you move backwards through the string.
Page Index Toggle Pages: 1