[英]Successive approximation of unkown value
I have a url with a page system.我有一个带有寻呼系统的 url。
For instance https://myURL?p=50例如 https://myURL?p=50
But I want a script to find the last page available, for instance, let's say p=187但是我想要一个脚本来找到可用的最后一页,例如,假设 p=187
I have a function checkEmpty() that tells me whether the page is empty or not.我有一个 function checkEmpty() 告诉我页面是否为空。 So for instance:
例如:
$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
I did a naive algorithm, that you might guess it, performs too much requests.我做了一个天真的算法,你可能会猜到它执行了太多的请求。
My question is: What would be the algorithm to find the last page with the minimal amount of requests?我的问题是:用最少的请求找到最后一页的算法是什么?
EDIT As requested by people in the comment here is the checkEmpty() implementation编辑按照评论中的人们的要求,这里是 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;
}
}
Since the upper bound is not known, exponentially increase the page no by 2 starting from 1. The moment you hit a non-existent page, you can do a binary search
from previous existing page + 1 till this new upper bound where the page doesn't exist.由于上限未知,因此从 1 开始以指数方式将页面编号增加 2。当您遇到不存在的页面时,您可以从先前的现有页面 + 1 进行
binary search
,直到该页面不存在的新上限'存在。
This way, you can get your answer in O(log(n))
attempts asymptotically where n
is the no.这样,您可以在
O(log(n))
次渐进尝试中得到答案,其中n
是编号。 of existing pages here as the sample space.此处的现有页面作为示例空间。
<?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.