Another interesting use of randomization is for distributing items evenly. This is another example of where randomization is counterintuitively used for the sake of creating order.
Probability theorists like to discuss the concept of putting “balls into bins.” That is, say we have 10 bins (or boxes, if you like) and want to distribute a whole bunch of balls into them evenly. This is easy to do if we know how many balls we have. If we have 1,000 balls, we place 100 balls in each bin. But what if we don’t know how many balls we have? How can we ensure that we distribute them evenly?
In such cases, we can still fill the bins evenly if we use a “round-robin” approach. That is, we rotate through the bins, putting a single ball in each bin. As long as we follow this pattern consistently, the bins will be filled practically evenly.
Now, here’s a question to ponder: what happens if we take each ball, one at a time, and place it in a random bin?
Here’s some code that does this. Here, we treat arrays as “bins” and integers as “balls.” That is, we throw 1,000 integers into 10 different arrays, choosing a random array for each integer:
| | import random |
| | |
| | |
| | bins = [[], [], [], [], [], [], [], [], [], []] |
| | |
| | for ball in range(1000): |
| | bin = bins[random.randint(0, 9)] |
| | bin.append(ball) |
| | |
| | for bin in bins: |
| | print(len(bin)) |
Because we choose the bins randomly, each time I run this code, I get a slightly different result. However, all the results are similar. Here’s one outcome of how many balls each bin contains:
| | 103 |
| | 95 |
| | 101 |
| | 105 |
| | 88 |
| | 91 |
| | 105 |
| | 113 |
| | 106 |
| | 93 |
Whoa. While the balls haven’t been distributed perfectly evenly, it’s surprisingly close.
Because each bin is chosen at random, and each bin is as likely to be chosen as every other bin, the laws of probability dictate that the bins are likely to contain roughly the same number of balls. Probability theorists use math to define how likely this is, but for our purposes, it’s likely enough. This may not be true with a small number of balls relative to the bins, but when we have many more balls than bins, the distribution is pretty uniform. Feel free to play with the code and change the number of “balls”—it’s interesting to see the results.