-2

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?
catch23
  • 17,519
  • 42
  • 144
  • 217
  • Just as an observation, the line `i = generator.nextInt(wordLen);` is wrong, since that can return `wordlen - 1`, which is the last position (and your directions say explictly not to) – Dennis Meng Jul 04 '13 at 17:24
  • @Dennis Meng `nextInt(n)` return on the border `0 ... n-1` – catch23 Jul 04 '13 at 17:29
  • http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int) - `IllegalArgumentException - if n is not positive` – Brian Roach Jul 04 '13 at 17:35
  • @nazar_art Yes, and you don't want to be able to return `n-1` there... – Dennis Meng Jul 05 '13 at 00:49

2 Answers2

1

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);
}
catch23
  • 17,519
  • 42
  • 144
  • 217
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0
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.

Kon
  • 10,702
  • 6
  • 41
  • 58
  • You give some "bull" code: `int len = String.length()` how can it work? – catch23 Jul 04 '13 at 17:30
  • My mistake, I'm typing on my machine w/o JDK, so did not test run code. I meant int len = word.length(), obviously. – Kon Jul 04 '13 at 17:37