Skip to content

Latest commit

 

History

History
54 lines (38 loc) · 1.32 KB

Ex_1_3_35.md

File metadata and controls

54 lines (38 loc) · 1.32 KB
title date draft tags categories
Algorithm4 Java Solution 1.3.35
2019-07-04 05:47:10 +0800
false
JAVA
TECH
archives

1.3.35

Problem:

Random queue. A random queue stores a collection of items and supports the following API:

2019-07-24-002

Write a class RandomQueue that implements this API. Hint : Use an array representation (with resizing). To remove an item, swap one at a random position (indexed 0 through N-1) with the one at the last position (index N-1). Then delete and return the last object, as in ResizingArrayStack. Write a client that deals bridge hands (13 cards each) using RandomQueue.

Solution:

Ex_1_3_35.java

Ex_1_3_35_BridgeClient.java

    public Item dequeue() {
      if (isEmpty()) {
        return null;
      }
      if (N > 0 && N == a.length / 4) {
        resize(a.length / 2);
      }
      int r = StdRandom.uniform(N);
      Item item = a[r];
      // delete
      a[r] = a[N - 1];
      a[N - 1] = null;
      N--;
      return item;
    }

Reference:

桥牌

xiaohei