Really fast solution, not bruteforce
This commit is contained in:
44
24/main.py
Normal file
44
24/main.py
Normal file
@@ -0,0 +1,44 @@
|
||||
# Get the millionth lexicographic permutation of the digits
|
||||
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
|
||||
|
||||
import math
|
||||
|
||||
def fac(n):
|
||||
if n == 0:
|
||||
return 1
|
||||
else:
|
||||
return n * fac(n-1)
|
||||
|
||||
def getPermutation(n, s):
|
||||
p = sorted(s)
|
||||
l = len(s)
|
||||
x = n - 1
|
||||
seq = []
|
||||
|
||||
assert n > 0
|
||||
assert l > 0
|
||||
assert n <= fac(l)
|
||||
|
||||
f = fac(l)
|
||||
while l > 0:
|
||||
part = math.floor(f / l)
|
||||
f /= l
|
||||
y = math.floor(x / part)
|
||||
x -= y * part
|
||||
seq.append(y)
|
||||
l -= 1
|
||||
|
||||
res = []
|
||||
for se in seq:
|
||||
res.append(p.pop(se))
|
||||
|
||||
return res
|
||||
|
||||
def main():
|
||||
print("Hello, this is Patrick")
|
||||
|
||||
r = getPermutation(1000000, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
||||
print(r)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user