这是洗牌算法变种,也可以理解为摸牌算法。就是生成就是随机的1-100个数。且不重复。
public class CreateRandomNumber {
public static void main(String[] args) {
int length = 100;
int[] a = new int[length];
shuffle(a);
printArray(a);
}
/**
* 打印数组a,每行10个元素
* */
public static void printArray(int[] a) {
int i = 1;
int len = a.length;
for (; i <= len; i++) {
if (i != 0 && i % 10 == 0)
System.out.println(a[i - 1]);
else
System.out.print(a[i - 1] + ", ");
}
}
/**
* <b>洗牌算法变种
* <p>
* 生成时即随机,并非生成后再洗牌
* <p>
* 生成从1到100的一个数组,且每个数字只出现一次。
* */
public static void shuffle(int[] a) {
for (int i = 0; i < a.length;) {
int random = (int) Math.floor(Math.random() * (i + 0.999));
a[i] = a[random];
a[random] = ++i;
}
}
}
关于洗牌算法的分析,有一篇文章写得很好。
http://hi.baidu.com/wulei407/blog/item/b6ea451b6572f9fdaf513315.html