I have a code that get all question from datastore:
queQ := datastore.NewQuery("Question")
questions := make([]questionData, 0)
if keys, err := queQ.GetAll(c, &questions); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
I wanted to display these question one a time but in a random manner. I would like to do the reordering of the question slice in go(server) and not in the client. How could it be possible to scramble the ordering of the slices? I have thought of generating ramdom number but I think there is an easy way to do it. Many thanks to all!
perhaps you can use package math/rand
randomQuestion:=questions[rand.Intn(len(questions)]
In your code, keys
and questions
are synchronized slices for the datastore keys and values. Therefore, use a random sequence of slice indices to access questions
. For example, to select all the key and value slices randomly,
package main
import (
"fmt"
"math/rand"
"time"
)
type Key struct{}
type Value interface{}
func main() {
keys := make([]*Key, 5)
values := make([]Value, len(keys))
rand.Seed(time.Now().Unix())
for _, r := range rand.Perm(len(keys)) {
k := keys[r]
v := values[r]
fmt.Println(r, k, v)
}
}
Output:
2 <nil> <nil>
3 <nil> <nil>
4 <nil> <nil>
0 <nil> <nil>
1 <nil> <nil>
The code has been revised to use the rand.Perm function.