Created
June 28, 2019 16:58
-
-
Save jubishop/8e8def2089209587327512fe9e3f56dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fact(n) | |
return n if (n < 3) | |
ans = 1 | |
n.downto(2) { |x| | |
ans *= x | |
} | |
return ans | |
end | |
def get_permutation(n, k, nums = (1..n).to_a) | |
answer = [] | |
remaining = k-1 | |
(n-1).downto(0) { |x| | |
perms = fact(x) | |
index = perms == 0 ? remaining : (remaining / perms).ceil | |
answer.push(nums.slice!(index)) | |
remaining -= perms * index | |
} | |
return answer.join("") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment