Algs4-1.3.35随机队列

1.3.35随机队列。随机队列能够存储一组元素并支持表1.3.11中的API:
表1.3.11泛型随机队列的API
public class RandomQueue<Item>
    RandomQueue()//创建一条空的随机队列
    boolean isEmpty()//队列是否为空
    void enqueue(Item item)//添加一个元素
    Item dequeue()//删除并随机返回一个元素(取样且不放回)
    Item sample()//随机返回一个元素但不删除它(取样且放回)
编写一个RandomQueue类来实现这份API。提示:使用(能够动态调整大小的)数组表示数据。删除一个元素时,随机交换某个元素(索引0和N-1之间)和末位元素(索引为N-1)的位置,然后象ResizingArrayStack一样删除并返回末位元素。编写一个用例,使用RandomQueue<Card>在桥牌中发牌(每人13张)。
答:
图片

public class RandomQueue<Item>
{
    private int N=0;
    private Item[] a=(Item[]) new Object[1];
    public RandomQueue()
    {
    }
   
    public boolean isEmpty()
    {return N==0;}
   
    public void enqueue(Item item)
    {
        if(N==a.length) resize(2*N);
        a[N]=item;
        N++;
    }
   
    public Item dequeue()
    {
        int r=StdRandom.uniform(N);
        Item item=a[r];
        a[r]=a[N-1];
        N--;
        if(N==a.length/4) resize(2*N);
        return item;
     }
   
    public Item sample()
    {
        int r=StdRandom.uniform(N);
        return a[r];
    }
   
    private void resize(int max)
    {
        Item[] temp=(Item[]) new Object[max];
        for(int i=0;i<N;i++)
            temp[i]=a[i];
        a=temp;
    }
   
    public static void main(String[] args)
    {
        RandomQueue<Card> cards=new RandomQueue<Card>();

       
        for(int value=1;value<=13;value++)
            for(int type=1;type<=4;type++)
               {
                  Card c=new Card();
                  c.value=value;
                  c.type=type;
                  cards.enqueue(c);
              }
        //
       StdOut.printf("---Format:(CardValue,CardType)--- ");
       StdOut.printf(" person 1----- ");
       for(int i=1;i<=13;i++)
          {
           Card c=cards.dequeue();
           StdOut.print("("+c.value+"," +c.type+")");
          }
       //
       StdOut.printf(" person 2----- ");
       for(int i=1;i<=13;i++)
          {
           Card c=cards.dequeue();
           StdOut.print("("+c.value+"," +c.type+")");
          }
        //
       StdOut.printf(" person 3----- ");
       for(int i=1;i<=13;i++)
          {
           Card c=cards.dequeue();
           StdOut.print("("+c.value+"," +c.type+")");
          }
       //
       StdOut.printf(" person 4----- ");
       for(int i=1;i<=13;i++)
          {
           Card c=cards.dequeue();
           StdOut.print("("+c.value+"," +c.type+")");
          }
    }
}


public class Card
{
  public  int value;//1-13
  public  int type;//1-4
 }

原文地址:https://www.cnblogs.com/longjin2018/p/9854313.html