I have to implement the following instructions (pseudocode):
Read a word.
Repeat word.length() times
Pick a random position i in the word, but not the last position.
Pick a random position j > i in the word. (this is a tricky point!)
Swap the letters at positions j and i.
Print the word.
My code throws - IllegalArgumentException
here:
j = i + 1 + generator.nextInt( word.length() - i - 1 );
I stack here and don't know how to circumvent this point.
Code:
public String scramble(String word) {
Random generator = new Random(42);
int x, i = 0, j = 0, wordLen = word.length();
for (x = 0; x < wordLen; x++) {
i = generator.nextInt(wordLen);
j = i + 1 + this.generator.nextInt( word.length() - i - 1 );
}
I can't find a good solution for this step:
Pick a random position j > i in the word.
- How to solve this issue?