Commit Diff


commit - /dev/null
commit + 3889536a56748500b2332aea768ae954dfd48132
blob - /dev/null
blob + 485dee64bcfb48793379b200a1afd14e85a8aaf4 (mode 644)
--- /dev/null
+++ .gitignore
@@ -0,0 +1 @@
+.idea
blob - /dev/null
blob + 53786bec346a8403981c543e48ddaeef697742d7 (mode 644)
--- /dev/null
+++ LICENSE
@@ -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.
blob - /dev/null
blob + 716e4633c9fe0c4a50a2e53b7d927de973387dd4 (mode 644)
--- /dev/null
+++ README.md
@@ -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]
+```
blob - /dev/null
blob + 50f02b6ecf89d53e8dcaeafb871e98fe1edeb7d0 (mode 644)
--- /dev/null
+++ go.mod
@@ -0,0 +1,3 @@
+module git.fputs.com/fputs/permutation
+
+go 1.18
blob - /dev/null
blob + ab0e1ae82f9fa54cf0b6370143f21209339e92e2 (mode 644)
--- /dev/null
+++ permutation.go
@@ -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
+}
blob - /dev/null
blob + 7bb94ec4947a0869eaae87b5718d42b8745b1bef (mode 644)
--- /dev/null
+++ permutation_test.go
@@ -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)
+}