Advertisement
andrelaszlo

fisher yates usage

Apr 8th, 2013
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.63 KB | None | 0 0
  1. <?php
  2. /*
  3. Answer to: http://stackoverflow.com/a/6557893/98057
  4.  
  5. Tested with PHP 5.4.13
  6. */
  7. function fisherYatesShuffle(&$items, $seed=null)
  8. {
  9.     if ($seed !== null) {
  10.         @mt_srand($seed);
  11.     }
  12.     for ($i = count($items) - 1; $i > 0; $i--)
  13.     {
  14.         $j = @mt_rand(0, $i);
  15.         $tmp = $items[$i];
  16.         $items[$i] = $items[$j];
  17.         $items[$j] = $tmp;
  18.     }
  19. }
  20.  
  21. $arr = [0, 1,2,3,4,5,6,7,8,9];
  22. fisherYatesShuffle($arr, 0);
  23. print_r($arr);
  24. /* will print:
  25. Array
  26. (
  27.     [0] => 6
  28.     [1] => 0
  29.     [2] => 7
  30.     [3] => 2
  31.     [4] => 9
  32.     [5] => 3
  33.     [6] => 1
  34.     [7] => 8
  35.     [8] => 5
  36.     [9] => 4
  37. )
  38. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement