Question

import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; import java.util.ArrayList; public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>> implements...

import java.util.Iterator;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.ArrayList;


public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>> implements Iterable<Pair<K, V>> {


   private static final long serialVersionUID = -6229569372944782075L;

  
   public void add(K k, V v) {
      
if (!containsKey(k)) {

put(k, new LinkedList<V>());
}
get(k).add(v);
   }

  
   public V removeFirst(K k) {
      
       if (!containsKey(k)) {
return null;
       }

V value = get(k).removeFirst();

if (get(k).isEmpty()) {

super.remove(k);
}
return value;
   }

  
   public Pair<K, V> removeFirst() { // Problem 3
       // TODO complete this method
if (isEmpty()) {
return null;
}
K k = firstKey();
V v = removeFirst(k);
Pair<K, V> p = new Pair<K, V>(k, v);
return p;
      
   }


   public Iterator<Pair<K, V>> iterator() { // Problem 6
       // TODO complete this method
ArrayList<Pair<K, V>> list = new ArrayList<Pair<K, V>>();
for (K k : keySet()) {
for (V v : get(k)) {
list.add(new Pair<K, V>(k, v));
}
}
return list.iterator();
      
   }


   public static void main(String[] args) {
       MultiValuedTreeMap<Integer, String> m = new MultiValuedTreeMap<Integer, String>();
       m.add(1, "b");
       m.add(1, "a");
       m.add(0, "c");
       System.out.println(m);

       System.out.println(m.removeFirst(1));
       System.out.println(m);
       System.out.println(m.removeFirst());
       System.out.println(m.removeFirst());
       System.out.println(m.removeFirst());

       m.add(1, "b");
       m.add(1, "a");
       m.add(0, "c");
       System.out.println(m);
       for (Pair<Integer, String> p : m) {
           System.out.println(p);
       }
   }
}

public class Pair<F, S> {

   protected F first;
   protected S second;

  
   public Pair(F first, S second) {
       this.first = first;
       this.second = second;
   }
  
   public F first() {
       return first;
   }

   public S second() {
       return second;
   }

   @Override
   public String toString() {
       return "(" + first + ", " + second + ")";
   }

}


public class Simulator {

  
   protected MultiValuedTreeMap<Double, Task> scheduledTasks = new MultiValuedTreeMap<Double, Task>();


   public void schedule(Task task, double simulationTime) { // Problem 4
       // TODO complete this method
      
   }

  
   public void start() { // Problem 5
       // TODO complete this method
      
   }

  
   public static void main(String[] args) {
       Simulator simulator = new Simulator(); // construct a Simulator
       simulator.schedule(new Task() { // schedule a task that prints "1: " and then the simulation time 1000
           public void run(double simulationTime) {
               System.out.println("1: " + simulationTime);
           }
       }, 1000);
       simulator.schedule(new Task() { // schedule a task that prints "2: " and then the simulation time 2000
           public void run(double simulationTime) {
               System.out.println("2: " + simulationTime);
           }
       }, 2000);
       simulator.schedule(new Task() { // schedule a task that prints "3: " and then the simulation time 1000
           public void run(double simulationTime) {
               System.out.println("3: " + simulationTime);
           }
       }, 1000);
       simulator.start();
   }
}

public interface Task {

   public abstract void run(double simulationTime);

}

Problem 4. In Simulator.java, implement the schedule(Task task, double simulationTime)
method. This method must associate the specied simulationTime with the specied task using
the scheduledTasks member variable of the Simulator class. The type of scheduledTasks is
MultiValuedTreeMap so that scheduledTasks can associate each simulation time
with multiple Tasks while maintianing them in the order of increasing simulation time.

Problem 5. In Simulator.java, implement the start() method. This method
must perform the simulation while (i) extracting Tasks from scheduledTasks in the order of in-
creasing simulation time (in the insertion order in the case of Tasks associated with the same
simulation time), (ii) invoking the run(double simulationTime) method on each extracted Task,
and (iii) terminating this process when the scheduledTasks collection becomes empty. If both
the schedule(Task task, double simulationTime) and start() methods are implemented cor-
rectly, the following code:
Simulator simulator = new Simulator ( ) ;
simulator . schedule ( new Task ( ) f
public void run ( double simulationTime ) f
System . out . println ( "1: " + simulationTime ) ;
g
g , 1 0 0 0 ) ;
simulator . schedule ( new Task ( ) f
public void run ( double simulationTime ) f
System . out . println ( "2: " + simulationTime ) ;
g
g , 2 0 0 0 ) ;
simulator . schedule ( new Task ( ) f
public void run ( double simulationTime ) f
System . out . println ( "3: " + simulationTime ) ;
g
g , 1 0 0 0 ) ;
simulator . start ( ) ;
will display:
1: 1000.0
3: 1000.0
2: 2000.0

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

Here is the completed code for this problem. Only the Simulator class is attached as there is no changes for any other classes. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// Simulator.java

public class Simulator {

      protected MultiValuedTreeMap<Double, Task> scheduledTasks = new MultiValuedTreeMap<Double, Task>();

      public void schedule(Task task, double simulationTime) { // Problem 4

            // simply adding to the scheduledTasks map, with simulationTime being

            // the key and task being the value. since MultiValuedTreeMap is a

            // TreeMap, the default ordering of elements will be based on the

            // increasing order of key value - here the simulation time, so we dont

            // need to worry about the order.

            scheduledTasks.add(simulationTime, task);

      }

      public void start() { // Problem 5

            // loops until scheduledTasks is empty

            while (!scheduledTasks.isEmpty()) {

                  // removing the first key-value pair (with least simulation time) to

                  // get a Pair object

                  Pair<Double, Task> p = scheduledTasks.removeFirst();

                  // here the p.second will be the Task and p.first will be the

                  // simulation time. we simply call run method on task and passing

                  // simulation time

                  p.second().run(p.first());

            }

      }

      public static void main(String[] args) {

            Simulator simulator = new Simulator(); // construct a Simulator

            simulator.schedule(new Task() { // schedule a task that prints "1: " and

                                                             // then the simulation time 1000

                              public void run(double simulationTime) {

                                    System.out.println("1: " + simulationTime);

                              }

                        }, 1000);

            simulator.schedule(new Task() { // schedule a task that prints "2: " and

                                                             // then the simulation time 2000

                              public void run(double simulationTime) {

                                    System.out.println("2: " + simulationTime);

                              }

                        }, 2000);

            simulator.schedule(new Task() { // schedule a task that prints "3: " and

                                                             // then the simulation time 1000

                              public void run(double simulationTime) {

                                    System.out.println("3: " + simulationTime);

                              }

                        }, 1000);

            simulator.start();

      }

}

/*OUTPUT*/

1: 1000.0

3: 1000.0

2: 2000.0

Add a comment
Know the answer?
Add Answer to:
import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; import java.util.ArrayList; public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>> implements...
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
  • //MultiValuedTreeMap.java import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; //import java.util.ArrayList; public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>>...

    //MultiValuedTreeMap.java import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; //import java.util.ArrayList; public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>> implements Iterable<Pair<K, V>> {    private static final long serialVersionUID = -6229569372944782075L;       public void add(K k, V v) { // Problem 1 method        // empty linked list, with key=k         if (!containsKey(k)) {               put(k, new LinkedList<V>());         }         // adding v to the linked list associated with key k         get(k).add(v);    }    public V removeFirst(K k)...

  • Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements...

    Implement the missing methods in java! Thanks! import java.util.Iterator; import java.util.NoSuchElementException; public class HashTableOpenAddressing<K, V> implements DictionaryInterface<K, V> { private int numEntries; private static final int DEFAULT_CAPACITY = 5; private static final int MAX_CAPACITY = 10000; private TableEntry<K, V>[] table; private double loadFactor; private static final double DEFAULT_LOAD_FACTOR = 0.75; public HashTableOpenAddressing() { this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR); } public HashTableOpenAddressing(int initialCapacity, double loadFactorIn) { numEntries = 0; if (loadFactorIn <= 0 || initialCapacity <= 0) { throw new IllegalArgumentException("Initial capacity and load...

  • complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class...

    complete this in java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class WordDetective { /** * Picks the first unguessed word to show. * Updates the guessed array indicating the selected word is shown. * * @param wordSet The set of words. * @param guessed Whether a word has been guessed. * @return The word to show or null if all have been guessed. */    public static String pickWordToShow(ArrayList<String> wordSet, boolean []guessed) { return null;...

  • import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Main { public static void main(String[] args) {...

    import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Main { public static void main(String[] args) { int programCounter = 0; List<String> program = new ArrayList<String>(); Stack<String> stack = new Stack<String>(); // TODO string probably not best program.add("GOTO start<<1>>"); program.add("LABEL Read"); program.add("LINE -1"); program.add("FUNCTION Read -1 -1"); program.add("READ"); program.add("RETURN "); program.add("LABEL Write"); program.add("LINE -1"); program.add("FUNCTION Write -1 -1"); program.add("FORMAL dummyFormal 0"); program.add("LOAD 0 dummyFormal"); program.add("WRITE"); program.add("RETURN "); program.add("LABEL start<<1>>"); program.add("LINE 1"); program.add("FUNCTION main 1 4"); program.add("LIT 0 i"); program.add("LIT 0 j");...

  • departmentstore: package departmentstorepkg; import java.util.ArrayList; public class DepartmentStore {    private static final int DEFAULT_SIZE =...

    departmentstore: package departmentstorepkg; import java.util.ArrayList; public class DepartmentStore {    private static final int DEFAULT_SIZE = 10; private StaffMember [] myEmployees; private int myNumberEmployees; private String myFileName; private StaffMember[] employee; public DepartmentStore (String filename){ myFileName = filename; myEmployees = employee;    } public String toString(){ return this.getClass().toString() + ": " + myFileName; } public void addEmployee(Employee emp){ } /** * prints out all the employees in the array list held in this class */ public void print(){ for(int i =...

  • Please implement MyMaxPriorityQueue below. Thanks import net.datastructures.Entry; public class MyMaxPriorityQueue<K, V> {    @Override    public...

    Please implement MyMaxPriorityQueue below. Thanks import net.datastructures.Entry; public class MyMaxPriorityQueue<K, V> {    @Override    public int size() {        // TODO Auto-generated method stub        return 0;    }    @Override    public Entry<K, V> insert(K key, V value) throws IllegalArgumentException {        // TODO Auto-generated method stub        return null;    }    @Override    public Entry<K, V> max() {        // TODO Auto-generated method stub        return null;    }   ...

  • import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListPractice {       private static final int[]...

    import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListPractice {       private static final int[] arr = new int[100000];    public static void main(String[] args) {        for(int i=0; i<100000; i++)            arr[i] = i;               //TODO comment out this line        LinkedList<Integer> list = new LinkedList<Integer>();               //TODO uncomment this line        //List<Integer> list = new ArrayList<Integer>();               //TODO change the rest of the...

  • import java.util.Scanner; public class StudentClient {       public static void main(String[] args)    {   ...

    import java.util.Scanner; public class StudentClient {       public static void main(String[] args)    {        Student s1 = new Student();         Student s2 = new Student("Smith", "123-45-6789", 3.2);         Student s3 = new Student("Jones", "987-65-4321", 3.7);         System.out.println("The name of student #1 is ");         System.out.println("The social security number of student #1 is " + s1.toString());         System.out.println("Student #2 is " + s2);         System.out.println("the name of student #3 is " + s3.getName());         System.out.println("The social security number...

  • import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private...

    import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private ArrayList<String> words; private HashSet<String> foundWords = new HashSet<String>(); public FindWordInMaze(char[][] grid) { this.grid = grid; this.words = new ArrayList<>();    // add dictionary words words.add("START"); words.add("NOTE"); words.add("SAND"); words.add("STONED");    Collections.sort(words); } public void findWords() { for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[i].length; j++) { findWordsFromLocation(i, j); } }    for(String w: foundWords) { System.out.println(w); } } private boolean isValidIndex(int i, int j, boolean visited[][]) { return...

  • import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private...

    import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class FindWordInMaze { private char grid[][]; private ArrayList<String> words; private HashSet<String> foundWords = new HashSet<String>(); public FindWordInMaze(char[][] grid) { this.grid = grid; this.words = new ArrayList<>();    // add dictionary words words.add("START"); words.add("NOTE"); words.add("SAND"); words.add("STONED");    Collections.sort(words); } public void findWords() { for(int i=0; i<grid.length; i++) { for(int j=0; j<grid[i].length; j++) { findWordsFromLocation(i, j); } }    for(String w: foundWords) { System.out.println(w); } } private boolean isValidIndex(int i, int j, boolean...

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