spelltwister
Programmer
Hey everyone,
I was wondering, just for efficiency, is there a way to randomly select a non-zero element in an array.
Here's what I got:
$offense_infantry = array( "number" => array(), "nation" => array() );
$defense_infantry = array( "number" => array(), "nation" => array() );
for($k=0;$k<$defHits{
if($attInfantry>0){
$upper = sizeof($offense_infantry["nation"]);
$index = rand(0,$upper-1);
if($offense_infantry["number"][$index] > 0){
$attInfantry--;
$offense_infantry["number"][$index] -= 1;
$k+=1;
echo 'Attacker lost an infantry to artillery</br>';
}else{
echo 'empty attacker infantry to artillery</br>';
}...
Essentially, this is very unefficient as I look at my turn results there are many cases where it falls into the else part of that if statement. As you can see, it will not leave the for loop until enough hits have been done (the k+=1 has to reach the target $defHits var) and this sometimes takes a while.
Is there a better way to randomly select a non-zero element from the array?
If you need more info/clarification, please ask.
Thanks,
Mike
I was wondering, just for efficiency, is there a way to randomly select a non-zero element in an array.
Here's what I got:
$offense_infantry = array( "number" => array(), "nation" => array() );
$defense_infantry = array( "number" => array(), "nation" => array() );
for($k=0;$k<$defHits{
if($attInfantry>0){
$upper = sizeof($offense_infantry["nation"]);
$index = rand(0,$upper-1);
if($offense_infantry["number"][$index] > 0){
$attInfantry--;
$offense_infantry["number"][$index] -= 1;
$k+=1;
echo 'Attacker lost an infantry to artillery</br>';
}else{
echo 'empty attacker infantry to artillery</br>';
}...
Essentially, this is very unefficient as I look at my turn results there are many cases where it falls into the else part of that if statement. As you can see, it will not leave the for loop until enough hits have been done (the k+=1 has to reach the target $defHits var) and this sometimes takes a while.
Is there a better way to randomly select a non-zero element from the array?
If you need more info/clarification, please ask.
Thanks,
Mike