How to get a certain amount of random items from a collection in Smalltalk?

How can I elegantly get a certain number (> 1) of different random elements from a collection?

+6
source share
2 answers

This is what I find more or less enjoyable, but not as effective as possible:

yourCollection asSet asOrderedCollection shuffled first: numberOfElements 
+2
source

Consider the following code snippet

 sample: anInteger from: aCollection using: aGenerator | sample | sample := Set new: anInteger. [sample size = anInteger] whileFalse: [ | element | element := aCollection atRandom: aGenerator. sample add: element]. ^sample asArray 

Some notes

  • Explicit generator: it explicitly uses the given generator, i.e. instance of Random , which I called aGenerator . For mathematical reasons, if you get samples for your application, they should all use the same generator in your program. In addition, this will give you an additional advantage: save and then restore the seed , and you can reproduce the previous "random" behavior of your system, which is good for testing.

  • There is no availability check: the code does not verify that the desired sample can be obtained, which would happen if aCollection does not have at least anInteger different elements.

  • Classless code: the method should go to some class.

For instance:

  Random >> sample: anInteger from: aCollection | sample | sample := Set new: anInteger. [sample size = anInteger] whileFalse: [ | element | element := aCollection atRandom: self. sample add: element]. ^sample asArray 

UPDATE

Here is another approach:

 Random >> remove: anInteger from: aCollection | sample | sample := OrderedCollection new: anInteger. anInteger timesRepeat: [| index element | index := aCollection size atRandom: self. element := aCollection removeAt: index. sample add: element]. ^sample 

A comment

It usually happens that when we want to select without repeating, we also want to remove elements from the collection when we arbitrarily select them. In these cases, it often happens that the collection is not known to have repetitions.

+5
source

All Articles