Question

Please Modify TestPart2 to test the correctness and efficiency of FasterDefaultList. Thanks

Note: A DumbDefaultList class has already been implemented for you. You can use it to help test correctness of your implementation.

import java.util.List;
import java.util.AbstractList;
import java.util.Map;
import java.util.HashMap;

public class DumbDefaultList<T> extends AbstractList<T> {
  Map<Integer,T> map;

  public DumbDefaultList() {
    map = new HashMap<Integer,T>();
  }

  public int size() {
    return Integer.MAX_VALUE;
  }

  public T get(int i) {
    return map.get(i);
  }

  public T set(int i, T x) {
    return map.put(i, x);
  }

  public void add(int i, T x) {
    Map<Integer, T> map2 = new HashMap<Integer,T>();
    for (Integer k : map.keySet()) {
      if (k >= i) {
        map2.put(k, map.get(k));
      }
    }
    for (Integer k : map2.keySet()) {
      map.remove(k);
    }
    for (Map.Entry<Integer,T> e : map2.entrySet()) {
      map.put(e.getKey()+1, e.getValue());
    }
    map.put(i, x);
  }

  public T remove(int i) {
    Map<Integer, T> map2 = new HashMap<Integer,T>();
    for (Integer k : map.keySet()) {
      if (k >= i) {
        map2.put(k, map.get(k));
      }
    }
    for (Integer k : map2.keySet()) {
      map.remove(k);
    }
    T retval = map2.remove(i);
    for (Map.Entry<Integer,T> e : map2.entrySet()) {
      map.put(e.getKey()-1, e.getValue());
    }
    return retval;
  }

  public static void main(String[] args) {
    Tester.testDefaultList(new DumbDefaultList<Integer>());
  }
}

-----------------------------------------------------------------------------------------------------

import java.lang.reflect.Array;
import java.lang.IllegalStateException;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;


/**
 * Implements the List interface as a skiplist so that all the
 * standard operations take O(log n) time
 *
 * TODO: Modify this so that it creates a DefaultList, which is basically
 *       an infinitely long list whose values start out as null
 *
 */
public class FastDefaultList<T> extends AbstractList<T> {
   class Node {
      T x;
      Node[] next;
      int[] length;
      @SuppressWarnings("unchecked")
      public Node(T ix, int h) {
         x = ix;
         next = (Node[])Array.newInstance(Node.class, h+1);
         length = new int[h+1];
      }
      public int height() {
         return next.length - 1;
      }
   }

   /**
    * This node sits on the left side of the skiplist
    */
   protected Node sentinel;

   /**
    * The maximum height of any element
    */
   int h;

   /**
    * The number of elements stored in the skiplist
    */
   int n;   // Hint: You don't need this anymore!

   /**
    * A source of random numbers
    */
   Random rand;

   public FastDefaultList() {
      n = 0;
      sentinel = new Node(null, 32);
      h = 0;
      rand = new Random(0);
   }

   /**
    * Find the node that precedes list index i in the skiplist.
    *
    * @param x - the value to search for
    * @return the predecessor of the node at index i or the final
    * node if i exceeds size() - 1.
    */
   protected Node findPred(int i) {
        // Hint: It's not enough to know u, you also need the value j,
        //       maybe return the pair (u,j)
      Node u = sentinel;
      int r = h;
      int j = -1;   // index of the current node in list 0
      while (r >= 0) {
         while (u.next[r] != null && j + u.length[r] < i) {
            j += u.length[r];
            u = u.next[r];
         }
         r--;
      }
      return u;
   }

   public T get(int i) {
        // Hint: this is too restrictive any non-negative i is allowed
      if (i < 0 || i > n-1) throw new IndexOutOfBoundsException();
        // Hint: Are you sure findPred(i).next is the node you're looking for?
      return findPred(i).next[0].x;
   }

   public T set(int i, T x) {
        // Hint: this is too restrictive any non-negative i is allowed
      if (i < 0 || i > n-1) throw new IndexOutOfBoundsException();
        // Hint: Are you sure findPred(i).next is the node you're looking for?
        //       If it's not, you'd better add a new node, maybe get everything
        //       else working and come back to this later.
      Node u = findPred(i).next[0];
      T y = u.x;
      u.x = x;
      return y;
   }

   /**
    * Insert a new node into the skiplist
    * @param i the index of the new node
    * @param w the node to insert
    * @return the node u that precedes v in the skiplist
    */
   protected Node add(int i, Node w) {
      Node u = sentinel;
      int k = w.height();
      int r = h;
      int j = -1; // index of u
      while (r >= 0) {
         while (u.next[r] != null && j+u.length[r] < i) {
            j += u.length[r];
            u = u.next[r];
         }
         u.length[r]++; // accounts for new node in list 0
         if (r <= k) {
            w.next[r] = u.next[r];
            u.next[r] = w;
            w.length[r] = u.length[r] - (i - j);
            u.length[r] = i - j;
         }
         r--;
      }
      n++;
      return u;
   }

   /**
    * Simulate repeatedly tossing a coin until it comes up tails.
    * Note, this code will never generate a height greater than 32
    * @return the number of coin tosses - 1
    */
   protected int pickHeight() {
      int z = rand.nextInt();
      int k = 0;
      int m = 1;
      while ((z & m) != 0) {
         k++;
         m <<= 1;
      }
      return k;
   }

   public void add(int i, T x) {
        // Hint: bounds checking again!
      if (i < 0 || i > n) throw new IndexOutOfBoundsException();
      Node w = new Node(x, pickHeight());
      if (w.height() > h)
         h = w.height();
      add(i, w);
   }

   public T remove(int i) {
        // Hint: bounds checking again!
      if (i < 0 || i > n-1) throw new IndexOutOfBoundsException();
      T x = null;
      Node u = sentinel;
      int r = h;
      int j = -1; // index of node u
      while (r >= 0) {
         while (u.next[r] != null && j+u.length[r] < i) {
            j += u.length[r];
            u = u.next[r];
         }
         u.length[r]--;  // for the node we are removing
         if (j + u.length[r] + 1 == i && u.next[r] != null) {
            x = u.next[r].x;
            u.length[r] += u.next[r].length[r];
            u.next[r] = u.next[r].next[r];
            if (u == sentinel && u.next[r] == null)
               h--;
         }
         r--;
      }
      n--;
      return x;
   }


   public int size() {
      return Integer.MAX_VALUE;
   }

   public String toString() {
        // This is just here to help you a bit with debugging
      StringBuilder sb = new StringBuilder();
         int i = -1;
         Node u = sentinel;
         while (u.next[0] != null) {
            i += u.length[0];
            u = u.next[0];
            sb.append(" " + i + "=>" + u.x);
         }
         return sb.toString();
   }

   public static void main(String[] args) {
      Tester.testDefaultList(new FastDefaultList<Integer>());
   }
}

------------------------------------------------------------------------------------

This needs to be modified

import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Tester {

  public static boolean testPart2(List<Integer> ell) {
    // put your testing code here
    return true;
  }

  public static void testDefaultList(List<Integer> ell) {
    long start = System.nanoTime();
    boolean result = Tester.testPart2(ell);
    long stop = System.nanoTime();
    double elapsed = (stop-start)/1e9;
    System.out.println("testPart1 returns " + result + " in " + elapsed + "s"
                       + " when testing a " + ell.getClass().getName());
  }

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//

//Tester.java

import java.util.Random;

import java.util.List;

public class Tester {

public static boolean testPart2(List<Integer> ell) {

if(ell==null)

return false;

Random rand = new Random();

  

for(int i=0;i<1000;i++){

ell.add(i,rand.nextInt(500));

}

if(ell.isEmpty())

return false;

int ele = ell.get(4);

int ele2 = ell.remove(4);

if(ele != ele2)

return false;

for(int i=0; i<999;i++){

ell.remove(0);

}

if(!ell.isEmpty())

return false;

return true;

}

public static void testDefaultList(List<Integer> ell) {

long start = System.nanoTime();

boolean result = Tester.testPart2(ell);

long stop = System.nanoTime();

double elapsed = (stop-start)/1e9;

System.out.println("testPart1 returns " + result + " in " + elapsed + "s"

+ " when testing a " + ell.getClass().getName());

}

}

Add a comment
Know the answer?
Add Answer to:
Please Modify TestPart2 to test the correctness and efficiency of FasterDefaultList. Thanks import java.util.List; import java.util.AbstractList;...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • Improve the speed of public T get(int i) by having it work backward from the end...

    Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index. Code import java.util.Iterator; public class DLList<T> implements Iterable<T> {    private static class Node<T> {        public Node<T> prev, next;...

  • Please help with the codes for the implementation of java.util.List, specifically for the 3 below overridden...

    Please help with the codes for the implementation of java.util.List, specifically for the 3 below overridden methods @Override        public int lastIndexOf(Object arg0) { required code }        @Override        public ListIterator<R> listIterator() { required code }        @Override        public ListIterator<R> listIterator(int arg0) { required code } PLEASE NOTE: Below are some of other overridden methods that are already implemented, they are meant to be examples of what the answers to the above questions for the 3 methods should...

  • Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import...

    Java help! Please help complete the min method below in bold. import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Provides an implementation of a binary search tree * with no balance constraints, implemented with linked nodes. * * * */ public class Bst<T extends Comparable<T>> implements Iterable<T> { ////////////////////////////////////////////////////////////////// // I M P L E M E N T T H E M I N M E T H O D B E L O W...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java....

    The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java.io.*; import java.util.*; //Create the class public class DPriorityQueue { //Declare the private members variables. private int type1,type2; private String CostInTime[][], SVertex, DVertex; private List<String> listOfTheNodes; private Set<String> List; private List<Root> ListOfVisitedNode; private HashMap<String, Integer> minimalDistance; private HashMap<String, Integer> distOfVertices; private PriorityQueue<City> priorityQueue; // prove the definition...

  • What is the time and space complexity of this code with explanation? public static int getv(int...

    What is the time and space complexity of this code with explanation? public static int getv(int num, List<Integer> rating, int target) { int count 0; HashMap<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < num; i++){ if(!map.containsKey(rating.get(i))){ map.put(rating.-get(i), 0); } map.put(rating.get(i), map.get(rating.get(i))+1); } for(int i = 0; i < num; i++){ if(map.get(target -rating.get(i)) != null){ count += map.get(target-rating.get(i)); } if(target-rating.get(i) == rating.get(i)){ count--; } return count/2; }

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • please help!!!! JAVA I done the project expect one part but I still give you all...

    please help!!!! JAVA I done the project expect one part but I still give you all the detail that you needed... and I will post my code please help me fix the CreateGrid() part in main and make GUI works    List Type Data Structures Overview : You will be implementing my version of a linked list. This is a linked list which has possible sublists descending from each node. These sublists are used to group together all nodes which...

  • please help me to creating UML class diagrams. Snake.java package graphichal2; import java.awt.Color; import java.awt.Font; import...

    please help me to creating UML class diagrams. Snake.java package graphichal2; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; enum Dir{L, U, R, D}; class Food { public static int FOODSTYLE = 1; private int m = r.nextInt(Yard.WIDTH / Yard.B_WIDTH); private int n = r.nextInt(Yard.HEIGHT / Yard.B_WIDTH - 30/Yard.B_WIDTH) + 30/Yard.B_WIDTH;// 竖格 public static Random r = new Random(); public int getM() { return m; } public void setM(int m)...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT