Processing strings Generating passwords

The password is hard to crack if it contains at least A uppercase letters, at least B lowercase letters, at least C digits and includes exactly N symbols. Also, a password cannot contain two or more same characters coming one after another.

For the given numbers A, B, C, N you should output a password that matches these requirements.

It is guaranteed A, B, C, and N are non-negative integers and A + B + C <= N. Keep in mind, that any parameter can be equal to zero. It means that it's ok if the password doesn't contain symbols of such type.

Sample Input 1:

3 2 3 10

Sample Output 1:

ABAab121AB

Solution:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = scanner.nextInt();
        int n = scanner.nextInt();
        int i = 0;
        String passwords = "";

        while (a + b + c < n) {
            int s = (int) (Math.random() * 3);
            if (s == 0) {
                a++;
            }
            if (s == 1) {
                b++;
            }
            if (s == 2) {
                c++;
            }
        }

        char[] singleChar = new char[n];
        while (i < n) {
            int s = (int) (Math.random() * 3);
            switch (s) {
                case 0:
                    singleChar[i] = (char) (Math.random() * 26 + 65);
                    if (i == 0 || singleChar[i] != singleChar[i - 1] && a > 0) {
                        --a;
                        ++i;
                        break;
                    }

                case 1:
                    singleChar[i] = (char) (Math.random() * 26 + 97);
                    if (i == 0 || singleChar[i] != singleChar[i - 1] && b > 0) {
                        --b;
                        ++i;
                        break;
                    }

                case 2:
                    singleChar[i] = (char) (Math.random() * 10 + 48);
                    if (i == 0 || singleChar[i] != singleChar[i - 1] && c > 0) {
                        --c;
                        ++i;
                        break;
                    }

            }

        }
        for (int j = 0; j < n; j++) {
            passwords += singleChar[j];
        }
        System.out.println(passwords);
    }
}

这里要注意,如果遇到总位数大于各要求的分位数的情况,可以将各分位数先补齐,再按照一般的方法进行计算。

posted @ 2020-08-11 14:30  longlong6296  阅读(150)  评论(0)    收藏  举报