In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how go language generates random numbers and random strings, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Generate random number
The generation of random numbers is not only a research field of computer science, but also an art. This is because computers are purely logical machines, so it is extremely difficult to use computers to generate random numbers!
You can use math/rand packages to generate random numbers. Before you start to generate random numbers, you need a seed, which is used for initialization of the whole process, which is very important. Because if you initialize with the same seed every time, you will always get the same sequence of random numbers. This means that everyone can regenerate the same sequence, so the sequence can no longer be regarded as random at all!
The program we will use to generate random numbers is called randomNumbers.go, which is divided into four parts. This program requires several parameters, namely, the lower limit of the generated random number, the upper limit of the generated random number, and the number of generated random numbers. If you also use the fourth command argument, the program will use it as the seed of the random number generator. When testing, you can use this parameter to generate the same sequence again.
The first part of the program is as follows:
Package mainimport ("fmt"math/rand"os"strconv"time") func random (min, max int) int {return rand.Intn (max-min) + min}
The random () function does all the work, generating random numbers by calling rand.Intn () based on the specified range.
The second part of the command line program is as follows:
Func main () {MIN: = 0 MAX: = 100TOTAL: = 100SEED: = time.Now () .Unix () arguments: = os.Args
This section initializes the variables that will be used in the program.
The third part of the randomNumbers.go contains the following Go code:
Switch len (arguments) {case 2: fmt.Println ("Usage:. / randomNumbers MIN MAX TOTAL SEED") MIN, _ = strconv.Atoi (arguments [1]) MAX = MIN + 100 case 3: fmt.Println ("Usage:. / randomNumbers MIN MAX TOTAL SEED") MIN, _ = strconv.Atoi (arguments [1]) MAX _ = strconv.Atoi (arguments [2]) case 4: fmt.Println ("Usage:. / randomNumbers MIN MAX TOTAL SEED") MIN, _ = strconv.Atoi (arguments [1]) MAX, _ = strconv.Atoi (arguments [2]) TOTAL, _ = strconv.Atoi (arguments [3]) case 5: MIN, _ = strconv.Atoi (arguments [1]) MAX _ = strconv.Atoi (arguments [2]) TOTAL, _ = strconv.Atoi (arguments [3]) SEED, _ = strconv.ParseInt (arguments [4], 10,64) default: fmt.Println ("Using default values!")}
The logic behind the switch code block is relatively simple: depending on the number of command-line arguments, determine whether the parameters in the program use the default default or user-supplied values. To simplify the program, the error parameters returned by the strconv.Atoi () and strconv.ParseInt () functions are received using underscore characters and then ignored. If it is a business program, you must not ignore the error parameters returned by the strconv.Atoi () and strconv.ParseInt () functions!
Finally, you use strconv.ParseInt () to assign a new value to the SEED variable because the parameter type required by the rand.Seed () function is int64. The first argument to strconv.ParseInt () is the string to be parsed, the second is the cardinality of the output, and the third is the number of digits of the output. Since we want to generate a 64-bit decimal integer, we use 10 as the cardinality and 64 as the number of digits. Note that you should use the strconv.ParseUint () function instead if you want to parse unsigned integers.
The last part of randomNumbers.go is the following Go code:
Rand.Seed (SEED) for I: = 0; I
< TOTAL; i++ { myrand := random(MIN, MAX) fmt.Print(myrand) fmt.Print(" ") } fmt.Println()} 除了使用 Unix 时间戳作为随机数生成器的种子,你还可以使用 /dev/random 这个系统设备。你可以在第 8 章"Go Unix系统编程"中了解 /dev/random 的相关内容。 执行 randomNumbers.go 将会生成如下输出: $ go run randomNumbers.go75 69 15 75 62 67 64 8 73 1 83 92 7 34 8 70 22 58 38 8 54 91 65 1 50 76 5 82 61 90 10 38 40 63 6 28 51 54 49 27 52 92 76 35 44 9 66 76 90 10 29 22 20 83 33 92 80 50 62 26 19 45 56 75 40 30 97 23 87 10 43 11 42 65 80 82 25 53 27 51 99 88 53 36 37 73 52 61 4 81 71 57 30 72 51 55 62 63 79$ go run randomNumbers.go 1 3 2Usage: ./randomNumbers MIN MAX TOTAL SEED1 1 $ go run randomNumbers.go 1 3 2Usage: ./randomNumbers MIN MAX TOTAL SEED2 2$ go run randomNumbers.go 1 5 10 103 1 4 4 1 1 4 4 4 3$ go run randomNumbers.go 1 5 10 103 1 4 4 1 1 4 4 4 3 如果你对随机数生成真的很有兴趣,那么你应该先读一下 Donald E.Knuth 写的 The Art of Computer Programming (Addison-Wesley Professional, 2011) 的第二卷。 如果需要用 Go 生成更安全的随机数的话,你可以使用 crypto/rand 包。这个包中实现了满足密码学安全的伪随机数生成器。你可以在 https://golang.org/pkg/crypto/rand/ 文档页面了解更多关于 crypto/rand 包的信息。 生成随机字符串 一旦你知道了计算机是如何呈现出单个字符,从随机数过渡到随机字符串就不难了。这一节将会介绍如何使用前一节中 randomNumbers.go 的代码生成难以猜出的密码。用于完成这个任务的 Go 程序叫做 generatePassword.go,下面将分四个部分进行介绍。这个程序只需要一个命令行参数,就是你需要生成的密码的长度。 generatePassword.go 的第一部分包含如下的 Go 代码: package mainimport ( "fmt" "math/rand" "os" "strconv" "time")func random(min, max int) int { return rand.Intn(max-min) + min} generatePassword.go 的第二个代码段如下: func main() { MIN := 0 MAX := 94 SEED := time.Now().Unix() var LENGTH int64 = 8 arguments := os.Arg 我们只想得到可打印的 ASCII 字符,所以对生成随机数的范围进行了限制。ASCII 字符表中可打印的字符一共有 94 个。这意味着该程序生成的随机数的范围应该是从 0 到 94 且不包括 94。 generatePassword.go 的第三个代码段如下: switch len(arguments) { case 2: LENGTH, _ = strconv.ParseInt(os.Args[1], 10, 64) default: fmt.Println("Using default values!") } rand.Seed(SEED) generatePassword.go 的最后一部分如下: startChar := "!" var i int64 = 1 for { myRand := random(MIN, MAX) newChar := string(startChar[0] + byte(myRand)) fmt.Print(newChar) if i == LENGTH { break } i++ } fmt.Println()} startChar 参数保存了这个程序可以生成的第一个 ASCII 字符,也就是十进制 ASCII 值为 33 的感叹号。已知该程序生成的随机数小于 94,可以计算出生成的最大的 ASCII 值为 93 + 33,等于 126,也就是 ~ 的 ASCII 值。下面的输出是含有十进制数值的 ASCII 字符表: The decimal set: 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 56 8 57 9 58 : 59 ; 60 < 61 = 62 >63?
64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G
72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O
80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W
88 X 89 Y 90 Z 91 [92\ 93] 94 ^ 95 _
96 `97 a 98 b 99 c 100 d 101 e 102 f 103 g
104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o
112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w
120 x 121 y 122 z 123 {124 | 125} 126-127 del
Type man ascii into your favorite Unix shell to generate an easy-to-read ASCII character table.
Executing generatePassword.go and passing in the appropriate command line arguments will produce the following output:
$go run generatePassword.goUsing default valuesgenerating ugswords 5mv1 $go run generatePassword.goUsing default valuesworth PAUniplash 8hA numbers $go run generatePassword.go 20HBR+=3\ UA'B@ExT4QG | o $go run generatePassword.go 20XLcr | R {* pX/::' t2u ^ T'is all the contents of the article "how to generate random numbers and random strings in go language". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.