How to get unique random elements from an array?

Hey there,
I have an array of (unique) objects and you want to get 4 random objects of this array, but the same object should not be extracted twice, so using a simple random function will not work.

I had two ideas:
1. Shuffle the array and get the first 4 elements. → Overhead, because the array can be very large.
2. Create a random index. If this index was used before, try again and so on ... → Somewhat unreliable ...

Do you know a more efficient and effective method?

+3
source share
1 answer

4 . → , .

Fisher Yates shuffle, in-place, , , . .

, , ,

+10

Source: https://habr.com/ru/post/1793294/


All Articles