arrays - 如何修复此代码,使其随机排列字母并且不影响第一个字母和最后一个字母、标点符号

标签 arrays go slice shuffle letter

我正在处理 go/golang,尝试编写需要字符串和种子的代码。它应该返回一个打乱的字符串,其中单词中的第一个和最后一个字母、标点符号和数字保持不变。

示例:

my name is Nikki. My number is 333

应该是

my nmae is Nkiki. My nebumr is 333

我对 goland/go 很陌生。尝试使用 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))

}

但这仅返回一个字母,并且仅当 remoe f==0f==l 时,它不会跳到下一个单词。

最佳答案

I'm very new to goland/go.

<小时/>

避免使用新语言编写程序,就像仍在使用旧语言编写程序一样。

<小时/>

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

这是用 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\n", text)
        fmt.Printf("%q\n", 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

输出:

"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."
"\nLorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, \nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \nExcepteur sint occaecat cupidatat non proident, \nsunt in culpa qui officia deserunt mollit anim id est laborum.\n"
"\nLorem isupm dloor sit amet, csttunoecer andiipcsig elit, \nsed do emiousd tepmor idinicdnut ut lorbae et dorloe mgnaa aqilua. \nUt einm ad miinm vinaem, \nquis notursd eioattxceirn ualmlco libroas nisi ut aqiiulp ex ea cdmoomo cuanqesot. \nDius aute iurre dolor in rienreehredpt in vlptuotae vielt esse clulim drlooe eu fuagit nulla ptaaiurr. \nEepuxcter snit ocecacat citapadut non prinodet, \nsnut in cpula qui oficfia dsuenret milolt ainm id est laorbum.\n"

关于arrays - 如何修复此代码,使其随机排列字母并且不影响第一个字母和最后一个字母、标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57946792/

相关文章:

javascript - 通过参数传递图像,JQuery Mobile

pointers - 在 Go 中取消引用指针

python - 使用 h5py 读取 HDF5 文件时使用 python 切片对象?

fortran - 在 Fortran 中,切片数组是否会在内存中创建副本?

javascript - Javascript 中的 Array() 和 [] 有什么区别,为什么我要使用一个而不是另一个?

javascript - 在 JavaScript 中过滤对象的对象并使用最后 7 个对象创建新数组

戈朗 : fatal error: all goroutines are asleep - deadlock

Golang 从 AST 编译为二进制

Python数组: Take two and skip two

c - 将 int 写入 char 数组