**Weighted Random Distribution**

for AutoHotkey v1.1 (Original article - Thanks Ferry Boender)

**Preface**

Randomly selecting elements from a set of items is easy. Just generate a random number between 0 and the length of the set minus one, and use that as an index in the set [if it is an array] to get a random entry. The chance that an entry is picked is the same for each entry in the set. This is called even distribution or uniform distribution.

But what if we do not want each entry to appear as much as every other? Suppose we’re creating a question-answer game, and we want the questions the user got wrong previously to appear more often than the question he or she got right? This is called a Weighted Random Distribution, or sometimes Weighted Random Choice, and there are multiple methods of implementing such as random picker.

This article explains these various methods of implementing Weighted Random Distribution along with their pros and cons. We use AutoHotkey as our language of choice, because it has an easy to read syntax, and provides many useful tools which would take many more lines of code in most other languages. Along the way all AutoHotkey “tricks” will be explained.

The latest version of original article is always available here in PDF, HTML and AsciiDoc format.

**Methods**

In each of the methods below, we assume a default set of choices and weights which we’ll need to make random selections from. When I say “set”, I don’t mean a AutoHotkey set, which is basically an immutable array which does not allow duplicate values, but a collection of choices with their associated weight.

We assume we have the following dictionary [Jargon for an associative array, also known as a hashmap] of choices with their weights:

Code: Select all

`w:= {"A": 2, "B": 4, "C": 3, "D": 1}`