lundi 4 juillet 2016

Choose random index of array with condition on value

I have an array of booleans, from which I want to pick a random index whose value is true and set it to false.

I can, of course, do this with brute force by picking indices until I hit one whose value is true:

$arr = array(true, false, false, true, false, true);

var_dump($arr);

$i = array_rand($arr);
while(!$arr[$i])
{
    $i = array_rand($arr);
}
$arr[$i] = false;

var_dump($arr);

This creates something like this, where the fourth entry got changed.

array(6) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
  [3]=>
  bool(true)
  [4]=>
  bool(false)
  [5]=>
  bool(true)
}

array(6) {
  [0]=>
  bool(true)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
  [3]=>
  bool(false)
  [4]=>
  bool(false)
  [5]=>
  bool(true)
}

However, I have to do this operation several times with a significantly larger array. At some point the array is nearly completely false, in which case the brute force method is rather inefficient.

Is there any more elegant method of solving this problem? Any kind of array_rand() function, where I can give a precondition?




Aucun commentaire:

Enregistrer un commentaire