简体   繁体   中英

Where is my flaw in determining whether there exists an int N such that x1 + v1 * N = x2 + v2 * N

So I was trying to solve a problem where you determining whether two kangaroos will eventually land on the same point at the same time given that one starts at position x1 and travels distance v1 per hop, and the other x2 and v2 for measuring the same.

Example:

Input 0 3 4 2 means x1=0 , v1=3 , x2=4 , v2=2 . They will eventually land on the same point because their distances from the start and after each hop are like

0 -> 3 -> 6 -> 9  -> 12
4 -> 6 -> 8 -> 10 -> 12

My solution is failing some test cases and I'm wondering where the flaw is in the logic of my O(1) solution:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
    static void Main(String[] args) {
        string[] tokens_x1 = Console.ReadLine().Split(' ');
        int x1 = Convert.ToInt32(tokens_x1[0]);
        int v1 = Convert.ToInt32(tokens_x1[1]);
        int x2 = Convert.ToInt32(tokens_x1[2]);
        int v2 = Convert.ToInt32(tokens_x1[3]);
        // What needs to be determined is whether there exists an N such that
        // x1 + v1 * N = x2 + v2 * N
        // or, equivalenly, 
        // (x1 - x2) = (v2 - v1) * N 
        double ndouble = ((double)x1 - (double)x2) / ((double)v2 - (double)v1); 
        Console.WriteLine(ndouble == (int)ndouble ? "YES" : "NO");
    }
}

There are two problems:

  1. floating point numbers lead to rounding erros
  2. division by zero (as @samgak mentioned)

So your method becomes this:

return (x1 == x2) || 
  (((x1 < x2 && v1 > v2) || (x2 < x1 && v2 > v1)) && (x1 - x2) % (v1 - v2) == 0);

If x1 is the same as x2 then we don't have to look any further. This is the only case where v1 == v2 and the kangaroos meet. The check if the first number is dividable by the second is done with a modulo and integers, so that there can be no rounding errors. Before applying the modulo we ensure that the kangaroos are moving towards each other and not away from each other (1 % -1 == 0 but is no solution as @zerkms pointed out).

Here is a C solution to this

int main(){
    int x1; 
    int v1; 
    int x2; 
    int v2; 
    scanf("%d %d %d %d",&x1,&v1,&x2,&v2);
    int x = x1-x2,v = v2-v1;
    if((v==0 && x==0)||(x!=0 && v!=0 && x%v==0 && (x*v>=0)))
        printf("YES\n");
    else
        printf("NO\n");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM