Source file src/math/rand/v2/example_test.go

     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/v2"
    10  	"os"
    11  	"strings"
    12  	"text/tabwriter"
    13  	"time"
    14  )
    15  
    16  // These tests serve as an example but also make sure we don't change
    17  // the output of the random number generator when given a fixed seed.
    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  // This example shows the use of each of the methods on a *Rand.
    46  // The use of the global functions is the same, without the receiver.
    47  func Example_rand() {
    48  	// Create and seed the generator.
    49  	// Typically a non-fixed seed should be used, such as Uint64(), Uint64().
    50  	// Using a fixed seed will produce the same output on every run.
    51  	r := rand.New(rand.NewPCG(1, 2))
    52  
    53  	// The tabwriter here helps us generate aligned output.
    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  	// Float32 and Float64 values are in [0, 1).
    61  	show("Float32", r.Float32(), r.Float32(), r.Float32())
    62  	show("Float64", r.Float64(), r.Float64(), r.Float64())
    63  
    64  	// ExpFloat64 values have an average of 1 but decay exponentially.
    65  	show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
    66  
    67  	// NormFloat64 values have an average of 0 and a standard deviation of 1.
    68  	show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
    69  
    70  	// Int32, Int64, and Uint32 generate values of the given width.
    71  	// The Int method (not shown) is like either Int32 or Int64
    72  	// depending on the size of 'int'.
    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  	// IntN, Int32N, and Int64N limit their output to be < n.
    78  	// They do so more carefully than using r.Int()%n.
    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  	// Perm generates a random permutation of the numbers [0, n).
    84  	show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
    85  	// Output:
    86  	// Float32     0.95955694          0.8076733            0.8135684
    87  	// Float64     0.4297927436037299  0.797802349388613    0.3883664855410056
    88  	// ExpFloat64  0.43463410545541104 0.5513632046504593   0.7426404617374481
    89  	// NormFloat64 -0.9303318111676635 -0.04750789419852852 0.22248301107582735
    90  	// Int32       2020777787          260808523            851126509
    91  	// Int64       5231057920893523323 4257872588489500903  158397175702351138
    92  	// Uint32      314478343           1418758728           208955345
    93  	// IntN(10)    6                   2                    0
    94  	// Int32N(10)  3                   7                    7
    95  	// Int64N(10)  8                   9                    4
    96  	// Perm        [0 3 1 4 2]         [4 1 2 0 3]          [4 3 2 0 1]
    97  }
    98  
    99  func ExamplePerm() {
   100  	for _, value := range rand.Perm(3) {
   101  		fmt.Println(value)
   102  	}
   103  
   104  	// Unordered output: 1
   105  	// 2
   106  	// 0
   107  }
   108  
   109  func ExampleN() {
   110  	// Print an int64 in the half-open interval [0, 100).
   111  	fmt.Println(rand.N(int64(100)))
   112  
   113  	// Sleep for a random duration between 0 and 100 milliseconds.
   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  	// Shuffle numbers, swapping corresponding entries in letters at the same time.
   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