我正在尝试生成一个字母的随机密钥,这些字母在整个密钥中只使用一次。我目前有一个数组"regKey",它按正常顺序存储字母A-Z。我想创建一个新的数组"newKey",其中字母的顺序是完全随机的,但在创建这个新数组时会使用每个字母。新数组中不应存在任何字母的重复。
到目前为止,我已经能够生成一个随机密钥,但通常会有某些字母的重复。下面是我的代码供参考。
public void keyGen() {
char [] regKey = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char [] newKey = new char [26];
int tempNum;
int totalChoice = 26;
Random rand = new Random();
for(int i = 0; i<26; i++) {
tempNum = rand.nextInt(totalChoice);
newKey[i] = regKey[tempNum];
System.out.print(newKey[i]);
}
String keyString = new String (newKey);
label_key.setText(keyString);
}
您想要做的叫做"shuffle"。您可以使用Collections.shuffle
来"随机化"数组。
List<Character> regKeyAsList = Arrays.asList(regKey);
Collections.shuffle(regKeyAsList);
char[] newKey = regKeyAsList.toArray();
假设您首先肯定需要一个Array,那么以下代码确实会创建您想要的输出:
char [] regKey = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char [] newKey = new char [26];
String[] array = new String(regKey).split("", 0);
ArrayList<String> yourNewArrayList = new ArrayList<String>();
Collections.addAll(yourNewArrayList, array);
Collections.shuffle(yourNewArrayList);
for (int i = 0; i < newKey.length; i++) {
newKey[i] = yourNewArrayList.remove(0).toCharArray()[0];
}
使用Collections.shuffle
。这里使用Unicode代码点。
List<Integer> alphabet = IntStream.rangeClosed('A', 'Z').boxed()
.collect(Collection.toList());
// Or enumerate all:
// List<Integer> alphabet = IntStream.of('A', 'B', 'C', ..., 'X', 'Y', 'Z').boxed()
// .collect(Collection.toList());
Collections.shuffle(alphabet);
String newKey = new String(alphabet.stream()
.mapToInt(Integer::intValue)
.toArray(), 0, alphabet.size());
或者:
for (int i = 0; i < 26 - 1; i++) {
int pickedI = i + rand.nextInt(26 - i);
// Swap i and pickedI:
int old = newKey[i];
newKey[i] = regKey[pickedI];
newKey[pickedI] = old;
System.out.print(newKey[i]);
}