我需要使用一组已定义的 2-4 个字母来创建一个完全随机的字符串。如何将字母组合成一个字符串,随机化每个字符的位置,然后将该大字符串变成两个随机大小(但 >= 2)的其他字符串。感谢大家的帮助。
到目前为止我的代码是:
//shuffles letters
ArrayList arrayList = new ArrayList();
arrayList.add(fromFirst);
arrayList.add(fromLast);
arrayList.add(fromCity);
arrayList.add(fromSong);
Collections.shuffle(arrayList);
但我发现这会打乱字符串而不是单个字母。它也是一个数组,具有在常规书写中找不到的括号,我确实希望它看起来像字母的随机组合
最佳答案
这是一种相当蛮力的方法,但它确实有效。它打乱索引位置并将它们映射到原始位置。
final String possibleValues = "abcd";
final List<Integer> indices = new LinkedList<>();
for (int i = 0; i < possibleValues.length(); i++) {
indices.add(i);
}
Collections.shuffle(indices);
final char[] baseChars = possibleValues.toCharArray();
final char[] randomChars = new char[baseChars.length];
for (int i = 0; i < indices.size(); i++) {
randomChars[indices.get(i)] = baseChars[i];
}
final String randomizedString = new String(randomChars);
System.out.println(randomizedString);
final Random random = new Random();
final int firstStrLength = random.nextInt(randomChars.length);
final int secondStrLength = randomChars.length - firstStrLength;
final String s1 = randomizedString.substring(0, firstStrLength);
final String s2 = randomizedString.substring(firstStrLength);
System.out.println(s1);
System.out.println(s2);
关于java - 在Java中随机化一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349962/