Friday 24 November 2017

Kangaroo Hacker Rank Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

char* kangaroo(int x1, int v1, int x2, int v2) {
    // Complete this function
  
if(v1>v2)
{
    if((x2-x1)%(v1-v2) == 0)
        return("YES");
    else
        return("NO");
}
else
    return("NO");
}
int main() {
    int x1;
    int v1;
    int x2;
    int v2;
    scanf("%i %i %i %i", &x1, &v1, &x2, &v2);
    int result_size;
    char* result = kangaroo(x1, v1, x2, v2);
    printf("%s\n", result);
    return 0;
}

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. how u came up with-
    (x2-x1)%(v1-v2) == 0 ??

    ReplyDelete
  3. The initial difference between distance has to be covered by the difference in the speed.
    For ex:kangaroo1 is jumping with speed 3 kms/hr and started at point 3
    kangaroo2 is jumping with speed 2 kms/hr and started at point 6
    After first hour
    Kangaroo1 will be at point 6
    kangaroo2 will be at point 8

    After second hour
    Kangaroo1 will be at point 9
    kangaroo2 will be at point 10

    After third hour
    Kangaroo1 will be at point 12
    kangaroo2 will be at point 12

    every hour the first kangaroo will catch up 1 point that it is lagging behind second kangaroo.

    I hope this example clears your doubt.

    ReplyDelete
  4. You have assumed that always x1 will be smaller and v1 will be greater. If you reverse the case your algo will fail.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. This comment has been removed by the author.

      Delete
    3. your comment has no logic in it..as you are comparing position and velocity in your comment

      Delete