Java 我怎样才能打乱一个单词的字母?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20588736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:57:54  来源:igfitidea点击:

How can I shuffle the letters of a word?

javaarraysrandom

提问by morgothraud

What is the easiest way to shuffle the letters of a word which is in an array? I have some words in an array and I choose randomly a word but I also want to shuffle the letters of it.

打乱数组中单词的字母的最简单方法是什么?我在数组中有一些单词,我随机选择一个单词,但我也想对它的字母进行洗牌。

public static void main (String[] args ) {
    String [] animals = { "Dog" , "Cat" , "Dino" } ;    
    Random random = new Random();
    String word = animals [random.nextInt(animals.length)];

    System.out.println ( word ) ;
    //I Simply want to shuffle the letters of word     
}

I am not supposed to use that List thing. I've come up with something like this but with this code it prints random letters it doesn't shuffle. Maybe I can code something like do not print if that letter already printed?

我不应该使用那个 List 的东西。我想出了这样的东西,但是使用此代码,它会打印不会随机播放的随机字母。也许我可以编写一些代码,例如如果那封信已经打印,则不要打印?

//GET RANDOM LETTER
for (int i = 0; i< word.length(); i++ ) {

char c = (word.charAt(random.nextInt(word.length())));
System.out.print(c); } 
  }

采纳答案by Rastikan

Really no need for collection and anything more than what follows:

真的不需要收集以及以下内容:

public static void main(String[] args) {

    // Create a random object
    Random r = new Random();

    String word = "Animals";

    System.out.println("Before: " + word );
    word = scramble( r, word );
    System.out.println("After : " + word );
}

public static String scramble( Random random, String inputString )
{
    // Convert your string into a simple char array:
    char a[] = inputString.toCharArray();

    // Scramble the letters using the standard Fisher-Yates shuffle, 
    for( int i=0 ; i<a.length ; i++ )
    {
        int j = random.nextInt(a.length);
        // Swap letters
        char temp = a[i]; a[i] = a[j];  a[j] = temp;
    }       

    return new String( a );
}

回答by Alexis C.

You can use Collections.shuffle:

您可以使用Collections.shuffle

List<Character> l = new ArrayList<>();
for(char c :  word.toCharArray()) //for each char of the word selectionned, put it in a list
    l.add(c); 
Collections.shuffle(l); //shuffle the list

StringBuilder sb = new StringBuilder(); //now rebuild the word
for(char c : l)
  sb.append(c);

word = sb.toString();


I am not supposed to use that List thing.

我不应该使用那个 List 的东西。

Then you can create two StringBuilderobjects. One will hold the original word and one will create the shuffled one :

然后你可以创建两个StringBuilder对象。一个将保留原始单词,另一个将创建洗牌的单词:

StringBuilder s = new StringBuilder(word);
StringBuilder wordShuffled = new StringBuilder();
while(s.length() != 0){
    int index = random.nextInt(s.length());
    char c = s.charAt(index);
    wordShuffled.append(c);
    s.deleteCharAt(index);
}
System.out.println(wordShuffled.toString());


I found something like deleteCharAt but I guess it works with StringBuilder or something. I cannot use that

我发现了类似 deleteCharAt 的东西,但我想它适用于 StringBuilder 或其他东西。我不能用那个

Hereyou can find some nice utilities methods that permits to shuffle an array.

在这里,您可以找到一些不错的实用程序方法,它们允许对数组进行洗牌。

public static char[] shuffleArray(char[] x) {    
       for ( int i = x.length; i > 0; i-- ) {
            int rand = (int)(Math.random()*(i));
            char temp = x[i-1];
            x[i-1] = x[rand];
            x[rand] = temp;
        }
       return x;
}

Then just call this method and use the constructor String(char[] value):

然后只需调用此方法并使用构造函数String(char[] value)

System.out.println(new String(shuffleArray(word.toCharArray())));

Next time clearly state, what you can use/not use.

下次明确说明,您可以使用/不使用什么。

回答by Elliott Frisch

How about something like this?

这样的事情怎么样?

// Shuffle an array of characters.
public static void shuffleArray(char[] a) {
  int n = a.length; // the length of the array.
  for (int i = 0; i < n; i++) {
    int t = random.nextInt(n); // pick a random number 0 - the length.
    if (t == i) {              // if the random number is the loop counter
      if (i > 0) {             // check if we're at the first element.
        t = random.nextInt(i); // pick another number between 0 - and the loop counter.
      } else {
        t = a.length - 1;      // the end of the loop.
      }
    }
    a[i] ^= a[t];              // swap a[i] and a[t]
    a[t] ^= a[i];
    a[i] ^= a[t];
  }
}

private static Random random = new Random(); // the shared random.

public static void main(String[] args) {
  String[] animals = { "Dog", "Cat", "Dino" };
  String word = animals[random
      .nextInt(animals.length)];

  System.out.println(word);            // the random word.
  char[] arr = word.toCharArray();     // the char[] from the word.
  shuffleArray(arr);                   // shuffle it.
  System.out.println(new String(arr)); // print it.
}