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.

GoData Integrity

Code

gosnippet
30 lines
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

FAQ

What does Random Sample Without Replacement print when run?
Run it as a complete program — the output lines carry labels such as `winners:`.