If you want to make money online : Register now

# [Solved]: Schedule two trains whose tracks overlap so they don't crash

, ,
Problem Detail:

I've encountered scheduling problems in my algorithms class before like the type we use vertex cover to solve.

Recently I was asked this question and did not even know what algorithmic technique to use to answer it!

There are two trains, which run between stations and share a portion of track. For instance train 1 runs between stations A B C D E F G H and train 2 runs between stations I J K B C D E F L M so the trains share the track between B C D. At each end of the track the train turns around and goes the other way on its track. The trains go from station to station in 1 unit time. I need to prevent the trains from crashing head on on the shared track, I have the power to stop either train at any station and restart it again when I please.

How can I solve this problem without using a ton of if else clauses, what CS principles should I be using here?

edit

Some background, the first solution I wrote was just a simple check to see if the other train was on the shared track before sending the other train out. That seemed ad hoc to me and I'm sure it did to the company I interviewed for as well.

I figure there must be an algorithm or at least a school of thought for this type of problem, after all how do they build extensible systems for managing shared runway space at an airport, or managing traffic flow at stop lights.

My intuition is that this is a very introductory problem to a school of thought in computational problem solving I have not yet encountered.

I might be wrong, but could anybody clear the air for me?

If you calculate the cycle, as there are only two trains and distance between every station is one, you could simply run them in order and appoint wait in some station to avoid crash.

If you have to implement some unfortunate events (first one stops for some reason, reschedule it to run on itd own time).

With two trains it will work without problems.

Otherwise use semaphores (it fits even literally ;)

There is no explicitly given synchronisation problem, so nasty trick works.