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