This commit is contained in:
Evan Burkey 2022-01-21 13:12:47 -08:00
commit 3889536a56
6 changed files with 96 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.idea

13
LICENSE Normal file
View File

@ -0,0 +1,13 @@
Copyright 2021 Evan Burkey <dev@fputs.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

34
README.md Normal file
View File

@ -0,0 +1,34 @@
# permutation
A simple permutation package using generics. Requires go1.18beta1 or higher
## Install
```bash
go get git.fputs.com/fputs/permutation
```
## Usage
```go
package main
import (
"fmt"
perm "git.fputs.com/fputs/permutation"
)
func main() {
a := []int{1, 2, 3, 4}
p := perm.Permutations(a)
fmt.Println(p)
}
```
result:
```
[1 2 3]
[2 1 3]
[3 1 2]
[1 3 2]
[2 3 1]
[3 2 1]
```

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.fputs.com/fputs/permutation
go 1.18

33
permutation.go Normal file
View File

@ -0,0 +1,33 @@
package permutation
type GenSlice[T any] []T
func Permutations[T any](arr GenSlice[T]) []GenSlice[T] {
var helper func(GenSlice[T], int)
var res []GenSlice[T]
helper = func(arr GenSlice[T], n int) {
if n == 1 {
var tmp GenSlice[T]
for _, i := range arr {
tmp = append(tmp, i)
}
res = append(res, tmp)
} else {
for i := 0; i < n; i++ {
helper(arr, n-1)
if n%2 == 1 {
tmp := arr[i]
arr[i] = arr[n-1]
arr[n-1] = tmp
} else {
tmp := arr[0]
arr[0] = arr[n-1]
arr[n-1] = tmp
}
}
}
}
helper(arr, len(arr))
return res
}

12
permutation_test.go Normal file
View File

@ -0,0 +1,12 @@
package permutation
import (
"fmt"
"testing"
)
func Test(t *testing.T) {
a := []int{1, 2, 3, 4}
p := Permutations(a)
fmt.Println(p)
}