let say I have an array of this values:
$arr = array(190, 2215, 2, 61);
after I run my code with 694 loops, I got this final values:
Array
(
[0] => 696
[1] => 696
[2] => 696
[3] => 696
)
how can I make the process faster and much better?? I only can increase or decrease the value by 1
Below are my codes.
<?php
echo '<pre>';
$arr = array(190, 2215, 2, 61);
sort($arr);
print_r($arr);
$arrLength = count($arr);
$counter = 0;
loop:
$counter++;
for($i=0; $i<$arrLength; $i++){
if($arr[$i] < $arr[$arrLength-1] && $arr[$arrLength-1] != $arr[$arrLength-2]) {
$arr[$i]++;
$arr[$arrLength-1]--;
}else if($arr[$i] < $arr[$arrLength-1] && $arr[$arrLength-1] == $arr[$arrLength-2]) {
$arr[$i]++;
}
}
if($arr[0] != $arr[$arrLength-1]) goto loop;
print_r($arr);
print_r($counter);
?>
Your code just finds a weighted average between the two largest values in an array, and then sets everything to it (Second largest element has weight of the
number of elements - 1, the largest element has weight 1). You can do this much more easily and faster like this:Note: if all you need is the number (696) then you don’t need the
array_fillline. Just use the$avgvariable for whatever you need it for later.