-
Notifications
You must be signed in to change notification settings - Fork 15
/
StringPermutation.go
48 lines (41 loc) · 1.18 KB
/
StringPermutation.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
/*
String permutations in Go
This is an exercise in recursion encountered in programming training books:
PROBLEM: Implement a routine that prints all possible orderings of the characters
in a string. In other words, print all permutations that use all the characters from
the original string. For example, given the string “hat”, your function should print
the strings “tha”, “aht”, “tah”, “ath”, “hta”, and “hat”. Treat each character in the
input string as a distinct character, even if it is repeated. Given the string “aaa”,
your routine should print “aaa” six times. You may print the permutations in any
order you choose.
*/
package main
import "fmt"
func startPermutation(input string) {
p := &Permutation{
in: []rune(input),
used: make([]bool, len(input)),
}
p.permute()
}
type Permutation struct {
used []bool
out []rune
in []rune
}
func (p *Permutation) permute() {
if len(p.out) == len(p.in) {
fmt.Println(string(p.out))
return
}
for i := 0; i < len(p.in); i++ {
if p.used[i] == true {
continue
}
p.out = append(p.out, p.in[i])
p.used[i] = true
p.permute()
p.used[i] = false
p.out = p.out[:len(p.out)-1]
}
}