簡體   English   中英

未知值的逐次逼近

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM