Skip to content

Commit d24d2d0

Browse files
committedSep 5, 2015
moar interfaces
1 parent 3deaad6 commit d24d2d0

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
 

‎day18-interfaces/shuffeler.go

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
)
7+
8+
type shuffler interface {
9+
Len() int
10+
Swap(i, j int)
11+
}
12+
13+
func shuffle(s shuffler) {
14+
for i := 0; i < s.Len(); i++ {
15+
j := rand.Intn(s.Len() - i)
16+
s.Swap(i, j)
17+
18+
}
19+
}
20+
21+
type intSlice []int
22+
23+
func (is intSlice) Len() int {
24+
return len(is)
25+
}
26+
27+
func (is intSlice) Swap(i, j int) {
28+
is[i], is[j] = is[j], is[i]
29+
}
30+
31+
type stringSlice []string
32+
33+
func (ss stringSlice) Len() int {
34+
return len(ss)
35+
}
36+
37+
func (ss stringSlice) Swap(i, j int) {
38+
ss[i], ss[j] = ss[j], ss[i]
39+
}
40+
41+
func main() {
42+
ii := intSlice{1, 2, 3, 4, 5, 6}
43+
shuffle(ii)
44+
fmt.Printf("%v\n", ii)
45+
46+
si := stringSlice{"interfaces", "are", "awesome", "!"}
47+
shuffle(si)
48+
fmt.Printf("%v\n", si)
49+
}

0 commit comments

Comments
 (0)
Please sign in to comment.