Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| ArrayRandomize | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
4 | |
100.00% |
1 / 1 |
| yates | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| knuth | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Jingga |
| 4 | * |
| 5 | * PHP Version 8.1 |
| 6 | * |
| 7 | * @package phpOMS\Utils\RnG |
| 8 | * @copyright Dennis Eichhorn |
| 9 | * @license OMS License 2.0 |
| 10 | * @version 1.0.0 |
| 11 | * @link https://jingga.app |
| 12 | */ |
| 13 | declare(strict_types=1); |
| 14 | |
| 15 | namespace phpOMS\Utils\RnG; |
| 16 | |
| 17 | /** |
| 18 | * Array randomizer class |
| 19 | * |
| 20 | * @package phpOMS\Utils\RnG |
| 21 | * @license OMS License 2.0 |
| 22 | * @link https://jingga.app |
| 23 | * @since 1.0.0 |
| 24 | */ |
| 25 | class ArrayRandomize |
| 26 | { |
| 27 | /** |
| 28 | * Yates array shuffler. |
| 29 | * |
| 30 | * @param array $arr Array to randomize. Array must NOT be associative |
| 31 | * |
| 32 | * @return array |
| 33 | * |
| 34 | * @since 1.0.0 |
| 35 | */ |
| 36 | public static function yates(array $arr) : array |
| 37 | { |
| 38 | $shuffled = []; |
| 39 | |
| 40 | while (!empty($arr)) { |
| 41 | $rnd = (int) \array_rand($arr); |
| 42 | $shuffled[] = $arr[$rnd] ?? null; |
| 43 | \array_splice($arr, $rnd, 1); |
| 44 | } |
| 45 | |
| 46 | return $shuffled; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Knuths array shuffler. |
| 51 | * |
| 52 | * @param array $arr Array to randomize |
| 53 | * |
| 54 | * @return array |
| 55 | * |
| 56 | * @since 1.0.0 |
| 57 | */ |
| 58 | public static function knuth(array $arr) : array |
| 59 | { |
| 60 | $shuffled = []; |
| 61 | |
| 62 | for ($i = \count($arr) - 1; $i > 0; --$i) { |
| 63 | $rnd = \mt_rand(0, $i); |
| 64 | $shuffled[$i] = $arr[$rnd]; |
| 65 | $shuffled[$rnd] = $arr[$i]; |
| 66 | } |
| 67 | |
| 68 | return $shuffled; |
| 69 | } |
| 70 | } |