diff options
author | claw0ry <me@claw0ry.net> | 2024-12-11 13:56:52 +0100 |
---|---|---|
committer | claw0ry <me@claw0ry.net> | 2024-12-11 13:56:52 +0100 |
commit | 4719cc03837490ed4bf1b9725d75a686e56e5a6a (patch) | |
tree | 769dd3a3a87153df049b3043196bd131495b10ad /content/posts/golang-generate-random-numbers.md |
fresh start
Diffstat (limited to 'content/posts/golang-generate-random-numbers.md')
-rw-r--r-- | content/posts/golang-generate-random-numbers.md | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/content/posts/golang-generate-random-numbers.md b/content/posts/golang-generate-random-numbers.md new file mode 100644 index 0000000..88ab942 --- /dev/null +++ b/content/posts/golang-generate-random-numbers.md @@ -0,0 +1,53 @@ +--- +title: 'Golang: Generate Random Numbers' +description: "Here's how to generate pseudorandom numbers in Go between to values. NOTE: You should always seed your random generator, or else it will produce the same result every time." +date: 2021-08-13T11:18:04+02:00 +tags: ['go', 'golang'] +draft: false +--- + +Here's how to generate pseudorandom numbers in Go between to values. NOTE: You should always seed your random generator, or else it will produce the same result every time. Include this snippet at the top of your main func. + +<!--more--> + +```golang +func main() { + rand.Seed(time.Now().UnixNano()) + + // ... +} +``` + +## Generate a random int between two values + +This example returns a random integer between min and max, where min is inclusive and max is exclusive. + +```golang +func getRandomInt(min, max int) int { + return rand.Intn(max-min) + min +} + +// example +for i := 0; i < 5; i += 1 { + fmt.Printf("%d ", getRandomInt(5, 10)) +} + +// output: 8 9 7 6 9 +``` + +## Generate a random int between two values (inclusive) + +This example returns a random integer between min and max, where both min and max is inclusive. + +```golang +func getRandomIntInclusive(min, max int) int { + return rand.Intn((max - min + 1)) + min +} + +// example +for i := 1; i <= 5; i += 1 { + fmt.Printf("%d ", getRandomIntInclusive(5, 10)) +} + +// output: 10 5 6 9 9 +``` |