dpv50040 2018-09-04 19:24
浏览 695
已采纳

在golang中获取未定义的rand.Shuffle

So I have a slice of letters and want to shuffle them. I've implemented this code snippet:

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

When running the program it gets stuck at the first line saying: "undefined: rand.Shuffle". in my import declaration i have imported "math/rand" I also run this code snippet before the snippet with a problem:

rand.Seed(seed)

Where "seed" is given earlier in the code.

Also what i want is to shuffle a word but don't touch the first and last letter. Is there an easy solution to this. I have written the code like this:

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

Full code:

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

}

  • 写回答

1条回答 默认 最新

  • dongqing314511 2018-09-04 21:10
    关注

    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.


    For the rand.Shuffle function, you need at least Go 1.10.

    Run go version to check your version.

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

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作