doujiu8145 2019-09-15 17:57
浏览 114

如何修复此代码,以使其改组字母,并且不影响首字母和尾字母,标点符号

I'm dealing with go/golang, trying to write code that takes a string and seed. It should return a shuffled string where the 1st and last letters in the word, punctuation and numbers are untouched.

Example:

my name is Nikki. My number is 333

should be

my nmae is Nkiki. My nebumr is 333

I'm very new to goland/go. Have tried to do it with rand.Shuffle:

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


    func scramble(text string, seed int64) string {

    rand.Seed(seed)
    split := splitText(text)

    for i := range split {
        e := split[i]

        r := []byte(e)

        for i := 0; i < len(r); i++ {
            l := len(r) - 1
            if i == 0 {
                return string(r[0])
            }
            if i == l {
                return string(r[l])
            }

            if i > 0 || i < l {
                n := rand.Intn(l)
                x := r[i]
                r[i] = r[n]
                r[n] = x

            }

            if (r[i] >= 32 && r[i] <= 62) || (r[i] >= 91 && r[i] <= 96) {
                return string(r[i])
            }
        }

    }
    return text

}

func main() {

    v := ("The quick brown fox jumps over the lazy dog.")
    scramble(v, 100)
    fmt.Println(scramble(v, 100))

}

But this returns only one letter and only if remoe f==0 or f==l, it doesn't hop to the next word.

  • 写回答

1条回答 默认 最新

  • dongxiai3003 2019-09-16 14:07
    关注

    I'm very new to goland/go.


    Avoid writing programs in a new language as if you are still writing programs in an old language.


    write code that takes a string and seed. It should return a shuffled string where the 1st and last letters in the word, punctuation and numbers are untouched.

    Example:

    my name is Nikki. My number is 333
    

    should be

    my nmae is Nkiki. My nebumr is 333
    

    Here is a solution written in Go.

    package main
    
    import (
        "fmt"
        "math/rand"
        "unicode"
    )
    
    func shuffle(word []rune, rand *rand.Rand) {
        if len(word) < 4 {
            return
        }
        chars := word[1 : len(word)-1]
        rand.Shuffle(
            len(chars),
            func(i, j int) {
                chars[i], chars[j] = chars[j], chars[i]
            },
        )
    }
    
    func scramble(text string, seed int64) string {
        rand := rand.New(rand.NewSource(seed))
    
        chars := []rune(text)
        inWord := false
        i := 0
        for j, char := range chars {
            if !unicode.IsLetter(char) {
                if inWord {
                    shuffle(chars[i:j], rand)
                }
                inWord = false
            } else if !inWord {
                inWord = true
                i = j
            }
        }
        if inWord {
            shuffle(chars[i:len(chars)], rand)
        }
        return string(chars)
    }
    
    func main() {
        for _, text := range []string{
            "my name is Nikki. My number is 333",
            "The quick brown fox jumps over the lazy dog.",
            loremipsum,
        } {
            fmt.Printf("%q
    ", text)
            fmt.Printf("%q
    ", scramble(text, 100))
        }
    }
    
    var loremipsum = `
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
    Ut enim ad minim veniam, 
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
    Excepteur sint occaecat cupidatat non proident, 
    sunt in culpa qui officia deserunt mollit anim id est laborum.
    `
    

    Playground: https://play.golang.org/p/NoHXynQSD4p

    Output:

    "my name is Nikki. My number is 333"
    "my name is Nkiki. My neubmr is 333"
    "The quick brown fox jumps over the lazy dog."
    "The quick bowrn fox jmups over the lzay dog."
    "
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
    Ut enim ad minim veniam, 
    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
    Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. 
    Excepteur sint occaecat cupidatat non proident, 
    sunt in culpa qui officia deserunt mollit anim id est laborum.
    "
    "
    Lorem isupm dloor sit amet, csttunoecer andiipcsig elit, 
    sed do emiousd tepmor idinicdnut ut lorbae et dorloe mgnaa aqilua. 
    Ut einm ad miinm vinaem, 
    quis notursd eioattxceirn ualmlco libroas nisi ut aqiiulp ex ea cdmoomo cuanqesot. 
    Dius aute iurre dolor in rienreehredpt in vlptuotae vielt esse clulim drlooe eu fuagit nulla ptaaiurr. 
    Eepuxcter snit ocecacat citapadut non prinodet, 
    snut in cpula qui oficfia dsuenret milolt ainm id est laorbum.
    "
    
    评论

报告相同问题?

悬赏问题

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