N副牌无限循环可控洗牌算法,可控洗牌算法,/** * N副
分享于 点击 20057 次 点评:257
N副牌无限循环可控洗牌算法,可控洗牌算法,/** * N副
/** * N副牌 */ public final class Deck { /** 存储所有扑克牌点数,忽略花色 */ private final int[] cards; /** N(umber)副牌 */ private final int number; /** 伪随机数对象 */ private final Random random=new Random(); /** */ private final int size; public Deck(int number) { /** 4种基本花色 */ int suits=4; /** 1副牌52张扑克的所有点数 */ int[] points={ 1,2,3,4,5,6,7,8,9,0,0,0,0 }; /** 13种基本点数 */ int ranks=points.length; this.number=number; this.cards=new int[suits*ranks*this.number]; for(int i=0,card=0;i<this.number && card<cards.length;i++) { for (int rank=0; rank<ranks;rank++) { for (int suit=0;suit<suits;suit++) { cards[card]=points[rank]; card=card+1; } } } this.size=cards.length; /** 无限循环洗牌 */ this.shuffle(); } /** * 随机抽取一张牌 */ public final int getCard() { return this.cards[this.random.nextInt(size)]; } /** * 洗牌算法 * 独立线程定时器死循环洗牌 */ private final void shuffle() { ( new Thread ( new Runnable() { @Override public final synchronized void run() { (new Timer()).schedule ( new TimerTask() { /** 定时器自增索引 */ private int index=0; /** 中间变量 */ private int swap=0; /** 交换对象索引 */ private int target=0; @Override public final synchronized void run() { /** 生成随机索引 */ this.target=this.index+random.nextInt(size-this.index); /** 缓存 */ this.swap=cards[this.index]; cards[this.index]=cards[this.target]; cards[this.target]=this.swap; this.index=(this.index==(size-1) ? 0 : this.index+1); } }, 0, // 无延迟 1 // 1 秒执行一次 ); } } ) ).start(); } }//该片段来自于http://byrx.net
用户点评