[ create a new paste ] login | about

Link: http://codepad.org/gJfzxkEU    [ raw code | output | fork ]

PHP, pasted on Feb 22:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
$data = 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)
);

function weightedshuffle ($a, $b) {
    return rand(0, $a['rank'] + $b['rank']) <= $a['rank'];
}

usort($data, 'weightedshuffle');

var_dump($data);


Output:
array(5) {
  [0]=>
  array(2) {
    ["name"]=>
    string(3) "Bob"
    ["rank"]=>
    int(1)
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(4) "Todd"
    ["rank"]=>
    int(4)
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(4) "John"
    ["rank"]=>
    int(3)
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(4) "Todd"
    ["rank"]=>
    int(8)
  }
  [4]=>
  array(2) {
    ["name"]=>
    string(4) "Todd"
    ["rank"]=>
    int(14)
  }
}


Create a new paste based on this one


Comments: