Last active
May 7, 2018 07:44
-
-
Save Attumm/e400923485197a05213ab738795355f9 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 | |
//golang implentation of heap algo | |
//https://en.wikipedia.org/wiki/Heap%27s_algorithm | |
//Result datastructure should be changed to fit your needs | |
func permutations(a []int) [][]int { | |
n := len(a) | |
result := [][]int{} | |
c := make([]int, n) | |
result = cAppend(result, a) | |
i:=0 | |
for i<n { | |
if c[i] < i { | |
if i % 2 == 0 { | |
a[0], a[i] = a[i], a[0] | |
} else { | |
a[c[i]], a[i] = a[i], a[c[i]] | |
} | |
result = cAppend(result, a) | |
c[i] += 1 | |
i = 0 | |
} else { | |
c[i] = 0 | |
i += 1 | |
} | |
} | |
return result | |
} | |
func cAppend(result [][]int, n []int) [][]int { | |
copy_n := make([]int, len(n)) | |
copy(copy_n, n) | |
return append(result, copy_n) | |
} | |
~ |
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 ( | |
"testing" | |
"reflect" | |
"fmt" | |
) | |
func TestPermuations(t *testing.T) { | |
testcases := []struct{ | |
input []int | |
expected [][]int | |
} { | |
{[]int{}, [][]int{[]int{}}}, | |
{[]int{1}, [][]int{[]int{1}}}, | |
{[]int{1, 2}, [][]int{ | |
[]int{1, 2}, | |
[]int{2, 1}, | |
}, | |
}, | |
{[]int{1, 2, 3}, [][]int{ | |
[]int{1, 2, 3}, | |
[]int{2, 1, 3}, | |
[]int{3, 1, 2}, | |
[]int{1, 3, 2}, | |
[]int{2, 3, 1}, | |
[]int{3, 2, 1}, | |
}, | |
}, | |
} | |
for number, testcase := range testcases { | |
result := permutations(testcase.input) | |
if !reflect.DeepEqual(result, testcase.expected) { | |
fmt.Println("expected") | |
for _,row := range testcase.expected { | |
fmt.Println(row) | |
} | |
fmt.Println("result") | |
for _,row := range result { | |
fmt.Println(row) | |
} | |
t.Error("Error testcase:", number, "input:", testcase.input, "result", result, "!=", testcase.expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment