Source file
src/math/rand/v2/example_test.go
1
2
3
4
5 package rand_test
6
7 import (
8 "fmt"
9 "math/rand/v2"
10 "os"
11 "strings"
12 "text/tabwriter"
13 "time"
14 )
15
16
17
18
19 func Example() {
20 answers := []string{
21 "It is certain",
22 "It is decidedly so",
23 "Without a doubt",
24 "Yes definitely",
25 "You may rely on it",
26 "As I see it yes",
27 "Most likely",
28 "Outlook good",
29 "Yes",
30 "Signs point to yes",
31 "Reply hazy try again",
32 "Ask again later",
33 "Better not tell you now",
34 "Cannot predict now",
35 "Concentrate and ask again",
36 "Don't count on it",
37 "My reply is no",
38 "My sources say no",
39 "Outlook not so good",
40 "Very doubtful",
41 }
42 fmt.Println("Magic 8-Ball says:", answers[rand.IntN(len(answers))])
43 }
44
45
46
47 func Example_rand() {
48
49
50
51 r := rand.New(rand.NewPCG(1, 2))
52
53
54 w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
55 defer w.Flush()
56 show := func(name string, v1, v2, v3 any) {
57 fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
58 }
59
60
61 show("Float32", r.Float32(), r.Float32(), r.Float32())
62 show("Float64", r.Float64(), r.Float64(), r.Float64())
63
64
65 show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
66
67
68 show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
69
70
71
72
73 show("Int32", r.Int32(), r.Int32(), r.Int32())
74 show("Int64", r.Int64(), r.Int64(), r.Int64())
75 show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
76
77
78
79 show("IntN(10)", r.IntN(10), r.IntN(10), r.IntN(10))
80 show("Int32N(10)", r.Int32N(10), r.Int32N(10), r.Int32N(10))
81 show("Int64N(10)", r.Int64N(10), r.Int64N(10), r.Int64N(10))
82
83
84 show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
85
86
87
88
89
90
91
92
93
94
95
96
97 }
98
99 func ExamplePerm() {
100 for _, value := range rand.Perm(3) {
101 fmt.Println(value)
102 }
103
104
105
106
107 }
108
109 func ExampleN() {
110
111 fmt.Println(rand.N(int64(100)))
112
113
114 time.Sleep(rand.N(100 * time.Millisecond))
115 }
116
117 func ExampleShuffle() {
118 words := strings.Fields("ink runs from the corners of my mouth")
119 rand.Shuffle(len(words), func(i, j int) {
120 words[i], words[j] = words[j], words[i]
121 })
122 fmt.Println(words)
123 }
124
125 func ExampleShuffle_slicesInUnison() {
126 numbers := []byte("12345")
127 letters := []byte("ABCDE")
128
129 rand.Shuffle(len(numbers), func(i, j int) {
130 numbers[i], numbers[j] = numbers[j], numbers[i]
131 letters[i], letters[j] = letters[j], letters[i]
132 })
133 for i := range numbers {
134 fmt.Printf("%c: %c\n", letters[i], numbers[i])
135 }
136 }
137
138 func ExampleIntN() {
139 fmt.Println(rand.IntN(100))
140 fmt.Println(rand.IntN(100))
141 fmt.Println(rand.IntN(100))
142 }
143
View as plain text