Shuffling (Shuffling)
Suppose you have a row order of playing cards, you have to do is reorder making the original order into a disordered arrangement.
- The initial order of the cards is as follows
Sort shuffle (Shuffle sort)
step
- Generating a random number for each of the playing cards
- Playing cards sorted according to the random number under each playing card
Examples
- The initial cards
- Add poker random numbers
- The random numbers are sorted in the poker
Code by java
static public void shuffle(int a[]){
TreeMap<Float,Integer> tm=new TreeMap<>();//使用Float(随机数)--Integer(数字)键值对的map来存储随机数和数字的组合
//同时利用Treemap对键的排序功能对随机数进行排序
Random r=new Random();//创建Random对象
for(int i=0;i<a.length;i++)//按顺序给每个数字一个随机数,并添加到Treemap
tm.put(r.nextFloat(),a[i]);
int i=0;
for(Float key:tm.keySet()) {//从Treemap中按顺序取出值,并放入到原数组中
a[i] = tm.get(key);
i++;
}
}
Feature
- Sorting depending randomness of the randomness of the random number generator
- When faced with a large-scale reshuffle, is actually relatively time-consuming sorting
Knuth shuffle
step
- Each iteration i, randomly selected from a 0-i playing cards in a card with the i-card exchange
Examples
- i iteration i
- R randomly generated number between 0-i of the
Code by java
static public void kunthShuffle(int[] a){
Random r=new Random();//创建Random对象
int temp;//交换临时变量
for(int i=1;i<a.length;i++){//显而易见下标为0的数字不用交换
int ri=r.nextInt(i+1);//随机生成的0-i的下标
temp=a[ri];//交换下标为i和下标为ri的两个数
a[ri]=a[i];
a[i]=temp;
}
}
Feature
- Effective sequence randomizes
- Can be completed within the time-line of