ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
class.ilArrayElementShuffler.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (c) 1998-2013 ILIAS open source, Extended GPL, see docs/LICENSE */
3 
4 
12 {
16  protected $seed;
17 
20  public function __construct()
21  {
22  $this->setSeed($this->buildRandomSeed());
23  }
24 
28  public function getSeed()
29  {
30  return $this->seed;
31  }
32 
36  public function setSeed($seed)
37  {
38  $this->seed = $seed;
39  }
40 
44  public function buildRandomSeed()
45  {
46  list($usec, $sec) = explode(' ', microtime());
47  return (int) ($sec + ($usec * 100000));
48  }
49 
54  public function buildSeedFromString($string)
55  {
56  return hexdec(substr(md5($string), 0, 10));
57  }
58 
63  public function shuffle($array)
64  {
65  $this->initSeed($this->getSeed());
66  $array = $this->shuffleArray($array);
67  $this->initSeed($this->buildRandomSeed());
68  return $array;
69  }
70 
74  private function initSeed($seed)
75  {
76  $seed = (int) $seed; // (mt_)srand seems to not cast to integer itself (string seeds avoid randomizing) !!
77 
78  if ($this->isMtRandomizerAvailable()) {
79  mt_srand($seed);
80  } else {
81  srand($seed);
82  }
83  }
84 
89  private function shuffleArray($array)
90  {
91  if ($this->isMtRandomizerAvailable()) {
92  return $this->mtShuffle($array);
93  }
94 
95  shuffle($array);
96  return $array;
97  }
98 
103  private function mtShuffle($orderedArray)
104  {
105  $shuffledArray = array();
106 
107  while (count($orderedArray) > 0) {
108  $key = mt_rand(0, (count($orderedArray) - 1));
109  $splice = array_splice($orderedArray, $key, 1);
110  $shuffledArray[] = current($splice);
111  }
112 
113  return $shuffledArray;
114  }
115 
119  private function isMtRandomizerAvailable()
120  {
121  return function_exists('mt_srand') && function_exists('mt_rand');
122  }
123 }
$key
Definition: croninfo.php:18