From 39cef020923a78bc2f7ec7f3f9f486f16b98a568 Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Sat, 21 Dec 2019 12:49:14 +0100 Subject: [PATCH] Added statistical method to ints package. --- ints/statistics.go | 47 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ints/statistics.go diff --git a/ints/statistics.go b/ints/statistics.go new file mode 100644 index 0000000..244c365 --- /dev/null +++ b/ints/statistics.go @@ -0,0 +1,47 @@ +package ints + +// Faculty returns the faculty of i. +func Faculty(i int) int { + if i < 2 { + return 1 + } + return i * Faculty(i-1) +} + +// Faculty64 returns the faculty of i. +func Faculty64(i int64) int64 { + if i < 2 { + return 1 + } + return i * Faculty64(i-1) +} + +// Permutations returns all possible permutations of the the set integers. +func Permutations(set []int) [][]int { + var n = len(set) + if n == 0 { + return nil + } + var res = make([][]int, 0, Faculty(n)) + var p = append([]int(nil), set...) + + var c = make([]int, n) + res = append(res, append([]int(nil), p...)) + i := 0 + for i < n { + if c[i] < i { + if i%2 == 0 { + p[0], p[i] = p[i], p[0] + } else { + p[c[i]], p[i] = p[i], p[c[i]] + } + res = append(res, append([]int(nil), p...)) + c[i] = c[i] + 1 + i = 0 + } else { + c[i] = 0 + i++ + } + } + return res +}