Hello,
How can I scramble a given string in a random order?
for example, apple --> pelap
I cannot use any arrays.
Thanks for the help.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Hello,
How can I scramble a given string in a random order?
for example, apple --> pelap
I cannot use any arrays.
Thanks for the help.
that's kind of difficult since strings are basically just character arrays...
but none the less, what you could do is create a new string result, then randomly remove a letter from the original string and concatenate (add it to the end) of the result string. Repeat this process until the original string is empty.
Dylan035 (October 13th, 2010)
That is exactly what I was thinking. The part where I am running into a problem is this:
How can I randomly pick a character from a string without picking that same index again? Say I generate a random number to pick the index, how can I prevent that random number from being picked again?
I hope I'm being clear on my confusion.
Thanks again.
Remove it from your original string. This is much easier to do with a StringBuilder because it is mutable where Strings are not.
// removing a letter from a StringBuilder StringBuilder b = new StringBuilder("hello"); b.deleteCharAt(1); // remove the 2rd letter, which is e
I see what you mean, I think that would work perfectly for what I need.
Let's say I have
String word = "bobcat";
How can I change 'word' from a String to a StringBuilder?
Could I do:
StringBuilder b = new StringBuilder(word); ?
Yep, there's a StringBuilder constructor which takes a string.
If you're unsure about whether something is possible or not, there are 2 good courses of action:
1. Try it
2. Look at the Javadoc (StringBuilder JavaDoc)