# knotkit/sampling

> Draws unbiased subsets, pairs, shuffles, and weighted samples over injected randomness

## Use

```ts
import { splitmix32 } from 'knotkit/prng'
import { sampleIndices, shuffled, weightedChoice } from 'knotkit/sampling'

const random = splitmix32(42)

sampleIndices(random, 10, 3) // three distinct indices in ascending order
shuffled(random, ['a', 'b', 'c']) // a new array; the input is untouched
weightedChoice(random, [1, 2, 0]) // index 0 or 1; never 2
```

```ts
import { splitmix32 } from 'knotkit/prng'
import { reservoirSampler } from 'knotkit/sampling'

const sampler = reservoirSampler<number>(splitmix32(42), 3)
sampler.addAll([1, 2, 3, 4, 5])
sampler.snapshot() // three of the five values, each retained with probability 3/5
```

## What it solves

* pick k distinct items from a population or an index range without shuffling the whole population
* shuffle a copy of a list reproducibly, so a rerun from the same seed yields the same order
* pick one item in proportion to its weight, or k items in proportion to their weights without replacement
* keep a bounded uniform sample of a stream whose length is not known in advance
* pick two distinct items, optionally at least a minimum number of positions apart
* replay a simulation or a generated test fixture exactly from a recorded seed

## Try it

Seed4242Draws4,0004000Reset

* 4,000 weighted choices with seed 42 and weights \[1, 2, 7, 0].
* Observed picks per item: 397, 828, 2775, 0.
* The zero-weight item is ineligible. Each call draws one item independently.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/sampling/demo.ts) against `knotkit/sampling` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                                | Returns                     | Does                                                                                                                                                                                                                       |
| ----------------------------------------------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`sampleIndices`](/reference/knotkit/sampling/functions/sampleindices/)                               | `readonly number[]`         | Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation.                                                                                     |
| [`samplePair`](/reference/knotkit/sampling/functions/samplepair/)                                     | `readonly [number, number]` | Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space.                                                                                                  |
| [`sampleConstrainedPair`](/reference/knotkit/sampling/functions/sampleconstrainedpair/)               | `readonly [number, number]` | Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.                                                            |
| [`shuffled`](/reference/knotkit/sampling/functions/shuffled/)                                         | `readonly T[]`              | Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched.                                                                                                                       |
| [`weightedChoice`](/reference/knotkit/sampling/functions/weightedchoice/)                             | `number`                    | One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.                                                                  |
| [`weightedSample`](/reference/knotkit/sampling/functions/weightedsample/)                             | `readonly number[]`         | k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.                                        |
| [`weightedSampleFromLogWeights`](/reference/knotkit/sampling/functions/weightedsamplefromlogweights/) | `readonly number[]`         | The same k indices without replacement taken from log-weights directly, skipping \`Math.exp\`, so a log-weight of \`-800\` stays eligible and \`-Infinity\` marks an entry as unreachable; O(n log k) time and O(k) space. |
| [`reservoirSampler`](/reference/knotkit/sampling/functions/reservoirsampler/)                         | `ReservoirSampler<T>`       | Vitter's Algorithm R over a stream: fills the first \`capacity\` values, then retains the n-th with probability \`capacity / n\`. \`add\` throws \`STREAM_LIMIT_EXCEEDED\` once 2^32 values have been observed.            |

Cost per member. Open a row for every operation.

`reservoirSampler` 4 members

| Member      | Cost           |
| ----------- | -------------- |
| `add`       | O(1) amortized |
| `addAll`    | O(1) per value |
| `seenCount` | O(1)           |
| `snapshot`  | O(capacity)    |

## What you pass in

| Input                                                                                                        | Type           | Get one from                     |
| ------------------------------------------------------------------------------------------------------------ | -------------- | -------------------------------- |
| randomness, consumed once per draw and never created or owned; the same source state replays the same sample | `RandomSource` | [`knotkit/prng`](/modules/prng/) |

## Errors

Every error this module throws is `SamplingInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `SamplingInvalidInputError`

  `INVALID_POPULATION_SIZE` `INVALID_SAMPLE_SIZE` `INVALID_RANGE` `INVALID_GAP` `INVALID_WEIGHT` `INVALID_LOG_WEIGHT` `ZERO_TOTAL_WEIGHT` `INSUFFICIENT_POSITIVE_WEIGHT` `INVALID_CAPACITY`

* `Other`

  `STREAM_LIMIT_EXCEEDED`

## When not to use it

| If you need to…                                                            | Use instead                                            |
| -------------------------------------------------------------------------- | ------------------------------------------------------ |
| a seeded random source of your own, or the sequence the draws come from    | [`knotkit/prng`](/modules/prng/)                       |
| randomness an attacker must not be able to predict                         | crypto.getRandomValues                                 |
| sample with replacement                                                    | one weighted draw per item over a shared random source |
| keep the drawn items ordered, or evict the weakest of them as more arrive  | [`knotkit/heap`](/modules/heap/)                       |
| estimate how many distinct values a stream held, or how often one occurred | [`knotkit/scalar-sketch`](/modules/scalar-sketch/)     |
| draw from a named distribution                                             | [`knotkit/distribution`](/modules/distribution/)       |
| test whether draws fit a distribution                                      | [`knotkit/hypothesis-test`](/modules/hypothesis-test/) |

## Performance

Measured by the suite in [`packages/sampling/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/sampling/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/samplingCopy prompt

```
Use knotkit/sampling for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/sampling'.

Exports:
- `sampleIndices` → `readonly number[]`: Floyd's uniform subset returned in ascending source order; O(k) expected plus O(k log k) to sort, with no population-sized allocation.
- `samplePair` → `readonly [number, number]`: Two distinct indices in ascending order, drawn as a two-item subset offset into the requested range; O(1) time and space.
- `sampleConstrainedPair` → `readonly [number, number]`: Two ascending indices whose gap lies inside the requested inclusive interval, each valid pair equally likely; one draw plus a binary search over the pair rank.
- `shuffled` → `readonly T[]`: Fisher-Yates permutation of a copy; O(n) time and O(n) space, and the input array is left untouched.
- `weightedChoice` → `number`: One index placed across cumulative intervals proportional to the weights, scaled by the largest weight so the sum stays finite; O(n) time and O(1) space.
- `weightedSample` → `readonly number[]`: k indices without replacement by Efraimidis-Spirakis logarithmic keys in a bounded min queue, one draw per eligible entry, ties to the lower index; O(n log k) time and O(k) space.
- `weightedSampleFromLogWeights` → `readonly number[]`: The same k indices without replacement taken from log-weights directly, skipping `Math.exp`, so a log-weight of `-800` stays eligible and `-Infinity` marks an entry as unreachable; O(n log k) time and O(k) space.
- `reservoirSampler` → `ReservoirSampler<T>`: Vitter's Algorithm R over a stream: fills the first `capacity` values, then retains the n-th with probability `capacity / n`. `add` throws `STREAM_LIMIT_EXCEEDED` once 2^32 values have been observed.

Inputs and their sources:
- randomness, consumed once per draw and never created or owned; the same source state replays the same sample: `RandomSource` from `knotkit/prng`

Use something else when:
- a seeded random source of your own, or the sequence the draws come from → knotkit/prng
- randomness an attacker must not be able to predict → crypto.getRandomValues
- sample with replacement → one weighted draw per item over a shared random source
- keep the drawn items ordered, or evict the weakest of them as more arrive → knotkit/heap
- estimate how many distinct values a stream held, or how often one occurred → knotkit/scalar-sketch
- draw from a named distribution → knotkit/distribution
- test whether draws fit a distribution → knotkit/hypothesis-test

Errors are SamplingInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/sampling.md
Types: node_modules/knotkit/sampling/ and https://knotkit.jkomyno.dev/reference/knotkit/sampling/
```

## See also

* [API reference](/reference/knotkit/sampling/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/sampling/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/sampling/knotkit.capability.json)suggest a change to the source record
