-2

I have a Set which contains multiple Elements. My goal is to get 10 random Elements out of it.

How can I achieve this goal in the simplest way (hopefully one line) without having to modify the Set itself or create a new reference Set?

christophriepe
  • 1,157
  • 12
  • 47

1 Answers1

1

Here's the shortest one-liner I came up with:

let randomTenElements = mySet.lazy.shuffled().prefix(10)

It returns an ArraySlice though so if you need the result as an array or another set you'll have to explicitly cast it to your desired type.

Vadim Belyaev
  • 2,456
  • 2
  • 18
  • 23
  • thanks for the answer. One last question: Why do you use .lazy ? – christophriepe Jun 06 '22 at 20:21
  • 1
    The hope was undoubtedly that it would be faster and take less memory to do this lazily. E.g., if you want 10 random values from a set of a million values, it is very inefficient to build an entire shuffled array of all million values, only to grab the first 10. You really want to lazily grab the first shuffled value, then the next, etc, until you have the 10 random values you wanted. But I just benchmarked both performance and memory usage, and `lazy` is _not_ accomplishing anything here. It is just as inefficient (both in memory and speed) as the non-lazy rendition. – Rob Jun 07 '22 at 00:09