Debian Codegraph @

docs/content/en/functions/collections/D.md

raw
1 ---
2 title: collections.D
3 description: Returns a sorted slice of unique random integers based on a given seed, count, and maximum value.
4 categories: []
5 keywords: [random]
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: '[]int'
10 signatures: [collections.D SEED N HIGH]
11 ---
12
13 {{< new-in 0.149.0 />}}
14
15 The `collections.D` function returns a sorted slice of unique random integers in the half-open [interval](g) `[0, HIGH)` using the provided [`SEED`](g) value. The number of elements in the resulting slice is `N` or `HIGH`, whichever is less.
16
17 - `N` and `H` must be integers in the closed interval `[0, 1000000]`
18 - `SEED` must be an integer in the closed interval `[0, 2^64 - 1]`
19
20 ## Return values
21
22 Condition|Return value
23 :--|:--|:--
24 `N <= HIGH`|A sorted random sample of size `N` using J. S. Vitter's [Method D][] for sequential random sampling
25 `N > HIGH`|The full, sorted range `[0, HIGH)` of size `HIGH`
26 `N == 0`|An empty slice
27 `N < 0`|Error
28 `N > 10^6`|Error
29 `HIGH == 0`|An empty slice
30 `HIGH < 0`|Error
31 `HIGH > 10^6`|Error
32 `SEED < 0`|Error
33 {.no-wrap-first-col}
34
35 ## Examples
36
37 ```go-html-template
38 {{ collections.D 6 7 42 }} → [4, 9, 10, 20, 22, 24, 41]
39 ```
40
41 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.
42
43 ```go-html-template
44 {{ collections.D 2 7 42 }} → [3, 11, 19, 25, 32, 33, 38]
45 ```
46
47 When `N` is greater than `HIGH`, this function returns the full, sorted range [0, `HIGH`) of size `HIGH`:
48
49 ```go-html-template
50 {{ collections.D 6 42 7 }} → [0 1 2 3 4 5 6]
51 ```
52
53 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:
54
55 ```go-html-template
56 <ul>
57 {{ $p := site.RegularPages }}
58 {{ range collections.D time.Now.YearDay 5 ($p | len) }}
59 {{ with (index $p .) }}
60 <li><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></li>
61 {{ end }}
62 {{ end }}
63 </ul>
64 ```
65
66 The construct above is significantly faster than using the [`collections.Shuffle`][] function.
67
68 ## Seed value
69
70 Choosing an appropriate seed value depends on your objective.
71
72 Objective|Seed example
73 :--|:--
74 Consistent result|`42`
75 Different result on each call|`int time.Now.UnixNano`
76 Same result per day|`time.Now.YearDay`
77 Same result per page|`hash.FNV32a .Path`
78 Different result per page per day|`hash.FNV32a (print .Path time.Now.YearDay)`
79
80 [Method D]: https://getkerf.wordpress.com/2016/03/30/the-best-algorithm-no-one-knows-about/
81 [`collections.Shuffle`]: /functions/collections/shuffle/
82 [day of the year]: /methods/time/yearday/