|
| 1 | +--- |
| 2 | +title: collections.D |
| 3 | +description: Returns a slice of sequentially ordered random integers. |
| 4 | +categories: [] |
| 5 | +keywords: [random] |
| 6 | +params: |
| 7 | + functions_and_methods: |
| 8 | + returnType: '[]int' |
| 9 | + signatures: [collections.D SEED N HIGH] |
| 10 | +--- |
| 11 | + |
| 12 | +{{< new-in 0.149.0 />}} |
| 13 | + |
| 14 | +The `collections.D` function returns a slice of `N` sequentially ordered unique random integers in the half-open [interval](g) [0, `HIGH`) using the provided `SEED` value. This function implements J. S. Vitter's Method D[^1] for sequential random sampling, a fast and efficient algorithm for this task. |
| 15 | + |
| 16 | +See [this article][] for a detailed explanation. |
| 17 | + |
| 18 | +```go-html-template |
| 19 | +{{ collections.D 6 7 42 }} → [4, 9, 10, 20, 22, 24, 41] |
| 20 | +``` |
| 21 | + |
| 22 | +The example above generates the _same_ random numbers each time it is called. To generate a _different_ set of 7 random numbers in the same range, change the seed value. |
| 23 | + |
| 24 | +```go-html-template |
| 25 | +{{ collections.D 2 7 42 }} → [3, 11, 19, 25, 32, 33, 38] |
| 26 | +``` |
| 27 | + |
| 28 | +> [!note] |
| 29 | +> All arguments are cast to integers, so setting the seed to `3.14` is the same as setting it to `3`. |
| 30 | +
|
| 31 | +A common use case is the selection of random pages from a page collection. For example, to render a list of 5 random pages using the [day of the year][] as the seed value: |
| 32 | + |
| 33 | +```go-html-template |
| 34 | +<ul> |
| 35 | + {{ $p := site.RegularPages }} |
| 36 | + {{ range collections.D now.YearDay 5 ($p | len) }} |
| 37 | + {{ with (index $p .) }} |
| 38 | + <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li> |
| 39 | + {{ end }} |
| 40 | + {{ end }} |
| 41 | +</ul> |
| 42 | +``` |
| 43 | + |
| 44 | +The construct above is significantly faster than using the [`collections.Shuffle`][] function. |
| 45 | + |
| 46 | +> [!note] |
| 47 | +> The slice created by this function is limited to 1 million elements. |
| 48 | +
|
| 49 | +[^1]: J. S. Vitter, "An efficient algorithm for sequential random sampling," _ACM Trans. Math. Soft._, vol. 13, pp. 58–67, Mar. 1987. |
| 50 | + |
| 51 | +[this article]: https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/ |
| 52 | +[`collections.Shuffle`]: /functions/collections/shuffle/ |
| 53 | +[day of the year]: /methods/time/yearday/ |
0 commit comments