Wednesday, July 26th

Will you reach the office in time?

Given an array of integers representing distances of train rides, and a decimal hour, determine the minimum positive integer speed required of the trains in order to arrive to the office by hour.  Trains leave on the hour, so a travel time with a decimal is rounded up.  The last train does not need to be rounded.  See the problem for the detailed description.



Using the inputs dists and hour, we can easily calculate whether or not a train will make it to the office in time for a given speed.

Will a given speed allow us to reach the office in time?

    bool testspeed(vector<int>& ds, double hour, int speed) {

int n=ds.size();
double total=0;
for(int i=0; i<n-1; i++) {
total+=ceil(ds[i]/double(speed) );
}
total+=ds[n-1]/double(speed);
return total<=hour ? 1 : 0;
}

Now we need to determine how to choose a train speed to test.  The problem defines the max speed as 10e7.  Naively, we can perform a linear search beginning at 1.  But we can do better with binary search.

Search through given speeds, and test whether one speed s will reach the office, but one speed lower s-1 will not reach it in time.  Adjust indices accordingly.

    int minSpeedOnTime(vector<int>& dist, double hour) {
        int n=dist.size();
        if( hour <= n-1 ) return -1;

        int l=0;
        int r=10e7;
        int s;
        bool ts, ts1;
        while(l<r) {
            s= l + (r-l)/2;
            ts = testspeed(dist, hour, s);
            ts1 = testspeed(dist, hour, s-1);
            if( ts && !ts1 ) {
                return s;
            } else if (ts){
                r=s;
            } else {
                l=s;
            }
        }
        return -2;
    }

This implementation of binary search tests for the condition when the minimum speed is found, namely, when a given speed s works, but speed s-1.  This is easy to implement, easy to read, and is intuitive.  

However, there are 2 calls to testspeed() when only 1 may be necessary.  So this solution isn't the fastest.  This is the second day in a row of a problem solved with binary search.  I look forward to becoming more comfortable with the nitty gritty indices of binary search with more practice.

Image of the Acela train courtesy of Peter Van den Bossche, distributed under the Creative Commons Attribution-Share Alike 2.0 Generic license.  No changes made.

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th