Skip to content

Commit 53ca783

Browse files
committed
WIP
1 parent 7f4d8e7 commit 53ca783

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from collections import Counter
2+
from functools import reduce
3+
from typing import Final
4+
5+
ELEMENTS: Final = (
6+
"A",
7+
"B",
8+
"C",
9+
"D",
10+
"E",
11+
)
12+
N_PERMUTATIONS: Final = reduce(lambda x, y: x * y, range(len(ELEMENTS), 0, -1))
13+
14+
15+
def rank(permutation: tuple[str, ...]) -> int:
16+
if Counter(permutation) != Counter(ELEMENTS):
17+
raise ValueError("Invalid permutation")
18+
19+
rank = 0
20+
for i, element in enumerate(permutation):
21+
rank += ELEMENTS.index(element) * len(ELEMENTS) ** (len(permutation) - i - 1)
22+
return rank
23+
24+
25+
def unrank(rank: int) -> tuple[str, ...]:
26+
if rank < 0 or rank >= len(ELEMENTS) ** len(ELEMENTS):
27+
raise ValueError("Invalid rank")
28+
29+
permutation = []
30+
for i in range(len(ELEMENTS)):
31+
permutation.append(ELEMENTS[rank % len(ELEMENTS)])
32+
rank //= len(ELEMENTS)
33+
34+
35+
if __name__ == "__main__":
36+
print(N_PERMUTATIONS)
37+
print(ELEMENTS)
38+
print(
39+
rank(
40+
(
41+
"A",
42+
"B",
43+
"C",
44+
"D",
45+
"E",
46+
)
47+
)
48+
)
49+
print(
50+
unrank(
51+
rank(
52+
(
53+
"A",
54+
"B",
55+
"C",
56+
"D",
57+
"E",
58+
)
59+
)
60+
)
61+
)
62+
print(unrank(1))

0 commit comments

Comments
 (0)