8000 src/bin/shuffle-an-array.rs · bestgopher/leetcode@b3f2408 · GitHub
[go: up one dir, main page]

Skip to content

Commit b3f2408

Browse files
committed
src/bin/shuffle-an-array.rs
1 parent 8077872 commit b3f2408

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/bin/shuffle-an-array.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
fn main() {}
2+
3+
/**
4+
* Your Solution object will be instantiated and called as such:
5+
* let obj = Solution::new(nums);
6+
* let ret_1: Vec<i32> = obj.reset();
7+
* let ret_2: Vec<i32> = obj.shuffle();
8+
*/
9+
struct Solution {
10+
nums: Vec<i32>,
11+
}
12+
13+
14+
/**
15+
* `&self` means the method takes an immutable reference.
16+
* If you need a mutable reference, change it to `&mut self` instead.
17+
*/
18+
impl Solution {
19+
fn new(nums: Vec<i32>) -> Self {
20+
Self { nums }
21+
}
22+
23+
/** Resets the array to its original configuration and return it. */
24+
fn reset(&self) -> Vec<i32> {
25+
self.nums.clone()
26+
}
27+
28+
/** Returns a random shuffling of the array. */
29+
fn shuffle(&self) -> Vec<i32> {
30+
use rand::Rng;
31+
32+
let mut rng = rand::thread_rng();
33+
let mut v = self.nums.clone();
34+
for i in 0..self.nums.len() {
35+
v.swap(rng.gen_range(0..self.nums.len()), i);
36+
}
37+
v
38+
}
39+
}

0 commit comments

Comments
 (0)
0