Random Sample Without Replacement
Draw unique items with rand/v2 Perm indexing into the pool, then validate coverage by counting distinct winners across repeated seeded runs.
Code
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
staff := []string{"ana", "bob", "cid", "dee", "eli"}
// 固定种子:抽样结果逐次运行完全一致
rng := rand.New(rand.NewPCG(2026, 11))
// Perm 生成 0..n-1 的无重复排列:取前 k 个即不重复抽样
pick := rng.Perm(len(staff))
winners := make([]string, 0, 3)
for _, idx := range pick[:3] {
winners = append(winners, staff[idx])
}
fmt.Println("winners:", winners)
// 复核无重复:map 计数,抽中次数都应为 1
counts := map[string]int{}
for _, name := range winners {
counts[name]++
}
for name, n := range counts {
fmt.Println(name, "picked", n, "time(s)")
}
}Inside the snippet
Random Sample Without Replacement reduces to the function main.
Repetition is confined to for _, idx := range pick[:3] — the rest of the file is straight-line.
Using it
The demo output is labeled (winners:), so every printed line maps back to its originating operation.
Key statements
for _, idx := range pick[:3] {
winners = append(winners, staff[idx])
}
for _, name := range winners {
counts[name]++
}
for name, n := range counts {
fmt.Println(name, "picked", n, "time(s)")
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.Passphrase GeneratorGenerate memorable multi-word passphrases from a fixed 150-word list with crypto randomness, separators, and capitalization options.
FAQ
- What does Random Sample Without Replacement print when run?
- Run it as a complete program — the output lines carry labels such as `winners:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.