| |
| |
| |
|
|
| package rand_test |
|
|
| import ( |
| "fmt" |
| "math/rand/v2" |
| "os" |
| "strings" |
| "text/tabwriter" |
| "time" |
| ) |
|
|
| |
| |
|
|
| func Example() { |
| answers := []string{ |
| "It is certain", |
| "It is decidedly so", |
| "Without a doubt", |
| "Yes definitely", |
| "You may rely on it", |
| "As I see it yes", |
| "Most likely", |
| "Outlook good", |
| "Yes", |
| "Signs point to yes", |
| "Reply hazy try again", |
| "Ask again later", |
| "Better not tell you now", |
| "Cannot predict now", |
| "Concentrate and ask again", |
| "Don't count on it", |
| "My reply is no", |
| "My sources say no", |
| "Outlook not so good", |
| "Very doubtful", |
| } |
| fmt.Println("Magic 8-Ball says:", answers[rand.IntN(len(answers))]) |
| } |
|
|
| |
| |
| func Example_rand() { |
| |
| |
| |
| r := rand.New(rand.NewPCG(1, 2)) |
|
|
| |
| w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0) |
| defer w.Flush() |
| show := func(name string, v1, v2, v3 any) { |
| fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3) |
| } |
|
|
| |
| show("Float32", r.Float32(), r.Float32(), r.Float32()) |
| show("Float64", r.Float64(), r.Float64(), r.Float64()) |
|
|
| |
| show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64()) |
|
|
| |
| show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64()) |
|
|
| |
| |
| |
| show("Int32", r.Int32(), r.Int32(), r.Int32()) |
| show("Int64", r.Int64(), r.Int64(), r.Int64()) |
| show("Uint32", r.Uint32(), r.Uint32(), r.Uint32()) |
|
|
| |
| |
| show("IntN(10)", r.IntN(10), r.IntN(10), r.IntN(10)) |
| show("Int32N(10)", r.Int32N(10), r.Int32N(10), r.Int32N(10)) |
| show("Int64N(10)", r.Int64N(10), r.Int64N(10), r.Int64N(10)) |
|
|
| |
| show("Perm", r.Perm(5), r.Perm(5), r.Perm(5)) |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| } |
|
|
| func ExamplePerm() { |
| for _, value := range rand.Perm(3) { |
| fmt.Println(value) |
| } |
|
|
| |
| |
| |
| } |
|
|
| func ExampleN() { |
| |
| fmt.Println(rand.N(int64(100))) |
|
|
| |
| time.Sleep(rand.N(100 * time.Millisecond)) |
| } |
|
|
| func ExampleShuffle() { |
| words := strings.Fields("ink runs from the corners of my mouth") |
| rand.Shuffle(len(words), func(i, j int) { |
| words[i], words[j] = words[j], words[i] |
| }) |
| fmt.Println(words) |
| } |
|
|
| func ExampleShuffle_slicesInUnison() { |
| numbers := []byte("12345") |
| letters := []byte("ABCDE") |
| |
| rand.Shuffle(len(numbers), func(i, j int) { |
| numbers[i], numbers[j] = numbers[j], numbers[i] |
| letters[i], letters[j] = letters[j], letters[i] |
| }) |
| for i := range numbers { |
| fmt.Printf("%c: %c\n", letters[i], numbers[i]) |
| } |
| } |
|
|
| func ExampleIntN() { |
| fmt.Println(rand.IntN(100)) |
| fmt.Println(rand.IntN(100)) |
| fmt.Println(rand.IntN(100)) |
| } |
|
|