Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weighted Shuffle of an Array or Arrays?

What is a good algorithm that shuffles an array or arrays using weights from the nested arrays?

Example:

$array = array(
  array("name"=>"John", "rank"=>3),
  array("name"=>"Bob", "rank"=>1),
  array("name"=>"Todd", "rank"=>8),
  array("name"=>"Todd", "rank"=>14),
  array("name"=>"Todd", "rank"=>4)
);

I want the array randomly shuffled but I want the rank value to be a weight. So those with a low number rank are more likely to be at the top of the list.

I've experimented with a few things, like iterating through the array and pulling out arrays chosen using mt_rand(mt_rand(0,$value),$value) but I don't think I'm on the right track...

like image 962
Jake Wilson Avatar asked Feb 22 '12 21:02

Jake Wilson


People also ask

How do you shuffle an array in C++?

Shuffle an Array using STL in C++ These are namely shuffle() and random_shuffle(). This method rearranges the elements in the range [first, last) randomly, using g as a uniform random number generator. It swaps the value of each element with that of some other randomly picked element.

How do you randomize an array in C#?

Shuffle an Array With the Random Class in C# The Random. Next() method generates a random integer value. We can use the Random. Next() method with LINQ to shuffle an array in C#.


1 Answers

I was able to solve this problem like so:

function compare($a, $b)
{
  $share_of_a = $a['rank'];
  $share_of_b = $b['rank'];
  return mt_rand(0, ($share_of_a+$share_of_b)) > $share_of_a ? 1 : -1;
}

usort($array, "compare"); // Sort the array using the above compare function when comparing
$array = array_reverse($array);
like image 143
Jake Wilson Avatar answered Sep 23 '22 20:09

Jake Wilson