TCS MockVita 2 Solution : Problem C

Problem : Minimum Distance

Two riders A and B are travelling on a highway towards each other on two roads that intersect at right angle at speeds VA meters/second and VB meters/second. A is at a distance of 'x' meters and B is at a distance of 'y' meters from the intersection. Calculate the minimum distance between these two riders that is possible.


Input Format:

First line contains the distance of Rider A from intersection denoted by x
Second line contains the distance of Rider B from intersection denoted by y
Third line contains the Velocity of Rider A denoted by VA
Fourth line contains the Velocity of Rider B denoted by VB

Output Format:

Print the minimum distance between these two riders, if minimum distance is nonzero. If minimum distance is zero, print it as 0.0

Constraints:

x > 0
y > 0
VA > 0
VB > 0
Calculation and printing of output should be done upto 11 precision

Input 1

100
100
10
10

Output 1

0.0

Input 2

500
300
20
14

Output 2

41.18252056395

Input 3

100
100
30
40

Output 3

22.36067977500

Input 4

05
0
20
30

Output 4

Invalid Input

C Implementation:

#include <stdio.h>
#include <math.h>
int main(void) {
 int x,y,va,vb;
 double min;
 double d;
 scanf("%d %d %d %d",&x,&y,&va,&vb);
 if(x<0 || y<0 || va<0 || vb<0)
  printf("Invalid Input");
 else
 {
   min = sqrt(x*x + y*y);
   while(x>=0 || y>=0)
   {
     x-=va;
     y-=vb;
     d=sqrt(x*x + y*y);
     if(d<min)
       min = d;
   }
  if(min==0.0)
   printf("0.0");
  else
   printf("%.11lf",min);
 }
 return 0;
}

Python Implementation:

from math import sqrt
x = int(raw_input())
y = int(raw_input())
va = int(raw_input())
vb = int(raw_input())
if x<0 or y<0 or va<0 or vb<0:
 print "Invalid Input"
else:
 min = sqrt(x**2 + y**2)
 while x>=0 or y>=0:
  x-=va
  y-=vb
  d=sqrt(x**2 + y**2)
  if d<min:
   min = d
 if min==0.0:
  print "0.0"
 else:
  print "%.11f"%min

Other Problems from TCS Mockvita - 1 and Mockvita - 2:

Solution : MockVita-I Problem D

Solution : MockVita-II Problem C

Solution : MockVita-II Problem B

Solution : MockVita-II Problem D

Solution : MockVita-II Problem A

Solution : MockVita-I Problem B

Solution : MockVita-I Problem C

Solution : MockVita-I Problem F

Solution : MockVita-I Problem A