package com.jjinfo.common.util;
import java.util.Arrays;
import java.util.Random;
/**
*
*/
public class RandomNumberGenerator {
/**
* 這是典型的隨機洗牌算法。
* 流程是從備選數(shù)組中選擇一個放入目標(biāo)數(shù)組中,將選取的數(shù)組從備選數(shù)組移除(放至最后,并縮小選擇區(qū)域)
* 算法時間復(fù)雜度O(n)
* @return 隨機8為不重復(fù)數(shù)組
*/
public static String generateNumber() {
String no= "" ;
//初始化備選數(shù)組
int [] defaultNums = new int [ 10 ];
for ( int i = 0 ; i < defaultNums.length; i++) {
defaultNums[i] = i;
}
Random random = new Random();
int [] nums = new int [LENGTH];
//默認(rèn)數(shù)組中可以選擇的部分長度
int canBeUsed = 10 ;
//填充目標(biāo)數(shù)組
for ( int i = 0 ; i < nums.length; i++) {
//將隨機選取的數(shù)字存入目標(biāo)數(shù)組
int index = random.nextInt(canBeUsed);
nums[i] = defaultNums[index];
//將已用過的數(shù)字扔到備選數(shù)組最后,并減小可選區(qū)域
swap(index, canBeUsed - 1 , defaultNums);
canBeUsed--;
}
if (nums.length> 0 ) {
for ( int i = 0 ; i < nums.length; i++) {
no+=nums[i];
}
}
return no;
}
private static final int LENGTH = 8 ;
private static void swap( int i, int j, int [] nums) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static String generateNumber2() {
String no= "" ;
int num[]= new int [ 8 ];
int c= 0 ;
for ( int i = 0 ; i < 8 ; i++) {
num[i] = new Random().nextInt( 10 );
c = num[i];
for ( int j = 0 ; j < i; j++) {
if (num[j] == c) {
i--;
break ;
}
}
}
if (num.length> 0 ) {
for ( int i = 0 ; i < num.length; i++) {
no+=num[i];
}
}
return no;
}
public static void main(String[] args) {
for ( int i = 0 ; i < 10 ; i++) {
// System.out.println(generateNumber());
System.out.println(generateNumber2());
}
}
}
|