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
}