Topic:
Shuffle a set of numbers without duplicates.
Analysis:
Random reordering of a set of arrays that do not contain duplicate elements, the Reset method returns the most primitive array, and the shuffle method randomly returns an array of arrays,
and the probability of getting each permutation of an array is the same. To do this, all permutations of the array can be evaluated at initialization time. When you use the shuffle method, you randomly return one of the full permutations.
Code:
Public classSolution {//stores all permutations of an arraylist<int[]> list =Newarraylist<int[]>(); PublicSolution (int[] nums) { //first ask for all permutationsPermutations (nums,list,0); } /**resets the array to its original configuration and return it.*/ Public int[] Reset () {returnList.get (0); } /**Returns A random shuffling of the array.*/ Public int[] Shuffle () {intindex = (int) (Math.random () *list.size ()); returnList.get (index); } //to find all permutations of an array Public voidPermutations (int[] array,list<int[]> list,intstart) { if(Array = =NULL){ return; } if(Start = =array.length) { int[] temp =New int[Array.Length]; System.arraycopy (Array,0,temp,0, Array.Length); List.add (temp); } for(inti = start; i < Array.Length; ++i) {swap (Array,i,start); Permutations (Array,list,start+1); Swap (Array,i,start); } } //Interchange Element Public voidSwapint[] Array,intIintj) { inttemp =Array[i]; Array[i]=Array[j]; ARRAY[J]=temp; }}/*** Your Solution Object would be instantiated and called as such: * Solution obj = new solution (nums); * int[] Param_1 = Obj.reset (); * int[] param_2 = Obj.shuffle (); */
384. Shuffle and Array (Java, array fully arranged, then randomly taken)