Skip to content

Instantly share code, notes, and snippets.

@raineorshine
Last active December 16, 2015 18:39
Show Gist options
  • Select an option

  • Save raineorshine/5478889 to your computer and use it in GitHub Desktop.

Select an option

Save raineorshine/5478889 to your computer and use it in GitHub Desktop.
Write a recursive function that determines how many seconds it takes for a cheetah to catch a gazelle.
/*
Cheetahs can run up to 60mph, or 88 feet per second. Gazelles can run up to 30mph, or 44 feet per
second. Write a recursive function that determines how many seconds it takes for a cheetah to catch
a gazelle given an initial starting point and how far away the gazelle is.
e.g. catchPrey(0, 1000) returns the number of seconds it takes for a cheetah at 0 feet to catch a
gazelle at 1000 feet.
To make things a little more interesting, the gazelle sees the cheetah at 500 feet and starts running
like hell.
If you're a total badass, you should immediately delete all of the code below and code this from
scratch.
If you're a badass-in-training, study the below code and substitute in your own code for A, B, and C.
Each of these are single, short expressions, so if you're writing more than 1 line for any of them
you're doing it wrong.
Hints:
A is the base case. When does the cheetah catch the gazelle?
B is the sight threshold. When does the gazelle see the cheetah?
C is the recursive call. You have to call catchPrey somewhere in this expression.
Remember, catchPrey returns the number of seconds it takes the cheetah to catch the gazelle.
The test functions provided should print 5 seconds for a gazelle at 200 ft, 13 seconds for 600
ft, and 21 seconds for 1200 ft (see below).
Good luck!!!
*/
var CHEETAH_SPEED = 88; // feet per second
var GAZELLE_SPEED = 44;
var GAZELLE_SIGHT = 500; // feet
var catchPrey = function(cheetahTraveled, gazelleTraveled) {
if(/*A*/) {
return 0;
}
else {
cheetahTraveled += CHEETAH_SPEED;
if(/*B*/) {
gazelleTraveled += GAZELLE_SPEED;
}
return /*C*/'???';
}
}
var test = function(gazelleDistance) {
console.log('Cheetah starts: 0ft');
console.log('Gazelle starts: ' + gazelleDistance + 'ft');
console.log('Cheetah catches Gazelle: ' + catchPrey(0, gazelleDistance) + ' seconds\n\n');
}
test(200);
test(600);
test(1200);
/* Correct answer:
Cheetah starts: 0ft
Gazelle starts: 200ft
Cheetah catches Gazelle: 5 seconds
Cheetah starts: 0ft
Gazelle starts: 600ft
Cheetah catches Gazelle: 13 seconds
Cheetah starts: 0ft
Gazelle starts: 1200ft
Cheetah catches Gazelle: 21 seconds
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment