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
+8.8k Golang : Generate EAN barcode
+11.1k Golang : Fuzzy string search or approximate string matching example
+13.6k Javascript : Prompt confirmation before exit
+21.6k Golang : How to run Golang application such as web server in the background or as daemon?
+40.4k Golang : How to count duplicate items in slice/array?
+6k PHP : Proper way to get UTF-8 character or string length
+16.4k Golang : Get own process identifier
+6k Unix/Linux : Use netstat to find out IP addresses served by your website server
+13.2k Golang : Activate web camera and broadcast out base64 encoded images
+13.8k Golang : How to pass map to html template and access the map's elements
+7.8k Golang : Routes multiplexer routing example with regular expression control
+4.3k Golang : How to pass data between controllers with JSON Web Token