Programming Assignment 2: Randomized Queues and Deques

时间:2021-04-15 17:38:04

问题详述:http://coursera.cs.princeton.edu/algs4/assignments/queues.html

Dequeue. A double-ended queue or deque (pronounced "deck") is a generalization of a stack and a queue that supports inserting and removing items from either the front or the back of the data structure. Create a generic data type Deque that implements the following API:

public class Deque<Item> implements Iterable<Item> { public Deque() // construct an empty deque public boolean isEmpty() // is the deque empty? public int size() // return the number of items on the deque public void addFirst(Item item) // insert the item at the front public void addLast(Item item) // insert the item at the end public Item removeFirst() // delete and return the item at the front public Item removeLast() // delete and return the item at the end public Iterator<Item> iterator() // return an iterator over items in order from front to end public static void main(String[] args) // unit testing } 

Throw a NullPointerException if the client attempts to add a null item; throw a java.util.NoSuchElementException if the client attempts to remove an item from an empty deque; throw an UnsupportedOperationException if the client calls the remove() method in the iterator; throw a java.util.NoSuchElementException if the client calls the next() method in the iterator and there are no more items to return.

Your deque implementation must support each deque operation in constant worst-case time and use space proportional to the number of items currently in the deque. Additionally, your iterator implementation must support the operations next() and hasNext() (plus construction) in constant worst-case time and use a constant amount of extra space per iterator.

我采用了一个双向链表并辅以首尾指针以保证常数时间内完成每个deque的操作;

代码:(Total: 15/15 tests passed!)

import java.util.Iterator;

public class Deque<Item> implements Iterable<Item> {
    private class node {
        Item item;
        node prev;
        node next;
    }
    private node first;
    private node last;
    private int N;
    public Deque() {                          // construct an empty deque
        first = last = null;
        N = 0;
    }
    public boolean isEmpty() {                // is the deque empty?
        return (N == 0);
    }
    public int size() {                       // return the number of items on the deque
        return N;
   }
   public void addFirst(Item item)          // insert the item at the front
   {
       if(item == null) throw new NullPointerException();
       node oldfirst = first;
       first = new node();
       first.item = item;
       first.next = oldfirst;
       if(isEmpty()) last = first;
       else {
           oldfirst.prev = first;
       }
       N++;      
   }
   public void addLast(Item item)           // insert the item at the end
   {
       if(item == null) throw new java.lang.NullPointerException();
       node oldlast = last;
       last = new node();
       last.item = item;
       last.prev = oldlast;
       if(isEmpty()) first = last;
       else {
           oldlast.next = last;
       }
       N++;
   }
   public Item removeFirst() {               // delete and return the item at the front
       if(N == 0) throw new java.util.NoSuchElementException();
       Item temp = first.item;
       first = first.next;
       N--;
       if(isEmpty()) last = null;
       else
           first.prev = null;
       return temp;
   }
   public Item removeLast() {                // delete and return the item at the end
       if(N == 0) throw new java.util.NoSuchElementException();
       Item temp = last.item;
       last = last.prev;
       N--;
       if(isEmpty()) first = null;
       else
           last.next = null;
       return temp;    
   }
   private class ListIterator implements Iterator<Item> {
       private node current = first;
       public boolean hasNext() {
           return current != null;
       }
       public void remove() {
           throw new java.lang.UnsupportedOperationException();
       } 
       public Item next() {
           if(!hasNext())
               throw new java.util.NoSuchElementException();
           Item item = current.item;
           current = current.next;
           return item;
       }
   }
   public Iterator<Item> iterator() {        // return an iterator over items in order from front to end
       return new ListIterator();
       
   }
   public static void main(String[] args) {  // unit testing
       Deque<String> deque = new Deque<String> ();
       deque.addFirst("aa");
       deque.addFirst("bb");
       deque.addFirst("cc");
       deque.addLast("dd");
       StdOut.println(deque.removeFirst());
       StdOut.println(deque.removeFirst());
       StdOut.println(deque.removeFirst());
       StdOut.println(deque.removeLast());
       StdOut.print("size:"+deque.size());
   } 
  
}

Randomized queue. A randomized queue is similar to a stack or queue, except that the item removed is chosen uniformly at random from items in the data structure. Create a generic data type RandomizedQueue that implements the following API:

public class RandomizedQueue<Item> implements Iterable<Item> { public RandomizedQueue() // construct an empty randomized queue public boolean isEmpty() // is the queue empty? public int size() // return the number of items on the queue public void enqueue(Item item) // add the item public Item dequeue() // delete and return a random item public Item sample() // return (but do not delete) a random item public Iterator<Item> iterator() // return an independent iterator over items in random order public static void main(String[] args) // unit testing } 

Throw a NullPointerException if the client attempts to add a null item; throw a java.util.NoSuchElementException if the client attempts to sample or dequeue an item from an empty randomized queue; throw an UnsupportedOperationException if the client calls the remove() method in the iterator; throw ajava.util.NoSuchElementException if the client calls the next() method in the iterator and there are no more items to return.

Your randomized queue implementation must support each randomized queue operation (besides creating an iterator) in constant amortized time and use space proportional to the number of items currently in the queue. That is, any sequence of M randomized queue operations (starting from an empty queue) should take at most cM steps in the worst case, for some constant c. Additionally, your iterator implementation must support construction in time linear in the number of items and it must support the operations next() and hasNext() in constant worst-case time; you may use a linear amount of extra memory per iterator. The order of two or more iterators to the same randomized queue should be mutually independent; each iterator must maintain its own random order.

这个问题我采用数组实现,一些细节问题可以参见视频https://class.coursera.org/algs4partI-006/lecture

也可以参见书籍《算法(第四版)》p88页。

代码:Total: 14/17 tests passed!

import java.util.Iterator;

public class RandomizedQueue<Item> implements Iterable<Item> {
    private Item[] a;
    private int N;
    
    public RandomizedQueue() {               // construct an empty randomized queue
        a = (Item[]) new Object[2];
        N = 0;
    }
       
    public boolean isEmpty() {                // is the queue empty?
        return (N == 0);
    }
    
    public int size() {                       // return the number of items on the queue
        return N;
    }
    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 void enqueue(Item item) {          // add the item
        if(item == null) throw new java.lang.NullPointerException();
        if(N == a.length) resize(a.length * 2);
        a[N++] = item;
    }
    public Item dequeue() {                   // delete and return a random item
        if(N == 0) throw new java.util.NoSuchElementException();
        int index = (int)(StdRandom.uniform(N));
        Item temp = a[index];
        if(index != N-1) a[index] = a[N-1];
        a[N-1] = null;
        N--;
        if(N >=0 && N == a.length/4) resize(a.length/2);
        return temp;
    }
        
    public Item sample() {                    // return (but do not delete) a random item
       if(N == 0) throw new java.util.NoSuchElementException();
       int index = (int)(StdRandom.random() * N);
       return a[index];             
    }
    public Iterator<Item> iterator() {        // return an independent iterator over items in random order
        return new ReverseArrayIterator();
    }
    private class ReverseArrayIterator implements Iterator<Item> {
    private int index = 0;
    private Item[] r;
    public ReverseArrayIterator() {
        r = (Item[]) new Object[N];
        for(int i=0; i<N; i++)
            r[i] = a[i];
        StdRandom.shuffle(r);
    }
    public boolean hasNext() {
        return index < N;
    }
    public void remove() {
        throw new java.lang.UnsupportedOperationException();
    }
    public Item next() {
        if(!hasNext()) throw new java.util.NoSuchElementException();
        Item item = r[index++];
        return item;
    }
    }
    public static void main(String[] args) {   // unit testing
       RandomizedQueue<String> deque = new RandomizedQueue<String> ();
       deque.enqueue("aa");
       deque.enqueue("bb");
       deque.enqueue("cc");
       deque.enqueue("dd");
       deque.dequeue();
       deque.dequeue();
       deque.dequeue();
       deque.dequeue();
       //deque.dequeue();
       StdOut.print("size:"+deque.size());
    }
}

这段代码我没有全部通过,有几个用例显示如下错误:

Programming Assignment 2: Randomized Queues and Deques

显示我在29行是出现数组越界,但是我figure it out。如果有人发现可以下面留言或评论。

Subset client. Write a client program Subset.java that takes a command-line integer k; reads in a sequence of N strings from standard input usingStdIn.readString(); and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 ≤kN, where N is the number of string on standard input.

% echo A B C D E F G H I | java Subset 3 % echo AA BB BB BB BB BB CC CC | java Subset 8 C BB G AA A BB CC % echo A B C D E F G H I | java Subset 3 BB E BB F CC G BB

The running time of Subset must be linear in the size of the input. You may use only a constant amount of memory plus either one Deque or RandomizedQueue object of maximum size at most N, where N is the number of strings on standard input. (For an extra challenge, use only one Deque or RandomizedQueue object of maximum size at most k.) It should have the following API.

public class Subset { public static void main(String[] args) }

Deliverables. Submit only Deque.java, RandomizedQueue.java, and Subset.java. We will supply stdlib.jar. You may not use any libraries other than those instdlib.jar, java.lang, java.util.Iterator, and java.util.NoSuchElementException.

这题比较简单,上代码:Total: 3/3 tests passed!

public class Subset {
    public static void main(String[] args) {
        int k = Integer.parseInt(args[0]);
        RandomizedQueue<String> deque = new RandomizedQueue<String>();
        while(!StdIn.isEmpty()) {
            deque.enqueue(StdIn.readString());       
        }
        for(int i = 0; i < k; i++) {
            StdOut.println(deque.dequeue());
        }      
    }
}