samedi 27 juin 2015

php Random variable countdown limited in time

I am writing a randomized countdown that show number of products left in promotion alongside a timer. Number of products left is stored in the database, so all users see the same number. I am using simple php/ajax/javascript solution. My problem is with distributing the random sales so all fit within limited timer and are nicely distributed.

Here is code I have so far:

function start() {
    $date= new DateTime();
    $prod_left = getval("SELECT * FROM counter LIMIT 1");
    if ( $prod_left == 20 ) {
        $fp = fopen("../index.html", "r+");
        while($buf = fgets($fp)){
            if(preg_match("/<!--(.|\s)*?-->/", $buf)){
                fputs($fp, '<script type="text/javascript">$(document).ready(function() {$(".countdown").circularCountdown({startDate:"' . $date->format('Y/m/d H:i:s') . '",endDate:"' . $date->modify("+5minutes")->format('Y/m/d H:i:s') . '",timeZone:+2});});</script></body></html>');
            }
        }
        fclose($fp);
        sleep(30);
        while ($prod_left > 0) {
            if (rand(0,4) > 2) {
                $prod_left--;
                sleep(rand(1,13));
                updateval($prod_left);
            }
        }

    } else {
        echo 'Promocja w trakcie lub zakończona, zresetuj zegar, jeżeli chcesz rozpocząć ponownie';
    }
    exit;
}

My assumption here is: 50% of time decrease timer and wait on average 6.5 seconds, which should on average give me 260 seconds for full sale. Unfortunately its very unevenly distributed. My goal is to have the $prod_value down to 0 not later than 270seconds after loop start, with quite evenly distributed value decreases (can accelerate towards ending) Will you be able to help?

Implementation doesnt need to be in any particular programing language, im just looking for a clue/concept I can follow to achieve this.

What is the strangest, the $prod_left value not always goes to 0, on sime iterations it just sits at 3 or 5.

Please help!

Aucun commentaire:

Enregistrer un commentaire