384. Shuffle and Array (Java, array fully arranged, then randomly taken)

Source: Internet
Author: User
Tags shuffle

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.