java生成4位不重複字元(包含大寫字母、小寫字母、數字)
阿新 • • 發佈:2018-12-30
需要生成4位不重複的字元作為唯一引數,要求只能使用大寫字母、小寫字母和數字的組合。大寫字母26個、小寫字母26個、10個數字共62個字元。不重複排列個數:62*62*62*62=14776336個。
/** * * @author wzp * 2016-3-18 */ public class DmSequenceUtil { static String bwords[] = { "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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; static Random random = new Random(); static int index1 = 0; static int index2 = 0; static int index3 = 0; static int index4 = 0; static boolean isRead = true; /** * 支援14776336個不重複4位字串 2016-3-18 * * @return * @throws Exception */ public static synchronized String getNoRepeatId() throws Exception { // 判斷是否需要讀取檔案記錄 if (isRead) { String sequence = read(); if (sequence != null && sequence.length() == 4) { index1 = getIndex(String.valueOf(sequence.charAt(0))) + 10; index2 = getIndex(String.valueOf(sequence.charAt(1))) + 10; index3 = getIndex(String.valueOf(sequence.charAt(2))) + 10; index4 = getIndex(String.valueOf(sequence.charAt(3))) + 10; } isRead = false; } getRandom(); String id = "" + bwords[index1 == 0 ? 0 : index1 - 1] + bwords[index2 == 0 ? 0 : index2 - 1] + bwords[index3 == 0 ? 0 : index3 - 1] + bwords[index4 - 1]; write(id); return id; } private static int getIndex(String word) { for (int i = 0; i < bwords.length; i++) { if (bwords[i].equals(word)) { return i; } } return 0; } private static void getRandom() throws Exception { if (index4 < 62) { index4++; } else { index4 = 1; if (index3 < 62) { index3++; } else { index3 = 1; if (index2 < 62) { index2++; } else { index2 = 1; if (index1 < 62) { index1++; } else { throw new Exception("結束"); } } } } } private static void write(String sequence) throws IOException { File file = new File("sequence.dat"); FileWriter fw = new FileWriter(file, false); fw.write(sequence); fw.flush(); fw.close(); } private static String read() throws IOException { String sequence = ""; File file = new File("sequence.dat"); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); sequence = br.readLine(); br.close(); fr.close(); } catch (Exception e) { System.err.println("讀取檔案出錯"); } return sequence; } }
Java高階群1群:224651178
Java高階群1群:134787504