基本思想:
假如你要随机打乱100个整数。首先你可以在0--99之间生成一个随机数,然后把这个下标对应的整数和数组的第一位交换位置。接着在1--99之间生成
随机数,将下标对应的整数和数组的第二个数交换位置。这样一直下去。。。
public class RandomCards {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] cards=new int[10];
for(int i=0;i<10;i++){
cards[i]=i+1;
}
shuffleCards(cards);
for(int i:cards){
System.out.println(i);
}
}
/**
*
* @param cards 代表牌
*/
public static void shuffleCards(int[] cards){
int len=cards.length;
for(int i=0;i<len;i++){
int randomIndex=(len-1)-new Random().nextInt(len-i);
int tmp=cards[randomIndex];
cards[randomIndex]=cards[i];
cards[i]=tmp;
}
}
}