-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?
4

2 回答 2

1

线

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

会抛出IllegalArgumentException参数<= 0 ..

来自 nextInt 文档

抛出: IllegalArgumentException - 如果 n 不是正数

length在调用该行之前检查字符串的


你可以这样做

for (x = 0; x < wordLen; x++) {
      i = generator.nextInt(wordLen - 1); 
      j = generator.nextInt(wordLen);           
      if (j <= i)
        j = i + generator.nextInt(wordLen - i);
}
于 2013-07-04T17:19:27.840 回答
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 

这为您提供了字符串上两个字符的索引,您可以随意交换它们。

于 2013-07-04T17:22:26.743 回答