Question

In: Computer Science

Question - Write a Client class with a main method that tests the data structures as...

Question - Write a Client class with a main method that tests the data structures as follows:

  • For the ArrayStack, LinkedStack, ArrayQueue, LinkedQueue, and ArrayList:
    • Perform a timing test for each of these data structures.
    • Each timing test should measure in nanoseconds how long it takes to add and remove N Integers from the structure.
    • N should vary from 10 to 1,000,000,000 increasing N by a factor of 10 for each test.
    • Depending on your system you may run out of memory before you reach the maximum value of N.
      • If you run out of memory, and your program crashes just decrease the maximum value of N by a factor of 10 and try a new run.
      • You should see that your program throws an OutOfMemoryError
      • Generally, you should not try to catch an Error because your memory space might be corrupted and there is not guarantee that you can recover from the error.
    • Test results must be displayed in a nicely formatted ASCII table similar to the examples provided.
    • In the ASCII table:
      • Values in each cell are padded by 2 blank spaces
      • Each column is just wide enough to display the widest entry in that column including the cell padding. Your program must dynamically adjust the width of each column based on the values that it needs to print.
      • Numeric values must be printed using the comma thousand separator, i.e.
        • you must print a large number like 12,345
        • and not 12345
      • It is strongly suggested that you create a method that generates and prints the ASCII table. You could pass this method a 2-dimensional array of values that are to be printed.
      • Future assignments may require that you print out results in a similar ASCII table.
    • You should have two final runs in your Word document.
    • For the first run set the max value of N to 1,000,000 so that the times are fairly small.
    • For the second run set the max value of N to 1,000,000,000
    • If you run out of memory reduce the max value of N by a factor of 10 and try a new run.
    • For this assignment your ASCII tables do NOT need to have column labels.
    • Include both runs in your Word document.
  • ArrayStack code:
  • public class ArrayStack<E> implements Stack<E> {
    public static final int CAPACITY=1000; // default array capacity
    private E[ ] data; // generic array used for storage
    private int t = -1; // index of the top element in stack
    public ArrayStack( ) { this(CAPACITY); } // constructs stack with default capacity
    public ArrayStack(int capacity) { // constructs stack with given capacity
    data = (E[ ]) new Object[capacity]; // safe cast; compiler may give warning
    }
    public int size( ) { return (t + 1); }
    public boolean isEmpty() {return (t == -1); }
    public void push(E e) throws IllegalStateException {
    if (size( ) == data.length) throw new IllegalStateException("Stack is full");
    data[++t] = e; // increment t before storing new item
    }
    public E top( ) {
    if (isEmpty( )) return null;
    return data[t];
    }
    public E pop( ) {
    if (isEmpty( )) return null;
    E answer = data[t];
    data [t] = null; // dereference to help garbage collection
    t--;
    return answer;
    }
    }

  • LinkedStack code:

  • public class LinkedStack<E> implements Stack<E> {
    private SinglyLinkedList<E> list = new SinglyLinkedList<>( ); // an empty list
    public LinkedStack( ) { } // new stack relies on the initially empty list
    public int size( ) { return list.size( ); }
    public boolean isEmpty( ) { return list.isEmpty( ); }
    public void push(E element) { list.addFirst(element); }
    public E top( ) { return list.first( ); }
    public E pop( ) { return list.removeFirst( ); }
    }

  • ArrayQueue code:
  • public class ArrayQueue<E> implements Queue<E> {
    // instance variables
    private E[ ] data; // generic array used for storage
    private int f = 0; // index of the front element
    private int sz = 0;
    private static int CAPACITY = 1000;
    // current number of elements

    // constructors
    public ArrayQueue( ) {this(CAPACITY);} // constructs queue with default capacity
    public ArrayQueue(int capacity) { // constructs queue with given capacity
    data = (E[ ]) new Object[capacity]; // safe cast; compiler may give warning
    }

    // methods
    /** Returns the number of elements in the queue. */
    public int size( ) { return sz; }

    /** Tests whether the queue is empty. */
    public boolean isEmpty( ) { return (sz == 0); }

    /** Inserts an element at the rear of the queue. */
    public void enqueue(E e) throws IllegalStateException {
    if (sz == data.length) throw new IllegalStateException("Queue is full");
    int avail = (f + sz) % data.length; // use modular arithmetic
    data[avail] = e;
    sz++;
    }

    /** Returns, but does not remove, the first element of the queue (null if empty). */
    public E first( ) {
    if (isEmpty( )) return null;
    return data[f];
    }

    /** Removes and returns the first element of the queue (null if empty). */
    public E dequeue( ) {
    if (isEmpty( )) return null;
    E answer = data[f];
    data[f] = null; // dereference to help garbage collection
    f = (f + 1) % data.length;
    sz--;
    return answer;
    }
    }

  • LinkedQueue code:

  • public class LinkedQueue<E> implements Queue<E> {
    private SinglyLinkedList<E> list = new SinglyLinkedList<>( ); // an empty list
    public LinkedQueue( ) { } // new queue relies on the initially empty list
    public int size( ) { return list.size( ); }
    public boolean isEmpty( ) { return list.isEmpty( ); }
    public void enqueue(E element) { list.addLast(element); }
    public E first( ) { return list.first( ); }
    public E dequeue( ) { return list.removeFirst( ); }
    }

  • ArrayList Code:

  • public class ArrayList<E> implements List<E> {
    // instance variables
    public static final int CAPACITY=16; // default array capacity
    private E[ ] data; // generic array used for storage
    private int size = 0; // current number of elements
    // constructors
    public ArrayList( ) { this(CAPACITY); } // constructs list with default capacity
    public ArrayList(int capacity) { // constructs list with given capacity
    data = (E[ ]) new Object[capacity]; // safe cast; compiler may give warning
    }
    // public methods
    /** Returns the number of elements in the array list. */
    public int size( ) { return size; }
    /** Returns whether the array list is empty. */
    public boolean isEmpty( ) { return size == 0; }
    /** Returns (but does not remove) the element at index i. */
    public E get(int i) throws IndexOutOfBoundsException {
    checkIndex(i, size);
    return data[i];
    }
    /** Replaces the element at index i with e, and returns the replaced element. */
    public E set(int i, E e) throws IndexOutOfBoundsException {
    checkIndex(i, size);
    E temp = data[i];
    data[i] = e;
    return temp;
    }
    /** Inserts element e to be at index i, shifting all subsequent elements later. */
    public void add(int i, E e) throws IndexOutOfBoundsException,
    IllegalStateException {
    checkIndex(i, size + 1);
    if (size == data.length) // not enough capacity
    throw new IllegalStateException("Array is full");
    for (int k=size-1; k>= i; k--) // start by shifting rightmost
    data[k+1] = data[k];
    data[i] = e; // ready to place the new element
    size++;
    }
    /** Removes/returns the element at index i, shifting subsequent elements earlier. */
    public E remove(int i) throws IndexOutOfBoundsException {
    checkIndex(i, size);
    E temp = data[i];
    for (int k=i; k< size-1; k++) // shift elements to fill hole
    data[k] = data[k+1];
    data[size-1] = null; // help garbage collection
    size--;
    return temp;
    }
    // utility method
    /** Checks whether the given index is in the range [0, n−1]. */
    protected void checkIndex(int i, int n) throws IndexOutOfBoundsException {
    if (i < 0 || i >= n)
    throw new IndexOutOfBoundsException("Illegal index: " + i);
    }

    /** Resizes internal array to have given capacity >= size. */
    protected void resize(int capacity) {
    E[ ] temp = (E[ ]) new Object[capacity]; // safe cast; compiler may give warning
    for (int k=0; k < size; k++)
    temp[k] = data[k];
    data = temp; // start using the new array
    }
    /** Inserts element e to be at index i, shifting all subsequent elements later. */

    }

Solutions

Expert Solution

To solve the given problem, the overall approach is to first add N integers to the concerned structure and then delete those N elements after the addition has been completed. To do this, run a for loop varying the value of N from 10 to 100,000,000 while checking for exception(outofmemoryerror) using try and catch block every time the structure is created of capacity N. When an exception is thrown, the loop breaks and goes to the next loop for the next structure. The time elapsed is calculated using System.nanoTime() which gives the current value of time and the elapsed time is calculated by tend - tstart.

In the end, a method is created which makes a 2d array corresponding to the value of N and time. There are 8 of these arrays. Two(add and delete) for each structure.

To create the ASCII table format(which is not shown in the question by the way), first, find out the maximum value of time and N and then convert them to string and store the corresponding length of the strings. Then run the for loop for the size of the array print the value of N and time with padding where the padding also includes the difference between the maximum string length and the current string length along with padding of size 2 on both the sides. In the below-given segment of code, I have only done this for the value of N but one can do this for the value of time also.

Remark: The code given below is giving an overall idea of what is to be done. It might not be accurate but is provided just for the sake of understanding. Also, the above given code in the question contains some error and needs to be corrected.

public class test
{

public static void main(String[] args) throws Exception
{
ArrayList<Float> asarray = new ArrayList<>();
ArrayList<Float> lsarray = new ArrayList<>();
ArrayList<Float> aqarray = new ArrayList<>();
ArrayList<Float> lqarray = new ArrayList<>();
ArrayList<Float> dasarray = new ArrayList<>();
ArrayList<Float> dlsarray = new ArrayList<>();
ArrayList<Float> daqarray = new ArrayList<>();
ArrayList<Float> dlqarray = new ArrayList<>();

int n = 0;
for(int i = 10; i<=100000000; i = i*10)
{
try
{

ArrayStack<Integer> as = new ArrayStack<>(i);
float tstart = (float)System.nanoTime();
for(int k = 0; k < i; k++)
{
as.push(1);

}
float tend = (float)System.nanoTime();
float time = 0;
if(i==10)
time = tend-tstart;
else
time = asarray.get(asarray.size()-1) + tend - tstart;
asarray.add(time);
n = i;

float dtstart = (float)System.nanoTime();
for(int k = 0; k < n; k++)
{
as.pop();

}
float dtend = (float)System.nanoTime();
float dtime =0;
if(i==10)
dtime = dtend-dtstart;
else
dtime = dasarray.get(dasarray.size()-1) + dtend - dtstart;
dasarray.add(dtime);
}
catch(OutOfMemoryError E)
{
break;
}

}

n = 0;
for(int i = 10; i<=100000000; i = i*10)
{
try
{

LinkedStack<Integer> ls = new LinkedStack<>(i);
float tstart = (float)System.nanoTime();
for(int k = 0; k < i; k++)
{
ls.push(1);

}
float tend =(float)System.nanoTime();
float time =0;
if(i==10)
time = tend-tstart;
else
time = lsarray.get(lsarray.size()-1) + tend - tstart;
lsarray.add(time);
n = i;

float dtstart = (float)System.nanoTime();
for(int k = 0; k < n; k++)
{
ls.pop();

}
float dtend = (float)System.nanoTime();
float dtime =0;
if(i==10)
dtime = dtend-dtstart;
else
dtime = dlsarray.get(dlsarray.size()-1) + dtend - dtstart;
dlsarray.add(dtime);
}
catch(OutOfMemoryError E)
{
break;
}

}

n = 0;
for(int i = 10; i<=100000000; i = i*10)
{
try
{

ArrayQueue<Integer> aq = new ArrayQueue<>(i);
float tstart = (float)System.nanoTime();
for(int k = 0; k < i; k++)
{
aq.enqueue(1);

}
float tend =(float)System.nanoTime();
float time =0;
if(i==10)
time = tend-tstart;
else
time = aqarray.get(aqarray.size()-1) + tend - tstart;
aqarray.add(time);
n = i;

float dtstart =(float)System.nanoTime();
for(int k = 0; k < n; k++)
{
aq.dequeue();

}
float dtend = (float)System.nanoTime();
float dtime =0;
if(i==10)
dtime = dtend-dtstart;
else
dtime = daqarray.get(daqarray.size()-1) + dtend - dtstart;
daqarray.add(dtime);
}
catch(OutOfMemoryError E)
{
break;
}

}

n = 0;
for(int i = 10; i<=100000000; i = i*10)
{
try
{

LinkedQueue<Integer> lq = new LinkedQueue<>(i);
float tstart = (float)System.nanoTime();
for(int k = 0; k < i; k++)
{
lq.enqueue(1);

}
float tend =(float)System.nanoTime();
float time =0;
if(i==10)
time = tend-tstart;
else
time = lqarray.get(lqarray.size()-1) + tend - tstart;
lqarray.add(time);
n = i;

float dtstart =(float)System.nanoTime();
for(int k = 0; k < n; k++)
{
lq.dequeue();

}
float dtend = (float)System.nanoTime();
float dtime =0;
if(i==10)
dtime = dtend-dtstart;
else
dtime = dlqarray.get(dlqarray.size()-1) + dtend - dtstart;
dlqarray.add(dtime);
}
catch(OutOfMemoryError E)
{
break;
}

}

float[][] as = to2d(asarray);
float[][] das = to2d(dasarray);
float[][] ls = to2d(lsarray);
float[][] dls = to2d(dlsarray);
float[][] aq = to2d(aqarray);
float[][] daq = to2d(daqarray);
float[][] lq = to2d(lqarray);
float[][] dlq = to2d(dlqarray);

totable(asarray);
totable(dasarray);
totable(lsarray);
totable(dlsarray);
totable(aqarray);
totable(daqarray);
totable(lqarray);
totable(dlqarray);

}
public float[][] to2d(ArrayList<Float> asarray)
{
float[][] asarr = new float[asarray.size()][2];
float m=10;
for(int i=0;i<asarray.size();i++)
{
asarr[i][0]=m;
m=m*10;
asarr[i][1]=asarray.get(i);
}
return asarr;
}

public void totable(float[][] arr)
{

int maxlen = 9
System.out.print("| N |"+"| time ");

for(int i=0;i<arr.length(0);i++)
{

int curlen = (String.valueOf(arr[i][0])).length();
String space = "";
for(int k = 0; k < maxlen - curlen; k++)
{
space += " "
}
System.out.print("| " + arr[i][0] + space + " |");
System.out.print("| " + arr[i][1] + " |");

System.out.println();
}
}

}

Please UPVOTE my answer if you find this explaination to be helpful !!


Related Solutions

Given the main method of a driver class, write a Fraction class. Include the following instance...
Given the main method of a driver class, write a Fraction class. Include the following instance methods: add, multiply, print, printAsDouble, and a separate accessor method for each instance variable. Write a Fraction class that implements these methods: add ─ This method receives a Fraction parameter and adds the parameter fraction to the calling object fraction. multiply ─ This method receives a Fraction parameter and multiplies the parameter fraction by the calling object fraction. print ─ This method prints the...
Name the project pa3 [Method 1] In the Main class, write a static void method to...
Name the project pa3 [Method 1] In the Main class, write a static void method to print the following text by making use of a loop. Solutions without a loop will receive no credit. 1: All work and no play makes Jack a dull boy. 2: All work and no play makes Jack a dull boy. 3: All work and no play makes Jack a dull boy. 4: All work and no play makes Jack a dull boy. [Method 2]...
3. [Method 1] In the Main class, write a static void method to print the following...
3. [Method 1] In the Main class, write a static void method to print the following text by making use of a loop. Solutions without a loop will receive no credit. 1: All work and no play makes Jack a dull boy. 2: All work and no play makes Jack a dull boy. 3: All work and no play makes Jack a dull boy. 4: All work and no play makes Jack a dull boy. 4. [Method 2] In the...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of Poem objects, read in the information from PoemInfo.txt and create Poem objects to populate the ArrayList. After all data from the file is read in and the Poem objects added to the ArrayList- print the contents of the ArrayList. Paste your PoemDriver.java text (CtrlC to copy, CtrlV to paste) into the open space before. You should not change Poem.java or PoemInfo.txt. Watch your time...
C++ Data Structures 4. Write a client function that merges two instances of the Sorted List...
C++ Data Structures 4. Write a client function that merges two instances of the Sorted List ADT using the following specification. MergeLists(SortedType list1, SortedType list2, SortedType& result) Function: Merge two sorted lists into a third sorted list. Preconditions: list1 and list2 have been initialized and are sorted by key using function ComparedTo. list1 and list2 do not have any keys in common. Postconditions: result is a sorted list that contains all of the items from list1 and list2. c. Write...
Define Loan Class – Add to your project. And write program in main method to test...
Define Loan Class – Add to your project. And write program in main method to test it. Note: Assume year is number of years, rate is the annual interest rate and P is principle is loan amount, then the total payment is Total payment = P *(1+ rate/12)^ year*12; Monthly Payment = TotalPayment/(year*12); java
In Java Create a class called "TestZoo" that holds your main method. Write the code in...
In Java Create a class called "TestZoo" that holds your main method. Write the code in main to create a number of instances of the objects. Create a number of animals and assign a cage and a diet to each. Use a string to specify the diet. Create a zoo object and populate it with your animals. Declare the Animal object in zoo as Animal[] animal = new Animal[3] and add the animals into this array. Note that this zoo...
Write a public class call CountInts. class CountInts has a main method. CountInts must have two...
Write a public class call CountInts. class CountInts has a main method. CountInts must have two methods: count and displayResults. 1. method count takes an array, aa, of ints and counts how many times each integer appears in aa. The integers can only be from 0 to 100 inclusive. 2. method display results displays the results of the count 3. use the template provided. insert your code in the places indicated and don't change anything else. Examples % java CountInts...
Error: Main method is not static in class ArrayReview, please define the main method as: public...
Error: Main method is not static in class ArrayReview, please define the main method as: public static void main(String[] args) please help me fast: import java.util. Random; import java.util.Scanner; //ArrayReview class class ArrayReview { int array[];    //constructor ArrayReview (int n) { array = new int[n]; //populating array Random r = new Random(); for (int i=0;i<n; i++) array[i] = r.nextInt (); } //getter method return integer at given index int getElement (int i) { return array[i]; }    //method to...
Data Structures ( Recursion ) Assignment Write a recursive method removeMiddle that receives an array list...
Data Structures ( Recursion ) Assignment Write a recursive method removeMiddle that receives an array list which has odd number of elements, then it deletes the element in the middle only. The method should receive only one parameter (the array list) The base case is when the array list has only one element, just remove that, otherwise, you need to remove the first one and the last one then call the method, then you need to add them again after...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT