Golang : Roll the dice example
Just a simple example on how to simulate dice rolling. Useful in situation where you need to use random single digit number to ensure different results very time.
UPDATE: The previous code used dice[rand.Intn(len(dice)-1)]
, which caused the dice to never reach the position 6
and also run rand.Seed(time.Now().UnixNano())
multiple times - which is an unnecessary overhead. The code below has been updated to correct the bug and rand.Seed()
function only executes once throughout the duration of this program. Thanks to Patrik Lundin for pointing this out.
Here you go!
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
var onlyOnce sync.Once
// prepare the dice
var dice = []int{1, 2, 3, 4, 5, 6}
func rollDice() int {
onlyOnce.Do(func() {
rand.Seed(time.Now().UnixNano()) // only run once
})
return dice[rand.Intn(len(dice))]
}
func main() {
dice1 := rollDice()
dice2 := rollDice()
dice3 := rollDice()
fmt.Println("Dice 1: ", dice1)
fmt.Println("Dice 2: ", dice2)
fmt.Println("Dice 3: ", dice3)
}
Sample output:
Dice 1: 6
Dice 2: 2
Dice 3: 2
Dice 1: 5
Dice 2: 1
Dice 3: 3
Happy coding!
Reference:
https://www.socketloop.com/tutorials/golang-how-to-run-your-code-only-once-with-sync-once-object
See also : Golang : Scramble and unscramble text message by randomly replacing words
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.5k Golang : Check if password length meet the requirement
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+11.3k Golang : Generate DSA private, public key and PEM files example
+28.7k Golang : Get first few and last few characters from string
+20.1k nginx: [emerg] unknown directive "passenger_enabled"
+6.6k Golang : How to solve "too many .rsrc sections" error?
+7.7k Golang Hello World Example
+19.6k Golang : How to run your code only once with sync.Once object
+12.8k Golang : List objects in AWS S3 bucket
+9.3k Golang : Read file with ioutil
+6.7k Nginx : Password protect a directory/folder
+25.4k Golang : How to write CSV data to file