Advertisement
jules0707

RandomizedQueue

Feb 19th, 2018 (edited)
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 4.13 KB | None | 0 0
  1. /** ====================================================================================
  2. http://coursera.cs.princeton.edu/algs4/assignments/queues.html
  3. Deques and Randomized Queues
  4. 100/100
  5. Hide grader output
  6. See the Assessment Guide for information on how to interpret this report.
  7.  
  8. ASSESSMENT SUMMARY
  9.  
  10. Compilation:  PASSED (0 errors, 3 warnings)
  11. API:          PASSED
  12.  
  13. Findbugs:     PASSED
  14. PMD:          PASSED
  15. Checkstyle:   FAILED (0 errors, 2 warnings)
  16.  
  17. Correctness:  43/43 tests passed
  18. Memory:       105/105 tests passed
  19. Timing:       136/136 tests passed
  20.  
  21. Aggregate score: 100.00%
  22. [Compilation: 5%, API: 5%, Findbugs: 0%, PMD: 0%, Checkstyle: 0%, Correctness: 60%, Memory: 10%, Timing: 20%]
  23. ========================================================================================
  24. **/
  25.  
  26. import java.util.Iterator;
  27. import edu.princeton.cs.algs4.StdRandom;
  28.  
  29. /*
  30.  * requirements are "constant amortized time " for non-iterator operations. And linear for iterator
  31.  * (repeated doubling and 1/4 full shrinking provides constant amortized when adding / popping  items)
  32.  */
  33.  
  34. public class RandomizedQueue<Item> implements Iterable<Item> {
  35.     private Item[] q; // a generic array of Items
  36.     private int N; // number of items in the array
  37.  
  38.     // constructor of an empty randomized queue
  39.     public RandomizedQueue() {
  40.         // "necessary ugly cast" of java arrays that are not generic
  41.         q = (Item[]) new Object[1]; // initial array capacity is set to 1
  42.         N = 0; // initial number of items in the array is zero.
  43.     }
  44.  
  45.     // is the array empty?
  46.     public boolean isEmpty() {
  47.         return N == 0;
  48.     }
  49.  
  50.     // return the number of items
  51.     public int size() {
  52.         return N;
  53.     }
  54.  
  55.     // add an item in amortized constant time
  56.     public void enqueue(Item item) {
  57.         if (item == null)
  58.             throw new java.lang.IllegalArgumentException("item is null");
  59.         if (N == q.length) // the array has reached its maximum
  60.                             // capacity
  61.             resize(2 * q.length);
  62.         q[N] = item;
  63.         N++;
  64.     }
  65.  
  66.     // remove and return a random item in constant time!
  67.     public Item dequeue() {
  68.         if (isEmpty())
  69.             throw new java.util.NoSuchElementException("empty queue");
  70.         int r = StdRandom.uniform(N);
  71.         Item item = q[r];
  72.         q[r] = q[N - 1]; // we fill up the deleted item with the last one of the
  73.                             // queue thanks sparkoo Michal Vala for the idea!
  74.         // and reduce the queue by one item
  75.         q[--N] = null; // for loitering
  76.         // resizing of array if necessary when 1/4 empty
  77.         if (N > 0 && N == q.length / 4)
  78.             resize(q.length / 2);
  79.         return item;
  80.     }
  81.  
  82.     // return a random item (but do not remove it)
  83.     public Item sample() {
  84.         if (isEmpty())
  85.             throw new java.util.NoSuchElementException("empty queue");
  86.         return q[StdRandom.uniform(N)];
  87.     }
  88.  
  89.     // return an independent iterator over items in random order
  90.     public Iterator<Item> iterator() {
  91.         return new RQIterator();
  92.     }
  93.  
  94.     private class RQIterator implements Iterator<Item> {
  95.         private int i = N;
  96.         // a shuffled copy of q
  97.         private final Item[] sq = shuffleCopy();
  98.  
  99.         // we make a ahuffled copy of q item by item
  100.         private Item[] shuffleCopy() {
  101.             Item[] shuffledCopy = (Item[]) new Object[N];
  102.             int index = 0;
  103.             if (q != null) {
  104.                 StdRandom.shuffle(q, 0, N);
  105.                 for (int j = 0; j < q.length; j++) {
  106.                     if (q[j] != null) {
  107.                         // and only copy when there is a non null value
  108.                         shuffledCopy[index] = q[j];
  109.                         index++;
  110.                     }
  111.                 }
  112.             }
  113.             return shuffledCopy;
  114.         }
  115.  
  116.         public boolean hasNext() {
  117.             return i > 0;
  118.         }
  119.  
  120.         public void remove() {
  121.             throw new java.lang.UnsupportedOperationException("not supported");
  122.         }
  123.  
  124.         public Item next() {
  125.             if (!hasNext())
  126.                 throw new java.util.NoSuchElementException("No more items");
  127.             return sq[--i];
  128.         }
  129.     }
  130.  
  131.     private void resize(int capacity) {
  132.         // a new queue to store the resized queue.
  133.         // necessary ugly cast java arrays not generic
  134.         Item[] resizedQ = (Item[]) new Object[capacity];
  135.         // we use two indices to remove the nulls during the copy process
  136.         int j = 0;
  137.         for (int index = 0; index < q.length; index++) {
  138.             if (q[index] != null) {
  139.                 // and only copy when there is a value
  140.                 resizedQ[j] = q[index];
  141.                 j++;
  142.             }
  143.         }
  144.         q = resizedQ;
  145.     }
  146. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement