Created
November 14, 2012 15:00
-
-
Save lukad/4072611 to your computer and use it in GitHub Desktop.
permutations in go
This file contains hidden or 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" | |
"os" | |
"strconv" | |
) | |
func intRangeSlice(start, stop int) []int { | |
if start > stop { | |
panic("Slice ends before it started") | |
} | |
xs := make([]int, stop-start) | |
for i := 0; i < len(xs); i++ { | |
xs[i] = i + 1 + start | |
} | |
return xs | |
} | |
func permute(xs []int) (perms [][]int) { | |
var rc func([]int, int) | |
rc = func(a []int, k int) { | |
if k == len(a) { | |
perms = append(perms, append([]int{}, a...)) | |
} else { | |
for i := k; i < len(xs); i++ { | |
a[k], a[i] = a[i], a[k] | |
rc(a, k+1) | |
a[k], a[i] = a[i], a[k] | |
} | |
} | |
} | |
rc(xs, 0) | |
return perms | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
fmt.Println("Error: no input") | |
os.Exit(1) | |
} | |
n, err := strconv.Atoi(os.Args[1]) | |
if err != nil { | |
fmt.Println(err.Error()) | |
os.Exit(1) | |
} | |
perms := permute(intRangeSlice(0, n)) | |
fmt.Println(len(perms)) | |
for i := 0; i < len(perms); i++ { | |
fmt.Println(perms[i]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment