Choose random winner based on weight

Evan Hahn wrote a nice JavaScript function to determine a random winner from a group of weighted items.

One real-world application scenario I immediately thought could use this is a draft lottery in sports.

Background

If you’re familiar with the NBA, consider how they conduct a draft lottery at the end of every season. The concept is simple: the lower-placed finishers have more draft “weight” than higher-placed finishers. So, the first-place team is less likely to draft near the top, while the last-place team(s) have a greater chance of getting the top pick. The idea is to balance the flow of talent amongst all teams.

The NBA draft lottery involves a random drawing of ping-pong balls from a large container. The order of team draft positions is then decided using a reverse-weighted system. Lower-placed finishers have less ping-pong balls than higher-placed finishers, thus decreasing the odds that a lower-placed finisher will be chosen at random (the less ping-pong balls you have, the less chance you will be picked). Since the draft lottery is conducted in reverse fashion (from the highest-number pick [13] down to the lowest-number pick [1]), the system makes sense and works fairly well.

Our objects

Below I have chosen four random NBA teams, and supplied a “weight” for each. The weight indicates how many ping-pong balls they have for the draft lottery:

[
  {
    "team": "Bulls",
    "weight": 4
  },
  {
    "team": "Magic",
    "weight": 1
  },
  {
    "team": "Bucks",
    "weight": 2
  },
  {
    "team": "Wizards",
    "weight": 1
  }
]

According to this object, the Magic and Wizards have the greatest chance for the number one pick, while the Bucks have the next greatest, then the Bulls with the least opportunity to draft number one.

Code in action

By clicking the button below, you will be pulling a ping-pong ball from the bunch. Test it out and see if it feels accurate. For example, click it four times, and you can reveal the number one pick (the team revealed on the fourth click). In most cases (each set of four clicks), it should be either the Magic or Wizards.

Here is the flow:

  • Click 1: Fourth pick in the draft
  • Click 2: Third pick in the draft
  • Click 3: Second pick in the draft
  • Click 4: First pick in the draft