shuffle a string in go

To shuffle a string in Go, we can convert the string to a slice of runes, shuffle the slice using the math/rand package, and then convert the shuffled slice back to a string.

Here's an example implementation:

main.go
package main

import (
    "fmt"
    "math/rand"
)

func shuffleString(s string) string {
    // Convert string to slice of runes
    runes := []rune(s)

    // Shuffle slice using Fisher-Yates algorithm
    for i := len(runes) - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        runes[i], runes[j] = runes[j], runes[i]
    }

    // Convert shuffled slice back to string
    return string(runes)
}

func main() {
    s := "hello world"
    shuffled := shuffleString(s)
    fmt.Println(shuffled)
}
502 chars
27 lines

The shuffleString function takes a string and returns a shuffled version of the string. We first convert the string to a slice of runes using []rune(s). We then shuffle the slice using the Fisher-Yates algorithm, which randomly swaps elements in the slice. Finally, we convert the shuffled slice back to a string using string(runes) and return the result.

related categories

gistlibby LogSnag