Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Java TreeMap Simulator

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Java TreeMap Simulator

    For my class we are making a simulator far a game, I'm just entirely confused on how to use TreeMaps, I understand there is a key and a value but how to go about all of this is a blur to me. I'm not looking for a cheat sheet or whatever, just some kind guidance would be appreciated!

    For the first part we have to call (in public void printAllScheduledTasks(PrintStream out))
    protected void print(Task task,long scheduledTime, PrintStream out).
    --This method must print out all the Tasks that are scheduled for execution

    I have some code for this part but have no idea if it is correct, and I'm still trying things as I type.
    ///////////////////

    For the second part Implement Vector<Task> getTasks(long simulationTime) so that
    public void schedule(Task task, long simulationTime) will work correctly. Vector<Task>
    getTasks(long simulationTime) must return the collection of Tasks which is associated (in
    scheduledTasks) with the speci ed simulation time. If no collection of Tasks is associated with
    the speci ed simulation time, a new collection needs to be created and then (before it is returned) inserted into scheduledTasks with the speci ed simulation time.

    --For this part I don't even know where to start, am I using treeMap, or vectors or wtf? All my classmates are stumped too so at least I don't feel alone. AGAIN I don't want the solution but help would be so much appreciated, Thank you.

    import java.io.PrintStream;
    import java.util.Iterator;
    import java.util.Vector;
     
    /**
     * A Simulator performs scheduled Tasks at the specified simulation times.
     * 
     * 
     */
    public class Simulator implements Iterable<Task> {
     
    	/**
    	 * The current time.
    	 */
    	protected long currentSimulationTime = 0;
     
    	/**
    	 * The scheduled tasks.
    	 */
    	protected java.util.TreeMap<Long, Vector<Task>> scheduledTasks = new java.util.TreeMap<Long, Vector<Task>>();
     
    	/**
    	 * The periodic Tasks and the periods of these Tasks (used for the scheduleAtFixedRate methods).
    	 */
    	protected java.util.Map<Task, Long> periodicTasks = new java.util.HashMap<Task, Long>();
     
    	/**
    	 * A flag that represents whether or not the simulation will be synchronized with the wall clock time.
    	 */
    	protected boolean realTimeSync;
     
    	/**
    	 * The wall clock time when the scheduler's start() method was invoked.
    	 */
    	protected long startWallClockTime = -1;
     
    	/**
    	 * Constructs a Simulator.
    	 */
    	public Simulator() {
    		this(true);
    	}
     
    	/**
    	 * Constructs a Simulator.
    	 * @param realTimeSync a flag to indicate whether or not to synchronize the Simulator with the actual wall-clock time.
    	 */
    	public Simulator(boolean realTimeSync) {
    		currentSimulationTime = 0;
    		this.realTimeSync = realTimeSync;
    	}
     
    	/**
    	 * Prints out all the Tasks that this Simulator has scheduled for execution.
    	 * @param out the print stream.
    	 */
    	public void printAllScheduledTasks(PrintStream out) {
    		// TODO updated this method (HW5. Problem 1, 20 points)
     
    	print(this.iterator().next(), getCurrentSimulationTime(), out);
    	}
     
    	/**
    	 * Prints the specified Task.
    	 * @param scheduledTime the time when the Task will be executed.
    	 * @param task the task to print
    	 * @param out the print stream.
    	 */
    	protected void print(Task task, long scheduledTime, PrintStream out) {
    		out.println("simulation time " + scheduledTime + ": " + task + (periodicTasks.containsKey(task)?" - periodic":""));
    	}
     
    	/**
    	 * Returns the current simulation time.
    	 * @return the current simulation time.
    	 */
    	public long getCurrentSimulationTime() {
    		return currentSimulationTime;
    	}
     
    	/**
    	 * Schedules the specified Task.
    	 * @param task the Task to be scheduled.
    	 * @param simulationTime the simulation time at which the Task to be executed.
    	 * @throws InvalidSimulationTimeException if the specified simulation time is earlier than the current simulation time.
    	 */
    	public void schedule(Task task, long simulationTime) throws InvalidSimulationTimeException {
    		if (simulationTime < currentSimulationTime)
    			throw new InvalidSimulationTimeException();
    		// finds the collection associated with the specified simulation time.
    		getTasks(simulationTime).add(task);
    	}
     
    	/**
    	 * Returns the collection of Tasks associated with the specified simulation time (if no such collection, a new collection is created).
    	 * @param simulationTime the simulation time of interest.
    	 * @return the collection of Tasks associated with the specified simulation time.
    	 */
    	protected Vector<Task> getTasks(long simulationTime) {
    		// TODO updated this method (HW5. Problem 2, 20 points)
     
     
    		return null;
    	}
     
    	/**
    	 * Schedules the specified Task for repeated fixed-rate execution, beginning
    	 * at the specified simulation time. Subsequent executions take place at regular
    	 * intervals, separated by the specified period.
    	 * 
    	 * @param task the Task to be scheduled.
    	 * @param simulationTime the first simulation time at which Task is to be executed
    	 * @param period the simulation time between successive executions.
    	 * @throws InvalidSimulationTimeException if the specified simulation time is earlier than the current simulation time.
    	 */
    	public void scheduleAtFixedRate(Task task, long simulationTime, long period) throws InvalidSimulationTimeException  {
    		// TODO updated this method (HW5. Problem 3, 20 points)
    	}
     
    	/**
    	 * Runs this Simulator.
    	 * @param duration the duration of the simulation.
    	 */
    	public void run(long duration) {
    		while (currentSimulationTime < duration) {
    			Task nextTask = nextTask(); // get the next Task.
    			run(nextTask); // run the Task.
    			// if the task is a periodic Task, reschedule the Task
    			try {
    				Long period = periodicTasks.get(nextTask);
    				if (period != null) { 
    					schedule(nextTask, currentSimulationTime + period.longValue());
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    	}
     
    	/**
    	 * Returns the next Task to run (if there is no scheduled Task, null is returned).
    	 * @return the next Task to run; null if there is no scheduled Task.
    	 */
    	protected Task nextTask() {
    		// TODO updated this method (HW5. Problem 4, 20 points)
    		return null; // no Task left;	
    	}
     
    	/**
    	 * Executes the specified Task.
    	 * @param task the Task to execute.
    	 */
    	protected void run(Task task) {
    		if (realTimeSync) { // if needs to be synchronized with the wall-clock time
    			waitUntil(startWallClockTime + currentSimulationTime);
    		}
    		if (task != null) {
    			task.set(this);
    			task.run(); // execute the current task
    		}
    	}
     
    	/**
    	 * Waits until the specified wall-clock time
    	 * @param wallClockTime the wall-clock time when the program will resume its execution.
    	 */
    	protected void waitUntil(long wallClockTime) {
    		// TODO updated this method (HW5. Problem 5, 20 points)
    	}
     
    	@Override
     
     
    }


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Java TreeMap Simulator

    See the following for a tutorial on how to use Map's
    The Map Interface (The Java™ Tutorials > Collections > Interfaces)
    A TreeMap is just an implementation of the Map interface explained above, which provides sorting of the Keys. See
    TreeMap (Java Platform SE 6)

  3. #3
    Member
    Join Date
    Jul 2011
    Posts
    33
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Java TreeMap Simulator

    My confusion is what TreeMap has to do with simulating something. Anyway, I recently learned more about TreeMap. Other examples I had seen typically loaded a key with String and used the add("blahblah") method to enter the values into the TreeMap and the examples worked fine because using a String literal in quotes allocates memory for each add. I initially used a scan in a loop for loading data into TreeMap, but got wierded out when all the keys turned out the same. The solution I found was to load data from the scan into a Vector, which actually holds data as opposed to points to it. Then load the record in Vector into TreeMap. Actually two Vectors, one for <Key> and the other for <Entry>. I suspect that a single Vector with the key as part of the iterator in the Vector would also work ok.

    Really cool about TreeMap is that the tree is a self balancing red-black tree (cf. Knuth), which could get to be significant for a big, long term project. Were this not for a class, for small apps I'd say load it all into a Vector because it is simpler and you can arrange things as you like among the elements.

    //Tm4I
    //
    //
    // TreeMap value V is a shallow copy. To make a TreeMap really have a payload of V values,
    // make a Vector array of the value V. How much you want to bet that the only reason why
    // keyword K worked is because the string constants in t.put are different locations ... ?
    //
    // Ok, now this works. What next?
    //
    // Class Index will be an improvement. You can put all the mess in what place.
    // TreeMap to do the actual work, Vectors containing String for K and int for V
    // K loads JList at top, V references particular record in Marc
    //
    //

    import java.util.*;

    public class Tm4
    {
    public static void main(String[] args)
    {
    Tm4I x0 = new Tm4I(1);
    Tm4I x1 = new Tm4I(2);
    Tm4I x2 = new Tm4I(3);
    Tm4I x3 = new Tm4I(4);
    Tm4I x4 = new Tm4I(5);
    Tm4I x5 = new Tm4I(6);
    Tm4I x6 = new Tm4I(7);
    Tm4I x7 = new Tm4I(8);
    Tm4I x8 = new Tm4I(9);
    Tm4I x9 = new Tm4I(10);
    Tm4I y;

    TreeMap<String,Tm4I> t = new TreeMap<String,Tm4I>();

    t.put("one ",x0);
    t.put("two",x1);
    t.put("three",x2);
    t.put("four",x3);
    t.put("five",x4);
    t.put("six",x5);
    t.put("seven",x6);
    t.put("eight",x7);
    t.put("nine",x8);
    t.put("ten",x9);


    System.out.println(t.subMap("one","ten").firstKey( ));

    System.out.println(t.firstKey() + "\n\n");
    y = t.get("six");
    System.out.println("***" + y.getI());

    y = t.get("two");
    System.out.println("***" + y.getI());


    {
    // search similar to matchPlus;
    String min = "one";
    String max = "ten";
    String cursor = t.floorKey(min);

    do
    {
    if((cursor != null) && (cursor.compareTo(max) <= 0))
    {
    System.out.println(cursor);
    cursor = t.higherKey(cursor);
    }
    }
    while(cursor.compareTo(max) <= 0);
    }





    }
    }

    // Used by Tm4

    public class Tm4I
    {

    public int i;

    Tm4I()
    {
    }

    Tm4I(int n)
    {
    i = n;
    }


    public int getI()
    {
    System.out.println(i);
    return i;
    }

    public void setI(int n)
    {
    i = n;
    System.out.println(i);
    }
    }


    Does not do much but run, but I hope it is a help. Like I say, I found using TreeMap a little strange. Good Luck!

Similar Threads

  1. AI Search Simulator Assistance
    By GeekWarth in forum What's Wrong With My Code?
    Replies: 12
    Last Post: September 17th, 2011, 03:40 PM
  2. How TreeMap does what it does.
    By meathead in forum Java Theory & Questions
    Replies: 2
    Last Post: July 21st, 2011, 04:20 PM
  3. Creating a Simulator
    By william in forum Java Theory & Questions
    Replies: 4
    Last Post: June 16th, 2011, 10:11 AM
  4. [SOLVED] Java Noob: Coin Toss Simulator (no GUI)
    By bgroenks96 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: June 4th, 2011, 10:28 PM
  5. JAVA simulator
    By YAS218 in forum Java Theory & Questions
    Replies: 8
    Last Post: July 20th, 2009, 09:57 AM