隨機密碼
1. 隨機密碼 : 6位數字
public static String randompassword ( ) {
char [ ] chars = new char [ 6 ] ;
Random rnd = new Random ( ) ;
for ( int i= 0 ; i < 6 ; i++ ) {
chars[ i] = ( char ) ( '0' + rnd. nextInt ( 10 ) ) ;
}
return new String ( chars) ;
}
2. 隨機密碼 : 8位密碼,但是包括字符,和特殊符合
private static final String SPECIAL_CHARS = “! @#$^ & * _= + / ”;
private static char nextChar ( Random rnd) {
switch ( rnd. nextInt ( 4 ) ) {
case 0 :
return ( char ) ( 'a' + rnd. nextInt ( 26 ) ) ;
case 1 :
return ( char ) ( 'A' + rnd. nextInt ( 26 ) ) ;
case 2 :
return ( char ) ( '0' + rnd. nextInt ( 10 ) ) ;
default :
return String SPECIAL_CHARS. charAt ( rnd. nextInt ( String SPECIAL_CHARS. length ( ) ) ) ;
}
}
public static String randomPassword ( ) {
char [ ] chars = new char ( 8 ) ;
Random rnd = new Random ( ) ;
for ( int i= 0 ; i < 8 ; i++ ) {
chars[ i] = nextChar ( rnd) ;
}
return new String ( chars) ;
}
3. 隨機密碼 : 復雜8位
private static int nextIndex ( char [ ] chars, Random rnd) {
int index= rnd. nextInt ( chars. length) ;
while ( chars[ index] != 0 ) {
index = rnd. nextInt ( chars. length) ;
}
return index;
}
private static char nextSecialChar ( Random rnd) {
return String SPECIAL_CHARS. charAt ( rnd. nextInt ( String SPECIAL_CHARS. length ( ) ) ) ;
}
private static char nextUpperLetter ( Random rnd) {
return ( char ) ( 'A' + rnd. nextInt ( 26 ) ) ;
}
private static char nextLowerLetter ( Random rnd) {
return ( char ) ( '0' + rnd. nextInt ( 10 ) ) ;
}
public static String randomPassword ( ) {
char [ ] chars = new char [ 8 ] ;
Random rnd = new Random ( ) ;
chars[ nextIndex ( chars, rnd) ] = nextSpecialChar ( rnd) ;
chars[ nextIndex ( chars, rnd) ] = nextUpperLetter ( rnd) ;
chars[ nextIndex ( chars, rnd) ] = nextLowerLetter ( rnd) ;
chars[ nextIndex ( chars, rnd) ] = nextNumLetter ( rnd) ;
for ( int i= 0 l i< 8 ; i++ ) {
if ( chars[ i] == 0 ) {
chars[ i] = nextChar ( rnd) ;
}
}
return new String ( chars) ;
}
4. 隨機的基本原理
Random產生的隨機數不是真正的隨機數,相反,他產生的隨機數一般為偽隨機數,真正的隨機數比較難以產生,計算機程序中的隨機數一般都是偽隨機數
偽隨機數 是基於一個種子數 的,然后需要一個隨機數,然后對當前種子進行一些數學運算,而得到新的隨機數和新的種子
在Random 中 隨機數 不是真正的隨機數,但是 種子 是一個真正的隨機數。
java8 中看到private static long seedUniquifier ( ) {
for ( ; ; ) {
long current = seedUniquifier. get ( ) ;
long next = current * 181783497276652981 L;
if ( seedUniquifier. compareAndSet ( current, next) )
return next;
}
}
種子 是seedUniquifier 和 System.nanoTime 按位異或的結果 System.nanoTime 返回一個更高精度的當前時間(納秒)
通過next 來生成指定位數的隨機數 protected int next ( int bits) {
long oldseed, nextseed;
AtomicLong seed = this . seed;
do {
oldseed = seed. get ( ) ;
nextseed = ( oldseed * multiplier + addend) & mask;
} while ( ! seed. compareAndSet ( oldseed, nextseed) ) ;
return ( int ) ( nextseed >>> ( 48 - bits) ) ;
}
就是使用這個公式nextSeed = ( oldseed * multiplier + addend) & mask ;
上面的方法 叫 線性同余隨機數生成器
通過 上面的方法,相同的就是 洗牌 和帶權重的隨機選擇,,都可以這樣 寫出