Question

Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads...

Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads in a sequence of strings from standard input using StdIn.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 k N , where N is the number of string on standard input. The running time of the program must be linear in the size of the input. You may use only a constant amount of memory plus either one LinkedDeque or ResizingArrayRandomQueue object of maximum size at most N. For an extra challenge, limit the maximum size to k.

The sample output is $ java Subset 8
AA BB BB BB BB BB CC CC
<ctrl-d>
BB
CC
AA
BB
BB
BB

Here are code I have finished.

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

// Takes a command-line integer k; reads in a sequence of strings from
// standard input; and prints out exactly k of them, uniformly at random.
// Note that each item from the sequence is printed out at most once.
public class Subset {
    public static void main(String[] args) {
        //CODE HERE
        ResizingArrayRandomQueue<String> q = new ResizingArrayRandomQueue<String>();
        int k = Integer.parseInt(args[0]);

        while (!StdIn.isEmpty()){
            String item = StdIn.readString();
            q.enqueue(item);
        }
        while (k > 0) {
            StdOut.println(q.dequeue());
            k--;
        }
    }
}

and class ResizingArrayRandomQueue

public class ResizingArrayRandomQueue<Item> implements Iterable<Item> {
    //CODE HERE
    private Item[] q;
    private int N;

    // Construct an empty queue.
    public ResizingArrayRandomQueue() {
        //CODE HERE
        q = (Item[]) new Object[1];
        N = 0;
    }

    // Is the queue empty?
    public boolean isEmpty() {
        //CODE HERE
        return N == 0;
    }

    // The number of items on the queue.
    public int size() {
        //CODE HERE
        return N;
    }

    // Add item to the queue.
    public void enqueue(Item item) {
        //CODE HERE
        if (item == null)
            throw new IllegalArgumentException();
        q[N++] = item;
        if (N == q.length)
            resize(q.length * 2);
    }

    // Helper method for resizing the underlying array.
    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++) {
            if (q[i] != null) {
                temp[i] = q[i];
            }
        }
        q = temp;
    }

    // Remove and return a random item from the queue.
    public Item dequeue() {
        //CODE HERE
        if (isEmpty())
            throw new NoSuchElementException("Empty");
        int rand = StdRandom.uniform(0, N);
        N--;
        Item dItem = q[rand];
        q[rand] = q[N];
        q[N] = null;
        if (N > 0 && N == q.length/4)
            resize(q.length/2);
        return dItem;
    }

    // Return a random item from the queue, but do not remove it.
    public Item sample() {
        //CODE HERE
        if (isEmpty())
            throw new NoSuchElementException("Empty");
        int rand = StdRandom.uniform(0, N);
        Item item = q[rand];
        return  item;
    }

    // An independent iterator over items in the queue in random order.
    public Iterator<Item> iterator() {
        //CODE HERE
        return new RandomQueueIterator();
    }

    // An iterator, doesn't implement remove() since it's optional.
    private class RandomQueueIterator implements Iterator<Item> {
        //CODE HERE
        private int a = N;
        private Item[] b = (Item[]) new Object[q.length];

        RandomQueueIterator() {
            //CODE HERE
            for (int i = 0; i < q.length; i++) {
                b[i] = q[i];
            }
        }

        public boolean hasNext() {
            //CODE HERE
            return a > 0;
        }
        public void remove() {
            throw new UnsupportedOperationException();
        }

        public Item next() {
            //CODE HERE
            if (!hasNext()) {
                throw new NoSuchElementException("No more items");
            }
            int rand = StdRandom.uniform(0, a);
            a--;
            Item item = b[rand];
            b[rand] = b[a];
            b[a] = item;
            return item;
        }
    }

I successfully compiled Subset, however, when I ran it, it gives me this information:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
   at Subset.main(Subset.java:11)

Please correct any error in my code. Thx.

Homework Answers

Answer #1

Instead of your Subset  try this one.....

Put that command line integer in try catch block....it will resolve you error.
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

// Takes a command-line integer k; reads in a sequence of strings from 
// standard input; and prints out exactly k of them, uniformly at random. 
// Note that each item from the sequence is printed out at most once.
public class Subset {
        public static void main(String[] args) {
                int k = 0;

                // If any arguments given, we try to parse it
                if (args.length > 0) {

                        try {
                                k = Integer.parseInt(args[0]);
                        } catch (NumberFormatException e) {
                                System.err.println("Argument" + args[0] + " must be an integer.");

                                // Program ends
                                System.exit(1);
                        }

                        ResizingArrayRandomQueue<String> q = new ResizingArrayRandomQueue<String>();
                        while (!StdIn.isEmpty()) {
                                q.enqueue(StdIn.readString());
                        }
                        for (int i = 0; i < k; i++) {
                                StdOut.println(q.dequeue());
                        }
                }
        }
}

I think you have posted incomplete Question... one or more class may be missing here

related to LinkedDeque...

I would have completed your question with output then..Anyway this try catch block will work fine...  

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may...
In Java: Initiate empty queue of strings and recreate .isempty, .size, .dequeue, .enqueue methods. //You may not use the original methods of the stack api to answer. import java.util.NoSuchElementException; import edu.princeton.cs.algs4.Stack; public class StringQueue {    //You may NOT add any more fields to this class.    private Stack stack1;    private Stack stack2;    /**    * Initializes an empty queue.    */    public StringQueue() { //TODO    }    /**    * Returns true if this queue...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {...
Please explain code 1 and code 2 for each lines code 1 public class MyQueue {    public static final int DEFAULT_SIZE = 10;    private Object data[];    private int index; code 2 package test; import java.util.*; /* Class Node */ class Node { protected Object data; protected Node link; /* Constructor */ public Node() { link = null; data = 0; } /* Constructor */ public Node(Object d,Node n) { data = d; link = n; } /*...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue...
You must alter the Queue class you created in L5 to make it a CIRCULAR Queue class . Call your class Queue. it must be a template class. public class Queue { } I have put a driver program in the module . It is called CircularQueue.java This driver program should then run with your Queue class (no modifications allowed to the driver program). Your Queue class should have at least the following methods: one or more constructors, enqueue, dequeue,...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to...
ex3 Write a method public static boolean isPalindrome(String input) that uses one or more stacks to determine if a given string is a palindrome. [A palindrome is a string that reads the same forwards and backwards, for example ‘racecar’, ‘civic’]. Make sure that your method works correctly for special cases, if any. What is the big-O complexity of your method in terms of the list size n. Supplementary Exercise for Programming (Coding) [Stacks] Download and unpack (unzip) the file Stacks.rar....
This file that has the outline of an iterator which will be used to return each...
This file that has the outline of an iterator which will be used to return each char within a String. Complete the hasNext() and next() methods to enable this iteration. In case it is of use, String has two methods which may provide useful -- size() (returning the number of chars it contains) and charAt() (returning the character at the location passed as an argument). import java.util.Iterator; import java.util.NoSuchElementException; public class CharacterIterator implements Iterator<Character> { /** The String whose characters...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line),...
Using SLLStack.java, implement an application, LineReverser.java, that reads a line from keyboard (user enters one line), insert each separate word into the stack, and read/print on the screen. So, if the user enters: This is a test the application output should be: test a is This. This is SLLSTACK.java below package linked_lists; public class SLLStack {    //instance variabels    private SLLNode top;    private int numOfItems;       //constructors    public SLLStack() {        top = null;   ...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped...
Create a class StacktwoPopArr using Arrays, Change the pop function so that two elements get popped everytime instead of the one. If there is only one element in the stack, just pop the one element and report that the stack is now empty. If stack is empty, it should just report that stack is empty. All other functions for StackArray remain the same. using java StackArray.java: public class StackArray {       private final int size = 20; //Size of...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template <class ItemType> class QueueADT { public:        // Action responsibilities        virtual void resetQueue() = 0;           // Reset the queue to an empty queue.           // Post: Queue is empty.        virtual void add(const ItemType& newItem) = 0;           // Function to add newItem to the queue.           // Pre: The queue exists and is not full.          ...