douzhe1264 2017-04-01 13:10
浏览 111
已采纳

在Go中随机化MongoDB查询的顺序

Here is my query :

c := session.DB("searchV").C("video")
var results []BadVideo
err5 := c.Find(nil).All(&results)
fmt.Println("request done")
if err5 != nil {
    panic(err5)
}
var i = 0
for _,badvideo := range results {
}

I would like to randomize the order of browsing the items of the query for making operation on each item of the request ...

So each time I run it, I browse it in a different order.

  • 写回答

1条回答 默认 最新

  • dongyiyu882684 2017-04-02 08:45
    关注

    Manual shuffling

    Here's a simple shuffle algorithm, which shuffles (randomizes) a []BadVido slice:

    func shuffle(r []BadVideo) {
        for i := len(r) - 1; i > 0; i-- {
            j := rand.Intn(i + 1)
            r[i], r[j] = r[j], r[i]
        }
    }
    

    So after you loaded your results, simply call shuffle(results) on it.

    For testing, I will use a simple BadVideo type:

    type BadVideo struct {
        Name string
    }
    
    func main() {
        rand.Seed(time.Now().UnixNano())
        results := []BadVideo{{"a"}, {"b"}, {"c"}, {"d"}, {"e"}}
        shuffle(results)
        fmt.Println(results)
    }
    

    Output (try it on the Go Playground):

    [{c} {d} {b} {e} {a}]
    

    How it works:

    To shuffle a slice, the shuffle() function randomly selects one element from the slice for each index. It does it like iterating over all elements downward, and selects a random element from the remaining slice (including index of the element we're currently selecting, because random orders also include ones where an element "stays in place"), and using a random index to swaps the element with the chosen random one. The loop goes until i > 0 (and not until i >=0), because if only 1 element left, no need to swap it with itself.

    Using rand.Perm()

    Another variant of shuffle() could take advantage of rand.Perm() which returns a slice containing shuffled numbers. We can use these random numbers to tell how to reorder the results:

    func shuffle(r []BadVideo) {
        r2 := append([]BadVideo(nil), r...)
        for i, j := range rand.Perm(len(r)) {
            r[i] = r2[j]
        }
    }
    

    Try this variant on the Go Playground.

    One thing to note here: before we do the reordering, we have to save the original slice (make a copy of it), so we can select the original elements specified by random indices when writing the results in the slice. I created a copy by appending the complete slice to a nil slice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波