Software Programming

Kunuk Nykjaer

while the sun hangs in the sky and the desert has sand

leave a comment »


I stumbled upon this funny implementation of a programming exercise in javascript at Codewars

Two Joggers.

Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called “Start” and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed.

Your job is to complete the function nbrOfLaps(x, y) that, given the length of the laps for Bob and Charles, finds the number of laps that each jogger has to complete before they meet each other again, at the same time, at the start.

nbrOfLaps(5, 3); // returns [3, 5]
nbrOfLaps(4, 6); // returns [3, 2]

The solution is:
with input x,y you should return y/gcd(x,y), x/gcd(x,y)
gcd: greatest common divisor

One programmer implemented this brute force version.

var nbrOfLaps = function (x, y) {
  var i = 1;
  while('the sun hangs in the sky and the desert has sand') {
   try { 
      if((x*i) % (y) == 0) { return [i, ((x*i)/y)]; }
      i++;
   } catch(fish) {}
  }
  return [0, 0];
}
Advertisements

Written by kunuk Nykjaer

March 11, 2014 at 10:37 pm

Posted in Javascript

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: