5

Hey there,
I have an array of (unique) objects and would like to get 4 random objects of this array, but the same object shouldn't be fetched twice, so using a simple random function won't work.

I had two ideas:
1. Shuffle the array and get the first 4 items. -> Overhead, because the array can be very large.
2. Generate a random index. If that index was used before, try again, and so on... -> Somewhat unreliable...

Do you know a better, more efficient method?

1 Answer 1

10

Shuffle the array and get the first 4 items. -> Overhead, because the array can be very large.

Use the modern version of the Fisher Yates shuffle. It can be performed in-place and if you stop after the first four swaps it will give you the result you need. There is no need to shuffle the entire array.

Compared to some other solutions, it also has the advantage that, if only part of the resulting permutation is needed, it can be stopped halfway through

Sign up to request clarification or add additional context in comments.

3 Comments

Is there ever a "get unique random items from an array" where Fisher-Yates is not applicable? :-/
Thank you, that's perfect. And pretty simple, too. :)
You link a Wikipedia page of a guy. How does this answer the question? You may as well link any person BIO who did a bit of math.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.