日期:2014-05-20  浏览次数:20737 次

随机密码生成问题
我随机生成一个6位数的包括任意数字和大小写字母的密码,但是我想排除以下情况的密码:连续的,比如像123456、abcdef,ABCDEF这样子的情况
请问我要怎么做?先谢谢各位了!!!

------解决方案--------------------
Java code
package com.ricky.www;

public class Test {
    public String getPassword() {
        int index = 0;
        String[] p_array = new String[62];
        /**
         * 填充数组
         */
        for (int i = 0; i <= 9; i++) {
            p_array[index++] = i + "";
        }

        for (int i = 'A'; i <= 'Z'; i++) {
            char c = (char) i;
            p_array[index++] = new String(c + "");
        }

        for (int i = 'a'; i <= 'z'; i++) {
            char c = (char) i;
            p_array[index++] = new String(c + "");
        }

        /**
         * 返回6位的随机密码
         */
        StringBuffer password = new StringBuffer();

        for (int i = 0; i < 6; i++) {
            int random =(int)(Math.random() * 62);
            password.append(p_array[random]);
        }

        if (rule(password.toString())) {
            return password.toString();
        } else {
            return getPassword();
        }
    }

    private boolean rule(String password) {
        char[] p_array = password.toCharArray();
        // 因为1 + 2 + 3 + 4 +5 +6 = 1 * 6 + 15;类推
        int total = p_array[0] * 6 + 15;
        int sum = 0;
        for (int i = 0; i < 6; i++) {
            sum += p_array[i];
        }
        if (sum == total) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String password = new Test().getPassword();
        System.out.print(password);
    }
}