Skip to content

Commit 100f289

Browse files
committed
Find Kth Permutation
1 parent ce0b69b commit 100f289

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

MathAndStats/FindKthPermutation.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
Find the Kth Permutation of a given number
3+
*/
4+
5+
package main
6+
7+
import ("fmt")
8+
9+
func Factorial(n int) int {
10+
var FactorialArray = []int{1,1}
11+
if n == 0 || n == 1 {return 1}
12+
for i:=2;i<n+1;i++ {
13+
FactorialArray = append(FactorialArray,i*FactorialArray[i-1])
14+
}
15+
return FactorialArray[n]
16+
}
17+
18+
func Remove(array []int,index int) []int {
19+
if index >= len(array) {
20+
return array
21+
} else {
22+
return append(array[:index],array[index+1:]...)
23+
}
24+
}
25+
26+
func FindKthPermutation(num []int,k int,) *[]int {
27+
var KthPermutation []int
28+
t := len(num)
29+
num1 := num
30+
if k > Factorial(len(num)) {
31+
KthPermutation = append(KthPermutation,-1)
32+
return &KthPermutation
33+
}
34+
for i:=0;i<len(num);i++ {
35+
blockSize := Factorial(t-1)
36+
selected := (k-1)/blockSize
37+
//fmt.Println(num1)
38+
//fmt.Println(selected)
39+
KthPermutation = append(KthPermutation,num1[selected])
40+
num1 = Remove(num1,selected) // The array is shrinking with every iteration
41+
k = k -selected*blockSize
42+
t--
43+
}
44+
return &KthPermutation
45+
}
46+
47+
48+
func main() {
49+
array := []int{1,2,3,4}
50+
KthPermutationPtr := FindKthPermutation(array,8)
51+
fmt.Println(*KthPermutationPtr)
52+
}
53+

0 commit comments

Comments
 (0)