Last active
December 30, 2015 17:38
-
-
Save evalphobia/4a7e96d6c323c2ee1501 to your computer and use it in GitHub Desktop.
golang permutations; ref:http://www.geocities.jp/m_hiroi/golang/yagp02.html
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() { | |
p := []string{"Tokyo", "Kyoto", "Osaka", "Nagoya"} | |
res := createPermurations(p) | |
fmt.Printf("%v\n", res) | |
} | |
func createPermurations(cities []string) [][]string { | |
max := len(cities) | |
var result [][]int | |
for i := 1; i < max; i++ { | |
list := []int{i, 0} | |
permutations(&result, list, 1, max) | |
} | |
perms := make([][]string, len(result)) | |
for i, list := range result { | |
perm := make([]string, len(cities)) | |
for j, idx := range list { | |
perm[j] = cities[idx] | |
} | |
perms[i] = perm | |
} | |
return perms | |
} | |
func permutations(result *[][]int, list []int, n, max int) []int { | |
if len(list) == max { | |
return list | |
} | |
for i := 1; i < max; i++ { | |
switch { | |
case i == 1 && list[0] <= i: | |
continue | |
case isMember(list, i): | |
continue | |
} | |
l := permutations(result, append(list, i), n+1, max) | |
if l != nil { | |
*result = append(*result,l) | |
} | |
} | |
return nil | |
} | |
func isMember(list []int, city int) bool { | |
for _, v := range list { | |
if v == city { | |
return true | |
} | |
} | |
return false | |
} |
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() { | |
p := []string{"Tokyo", "Kyoto", "Osaka", "Nagoya"} | |
res := createPermurations(p) | |
fmt.Printf("%v\n", res) | |
} | |
func createPermurations(cities []string) [][]string { | |
var result [][]string | |
var list []string | |
return permutations(result, cities, list) | |
} | |
func permutations(result [][]string, cities, list []string) [][]string { | |
if len(list) == len(cities) { | |
return append(result, list) | |
} | |
for _, city := range cities { | |
if isMember(list, city) { | |
continue | |
} | |
result = permutations(result, cities, append(list, city)) | |
} | |
return result | |
} | |
func isMember(list []string, city string) bool { | |
for _, v := range list { | |
if v == city { | |
return true | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment