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.

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

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划