package Cap1;
import edu.princeton.cs.introcs.StdOut;
import edu.princeton.cs.introcs.StdRandom;
public class RandomQueue<Item> {
/**
* @param args
*/
private Item[] a = (Item[]) new Object[1];
private int N = 0;
public boolean isEmpty() { return N == 0; }
private void resize(int length){
Item[] temp = (Item[]) new Object[length];
for(int i=0;i<N;i++){
temp[i] = a[i];
}
a = temp;
}
public void enqueue(Item item){
if(N == a.length) resize(2*a.length);
a[N++] = item;
}
public Item dequeue(){
if(isEmpty()) return null;
int k = StdRandom.uniform(N);
Item item = a[k];
a[k] = a[--N];
a[N] = null;
if(N <= a.length/4) resize(a.length/2);
return item;
}
public Item sample(){
if(isEmpty()) return null;
int k = StdRandom.uniform(N);
return a[k];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomQueue<Card> rq = new RandomQueue<Card>();
for(int i=0;i<13;i++)
for(int j=0;j<4;j++)
rq.enqueue(new Card(i,j));
String people1="",people2="", people3="", people4="";
for(int i=0;i<13;i++){
people1 += rq.dequeue().toString() + "\t";
people2 += rq.dequeue() + "\t";
people3 += rq.dequeue() + "\t";
people4 += rq.dequeue() + "\t";
}
System.out.println(people1);
System.out.println(people2);
System.out.println(people3);
System.out.println(people4);
}
}
class Card{
private String suit; //花色
private String point; //点数
final String[] POINT = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
final String[] SUIT = {"红桃","黑桃","梅花","方块"};
public Card(int m, int n){
point = POINT[m];
suit = SUIT[n];
}
public String toString(){
return suit + point;
}
}
结果
黑桃A 红桃8 梅花Q 方块7 梅花10 梅花8 方块5 黑桃4 红桃5 黑桃10 黑桃K 方块K 方块6
梅花7 红桃J 方块Q 梅花K 方块9 方块10 方块J 梅花J 红桃2 黑桃5 黑桃7 梅花4 方块4
红桃K 红桃9 红桃Q 黑桃Q 红桃7 方块A 梅花5 红桃4 黑桃9 红桃3 红桃6 梅花2 黑桃J
黑桃6 黑桃3 红桃10 梅花9 方块8 方块2 红桃A 方块3 黑桃2 梅花3 梅花6 梅花A 黑桃8