2

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!

sagit
  • 911
  • 1
  • 8
  • 14
  • possible duplicate of [How to get something random in datastore (AppEngine)?](http://stackoverflow.com/questions/3450926/how-to-get-something-random-in-datastore-appengine) – Shay Erlichmen Feb 17 '13 at 16:04

2 Answers2

2

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.

peterSO
  • 158,998
  • 31
  • 281
  • 276
1

perhaps you can use package math/rand

randomQuestion:=questions[rand.Intn(len(questions)]
Joe
  • 6,460
  • 1
  • 19
  • 15