Chris Day
Chris Day

Reputation: 129

Hare & Tortoise Calculation

I have data for 2 profiles that I would like to compare.

Each profile has a 'total points' value and a 'points per day' value and I would like to calculate how many days it would take the hare to overtake the tortoise.

$hare_points = 10000;
$hare_ppd = 700;

$tortoise_points = 16000;
$tortoise_ppd = 550;

What would be the most efficient way to determine how many days it would take for the hare to catch up with the tortoise? My first through was to run a loop to just count through the days, but very quickly realised there must be an efficient algorithm out there that will not want to destroy the server that it is running on lol

Upvotes: 0

Views: 236

Answers (2)

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

Assuming ppd is points per day:

<?php
$hare_points = 10000;
$hare_ppd = 700;

$tortoise_points = 16000;
$tortoise_ppd = 550;

$hare_diff = $tortoise_points - $hare_points;
$hare_ppd_diff = abs($tortoise_ppd - $hare_ppd);
$days = $hare_diff/$hare_ppd_diff;
echo $days; // 40

/* Test:
 * 40 * 700 = 28000; hare
 * 40 * 550 = 22000; tortoise
 * 
 * hare_p = 28000 + 10000 = 38 000
 * toit_p = 22000 + 16000 = 38 000
 * 
 * So the math is right. On 40th day, they are equal
 * 
 */

Upvotes: 2

viraptor
viraptor

Reputation: 34185

It's a simple set of equations to solve.

hare_total = hare_points + hare_ppd * days
tortoise_total = tortoise_points + tortoise_ppd * days

You're trying to find out the day the points are the same, so:

hare_total = tortoise_total
hare_points + hare_ppd * days = tortoise_points + tortoise_ppd * days
hare_points - tortoise_points = (tortoise_ppd - hare_ppd) * days

So there's your answer:

$days = ($hare_points - $tortoise_points) / ($tortoise_ppd - $hare_ppd)

Just plug that into your function and round up / down to an integer depending on how you want to interpret the answer.

Upvotes: 2

Related Questions