Black Horse programmer _ 7 k interview questions-traffic light system

Source: Internet
Author: User

Traffic Light Signal Simulation System


I. Overview

Simulate the traffic light management system logic at the crossroads. The specific requirements are as follows: (The requirements are directly from the instructor's documents)

① A vehicle traveling along each route is randomly generated asynchronously.

For example:

Vehicles from south to north-direct vehicles

Vehicles going from West to south-turn right

Vehicles from the east to the south-turn vehicles

...

② Ignore the yellow light, only the red light and the green light are considered.

③ A left-turn vehicle should be considered to control the traffic signals. A right-turn vehicle is not controlled by the traffic signals.

④ The specific traffic light control logic is the same as the ordinary traffic light control logic in real life, regardless of the control logic in special circumstances.

Note: vehicles in the North-South direction and vehicles in the east-west direction are allowed to interchangeably. vehicles in the same direction should be allowed to go directly and then turn left.

⑤ The intersection time of each vehicle is 1 second (Note: simulation can be performed by thread Sleep ).

⑥ You can set the random generation interval and traffic light switching interval.

7. You do not need to implement the GUI. You only need to implement the system logic. You can use the Log method to display the program running results.



Ii. Demand Analysis:

Looking at the requirements of the entire system, we can draw the following conclusions: at a crossroads, we can simulate the relationship between vehicles, lights, and roads, the road is designed as a container for storing vehicles. The vehicle comes and is stored in the container. When the vehicle is going to light up through the traffic lights on a certain road, the vehicle starts, which is equivalent to extracting the vehicle from the container, at the crossroads, we will introduce it carefully below:

Turn around for always green light, that is to say when the four sides can turn, that is, S--E, E--N, N--W, W--N, so we do not consider the following

We first from the S---N to see: Suppose There Is A S--N of the car can start, then this time there is a N--S of the car can start, that is to say, as long as the S--N can be opened to the train, then the N--S can be opened to the train

S--N green light stopped, S--N will no longer open to train, the same, N--S can not open to train.

The next green light is S--W: S--W can be opened to the train, N--E can also be opened to the train

S--W green light stop: The Next green light is E--W: E--W can be opened to, W--E can also be opened

E--W green light stop: The Next green light is E--S; E--S can be opened to, W--N can also be opened

E--S green light stop: The Next green light back to the S--N. This loop.

From the above analysis can be concluded that we only need four directions of the traffic light status can control the entire traffic system, because we found that they are in pairs, for example, as long as we know that S--N is a green light, so N--S should be green light, S--W is green light, N--E should also be green light, there are four corners on the turn is also fixed green light, therefore, we only need to control the entire system by four cores in four directions.


3. Object-Oriented Analysis and Design

① Vehicles on each road can be randomly added during a certain period of time. When the green light arrives, the number of vehicles on the road should be reduced. Of course, there is a sequence of vehicle reductions when the green light is on.

At a certain time point, there may be any vehicle on any road. Here we use 12 lamps, and we need to assume that there are 12 roads (in fact there are only 8 ), in addition, a vehicle may be waiting on the road at a certain time point (or directly passing through, but it must be a green light and there is no car in front of it ), that is to say, we need to create a vehicle storage container for each lamp. When a light is on, the car in the corresponding container can pass through,

② Check whether the traffic lights on the line are green at the specified time on each road. If the traffic lights on a certain line are red, remember to change the traffic lights in the next direction to green.

Design a Lamp class to represent a traffic light. Each traffic light maintains a state: Bright (green) or not bright (red) has a total of 12 routes. Therefore, A total of 12 traffic signals are generated in the system. The traffic lights at the right bend are evergreen, that is, they are always red. No matter where the program gets the lights in a certain direction, each time it gets the same instance object, it is very convenient for the Lamp class to use enumeration, there are always only instance objects that represent the lights in 12 directions. Design an enumeration class, which regularly turns the current green light red.

4. Writing of classes used

① Writing the Road class

Because there are 12 lines, a thread pool is enabled here, And the threads in the thread pool are allocated to add vehicles for each line.

At the same time, we also need to monitor the traffic lights (so that the vehicles on that line can be started), so we need to enable a thread to monitor the traffic lights and get the next green light during monitoring.

Package cn. itcast. traffic; import java. util. arrayList; import java. util. list; import java. util. random; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; public class Road {// Road is like a container with a private List on the Road
 
  
ArrRoad = new ArrayList
  
   
(); // Interface programming to improve program scalability String name = null; // specify the public Road (String name) generated on that Road {this. name = name; // the vehicle can be generated. // because the vehicle may be generated in every direction at a certain time point, the idea of Multithreading is used here: ExecutorService thread = Executors. newCachedThreadPool (); // when the thread pool thread.exe cute (new Runnable () {// when the task arrives, select a thread from the thread pool to execute the task @ Overridepublic void run () {// TODO Auto-generated method stubfor (int I = 0; I <1000; I ++) {// to be closer to reality, set a random number here, that is to say, there are There may be a car on the road. try {Thread. sleep (new Random (). nextInt (10) + 1) * 1000); // There is a car on ArrRoad in 1 s -- 10 s. add (Road. this. name + (I + 1); // specifies the number of vehicles on the road. // here is a knowledge point, when an anonymous internal class accesses the member variables of the peripheral class, you can set the member variables of the peripheral class to final, it can also be written like this // class name. this. member variable} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace () ;}}}); // I think so. A car comes up on a certain road. When a street lamp encounters, the car on this road will drive away, that is to say, the number of vehicles on this road will be reduced. // a separate thread should be enabled here to execute a monitoring (monitoring the green light) // dispatch (scheduling) // create a thread pool, it can be arranged in the given delay Run the command later or regularly. It is equivalent to specifying when to observe the traffic lights. ScheduledExecutorService dispatch = Executors. newScheduledThreadPool (1); // This indicates that a scheduled operation is enabled for the first time after the initial delay of 1 s is created and executed, after 1 s, execute the new Runnable implementation Class Object method dispatch. scheduleAtFixedRate (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stub // first judge whether the light on name is boolean light = Lamp. valueOf (Road. this. name ). isstate (); // here you want to know that the car on the road should go. First, you need to get the light if (ArrRoad. size ()> 0) {if (light) {System. out. println (Road. this. name + "car on the road" + ArrRoad. remove (0) + "Quick pass") ;}}}, 1, 1, TimeUnit. SECONDS );}}
  
 

② Compile the Lamp class

There are 12 lights in the system. In other places of the program, the corresponding lamp instance objects can be obtained based on the lamp name. Based on these factors, it is easier to define the Lamp class in the enumeration form in Java 5. The lights corresponding to the lights represented by the current object are indicated by correlight, whether there is a next light, and whether the current light is indicated by flag.
Three methods are added: Turn on the green light, turn off the green light, and obtain whether the current light is in the green light or red light status.
Here, the three parameters of the Lamp object are set to indicate whether there is a corresponding Lamp. If it is null, it indicates no and whether there is a next Lamp, if it is null, it indicates no. Whether the current light is green or not. If it is not false, it indicates a red light.
The implementation details are clearly described in the source code:
Package cn. itcast. traffic; // use enumeration to describe the lights at each intersection. // here we start from south to north, S, N, E, W represents south, north, east, and west, S2N even if South to North public enum Lamp {S2N ("N2S", "S2W", false), S2W ("N2E ", "E2W", false), E2W ("W2E", "E2S", false), E2S ("W2N", "S2N", false), N2S (null, null, false), N2E (null, null, false), W2E (null, null, false), W2N (null, null, false), S2E (null, null, true ), e2N (null, null, true), N2W (null, null, true), W2S (null, null, true); // It is necessary to explain S2N ("N2S ", "S2W", false): // parameter 1 is specified Forward the light to the corresponding light. Parameter 2: Specify the next light of the Light, // parameter 3: specify whether the light is on the green light // corresponding (corresponding) String correlight = null; string next = null; boolean flag; Lamp nextlight; Lamp (String correlight, String next, boolean flag) {this. correlight = correlight; this. next = next; this. flag = flag;} public boolean isstate () {return flag;} // specify the green light public void oppen () {flag = true; if (correlight! = Null) {// determines whether the current Lamp to be turned on has a corresponding Lamp. If yes, it is turned on. If no, it does not need to be turned on. It also prevents endless loop Lamp. valueOf (correlight ). oppen (); // here it means to get the light corresponding to the current object and turn on the green light // Lamp. valueOf (String str) returns an enumeration constant of the specified enumeration type with the specified name. The enumerated constant with the same name as correlight} // specifies to disable the green light public Lamp close () {flag = false; if (correlight! = Null) {Lamp. valueOf (correlight). close () ;}// when the light is off, you need to turn on the next light. if yes, if (next! = Null) {nextlight = Lamp. valueOf (next); nextlight. oppen ();} return nextlight ;}}


③ LampManage class Compilation

This class is the total control of a traffic light. For convenience, we create a thread pool with only one thread. This thread pool is used to control the traffic light switching time. Here, the initial light is S2N, in the run method that overwrites the Runnable interface, you need to obtain the next green light object returned by the close method in the Lamp class. In this way, the whole traffic light can be continuously controlled cyclically,

The next line is switched to the next line every 10 seconds.

Package cn. itcast. traffic; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; public class LampManage {// This class is used to manage the operation of the entire traffic light // that is, to create a timer, so that the traffic lights can switch between Lamp and public LampManage () {// specify lamp = Lamp starting with the lamp on that road. s2N; ScheduledExecutorService timer = Executors. newScheduledThreadPool (1); // you can specify a timer. Is to enable a thread timer. scheduleAtFixedRate (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubSystem. out. println (lamp + "light on ......... "); System. out. println ("the corresponding six directions can be opened: S2E, E2N, N2W, W2S," + lamp. correlight + "," + lamp); lamp = lamp. close (); // After enabling 10 s, execute the code, that is, close the current traffic light to open the next traffic light}, 10, 10, TimeUnit. SECONDS );}}

④ Write the MainManage class

The compilation of this class is very simple, that is, the construction of 12 lines, calling the total control class of traffic lights, so that you can randomly add cars on each line and mobilize the traffic lights to control the traffic between vehicles

Package cn. itcast. traffic; public class MainManage {// generate 12 Traffic lights public static void main (String [] args) {String lamp [] = {"S2N", "S2W ", "E2W", "E2S", "N2S", "N2E", "W2E", "W2N", "S2E", "E2N", "N2W ", "W2S"}; for (int I = 0; I
 
  

Now the traffic light simulation is over. It seems simple, but it uses a lot of basic knowledge, especially the object-oriented foundation. To learn better, the foundation is essential.












Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.