[英]Successive approximation of unkown value
我有一个带有寻呼系统的 url。
例如 https://myURL?p=50
但是我想要一个脚本来找到可用的最后一页,例如,假设 p=187
我有一个 function checkEmpty() 告诉我页面是否为空。 例如:
$myUrl = new URL(50); //https://myURL?p=50
$myUrl->checkEmpty();
//This evaluates to false -> the page exists
$myUrl = new URL(188); //https://myURL?p=188
$myUrl->checkEmpty();
//This evaluates to true -> the page does NOT exist
$myUrl = new URL(187); //https://myURL?p=187
$myUrl->checkEmpty();
//This evaluates to false -> the page exists
我做了一个天真的算法,你可能会猜到它执行了太多的请求。
我的问题是:用最少的请求找到最后一页的算法是什么?
编辑按照评论中的人们的要求,这里是 checkEmpty() 实现
<?php
public function checkEmpty() : bool
{
$criteria = "Aucun contenu disponible";
if(strstr( $this->replace_carriage_return(" ", $this->getHtml()), $criteria) !== false)
{
return true;
}
else
{
return false;
}
}
由于上限未知,因此从 1 开始以指数方式将页面编号增加 2。当您遇到不存在的页面时,您可以从先前的现有页面 + 1 进行binary search
,直到该页面不存在的新上限'存在。
这样,您可以在O(log(n))
次渐进尝试中得到答案,其中n
是编号。 此处的现有页面作为示例空间。
<?php
$lowerBound = 1;
$upperBound = 1;
while(true){
$myUrl = new URL($upperBound);
if($myUrl->checkEmpty()){
break;
}
$lowerBound = $upperBound + 1;
$upperBound <<= 1;
}
$ans = $lowerBound;
while($lowerBound <= $upperBound){
$mid = $lowerBound + (($upperBound - $lowerBound) >> 1);
$myUrl = new URL($mid);
if($myUrl->checkEmpty()){
$upperBound = $mid - 1;
}else{
$lowerBound = $mid + 1;
$ans = $lowerBound;
}
}
echo $ans;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.