编写此程序的更好方法,以使其执行时间最短
better way to write this program so that it consumes minimum time to execute
我想要用更少的执行时间获得相同的结果。有没有更好的方法来编写代码,以便我可以用最短的执行时间获得相同的结果。
<?php
$input1 = 5;
$input2 = 1;
$input3 = [9, 5, 10];
$numberOfWalls = count($input3);
$numberOfJumps = 0;
for($i=0; $i<$numberOfWalls; $i++){
if($input1 >= $input3[$i]){
$numberOfJumps += 1;
}else {
$tot = 0;
while(1){
if($tot + $input1 < $input3[$i]){
$tot = $tot + ($input1 - $input2);
$numberOfJumps += 1;
}else{
$tot = $tot + $input1;
$numberOfJumps += 1;
break;
}
}
}
}
echo $numberOfJumps;
这个怎么样:
// input
$forwards = 5;
$backwards = 1;
$walls = [9, 5, 10];
// computation
$oneJump = $forwards-$backwards;
$jumps = 0;
foreach ($walls as $wall) $jumps += ceil(($wall-$backwards)/$oneJump);
// output
echo "Jumps needed = $jumps";
我想要用更少的执行时间获得相同的结果。有没有更好的方法来编写代码,以便我可以用最短的执行时间获得相同的结果。
<?php
$input1 = 5;
$input2 = 1;
$input3 = [9, 5, 10];
$numberOfWalls = count($input3);
$numberOfJumps = 0;
for($i=0; $i<$numberOfWalls; $i++){
if($input1 >= $input3[$i]){
$numberOfJumps += 1;
}else {
$tot = 0;
while(1){
if($tot + $input1 < $input3[$i]){
$tot = $tot + ($input1 - $input2);
$numberOfJumps += 1;
}else{
$tot = $tot + $input1;
$numberOfJumps += 1;
break;
}
}
}
}
echo $numberOfJumps;
这个怎么样:
// input
$forwards = 5;
$backwards = 1;
$walls = [9, 5, 10];
// computation
$oneJump = $forwards-$backwards;
$jumps = 0;
foreach ($walls as $wall) $jumps += ceil(($wall-$backwards)/$oneJump);
// output
echo "Jumps needed = $jumps";