Skip to content

Instantly share code, notes, and snippets.

@jreisinger
Created October 23, 2018 10:03
Show Gist options
  • Select an option

  • Save jreisinger/0abfe791818429652b4e4d2e541b3fb7 to your computer and use it in GitHub Desktop.

Select an option

Save jreisinger/0abfe791818429652b4e4d2e541b3fb7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
)
// An abstract type, i.e. an interface
type shuffler interface {
Len() int
Swap(i, j int)
}
// Takes in any type that satisfies the shuffler interface
func shuffle(s shuffler) {
for i := 0; i < s.Len(); i++ {
j := rand.Intn(s.Len() - i)
s.Swap(i, j)
}
}
// A type that satisfies the shuffler interface
type intSlice []int
func (is intSlice) Len() int {
return len(is)
}
func (is intSlice) Swap(i, j int) {
is[i], is[j] = is[j], is[i]
}
type stringSlice []string
func (s stringSlice) Len() int {
return len(s)
}
func (s stringSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func main() {
is := intSlice{1, 2, 3, 4, 5, 6}
shuffle(is)
fmt.Printf("%v\n", is)
s := stringSlice{"The", "quick", "brown", "fox"}
shuffle(s)
fmt.Printf("%v\n", s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment