Home > Software design >  Random Password with 4 characters from String
Random Password with 4 characters from String

Time:01-05

I made a code that gives me every possible 4 character combination of a String. Now I need to make a program that chooses 1 random combination as a Password and then goes over every possible combination till it finds the chosen one and then tells me how many guesses it took to find the right one. This is what I have so far:

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]);
                    }
                }
            }
        }

I tried to store the pw[] in an array but I dont know exactly how to do it.

CodePudding user response:

Do you really need to store the values in a list beforehand? Do you need to generate each value exactly once, or it does not matter?

If you can just generate random passwords of size 4 N times, you could try something like this:

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();
}

}

If you really need to store them, so do it inside an ArrayList, instead of printing them as you are doing in your code.

After that, you can just traverse the ArrayList and search for your password in there.

CodePudding user response:

some of the methods you use, I haven't even learnd yet like generatePassword or Stringbuilder. I tried to put them in the array list like this:

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  ) {

                    combos.add(pw[i], pw[j], pw[k], pw[l]);
  • Related