Shuffle Slices With Seeded rand V2

Reorder slices with rand v2 Shuffle: a seeded PCG rng reproduces the exact permutation across runs while the package-level call shuffles randomly.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"fmt"
	"math/rand/v2"
)

func main() {
	// 固定种子:洗牌结果每次运行完全一致(快照测试/复现必需)
	rng := rand.New(rand.NewPCG(7, 42))
	deck := []string{"alpha", "beta", "gamma", "delta", "epsilon"}
	rng.Shuffle(len(deck), func(i, j int) {
		deck[i], deck[j] = deck[j], deck[i]
	})
	fmt.Println("shuffled:", deck)

	// 包级 rand.Shuffle 用随机种子:两次运行顺序不同
	deck2 := []string{"alpha", "beta", "gamma", "delta", "epsilon"}
	rand.Shuffle(len(deck2), func(i, j int) {
		deck2[i], deck2[j] = deck2[j], deck2[i]
	})
	fmt.Println("random  :", deck2)

	// 洗牌后取前 N 张:不重复抽样
	fmt.Println("top three:", deck[:3])
}

Tracing the steps

Shuffle Slices With Seeded rand V2 is built around the function main.

Putting it to use

Running the file prints labeled results such as shuffled:, random :, top three: — each operation’s effect is visible in the output.

Core lines

deck2 := []string{"alpha", "beta", "gamma", "delta", "epsilon"}

Interactive Tools for This Topic

FAQ

What does Shuffle Slices With Seeded rand V2 print when run?
Execute the whole file; each printed line is prefixed with a label like `shuffled:`, `random :`, `top three:`.