Skip to content

Commit c910d91

Browse files
committed
Shuffle an Array
1 parent 6ced0f0 commit c910d91

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Source : https://leetcode.com/problems/shuffle-an-array/
2+
// Author : Han Zichi
3+
// Date : 2017-01-23
4+
5+
/**
6+
* @param {number[]} nums
7+
*/
8+
var Solution = function(nums) {
9+
this.nums = nums;
10+
};
11+
12+
/**
13+
* Resets the array to its original configuration and return it.
14+
* @return {number[]}
15+
*/
16+
Solution.prototype.reset = function() {
17+
return this.nums;
18+
};
19+
20+
/**
21+
* Returns a random shuffling of the array.
22+
* @return {number[]}
23+
*/
24+
Solution.prototype.shuffle = function() {
25+
// @see https://github.com/hanzichi/underscore-analysis/issues/15
26+
function shuffle(a) {
27+
var length = a.length;
28+
var shuffled = Array(length);
29+
30+
for (var index = 0, rand; index < length; index++) {
31+
rand = ~~(Math.random() * (index + 1));
32+
if (rand !== index)
33+
shuffled[index] = shuffled[rand];
34+
shuffled[rand] = a[index];
35+
}
36+
37+
return shuffled;
38+
}
39+
40+
return shuffle(this.nums);
41+
};
42+
43+
/**
44+
* Your Solution object will be instantiated and called as such:
45+
* var obj = Object.create(Solution).createNew(nums)
46+
* var param_1 = obj.reset()
47+
* var param_2 = obj.shuffle()
48+
*/

0 commit comments

Comments
 (0)