以字符从阵列,并将它们随机创建的字符串并将、阵列、字符串、字符

2023-09-11 05:31:00 作者:北方爱人

我有一个字符数组(12号),可以是这样的:

I have got a char array (size 12) that can look like this:

{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'}  

和我想创建(以最有效的方式)的字符串,这将是从阵列以人物和命令他们〜随机的结果(让我们用这个词),例如:

And I would like to create (in the most efficient way) a String that would be the result of taking the characters from the array and ordering them ~randomly (let's use that word), for example:

"ahbejclfkdig"

我试着用StringBuffer的和随机摆放的解决方案,但没有位置重复的问题。另外,我想Collections.shuffle,但我不完全得到这个工作。我也看着线性反馈移位寄存器,但我不认为这里是合适的。这是很简单的情况下,我不会运行在大量的,所以内存分配和速度不应该提出任何重大问题。

I tried solutions with StringBuffer and random placing, but there was the problem of positions repeating. Also, I tried Collections.shuffle, but I don’t quite get this one working. I also looked at linear feedback shift register, but I don’t think is appropriate here. It is quite simple case, I will not be operating on large numbers, so memory allocation and speed should not raise any major issues.

推荐答案

您可以使用洗牌,但改变它的StringBuilder。我会不会用StringBuffer的,除非你有使用旧版本的Java。

You can use shuffle but change it for StringBuilder. I would wouldn't use StringBuffer unless you have to use old versions of Java.

public static void main(String... args) {
    StringBuilder sb = new StringBuilder("abcdefghijkl");
    for (int i = 0; i < 5; i++) {
        shuffle(sb);
        System.out.println(sb);
    }
}


public static void shuffle(StringBuilder sb) {
    Random rand = new Random();
    for (int i = sb.length() - 1; i > 1; i--) {
        int swapWith = rand.nextInt(i);
        char tmp = sb.charAt(swapWith);
        sb.setCharAt(swapWith, sb.charAt(i));
        sb.setCharAt(i, tmp);
    }
}

打印

kbljdhieagcf
gefabkhdclij
hbkfjilcgade
eacihdkjfgbl
hbjcfegdilka
 
精彩推荐
图片推荐