# weightedChoice

> **weightedChoice**(`random`, `weights`): `number`

Defined in: [packages/sampling/src/weighted-choice.ts:17](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/sampling/src/weighted-choice.ts#L17)

Sample one index proportionally to its finite non-negative weight.

Runs in O(weights.length) time and O(1) auxiliary space. Scaling by the largest weight keeps the cumulative sum finite without changing the distribution. The weights are not mutated.

## Parameters

### random

[`RandomSource`](/reference/knotkit/prng/type-aliases/randomsource/)

### weights

readonly `number`\[]

## Returns

`number`

## Throws

With code `INVALID_WEIGHT` when a weight is negative or non-finite, or `ZERO_TOTAL_WEIGHT` when the array is empty or contains no positive weight.

## Throws

With code `INVALID_SOURCE_VALUE` when the random source returns a value outside `[0, 1)`.
