Sample was added in ce7c277, however there are several problematic things:
- as of go1.18, compiler can't allocate the result on the stack, even when
Sample was inline and the k is constant (!); see:
- the map is not reused between different calls
- however, placing it into
Rand increases its size, and introduces a pointer in a previously pointer-free struct
- Floyd's sampling algorithm does not guarantee random order, so people are required to read the docs and don't forget to
Shuffle if required
- potential
PartialShuffle is much faster and guarantees random order (although it requires mutable slice of size n)
- having all 4 of
Perm, Sample, PartialShuffle and Shuffle is maybe too much
On the other hand, Sample runs in O(k) for both time and memory. Also, algorithm is simple but non-obvious (a bit like Shuffle), as is the linear-search-instead-of-map optimization.
Also, with #1, Sample may be not required at all.
Samplewas added in ce7c277, however there are several problematic things:Samplewas inline and thekis constant (!); see:PermRandincreases its size, and introduces a pointer in a previously pointer-free structShuffleif requiredPartialShuffleis much faster and guarantees random order (although it requires mutable slice of sizen)Perm,Sample,PartialShuffleandShuffleis maybe too muchOn the other hand,
Sampleruns in O(k) for both time and memory. Also, algorithm is simple but non-obvious (a bit likeShuffle), as is the linear-search-instead-of-map optimization.Also, with #1,
Samplemay be not required at all.