Search code examples
javaalgorithmnumberslcm

Belt Collision Time Calculation


Mr. Dis and Mr. Aster are mechanical engineers at Fiasco Iron Works. They were assigned to design roadways for automated trolleys to carry the iron ores across the smelting plants. They were supposed to make two circular roadways for the automated trolleys. However, by mistake Mr Dis and Mr Aster made the circular roadways tangential to each other (i.e. the two circular paths touch each other at a point).
Every morning at 0800 hrs the trolleys start at the point of tangency and move clockwise in their respective tracks. It is quite obvious that at some point the trolleys would collide at the point from where they started. In a desperate attempt to save the trolleys and the damage caused to the operations of the plant, the Chief Engineer of the plant has requested you to write a program that will sound a hooter 10 seconds before the collision such that the foreman can stop the trolleys in order to avoid the collision. Write a program to find out the time lapsed (in seconds) before the hooter should go off.

public static int timeLapsed(int perimeter1, int speed1, int perimeter2, int speed2) {
    int greater,smaller;
    int result = 0;
    if(perimeter1 >  perimeter2)    {
        greater = perimeter1;
        smaller = perimeter2;
    }   else    {
        greater = perimeter2;
        smaller = perimeter1;
    }
    for(int i=1;i<=smaller;i++)     {
        if(((greater*i)%smaller)==0)    {
            result = greater*i;
            break;
        }
    }

    return result/speed1-10;
}

Here, I am trying to calculate the distance before collision which is basically am LCM operation and then division by speed. But this is failing for some of the cases.Please help me understand why.


Solution

  • The belt having greater perimeter is considered for calculating the distance it covers before collision. So the speed can not be chosen arbitrarily, it should be of the belt having greater perimeter.

    Changes

    public static int timeLapsed(int perimeter1, int speed1, int perimeter2, int speed2) {
        int greater,smaller;
        int speed, result = 0;
        if(perimeter1 >  perimeter2)    {
            greater = perimeter1;
            smaller = perimeter2;
            speed = speed1;
        }   else    {
            greater = perimeter2;
            smaller = perimeter1;
            speed = speed2;
        }
        for(int i=1;i<=smaller;i++)     {
            if(((greater*i)%smaller)==0)    {
                result = greater*i;
                break;
            }
        }
    
        return result/speed-10;
    }