imajinyun /
leetcode-php
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace leetcode; |
||
| 6 | |||
| 7 | class ShuffleAnArray |
||
| 8 | { |
||
| 9 | private array $nums; |
||
| 10 | |||
| 11 | /** |
||
| 12 | * Initializes the object with the integer array nums. |
||
| 13 | * |
||
| 14 | * @param array $nums |
||
| 15 | */ |
||
| 16 | public function __construct(array $nums) |
||
| 17 | { |
||
| 18 | $this->nums = $nums; |
||
| 19 | } |
||
| 20 | |||
| 21 | /** |
||
| 22 | * Resets the array to its original configuration and return it. |
||
| 23 | * |
||
| 24 | * @return array |
||
| 25 | */ |
||
| 26 | public function reset(): array |
||
| 27 | { |
||
| 28 | return $this->nums; |
||
| 29 | } |
||
| 30 | |||
| 31 | /** |
||
| 32 | * Returns a random shuffling of the array. |
||
| 33 | * |
||
| 34 | * @return array |
||
| 35 | */ |
||
| 36 | public function shuffle(): array |
||
| 37 | { |
||
| 38 | if (!$this->nums) { |
||
|
0 ignored issues
–
show
|
|||
| 39 | return []; |
||
| 40 | } |
||
| 41 | $nums = $this->nums; |
||
| 42 | $n = count($nums); |
||
| 43 | for ($i = 0; $i < $n; $i++) { |
||
| 44 | $j = random_int(0, $i); |
||
| 45 | [$nums[$i], $nums[$j]] = [$nums[$j], $nums[$i]]; |
||
| 46 | } |
||
| 47 | |||
| 48 | return $nums; |
||
| 49 | } |
||
| 50 | } |
||
| 51 |
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.