Reputation: 10117
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 is to 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 ?
I need to add up all the $sleep
variables, and then determine if 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.
Upvotes: 0
Views: 541
Reputation: 96159
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
Upvotes: 2
Reputation:
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
Upvotes: 1
Reputation: 12900
Is there a reason not to just tack the extra onto $sleep1
?
if ( ($sleep1 + $sleep2 + $sleep3 + $sleep4) <= 60) {
$sleep1 += 61 - ($sleep1 + $sleep2 + $sleep3 + $sleep4);
}
Upvotes: 1