Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created June 28, 2019 16:58
Show Gist options
  • Save jubishop/8e8def2089209587327512fe9e3f56dc to your computer and use it in GitHub Desktop.
Save jubishop/8e8def2089209587327512fe9e3f56dc to your computer and use it in GitHub Desktop.
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