Created
November 30, 2018 11:13
-
-
Save marco-kretz/56ca5da603a88c3894c4c3ab69c9ed4f to your computer and use it in GitHub Desktop.
Fast FisherYatesShuffle PHP-Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
final class FisherYatesShuffle | |
{ | |
/** | |
* Shuffle an input sequence by Fisher-Yates-Shuffle. | |
* | |
* @url https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle | |
* | |
* @param array $input Array to shuffle | |
* | |
* @return array Shuffled array | |
*/ | |
public function shuffle(array $input): array | |
{ | |
$output = $input; | |
$length = count($output); | |
for ($i = ($length - 1); $i >= 1; $i--) { | |
$j = mt_rand(0, $i); | |
$temp = $output[$i]; | |
$output[$i] = $output[$j]; | |
$output[$j] = $temp; | |
} | |
return $output; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment