Browse Source

init

master
Evan Burkey 1 year ago
commit
b74dda109c
  1. 1
      .gitignore
  2. 13
      LICENSE
  3. 34
      README.md
  4. 3
      go.mod
  5. 33
      permutation.go
  6. 12
      permutation_test.go

1
.gitignore vendored

@ -0,0 +1 @@ @@ -0,0 +1 @@
.idea

13
LICENSE

@ -0,0 +1,13 @@ @@ -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

@ -0,0 +1,34 @@ @@ -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

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

33
permutation.go

@ -0,0 +1,33 @@ @@ -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

@ -0,0 +1,12 @@ @@ -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)
}
Loading…
Cancel
Save