/** * Randomizes the positions of the elements in an array. * * @param array $array The array to be shuffled. * * @return void */ public static function shuffle($array) { assert('is_carray($array)', vs(isset($this), get_defined_vars())); $array = splarray($array); // The Fisher-Yates algorithm. for ($i = $array->getSize() - 1; $i > 0; $i--) { $exchangeIdx = CMathi::intervalRandom(0, $i); $save = $array[$exchangeIdx]; $array[$exchangeIdx] = $array[$i]; $array[$i] = $save; } }
/** * Randomizes the positions of the characters in a string and returns the new string. * * @param string $string The string to be shuffled. * * @return string The shuffled string. */ public static function shuffle($string) { assert('is_cstring($string)', vs(isset($this), get_defined_vars())); // The Fisher-Yates algorithm. for ($i = self::length($string) - 1; $i > 0; $i--) { $exchangeIdx = CMathi::intervalRandom(0, $i); $save = self::charAt($string, $exchangeIdx); self::setCharAt($string, $exchangeIdx, self::charAt($string, $i)); self::setCharAt($string, $i, $save); } return $string; }
/** * Randomizes the positions of the characters in a string and returns the new string. * * @param string $string The string to be shuffled. * * @return string The shuffled string. */ public static function shuffle($string) { assert('is_cstring($string)', vs(isset($this), get_defined_vars())); // The Fisher-Yates algorithm. for ($i = strlen($string) - 1; $i > 0; $i--) { $exchangeIdx = CMathi::intervalRandom(0, $i); $save = $string[$exchangeIdx]; $string[$exchangeIdx] = $string[$i]; $string[$i] = $save; } return $string; }
public function testIntervalRandom() { for ($i = 0; $i < 10; $i++) { $rnd = CMathi::intervalRandom(12, 34); $this->assertTrue(12 <= $rnd && $rnd <= 34); } for ($i = 0; $i < 10; $i++) { $rnd = CMathi::intervalRandom(56, 78); $this->assertTrue(56 <= $rnd && $rnd <= 78); } for ($i = 0; $i < 10; $i++) { $rnd = CMathi::intervalRandom(56.01, 78.01000000000001); $this->assertTrue(56 <= $rnd && $rnd <= 78); } }