Skip to content

Instantly share code, notes, and snippets.

@MariaSzubski
Last active September 1, 2016 04:32
Show Gist options
  • Select an option

  • Save MariaSzubski/1c5bbe2903c8cda9a82cb3a7192fe654 to your computer and use it in GitHub Desktop.

Select an option

Save MariaSzubski/1c5bbe2903c8cda9a82cb3a7192fe654 to your computer and use it in GitHub Desktop.
Compare two equations to see if they are ever equal. #congruence #Hackerrank
/*
Solution for HackerRank > Algorithms > Implementation > Kangaroo
https://www.hackerrank.com/challenges/kangaroo
In this example, 0 <= x1 <= x2
*/
function kangaroos() {
var x1 = 43;
var v1 = 5;
var x2 = 49;
var v2 = 3;
var done = false;
// Test for simple solutions
switch (true){
case (x1 == x2 && v1 == v2) :
done = true;
console.log("YES");
break;
case ((x1 + v1) < v2) || ((x2 + v2) < v1) :
done = true;
console.log("NO");
break;
case ((x1 < x2 && v1 <= v2) || (x2 < x1 && v2 <= v1)) :
done = true;
console.log("NO");
break;
}
// If all switch cases are false, test for congruence
if (!done){
var sm, lg;
if (Math.abs(x1 - x2) <= Math.abs(v2 -v1)) {
lg = v2 - v1;
sm = x1 - x2;
} else {
lg = x1 - x2;
sm = v2 - v1;
}
// Is is possible for roo1 to be congruent to roo2?
(lg % sm == 0) ? console.log("YES") : console.log("NO");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment