[英]Random Password with 4 characters from String
我編寫了一個代碼,它為我提供了字符串的所有可能的 4 個字符組合。 現在我需要制作一個程序,選擇 1 個隨機組合作為密碼,然后檢查所有可能的組合,直到找到所選的組合,然后告訴我找到正確的組合需要多少次猜測。 這是我到目前為止所擁有的:
String alphabet = "ABCabc012!";
char pw[] = alphabet.toCharArray();
for (int i = 0; i < pw.length ; i++) {
for (int j = 0; j < pw.length ; j++) {
for (int k = 0; k < pw.length ; k++) {
for (int l = 0; l < pw.length ; l++) {
System.out.println(pw[i] + " " + pw[j] + " " + pw[k] + " " + pw[l]);
}
}
}
}
我試圖將 pw[] 存儲在一個數組中,但我不知道該怎么做。
您真的需要事先將值存儲在列表中嗎? 您是否需要每個值只生成一次,還是無關緊要?
如果你只能生成大小為 4 N 次的隨機密碼,你可以嘗試這樣的事情:
public class RandomPass {
static Random random = new Random();
public static void main(String[] args) {
String alphabet = "ABCabc012!";
String password = generatePassword(4, alphabet);
System.out.println("PW is: " + password);
int counter = 0;
while (!generatePassword(4, alphabet).equals(password)) {
counter++;
}
System.out.println("It took: " + counter + " times.");
}
private static String generatePassword(int size, String alphabet) {
StringBuilder pw = new StringBuilder();
for (int i = 0; i < size; i++) {
pw.append(alphabet.charAt(random.nextInt(0, alphabet.length())));
}
return pw.toString();
}
}
如果你真的需要存儲它們,那么就在 ArrayList 中進行,而不是像你在代碼中那樣打印它們。
之后,你可以遍歷ArrayList並在那里搜索你的密碼。
你其實很接近!
以下是構建組合的方法,將它們添加到 ArrayList、output 中,從列表中隨機選擇一個密碼,然后隨機生成密碼,直到獲得匹配為止:
public static void main(String[] args) {
String alphabet = "ABCabc012!";
char pw[] = alphabet.toCharArray();
// generate the combinations
ArrayList<String> combos = new ArrayList<>();
for (int i = 0; i < pw.length ; i++) {
for (int j = 0; j < pw.length ; j++) {
for (int k = 0; k < pw.length ; k++) {
for (int l = 0; l < pw.length ; l++) {
String pwCombo = "" + pw[i] + pw[j] + pw[k] + pw[l];
combos.add(pwCombo);
}
}
}
}
// output the combinations
for(String password : combos) {
System.out.println(password);
}
// pick a random passwrod
Random r = new Random();
int index = r.nextInt(combos.size());
String pwToGuess = combos.get(index);
System.out.println("Password to guess: " + pwToGuess);
// randomly generate a password until it matches
int tries = 0;
String pwGuess = "";
do {
tries++;
pwGuess = "" + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)] + pw[r.nextInt(pw.length)];
} while (!pwGuess.equals(pwToGuess));
System.out.println("It took " + tries + " tries to guess the password!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.