2013-08-19 66 views
0

我有2個配置文件的數據,我想比較。野兔和烏龜計算

每個配置文件都有一個「總點數」值和一個「每日點數」值,我想計算需要多少天兔子才能超過烏龜。

$hare_points = 10000; 
$hare_ppd = 700; 

$tortoise_points = 16000; 
$tortoise_ppd = 550; 

什麼是最有效的方式來確定野兔追趕烏龜需要多少天?我第一次通過運行一個循環來計算整個日子,但很快就意識到必須有一個高效的算法,不會破壞它運行的服務器lol

回答

2

假設PPD是每天幾點:

<?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 
* 
*/ 
+0

輝煌,謝謝:) –

2

這是一組簡單的方程來解決。

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

你試圖找出當天的點是一樣的,所以:

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

因此,有你的答案:

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

只需把它插入到你的函數和取決於您想要解釋答案的方式,向上/向下取整爲整數。

+0

謝謝viraptor。我也試過這個,確實得到了正確的輸出結果。 –