重新排序或混淆切片或映射中的元素 GAE Go

huangapple go评论85阅读模式
英文:

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

在你的代码中,keysquestions是数据存储键和值的同步切片。因此,使用随机序列的切片索引来访问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 (
	&quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;time&quot;
)

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 &lt;nil&gt; &lt;nil&gt;
3 &lt;nil&gt; &lt;nil&gt;
4 &lt;nil&gt; &lt;nil&gt;
0 &lt;nil&gt; &lt;nil&gt;
1 &lt;nil&gt; &lt;nil&gt;

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)]

huangapple
  • 本文由 发表于 2013年2月18日 00:01:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/14923017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定