以字符从阵列,并将它们随机创建的字符串 [英] Take chars from array and place them randomly to create String
问题描述
我有一个字符数组(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
这篇关于以字符从阵列,并将它们随机创建的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!