Amazon Interview Question
Software Engineer / DevelopersA cross road would have 4 roads at the intersection viz North (00), South (11), East (10) and West (01). These roads can be represented in binary format as represented in brackets.
The 4 major conditions to be active simultaneously are
1. NS and SN
2. EW and WE
3. NW and SE
4. ES and WN
if we consider the binary representation of the above conditions then
we get
1. 0011 and 1100
2. 1001 and 0110
3. 0001 and 1110
4. 1011 and 0100
Thus at any point of time the negation of the binary representation would be active at that time simultaneously
Please refer to :
ccs.neu.edu/home/vkp/Papers/Traffic-sigcse98.pdf
The solution given here can be extended to multiple lanes. Here are the basic classes :
Road
Place
Vehicle
TrafficSignal
If there is necessity for implementing pedestrian crossing, then we need two more classes: PedestrianSignal and Pedestrian
A road will have a set of places. Each place will have the link to next place in the valid direction. The place will maintain a queue of vehicles. Vehicles can be identified by their licence plate and make. Traffic signal will have three states, Red, Yellow and Green. The state transition will be based on a timer. There needs to be 4 signal objects to represent a 4 way intersection. Whenever the signal goes green, the cars can be dequeued from the place in the direction of the signal one at a time. When the state changes to red, the dequeue operation has to be stopped. A vehicle has to queue itself in the Place in direction where it wants to travel.
Here is my take:
- Anonymous March 13, 2010A simple crossroad can have traffic moving in 8 possible combinations:
1. Curve paths: East->North, North->West, West->South and South->East (first is the inital direction of motion and second is the direction after making a curve).
2. Straight path: All four directions.
Out of this two can happen at the same time:
ex: North->West and South->East and also in heading east and heading west can flow at the same time.
Thus out of eight combinations we have to decide only among 4 combinations, this is similar to a 2 bit problem where the state can revolve around four possible states:
00
01
10
11
Yes, more complex things can be incorporated as changing the interval to avoid congession etc. But this can give a head start to solve bigger problems :)..