ILIAS  release_5-1 Revision 5.0.0-5477-g43f3e3fab5f
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 {
80 mt_srand($seed);
81 }
82 else
83 {
84 srand($seed);
85 }
86 }
87
92 private function shuffleArray($array)
93 {
94 if( $this->isMtRandomizerAvailable() )
95 {
96 return $this->mtShuffle($array);
97 }
98
99 shuffle($array);
100 return $array;
101 }
102
107 private function mtShuffle($orderedArray)
108 {
109 $shuffledArray = array();
110
111 while( count($orderedArray) > 0 )
112 {
113 $key = mt_rand(0, (count($orderedArray)-1));
114 $splice = array_splice($orderedArray, $key, 1);
115 $shuffledArray[] = current($splice);
116 }
117
118 return $shuffledArray;
119 }
120
124 private function isMtRandomizerAvailable()
125 {
126 return function_exists('mt_srand') && function_exists('mt_rand');
127 }
128}