...
Run Format

Source file src/math/rand/example_test.go

Documentation: math/rand

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rand_test
     6  
     7  import (
     8  	"fmt"
     9  	"math/rand"
    10  	"os"
    11  	"strings"
    12  	"text/tabwriter"
    13  )
    14  
    15  // These tests serve as an example but also make sure we don't change
    16  // the output of the random number generator when given a fixed seed.
    17  
    18  func Example() {
    19  	rand.Seed(42) // Try changing this number!
    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  	// Output: Magic 8-Ball says: As I see it yes
    44  }
    45  
    46  // This example shows the use of each of the methods on a *Rand.
    47  // The use of the global functions is the same, without the receiver.
    48  func Example_rand() {
    49  	// Create and seed the generator.
    50  	// Typically a non-fixed seed should be used, such as time.Now().UnixNano().
    51  	// Using a fixed seed will produce the same output on every run.
    52  	r := rand.New(rand.NewSource(99))
    53  
    54  	// The tabwriter here helps us generate aligned output.
    55  	w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
    56  	defer w.Flush()
    57  	show := func(name string, v1, v2, v3 interface{}) {
    58  		fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
    59  	}
    60  
    61  	// Float32 and Float64 values are in [0, 1).
    62  	show("Float32", r.Float32(), r.Float32(), r.Float32())
    63  	show("Float64", r.Float64(), r.Float64(), r.Float64())
    64  
    65  	// ExpFloat64 values have an average of 1 but decay exponentially.
    66  	show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
    67  
    68  	// NormFloat64 values have an average of 0 and a standard deviation of 1.
    69  	show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
    70  
    71  	// Int31, Int63, and Uint32 generate values of the given width.
    72  	// The Int method (not shown) is like either Int31 or Int63
    73  	// depending on the size of 'int'.
    74  	show("Int31", r.Int31(), r.Int31(), r.Int31())
    75  	show("Int63", r.Int63(), r.Int63(), r.Int63())
    76  	show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
    77  
    78  	// Intn, Int31n, and Int63n limit their output to be < n.
    79  	// They do so more carefully than using r.Int()%n.
    80  	show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10))
    81  	show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10))
    82  	show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10))
    83  
    84  	// Perm generates a random permutation of the numbers [0, n).
    85  	show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
    86  	// Output:
    87  	// Float32     0.2635776           0.6358173           0.6718283
    88  	// Float64     0.628605430454327   0.4504798828572669  0.9562755949377957
    89  	// ExpFloat64  0.3362240648200941  1.4256072328483647  0.24354758816173044
    90  	// NormFloat64 0.17233959114940064 1.577014951434847   0.04259129641113857
    91  	// Int31       1501292890          1486668269          182840835
    92  	// Int63       3546343826724305832 5724354148158589552 5239846799706671610
    93  	// Uint32      2760229429          296659907           1922395059
    94  	// Intn(10)    1                   2                   5
    95  	// Int31n(10)  4                   7                   8
    96  	// Int63n(10)  7                   6                   3
    97  	// Perm        [1 4 2 3 0]         [4 2 1 3 0]         [1 2 4 0 3]
    98  }
    99  
   100  func ExamplePerm() {
   101  	for _, value := range rand.Perm(3) {
   102  		fmt.Println(value)
   103  	}
   104  
   105  	// Unordered output: 1
   106  	// 2
   107  	// 0
   108  }
   109  
   110  func ExampleShuffle() {
   111  	words := strings.Fields("ink runs from the corners of my mouth")
   112  	rand.Shuffle(len(words), func(i, j int) {
   113  		words[i], words[j] = words[j], words[i]
   114  	})
   115  	fmt.Println(words)
   116  
   117  	// Output:
   118  	// [mouth my the of runs corners from ink]
   119  }
   120  
   121  func ExampleShuffle_slicesInUnison() {
   122  	numbers := []byte("12345")
   123  	letters := []byte("ABCDE")
   124  	// Shuffle numbers, swapping corresponding entries in letters at the same time.
   125  	rand.Shuffle(len(numbers), func(i, j int) {
   126  		numbers[i], numbers[j] = numbers[j], numbers[i]
   127  		letters[i], letters[j] = letters[j], letters[i]
   128  	})
   129  	for i := range numbers {
   130  		fmt.Printf("%c: %c\n", letters[i], numbers[i])
   131  	}
   132  
   133  	// Output:
   134  	// C: 3
   135  	// D: 4
   136  	// A: 1
   137  	// E: 5
   138  	// B: 2
   139  }
   140  

View as plain text