1. 程式人生 > >java實現洗牌演算法

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++; } } }