0

I'm solving this problem

There are two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location x1 and moves at a rate of v1 meters per jump. The second kangaroo starts at location x2 and moves at a rate of v2 meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?

and this is my code

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution 
{
    static String kangaroo(int x1, int v1, int x2, int v2) 
    {
        // Complete this function
        String result = new String();
        int count = 0;
        if(x1 < x2 & v1 < v2)
        {
            result = "NO";
    }
    if(x2 < x1 & v2 < v1)
    {
        result = "NO";
    }
    int distance1 = 0, distance2 = 0;
    if (x1 > x2 & v2 > v1)
    {
        for (int i = 0; x2 > x1; i++)
        {
            x1+=v1;
            x2+=v2;
            if (x1 == x2)
            {
                result = "YES";
                count++;
                break;
            }
        }
    }
    //else
        //{
            if (x2 > x1 & v1 > v2)        
        {
            for (int i = 0; x1 > x2; i++)
        {
            x1+=v1;
            x2+=v2;
            if ( x1 == x2 )
            {
                result = "YES";
                count++;
                break;
            }
        }
        }
        //else
            //result = "NO";
    //}
    if (count == 0)
    {
        result = "NO";
    }
    return result;
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int x1 = in.nextInt();
    int v1 = in.nextInt();
    int x2 = in.nextInt();
    int v2 = in.nextInt();
    String result = kangaroo(x1, v1, x2, v2);
    System.out.println(result);
}

}

with input: 0 3 4 2 I get output: NO Correct output: YES

Thanks in advance

P.S. - I'm looking for problem with my code

Karan
  • 11
  • 1
  • 5

1 Answers1

0

Your method could be reduced to this:

static String kangaroo(int x1, int v1, int x2, int v2) {
     return (x2 - x1)%(v1-v2) == 0 ? "YES" : "NO";
}
P.An
  • 355
  • 1
  • 9
  • A really good answer but the problem is that if x2 = 12, x1 = 6 and v2 = 6 v1 = 3 this case will also pass your expression and method will return yes but you know this isn't possible as x2 > x1 and v2 > v1 therefore x1 will never catch x2. – Karan Sep 26 '17 at 16:23
  • This worked THANKS :) return ((x1-x2)/(v1-v2)>=0) ? "NO" : (( x1-x2 ) % ( v2-v1 )==0 ? "YES" : "NO"); – Karan Sep 26 '17 at 16:37
  • NAH this one will also fail if x1 and x2 are different but v1 and v2 are same because v1 - v2 is denominator – Karan Sep 26 '17 at 16:45
  • Final Version return ((x1-x2) != 0 & v1-v2 == 0)? "NO" : (((x1-x2)/(v1-v2)>=0) ? "NO" : (( x1-x2 ) % ( v2-v1 )==0 ? "YES" : "NO")); This worked – Karan Sep 26 '17 at 16:46