-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathShuffleAnArray.php
More file actions
50 lines (43 loc) · 915 Bytes
/
ShuffleAnArray.php
File metadata and controls
50 lines (43 loc) · 915 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
declare(strict_types=1);
namespace leetcode;
class ShuffleAnArray
{
private array $nums;
/**
* Initializes the object with the integer array nums.
*
* @param array $nums
*/
public function __construct(array $nums)
{
$this->nums = $nums;
}
/**
* Resets the array to its original configuration and return it.
*
* @return array
*/
public function reset(): array
{
return $this->nums;
}
/**
* Returns a random shuffling of the array.
*
* @return array
*/
public function shuffle(): array
{
if (!$this->nums) {
return [];
}
$nums = $this->nums;
$n = count($nums);
for ($i = 0; $i < $n; $i++) {
$j = random_int(0, $i);
[$nums[$i], $nums[$j]] = [$nums[$j], $nums[$i]];
}
return $nums;
}
}