Introduction
There are times that you have a list/an array of objects and you want to randomly pick one of them. The implementation for this is simple, as shown below.
Java implementation
The RandomPicker class takes as argument for its constructor a list/an array of objects of the generic type T. Afterwards, it can be used to randomly pick one element from the list using the pick method. It uses the Random class included in the java.util package to generate a pseudorandom index of the list, which represents the index of the item in the list that is picked.
Here is the RandomPicker class:
Here is an example of how it is used:
You can try running the above example multiple times to see that the element picked is not always the same.
Conclusion
The RandomPicker class can be easily translated to other programming languages. It is not common to be in need of such a class, but it might be useful to someone.
That's all. Let me know of any questions.
No comments:
Post a Comment