Golang : Randomly pick an item from a slice/array example
Problem:
You are building a game and you want to randomly pick an item from a slice of URLs. How to pick one item at random?
Solution:
You can either shuffle the items inside the slice and pick the first item or use the code example below.
pickRandomURL.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
URLs := []string{
"http://top-beautiful-women.com/images/1/Japan/Erina%20Mano.jpg",
"http://top-beautiful-women.com/images/1/Japan/Rina%20Uchiyama.jpg",
"http://cdn2.stylecraze.com/wp-content/uploads/2013/06/yui-aragaki.jpg",
"http://cdn2.stylecraze.com/wp-content/uploads/2013/06/rio-yamashita.jpg",
}
// randomly pick one beautiful girl(URL) from the URLs slice
rand.Seed(time.Now().UnixNano())
choosen := URLs[rand.Intn(len(URLs))]
fmt.Println("Randomly selected this URL : ", choosen)
}
Output:
>go run pickRandomURL.go
Randomly selected this URL : http://cdn2.stylecraze.com/wp-content/uploads/2013/06/yui-aragaki.jpg
>go run pickRandomURL.go
Randomly selected this URL : http://top-beautiful-women.com/images/1/Japan/Erina%20Mano.jpg
References:
https://www.socketloop.com/tutorials/golang-how-to-shuffle-elements-in-array-or-slice
See also : Golang : How to shuffle elements in array or slice?
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.2k Golang : Break string into a slice of characters example
+14k Golang : Convert IP version 6 address to integer or decimal number
+18k Golang : How to remove certain lines from a file
+10.5k Golang : Get currencies exchange rates example
+15.9k Golang : Loop each day of the current month example
+7.5k Golang : Example of how to detect which type of script a word belongs to
+15.6k Golang : Update database with GORM example
+8.9k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?
+4.4k JavaScript : Rounding number to decimal formats to display currency
+7.3k SSL : How to check if current certificate is sha1 or sha2 from command line
+5.8k Golang : Grab news article text and use NLP to get each paragraph's sentences