DEV Community

Ariel Davis
Ariel Davis

Posted on

Simple Weighted Random Number

Flatiron Student

I am currently on my 6th week at Flatiron School and I've it has been a roller coaster for sure. It is project week for us and a problem that I was facing in my project was working with probability. Now probability when working with Ruby (or from my research ANY language) can be either simple..or complicated enough to make you want to throw your laptop..needless to say..I almost threw my laptop.

Simple Stupid

I want to share with you my simple way to work with weighted random numbers (probability). Now as a disclaimer this is NOT THE MOST EFFICIENT METHOD TO WORKING WITH WEIGHTED RANDOM NUMBERS. This post is for a simple solution that has limited application.

More Than One Means

The basis of this solution to working with weighted probability is the following:
The more the are, the more likely it will get picked
If I had the following array:
arr = ["test1", "test2", "test1", "test1"]
and were to run the following method:
arr.sample
There would be a greater chance that test1 will be chosen from the .sample method.

Not DRY at all

This can lead to a lot of repetition in your code so to be honest I'd stay away from using something like this unless you were:

  • Working with a very small amount of data

That's it. Don't use this unless you're working with a small amount of data.

I will definitely continue to do more research in working with this and come back with a more advance way of working with weighted probability and make it as understanding as I can. Until then..

Top comments (0)