Last active
May 22, 2018 14:40
-
-
Save Attumm/39fce2b450a238dab89fe01f700d8244 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
result := make(chan string, 1000) | |
entrophy := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" | |
go combinations(entrophy, 7, result) | |
i := 1 | |
for val := range result { | |
i++ | |
fmt.Print(val, " - ", i, "\n") | |
} | |
} | |
func combinations(input string, size int, result chan string) { | |
defer close(result) | |
if size == 0 { | |
return | |
} | |
l := make([]int, size) | |
pool := []rune(input) | |
result <- makeResult(pool, l) | |
for { | |
l[0] += 1 | |
if overFlow(l, len(pool)) { | |
break | |
} | |
result <- makeResult(pool, l) | |
} | |
} | |
func overFlow(l []int, size int) bool { | |
for i := 0; i < len(l); i++ { | |
if l[i] >= size { | |
if i+1 >= len(l) { | |
return true | |
} | |
l[i], l[i+1] = 0, l[i+1]+1 | |
} | |
} | |
return false | |
} | |
func makeResult(pool []rune, l []int) string { | |
result := []rune{} | |
for i := 0; i < len(l); i++ { | |
result = append(result, pool[l[i]]) | |
} | |
return string(result) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"reflect" | |
"sort" | |
"testing" | |
) | |
func TestPermuations(t *testing.T) { | |
testcases := []struct { | |
iString string | |
iSize int | |
expected []string | |
}{ | |
{"1", 1, []string{"1"}}, | |
{"12", 2, []string{"11", "21", "12", "22"}}, | |
{"ABCD", 2, []string{"AA", "BA", "CA", "DA", "AB", "BB", "CB", "DB", "AC", "BC", "CC", "DC", "AD", "BD", "CD", "DD"}}, | |
{"123", 3, []string{"111", "211", "311", "121", "221", "321", "131", "231", "331", "112", "212", "312", "122", "222", "322", "132", "232", "332", "113", "213", "313", "123", "223", "323", "133", "233", "333"}}, | |
} | |
for number, testcase := range testcases { | |
resultChan := make(chan string) | |
go combinations(testcase.iString, testcase.iSize, resultChan) | |
result := []string{} | |
for item := range resultChan { | |
result = append(result, item) | |
} | |
// order of the permutation function should not matter | |
sort.Strings(result) | |
sort.Strings(testcase.expected) | |
if !reflect.DeepEqual(result, testcase.expected) { | |
t.Error("Error testcase:", number, "input:", testcase.iString, "result", result, "!=", testcase.expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment