-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperm.go
70 lines (61 loc) · 1.12 KB
/
perm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package practice
// Perm returns a slice of all possible permuations
// of the characters in an ascii encoded string.
func Perm(in string) []string {
// allocate a buffer to work in
buff := []byte(in)
n := len(buff)
if n == 0 {
return []string{}
} else if n == 1 {
return []string{string(buff)}
}
store := []string{}
var p func(n int)
p = func(n int) {
if n == 1 {
store = append(store, string(buff))
} else {
for i := 0; i < n; i++ {
p(n - 1)
if n%2 == 1 {
buff[n-1], buff[i] = buff[i], buff[n-1]
} else {
buff[n-1], buff[0] = buff[0], buff[n-1]
}
}
}
}
p(n)
return store
}
func PermChan(in string) <-chan string {
// allocate a buffer to work in
buff := []byte(in)
n := len(buff)
store := make(chan string)
if n == 0 {
close(store)
return store
}
var p func(n int)
p = func(n int) {
if n == 1 {
store <- string(buff)
} else {
for i := 0; i < n; i++ {
p(n - 1)
if n%2 == 1 {
buff[n-1], buff[i] = buff[i], buff[n-1]
} else {
buff[n-1], buff[0] = buff[0], buff[n-1]
}
}
}
}
go func() {
p(n)
close(store)
}()
return store
}