Math Rand V2 Seeded Deterministic Random

Seed math/rand/v2 with NewPCG for reproducible rolls and shuffles, and fall back to auto-seeded package functions when determinism is not required.

GoData Integrity

Code

gosnippet
24 lines
package main

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

func main() {
	// 显式播种:同样的 PCG 种子每次运行产生逐位一致的序列
	rng := rand.New(rand.NewPCG(42, 1024))

	fmt.Println("three rolls:", rng.IntN(6)+1, rng.IntN(6)+1, rng.IntN(6)+1)
	fmt.Printf("unit float: %.4f\n", rng.Float64())

	// Shuffle 原地打乱,交换逻辑由调用方提供
	rooms := []string{"api", "web", "jobs"}
	rng.Shuffle(len(rooms), func(i, j int) {
		rooms[i], rooms[j] = rooms[j], rooms[i]
	})
	fmt.Println("shuffled:", rooms)

	// 包级函数自动播种:对复现性没有要求的场合直接用
	fmt.Println("global IntN:", rand.IntN(100))
}

Execution shape

Math Rand V2 Seeded Deterministic Random is built around the function main.

Applying it

Look for the three rolls:, unit float:, shuffled: prefixes when the file runs; they tie each line to its step.

Statements that matter

rooms := []string{"api", "web", "jobs"}

Interactive Tools for This Topic

FAQ

What does Math Rand V2 Seeded Deterministic Random print when run?
The script runs standalone; its 4 labeled outputs include `three rolls:`, `unit float:`, `shuffled:`.