Issues (64)

src/leetcode/ShuffleAnArray.php (1 issue)

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
Bug Best Practice introduced by
The expression $this->nums of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

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.

Loading history...
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