Golang : Roll the dice example
Tags : golang rolling-dice random-digit integer
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.
Here you go!
package main
import (
"fmt"
"math/rand"
"time"
)
func rollDice() int {
// prepare the dice
dice := []int{1, 2, 3, 4, 5, 6}
rand.Seed(time.Now().UnixNano())
return dice[rand.Intn(len(dice)-1)]
}
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: 2
Dice 2: 2
Dice 3: 2
Dice 1: 5
Dice 2: 1
Dice 3: 3
Happy coding!
See also : Golang : Scramble and unscramble text message by randomly replacing words
Tags : golang rolling-dice random-digit integer
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.