在 golang 中获取 undefined rand.Shuffle

Getting undefined rand.Shuffle in golang

所以我有一片字母,想将它们打乱。 我已经实现了这个代码片段:

rand.Shuffle(len(letters), func(i, j int) {
    letters[i], letters[j] = letters[j], letters[i]
)}

当 运行 运行程序时,它卡在第一行说:"undefined: rand.Shuffle"。 在我的进口申报中,我进口了 "math/rand" 我也 运行 这个代码片段之前的代码片段有问题:

rand.Seed(seed)

代码前面给出了 "seed"。

另外我想要的是打乱一个单词但不要碰第一个和最后一个字母。有没有一个简单的解决方案。我写了这样的代码:

rand.Shuffle(len(letters), func(i, j int) {
    if i > 0 && i < (len(letters) - 1) && j > 0 && j < (len(letters) - 1){
        letters[i], letters[j] = letters[j], letters[i] 
    }
})

完整代码:

import (
    "math/rand"
    "strings"
    "regexp"
)

func splitText(text string) []string {
    re := regexp.MustCompile("[A-Za-z0-9']+|[':;?().,!\ ]")
    return re.FindAllString(text, -1)
}

func scramble(text string, seed int64) string {
token := splitText(text)
rand.Seed(seed)
if len(token) != 0{
    for i := 0; i < len(token); i++{
        word := token[i]
        if len(word) > 3{
            letters := strings.Split(word, "")
            rand.Shuffle(len(letters), func(i, j int) { 
                if i > 0 && i < (len(letters) - 1) && j > 0 && j < (len(letters) - 1){
                    letters[i], letters[j] = letters[j], letters[i] 
                }
            })
            token[i] = strings.Join(letters, "")
        }
    }
}

returnString := strings.Join(token, "")
return returnString

}

Go 1.10 Release Notes (February 2018)

Minor changes to the library

math/rand

The new Shuffle function and corresponding Rand.Shuffle method shuffle an input sequence.


对于rand.Shuffle函数,您至少需要Go 1.10。

运行 go version 检查你的版本。