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