Question

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?
Was it helpful?

Solution

The line

generator.nextInt( word.length() - i - 1 );

would throw IllegalArgumentException incase the argument <= 0..

From nextInt Docs

Throws: IllegalArgumentException - if n is not positive

Check the length of a string before calling the line


You could do it this way

for (x = 0; x < wordLen; x++) {
      i = generator.nextInt(wordLen - 1); 
      j = generator.nextInt(wordLen);           
      if (j <= i)
        j = i + generator.nextInt(wordLen - i);
}

OTHER TIPS

String word = "Example"
int len = word.length(); //len = 7
int placeHolder1 = (int) (Math.random() * length); //generates number between 0 and 6
int placeHolder2 = (int) 
int diff = length - placeHolder1;
placeHolder2 = (int) (Math.random() * diff + (length - diff + 1)); //Generates random between placeHolder1 and the length of the String 

This gives you the indices of two characters on the String, and you can swap them however you prefer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top