Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add problem 7 of chapter 8 #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/chapter8/problem7.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package chapter8

// Permutations returns permutations of givien string
func Permutations(str string) []string {
if len(str) == 0 {
return []string{""}
}

var res []string
for i := 0; i < len(str); i++ {
subs := Permutations(TrimAt(str, i))
for _, sub := range subs {
res = append(res, string(str[i])+sub)
}
}

return res
}

// TrimAt trims a char from given string by given index
func TrimAt(str string, i int) string {
switch {
case i < 0 || len(str) == 0 || i >= len(str):
return str
case i == len(str)-1:
return str[:len(str)-1]
case i == 0:
return str[1:]
default:
return string(append([]byte(str[0:i]), str[i+1:]...))
}
}
48 changes: 48 additions & 0 deletions src/chapter8/problem7_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package chapter8

import (
"reflect"
"testing"
)

func TestPermutations(t *testing.T) {
tests := map[string]struct {
in string
out []string
}{
"should return slice of empty string when empty string is given": {
in: "",
out: []string{""},
},
"should return 1 permutations when a is given": {
in: "a",
out: []string{"a"},
},
"should return 2 permutations when ab is given": {
in: "ab",
out: []string{"ab", "ba"},
},
"should return 6 permutations when abc is given": {
in: "abc",
out: []string{"abc", "acb", "bac", "bca", "cab", "cba"},
},
"should return 24 permutations when abcd is given": {
in: "abcd",
out: []string{
"abcd", "abdc", "acbd", "acdb", "adbc", "adcb",
"bacd", "badc", "bcad", "bcda", "bdac", "bdca",
"cabd", "cadb", "cbad", "cbda", "cdab", "cdba",
"dabc", "dacb", "dbac", "dbca", "dcab", "dcba",
},
},
}

for k, test := range tests {
t.Run(k, func(t *testing.T) {
out := Permutations(test.in)
if !reflect.DeepEqual(out, test.out) {
t.Errorf("actual=%+v expected=%+v", out, test.out)
}
})
}
}