1. 程式人生 > >演算法第四版 練習1.3.35

演算法第四版 練習1.3.35

RandomQueue.java

import edu.princeton.cs.algs4.StdRandom;

public class RandomQueue<Item> {
    private Item[] item;
    private int N;
    public RandomQueue()
    {
        item = (Item[])(new Object[10]);
    }
    public boolean isEmpty()
    {
        return N == 0;
    }
    public void
resize(int n) { @SuppressWarnings("unchecked") Item[] temp = (Item[])(new Object[n]); for (int i = 0; i < N; ++i) temp[i] = item[i]; item = temp; } public void enqueue(Item data) { if (N == item.length) resize(2 * N); item[N++] = data; } public
Item dequeue() { if (isEmpty()) return null; //random swap int r = StdRandom.uniform(N); Item temp = item[r]; item[r] = item[--N]; item[N] = null; return temp; } public Item sample() { if (isEmpty()) return
null; int r = StdRandom.uniform(N); Item ret = item[r]; return ret; } public int size() { return N; } }

Card.java

import edu.princeton.cs.algs4.StdRandom;

public class Card {
    private String name;
    private String flowercolor;
    public Card()
    {
        String[] nget = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
        String[] fget = {"紅桃","黑桃","梅花","棉花"};
        int n = StdRandom.uniform(13);
        int f = StdRandom.uniform(4);
        name = nget[n];
        flowercolor = fget[f];
    }
    public String toString()
    {
        return flowercolor + name;
    }
}

main.java

import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;

public class Main {
    public static void main(String[] args)
    {
        RandomQueue<Card> rd = new RandomQueue<Card>();
        for (int i = 0; i < 13; ++i)
            rd.enqueue(new Card());
        for (int i = 0; i < 13; ++i)
        {
            if (StdRandom.bernoulli())
                StdOut.println(rd.dequeue());
            else
                StdOut.println(rd.sample());
        }
        StdOut.println(rd.size());
    }
}

這裡寫圖片描述