Skip to content

Instantly share code, notes, and snippets.

@marco-kretz
Created November 30, 2018 11:13
Show Gist options
  • Save marco-kretz/56ca5da603a88c3894c4c3ab69c9ed4f to your computer and use it in GitHub Desktop.
Save marco-kretz/56ca5da603a88c3894c4c3ab69c9ed4f to your computer and use it in GitHub Desktop.
Fast FisherYatesShuffle PHP-Implementation
<?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