我有我想比较的 2 个配置文件的数据。
每个配置文件都有一个“总积分”值和一个“每天积分”值,我想计算兔子需要多少天才能超过乌龟。
$hare_points = 10000;
$hare_ppd = 700;
$tortoise_points = 16000;
$tortoise_ppd = 550;
确定兔子需要多少天才能赶上乌龟的最有效方法是什么?我的第一个方法是运行一个循环来计算天数,但很快意识到必须有一个有效的算法,不会破坏它正在运行的服务器,哈哈
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.
假设 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
*
*/