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