随机生成字符串中的字符

Asw*_*wan 3 java permutation

当用户点击按钮时,我需要在String java中生成随机字符.例如:如果我们采用cat示例,我需要在字符串中显示字符,如下所示:

CAT,ACT,TAC,TCA

提前致谢

阿斯旺

pol*_*nts 7

关于Fisher-Yates改组算法

Fisher-Yates shuffle是一种用于改组的标准算法.这是伪代码:

To shuffle an array a of n elements:
   for i from n - 1 downto 0 do
         j ? random integer with 0 ? j ? i
         exchange a[j] and a[i]
Run Code Online (Sandbox Code Playgroud)

这是一个简单的Java实现:

static String shuffled(String s) {
    char[] a = s.toCharArray();
    final int N = a.length;
    Random r = new Random();
    for (int i = N - 1; i >= 0; i--) {
        int j = r.nextInt(i + 1);
        swap(a, i, j);
    }
    return new String(a);
}
static void swap(char[] a, int i, int j) {
    char t = a[i];
    a[i] = a[j];
    a[j] = t;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以:

    String text = "stackoverflow";
    for (int i = 0; i < 10; i++) {
        System.out.println(shuffled(text));
    }
Run Code Online (Sandbox Code Playgroud)

这将产生10个字符串的混洗"stackoverflow"(另见ideone.com).


Guava + Java Collections Framework替代解决方案

如果您安装了Guava库,那么这将是一个不错的解决方案.以下是关键事实:

然后我们可以将两者结合起来以获得以下干净且可读的代码:

import com.google.common.primitives.*;
import java.util.*;

public class AnagramCreator {
    public static void main(String[] args) {
        String text = "stackoverflow";
        char[] arr = text.toCharArray();
        List<Character> list = Chars.asList(arr);

        for (int i = 0; i < 10; i++) {
            Collections.shuffle(list);
            System.out.println(new String(arr));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以上将打印10个字谜"stackoverflow".

需要注意的是番石榴仅用于提供List<Character> 实时取景char[].A char[]不会被自动装箱Character[](反之亦然),否则Arrays.asList(T...)就足够了.

也可以看看

相关问题