Last active
June 13, 2016 07:08
-
-
Save asm-jaime/26c85a3a3075f5cfc5f9311ad3cef904 to your computer and use it in GitHub Desktop.
permutation sequence of n without repeats (input: 3, output: [012 021 102 120 201 210])
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" | |
"sort" | |
"strconv" | |
) | |
const num_count int = 3 | |
type IntSlice []int | |
var this_slice IntSlice | |
var this_strs []string | |
var this_str string | |
var sum_count int = 0 | |
func main() { | |
this_slice = *sequence_int(num_count) | |
permutate(num_count) | |
sort.Strings(this_strs) | |
fmt.Print("\n") | |
fmt.Print(this_strs) | |
} | |
func permutate(n int) { | |
if n == 0 { | |
this_str = "" | |
sum_count++ | |
for _, cell := range this_slice { | |
this_str += strconv.Itoa(cell) | |
} | |
this_strs = append(this_strs, this_str) | |
return | |
} else { | |
for j := 0; j < n; j++ { | |
this_slice.swap(j, n-1) | |
permutate(n - 1) | |
this_slice.swap(j, n-1) | |
} | |
} | |
} | |
func (slice IntSlice) swap(i, j int) { | |
slice[i], slice[j] = slice[j], slice[i] | |
} | |
func sequence_int(num int) *[]int { | |
seq := make([]int, num) | |
for i := 0; i < num; i++ { | |
seq[i] = i | |
} | |
return &seq | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment