Skip to content

Commit 4e1241b

Browse files
add a solution for 384
1 parent ad10724 commit 4e1241b

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/main/java/com/fishercoder/solutions/_384.java

+38
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,43 @@ public int[] shuffle() {
7474
return result;
7575
}
7676
}
77+
78+
public static class Solution2 {
79+
/**
80+
* credit: https://leetcode.com/problems/shuffle-an-array/discuss/85958/First-Accepted-Solution-Java
81+
*/
82+
private int[] nums;
83+
private Random random;
84+
85+
public Solution2(int[] nums) {
86+
this.nums = nums;
87+
this.random = new Random();
88+
}
89+
90+
/**
91+
* Resets the array to its original configuration and return it.
92+
*/
93+
public int[] reset() {
94+
return this.nums;
95+
}
96+
97+
/**
98+
* Returns a random shuffling of the array.
99+
*/
100+
public int[] shuffle() {
101+
int[] shuffled = this.nums.clone();
102+
for (int i = 1; i < nums.length; i++) {
103+
int j = random.nextInt(i + 1);
104+
swap(shuffled, i, j);
105+
}
106+
return shuffled;
107+
}
108+
109+
private void swap(int[] shuffled, int i, int j) {
110+
int tmp = shuffled[i];
111+
shuffled[i] = shuffled[j];
112+
shuffled[j] = tmp;
113+
}
114+
}
77115
}
78116

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.common.utils.CommonUtils;
4+
import com.fishercoder.solutions._384;
5+
import org.junit.Test;
6+
7+
public class _384Test {
8+
private static _384.Solution2 solution2;
9+
10+
@Test
11+
public void test1() {
12+
solution2 = new _384.Solution2(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
13+
CommonUtils.printArray(solution2.shuffle());
14+
}
15+
}

0 commit comments

Comments
 (0)