Skip to content

Instantly share code, notes, and snippets.

@evalphobia
Last active December 30, 2015 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evalphobia/4a7e96d6c323c2ee1501 to your computer and use it in GitHub Desktop.
Save evalphobia/4a7e96d6c323c2ee1501 to your computer and use it in GitHub Desktop.
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
}
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