tags:

views:

185

answers:

4

I have a php script that is run once a minute. The script runs a second script, then sleeps for a given amount of time.

Right now the time is static. 20 seconds each time.

What i need to so is randomize the amount of time it sleeps. It can be more than a total of 60 seconds, but NOT less.

So here is what i have now.

$sleep1 = rand(2,18);
$sleep2 = rand(2,18);
$sleep3 = rand(2,18);
$sleep4 = rand(2,18);
if $sleep1 + $sleep2 + $sleep3 + $sleep4 <= 60 ?????????

What i need to do, is add up all the $sleep variables, and then determine is the total is less than 60. If it is, i need to increase the value of one or more of the variables to make up the difference.

+4  A: 

Why not pass that value to rand()?

sleep(rand(60, 120));

If you really need your method, just use max():

sleep(max(60, $sleep1 + $sleep2 + $sleep3 + $sleep4));
soulmerge
+2  A: 

If you're not bound to $sleep1,...,$sleep4 but can use something like $sleep[ 0...n ]:

<?php
$threshold = 60;

$sleep = array();
$sleep[] = rand(2,18);
$sleep[] = rand(2,18);
$sleep[] = rand(2,18);
$sleep[] = rand(2,18);

if ( array_sum($sleep) < $threshold ) {
  $sleep['padding'] = $threshold - array_sum($sleep);
}

foreach($sleep as $i=>$value) {
  echo $i, ': ', $value, "\n";
}

edit: if you want to "scale" each of the $sleep-values so that they sum up to 60 (or more):

<?php
$threshold = 60;

$sleep = array();
$sleep[] = rand(2,18);
$sleep[] = rand(2,18);
$sleep[] = rand(2,18);
$sleep[] = rand(2,18);

echo 'before: ', join(',', $sleep), '=', array_sum($sleep), "\n";
$sum = array_sum($sleep);
if ( $sum < $threshold ) {
  $add = (int)(($threshold-$sum) / count($sleep));
  $remainder = $threshold - ($sum+$add*count($sleep));
  foreach( $sleep as &$v ) {
    $v += (int)$add;
    if ( $remainder-- > 0) {
      $v += 1;
    }
  }
}

echo 'after: ', join(',', $sleep), '=', array_sum($sleep), "\n";

prints e.g.

before: 2,13,12,15=42
after: 7,18,16,19=60

before: 10,9,3,12=34
after: 17,16,9,18=60

before: 14,17,16,15=62
after: 14,17,16,15=62
VolkerK
+1  A: 

Is there a reason not to just tack the extra onto $sleep1?

if ( ($sleep1 +  $sleep2 + $sleep3 + $sleep4) <= 60) {
    $sleep1 += 61 - ($sleep1 +  $sleep2 + $sleep3 + $sleep4);
}
acrosman
+1  A: 

If you can have more than, or do not need exactly 4 $sleep_ variables:

<?php

$time = 0;
$i = 1;
$array = array();

do {
  $sleep{$i} = rand(2,18);
  $array[] = $sleep{$i};
  $time += $sleep{$i};
  $i++;
} while ($time <= 60);

print_r($array);

echo $time;

?>

Gives you something like:

Array
(
    [0] => 5
    [1] => 2
    [2] => 18
    [3] => 9
    [4] => 11
    [5] => 10
    [6] => 3
    [7] => 13
)

71
jonwd7