Question

Please help with my car traffic simulator!

2.) Create a simulation of an intersection using queues. Assume that there is a single lane going irn each direction, that thSome hints . Ultimately, with four variables, that means you will have four loops nested within each other in order to try al

E Cars: the number of cars in the east bound lane waiting to go at the conclusion of the experiment W Cars: the number of car

Code that I already have below, I do not know how to start it off!

public class IntersectionSimulation
{
        private final static int   EAST_WEST_GREEN_TIME    = 30 ;
        private final static int[] NORTH_SOUTH_GREEN_TIMES = { 20, 24, 30, 42 } ;
        private final static int[] CAR_INTERSECTION_RATES  = { 3,  5, 10 } ;
        private final static int[] CAR_QUEUEING_RATES      = { 5, 10, 30 } ;
        private final static int[] EXPERIMENT_DURATIONS    = { 3*60, 5*60, 10*60 } ;
                        
        public static void main( String[] args )
        {
                System.out.println( "E/W Green  N/S Green  Int. Rate  Q. Rate  Duration  N Cars  S Cars  E Cars  W Cars" ) ;
                System.out.println( "----------------------------------------------------------------------------------" ) ;

                for( int i = 0 ; i < 4 ; ++i )
                {
                        for( int j = 0 ; j < 3 ; ++j )
                        {
                                for( int k = 0 ; k < 3 ; ++k )
                                {
                                        for( int l = 0 ; l < 3 ; ++l )
                                        {
                                                int northSouthGreenTime = NORTH_SOUTH_GREEN_TIMES[ i ] ;
                                                int carIntersectionRate = CAR_INTERSECTION_RATES [ j ] ;
                                                int carQueueingRate     = CAR_QUEUEING_RATES     [ k ] ;
                                                int experimentDuration  = EXPERIMENT_DURATIONS   [ l ] ;
                                                
                                                //Logic goes here...
                                        }
                                }
                        }
                }
        }
        
        private static class Car
        {
                //This class can be completely empty.
                // We just need *something* in our queues.
                // It's the count of items in the queues we are concerned with,
                //  not the properties of the items in the queues.
        }
}

public class CircularArrayQueue<T> implements QueueADT<T>
{
   private final static int DEFAULT_CAPACITY = 100; //Static b/c it's only 1 version of it
   private int front, rear, count;
   private T[] queue;
  
   @SuppressWarnings("unchecked")
   public CircularArrayQueue(int initialCapacity)
   {
       front = rear = count = 0;
       queue = (T[]) new Object [ initialCapacity];
   }
     
   public CircularArrayQueue()
   {
       this(DEFAULT_CAPACITY);
   }
  
   public void enqueue(T element)
   {
       if (size() == queue.length)
           expandCapacity();
      
       queue [rear] = element;
       rear = (rear + 1) % queue.length;
       ++count;
   }
  
  

   public T dequeue() throws EmptyCollectionException
   {
       if(isEmpty())
      
           throw new EmptyCollectionException();
      
       T result = queue[front];
       queue [front] = null;
       front = (front + 1) % queue.length;
       --count;
      
       return result;
   }
  
   public T first() throws EmptyCollectionException
   {
       if(isEmpty())
           throw new EmptyCollectionException();
      
       return queue[front];
   }
  
   public int size()
   {
       return count;
   }

   public boolean isEmpty()
   {
       return count <=0;
   }
  
   private void expandCapacity()
   {
       @SuppressWarnings("unchecked")
       T[] larger = (T[]) new Object [queue.length * 2];
       for(int i = 0; i < count; i++)
       {
           larger[i] = queue [front];
           front = (front + 1) % queue.length;
       }
       front = 0;
       rear = count;
      
       queue = larger;
   }
  
   public String toString()
   {
       String output= "CircularArrayQueue -> [ ";
       int pointer = front;
       for(int i =0; i < count; i++)
       {
           output+= queue [pointer] + " ";
           pointer = (pointer + 1) % queue.length;
       }
       output+= "]";
       return output;
   }

  
}

public class EmptyCollectionException extends Exception
{
  
   private static final long serialVersionUID = 358083002087971606L;

   public EmptyCollectionException()
   {
       super();
   }
  
   public EmptyCollectionException(String msg)
   {
       super(msg);
   }
}
public class LinearNode<T>
{
   private LinearNode<T> next;
   private T           element;
  
   public LinearNode()
   {
       next = null;
       element = null;
   }
  
   public LinearNode(T elem)
   {
       next = null;
       element = elem;
   }
  
   public LinearNode<T> getNext()
   {
       return next;
   }
  
  
   public void setNext (LinearNode<T> node)
   {
       next = node;
   }
   public T getElement()
   {
       return element;
   }
  
   public void setElement(T elem)
   {
       element = elem;
   }
}

public class LinkedQueue<T> implements QueueADT<T>
{

   private int count;
   private LinearNode<T> head;
   private LinearNode<T> tail;
          
   public LinkedQueue()
   {
       count = 0;
       head = null;
       tail = null;
   }
   @Override
   public void enqueue(T element)
   {
       LinearNode<T> node = new LinearNode<T> (element);
       if(isEmpty())
           head = node;
       else
           tail.setNext(node);
       tail = node;
       ++count;
      
   }

   @Override
   public T dequeue() throws EmptyCollectionException
   {
       if (isEmpty())
       {
           throw new EmptyCollectionException();
       }
          
           T result = head.getElement();
           head = head.getNext();
           --count;
           if(isEmpty())
               tail = null;
           return result;
       }
      
  
  

   @Override
   public T first() throws EmptyCollectionException
   {
       if(isEmpty())
           throw new EmptyCollectionException();
       return head.getElement();
   }

   @Override
   public int size()
   {
       return count;
   }

   @Override
   public boolean isEmpty()
   {
       return count<=0;
   }
  
   public String toString()
   {
       String output = "LinkedQueue -> [ ";
       LinearNode<T> current = head;
       while(current != null)
       {
           output+= current.getElement().toString() + " ";
           current = current.getNext();
       }
       output+= "]";
       return output;
   }

}

public interface QueueADT<T>
{
       public void enqueue(T element);
      
       public T dequeue() throws EmptyCollectionException;
      
       public T first() throws EmptyCollectionException;
      
       public int size();
      
       public boolean isEmpty();
}

2.) Create a simulation of an intersection using queues. Assume that there is a single lane going irn each direction, that the lights are only red or green and change immediately (which would be super dangerous in real life), and that all vehicles perfectly follow the rules. These assumptions will make the program much simpler. Use a queue to represent the traffic coming from each of the four directions..names like northBoundVehicles, southBoundVehicles, etc make sense to me. The four variables in the experiment will be: The number of seconds the east/west lights will be a constant of 30 seconds for all experiments before switching to red. The number of seconds the north/south lights are green before switching to red will vary. (This is one variable that will have four possible values: 20, 24, 30, and 42.) The rate at which cars travel through the intersection: one car every 3 seconds, one car ever 5 seconds, and one car every 10 seconds. (This is one variable that will have three possible values.) The rate at which cars arrive in each of the 4 lanes: once every 5 seconds, once every 10 seconds, and once every 30 seconds. (This is one variables that will have three possible values.) Additionally, I want you to run this simulation for three different time periods: 3 minutes, 5 minutes, and 10 minutes. a. b. C. d.
Some hints . Ultimately, with four variables, that means you will have four loops nested within each other in order to try all combinations Within each loop, you will "run a simulation", which means a loop with a counter that represents the number of seconds the simulation runs for (so that's a fifth nested loop) That makes this a software engineering challenge regarding how to make the code readable and maintainable. A small number of points (5) will be reserved for the readability/maintainability that I perceive. If all of these loops are just embedded in each other in your main method, I will not perceive that as readable/maintainable, so use methods judiciously . We will be running 108 total experiments (each of the four variables' possible values multiplied together: 4x3x3x3). An additional challenge for this assignment is how to report out the data we collect from the experiment in a digestible manner. Here's a sample of the output from my implementation for 3 of the 108 experiments E/W Green N/S Green Int. Rate Q. Rate Duration N Cars scars E Cars พ Cars 30 30 30 20 20 180 300 600 18 18 10 10 48 48 Legend E/W Green: the number of seconds the east/west light is green N/S Green: the number of seconds the north/south light is green Int. Rate: the rate (in seconds) at which cars travel through the intersection Q. Rate: the rate (in seconds) at which cars arrive in line from each direction Duration: how long (in virtual seconds) the experiment ran for N Cars: the number of cars in the north bound lane waiting to go at the conclusion of the experiment S Cars: the number of cars in the south bound lane waiting to go at the conclusion of the experiment
E Cars: the number of cars in the east bound lane waiting to go at the conclusion of the experiment W Cars: the number of cars in the west bound lane waiting to go at the conclusion of the experiment You will want to use String.fomat() to specify the width of the "fields" Store al variables and work with everything in seconds to avoid unit conversion and confusion This program is more about implementing a logical problem, with queues as a tool involved than anything else. I have provided IntersectionSimulationStarter.java ...this will help you get started, but note it has a bunch of embedded loops. You can do better than this. I suggest getting your program running with those loops, then do what's called "refactoring", which is changing the structure of a program to be better, without changing the logic the
0 0
Add a comment Improve this question Transcribed image text
Answer #1

/Here's the code with comments for both the parts of the question 1:


public class Palindrome{
public static void main (String[] args) throws Exception{
checkPalindrome();
}

public static void checkPalindrome() throws Exception{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
taking the input into the variable str
String str = sc.nextLine();
checking using the queue
boolean queueCheck = checkForPalindromeUsingQueue(str);
checking using the stack
boolean stackCheck = checkForPalindromeUsingStack(str);
String isNotStringQueue = queueCheck ? "IS" : "IS NOT";
String isNotStringStack = stackCheck ? "IS" : "IS NOT";
printing the desired output
System.out.println("According to the queue method that statement " + isNotStringQueue + " a palindrome");
System.out.println("According to the queue method that statement " + isNotStringStack + " a palindrome");
System.out.println("Try another (y/n)?");
String input = sc.nextLine();
if (input.equals("y"))
checkPalindrome();
}

public static boolean checkForPalindromeUsingQueue(String str) throws Exception{
LinkedQueue queue = new LinkedQueue();
storing the string character by character into the queue in reverse order
because queue follows FIRST IN FIRST OUT logic
for(int i = str.length()-1; i >= 0; i--)
queue.enqueue(str.charAt(i));
creating the reverse string using the queue created above
on dequeuing the queue, it will output a new string in the reverse order of the original string
String reverse = "";
while(!queue.isEmpty()){
reverse += queue.dequeue();
}
if the reverse string is equal to the original string, then str is a palindrom otherwise no.
same logic is followed in the implementation using the stack except that the stack data structure is
used to store the string character by character.
return reverse.equals(str);
}

public static boolean checkForPalindromeUsingStack(String str){
Stack stack = new Stack();
for(int i = 0; i < str.length(); i++)
stack.push(str.charAt(i));

String reverse = "";
while(!stack.isEmpty())
reverse+=stack.pop();
return reverse.equals(str);
}
}

Add a comment
Know the answer?
Add Answer to:
Please help with my car traffic simulator! Code that I already have below, I do not know how to...
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
  • ------------------------------------------------------------------------------------------------------------ CODE ALREADY HAVE BELOW--------------------------------------------------------------------------------------- public class LinkedQueue<T>

    ------------------------------------------------------------------------------------------------------------ CODE ALREADY HAVE BELOW--------------------------------------------------------------------------------------- public class LinkedQueue<T> implements QueueADT<T> {    private int count;    private LinearNode<T> head;    private LinearNode<T> tail;               public LinkedQueue()    {        count = 0;        head = null;        tail = null;    }    @Override    public void enqueue(T element)    {        LinearNode<T> node = new LinearNode<T> (element);        if(isEmpty())            head = node;        else           ...

  • I just need a java mehod that follows the Javadocs Implented using an arraylist. public class...

    I just need a java mehod that follows the Javadocs Implented using an arraylist. public class WorkAheadQueue<T> implements WorkAheadQueueADT<T> {     private LinearNode<T> front;     private LinearNode<T> back;     private int numNodes;     private ArrayList<LinearNode<T>> frontFive; Removes and returns the element that is at place x in the queue. Precondition: x must be less than 5, x must be less than size * Note: indexing from 0: 0-front element, I =-second element, etc. eparam x the passed in index of...

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

  • Hello! I have a problem in my code please I need help, I don't know How I can wright precondition, so I need help about assertion of pre_condition of peek. Java OOP Task is! Improve the circular a...

    Hello! I have a problem in my code please I need help, I don't know How I can wright precondition, so I need help about assertion of pre_condition of peek. Java OOP Task is! Improve the circular array implementation of the bounded queue by growing the elements array when the queue is full. Add assertions to check all preconditions of the methods of the bounded queue implementation. My code is! public class MessageQueue{ public MessageQueue(int capacity){ elements = new Message[capacity];...

  • how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 }...

    how do I change my code to generic form *********************************************************************** public class UnboundedStackQueue { //question#3 } class Stack { Node head; int size; Stack() //default constructor { this.head=null; this.size=0; } //Input = data //Output = void (just adds value to list) // method pushes elements on stack // time: O(1) // space: O(1) public void push(int data) { Node node=new Node(data); node.next=head; head=node; size++; } //Input = none //Output = top of stack // method pops value from top of...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

  • I need help fixing my code.   My output should be the following. Hello, world! : false...

    I need help fixing my code.   My output should be the following. Hello, world! : false A dog, a panic in a pagoda : true A dog, a plan, a canal, pagoda : true Aman, a plan, a canal--Panama! : true civic : true If I had a hi-fi : true Do geese see God? : true Madam, I’m Adam. : true Madam, in Eden, I’m Adam. : true Neil, a trap! Sid is part alien! : true Never odd...

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