File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Algorithms/Shuffle an Array Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+ */
You can’t perform that action at this time.
0 commit comments