[JAVA]-efficiently randomly select n from m elements

Source: Internet
Author: User

Before the business encountered the need to select N from m elements, then just run the loop according to the length of random selection, and then put in the Set to go to the weight, until the collection of sufficient number.

The disadvantage of this is that, when the number of elements remaining is less, the more easily the selected elements are repeated, and, using Set deduplication, strings of the same value are considered to be the same elements, even if the given array does have duplicate data.

Until recently saw the Fisher-yates Shuffle algorithm, which received inspiration, wrote a method of selecting N from M elements, the method has a great improvement in performance, and can guarantee that the index of the retrieved element will never be duplicated. If the same element is true in the array, it does not affect the probability of being selected.

1      Public Static<T> t[] randomselected (t[] array,intnum) {2t[] Temp =arrays.copyof (array, array.length); Get a copy of the array3         intLength =temp.length;4         intleft =length;5          while(Length-left <num) {//Length-left to calculate how many times6             inti = (int) Math.floor (Math.random () * left--); Randomly select an element, left to subtract, so that the last result is not overwritten and the next selected range is reduced7T tmp =Temp[i]; Swap the selected number with the last one in the array8Temp[i] =Temp[left];9Temp[left] =tmp;Ten         } One         returnArrays.copyofrange (temp, 0, num > length?)length:num); Copies an array of the specified length from the temporary array A}

The algorithm is not only fast, but the index will never repeat! (if there are duplicate elements in the array, I think this is the result you want, after all, it's not a difficult thing to do)

If the incoming num equals the length of the array, you can also get an array of scrambled orders!

[JAVA]-efficiently randomly select n from m elements

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.