java实现洗牌算法

时间:2022-07-26 03:39:23

不定时更新一些java算法,以保持思维的灵活性

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;


/**打乱扑克牌*/
public class test1 {
public static void main(String[] args) {
String [] hua = new String[]{"黑桃","红桃","梅花","方砖"};
String [] num = {"1","2","3","4","5","6","7","8","9","10","J","Q","K","A"};
//抽象扑克牌集合
List<String> puke = new LinkedList<>();
for(int i=0;i<num.length;i++){
// System.out.print("\n");
for(int j=0;j<hua.length;j++){
// System.out.print(hua[j]+num[i] +"\t");
puke.add(hua[j]+num[i]);
}
}
//实例化个随机数
Random random = new Random();
String temp = null;
//模仿洗牌100次
for(int k=0;k<100;k++){
int max = puke.size();
int be = random.nextInt(max)%(max-0+1);
int af = random.nextInt(max)%(max-0+1);
//两次抽取的随机数相等的话就不洗,以免会出现重复数值
if(be==af)continue;
// System.out.println(me);
temp = puke.get(be);
puke.set(be, puke.get(af));
puke.set(af, temp);
}

int p = 0;
for(Iterator<String> it = puke.iterator();it.hasNext();){
if(p%4==0)System.out.print("\n");
System.out.print(it.next());
p++;
}
}
}