由于以上答案都不能确保唯一性,我决定添加另一个答案。
首先我们在一个数组中定义所有有效的选项:
char[] chars = new char[]{ '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',
'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',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
现在我们可以将算法更改为Random shuffling of an array,以获得前 8 个元素:
Random rnd = new Random();
int charsLength = chars.length;
int passLength = 8;
StringBuilder password = new StringBuilder();
for (int i = 0; i < passLength; i++)
{
int index = rnd.nextInt(charsLength - i - 1);
// Simple swap
char a = chars[i + index];
chars[i + index] = chars[i];
chars[i] = a;
password.append(a);
}
System.out.print(password);
它确保了唯一性,一旦char 出现在数组的前 8 个位置,它就不是下一轮的有效选择。
我得到的输出很少:
ifJjuYrR
NpY3TfIU
LGFm8Ng9
sV4Gctb7
4fyhlSuQ