In Go, you can shuffle an array using the Fisher-Yates shuffle algorithm.
In this example,
intArray
containing integers.intArray
.package main
import (
"fmt"
"math/rand"
"time"
)
func shuffleArray(array []int) {
rand.Seed(time.Now().UnixNano())
for i := len(array) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
array[i], array[j] = array[j], array[i]
}
}
func main() {
intArray := []int{1, 2, 3, 4, 5}
shuffleArray(intArray)
fmt.Println("Shuffled Array:", intArray)
}
Shuffled Array: [3 1 4 5 2]
In this example,
strArray
containing strings.strArray
.package main
import (
"fmt"
"math/rand"
"time"
)
func shuffleArray(array []string) {
rand.Seed(time.Now().UnixNano())
for i := len(array) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
array[i], array[j] = array[j], array[i]
}
}
func main() {
strArray := []string{"apple", "banana", "cherry"}
shuffleArray(strArray)
fmt.Println("Shuffled Array:", strArray)
}
Shuffled Array: [banana cherry apple]
In this tutorial, we learned How to Shuffle an Array in Go language with well detailed examples.