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”
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.
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);
}
}
prints
kbljdhieagcf
gefabkhdclij
hbkfjilcgade
eacihdkjfgbl
hbjcfegdilka
The following code which use Collections.shuffle works:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Shuffle {
public static void main(String[] args) {
Character[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'};
List<Character> shuffled = Arrays.asList(letters);
Collections.shuffle(shuffled);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < shuffled.size(); i++) {
sb.append(shuffled.get(i));
}
System.out.println(sb);
}
}
You may look up the Random class in the Java API. This will enable you to create random array indexes. So you can pick the characters from the array in random order.
String randomize(char[] letters) {
String newString = new String[letters.length];
for (int i = 0; i <= letters.length; i++) {
int randomChar = Math.floor(Math.random() * letters.length);
newString[i] = letters[randomChar];
}
return newString;
}
I have tried the following piece of code... I guess you can use it in your scenario!
String[] alphabets = new String[12];
int i = 0;
char[] arrayAlpha = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'};
for (char ch : arrayAlpha) {
alphabets[i++] = String.valueOf(ch);
}
List<String> list = Arrays.asList(alphabets);
Collections.shuffle(list);
for (String alpha : list) {
System.out.print(alpha + " ");
}