英文:
Reorder or Scrambling order of elements in slice or map GAE Go
问题
我有一个从数据存储中获取所有问题的代码:
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
}
我想要以随机的方式逐个显示这些问题。我希望在Go(服务器)中重新排序问题切片,而不是在客户端中进行。有什么办法可以打乱切片的顺序吗?我考虑过生成随机数,但我觉得应该有更简单的方法。非常感谢!
英文:
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!
答案1
得分: 2
在你的代码中,keys
和questions
是数据存储键和值的同步切片。因此,使用随机序列的切片索引来访问questions
。例如,要随机选择所有键和值切片,
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)
}
}
输出:
2 <nil> <nil>
3 <nil> <nil>
4 <nil> <nil>
0 <nil> <nil>
1 <nil> <nil>
代码已经修改为使用rand.Perm
函数。
英文:
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.
答案2
得分: 1
也许你可以使用math/rand
包
randomQuestion := questions[rand.Intn(len(questions))]
英文:
perhaps you can use package math/rand
randomQuestion:=questions[rand.Intn(len(questions)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论