Created
April 25, 2023 17:44
-
-
Save richardkiss/7f9643e1a61181206232823f73a7300f to your computer and use it in GitHub Desktop.
Hand permutations to index and vice versa
This file contains 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
from math import comb | |
from typing import List | |
Hand = List[int] | |
def hand_from_index(index: int, deck_indices: List[int], hand_size: int) -> Hand: | |
hand = [] | |
deck_size = len(deck_indices) | |
deck_index = 0 | |
cards_remaining = hand_size | |
while 0 < cards_remaining: | |
hands_including_this_card = comb( | |
deck_size - deck_index - 1, cards_remaining - 1 | |
) | |
if index < hands_including_this_card: | |
# we include the card at deck_index | |
hand.append(deck_indices[deck_index]) | |
cards_remaining -= 1 | |
else: | |
index -= hands_including_this_card | |
deck_index += 1 | |
assert index == 0 | |
return hand | |
def index_from_hand(hand_index_list, deck_size): | |
result = 0 | |
deck_index = 0 | |
hand_index = 0 | |
hand_size = len(hand_index_list) | |
for hand_index in hand_index_list: | |
while deck_index < hand_index: | |
hands_including_this_card = comb(deck_size - deck_index - 1, hand_size - 1) | |
result += hands_including_this_card | |
deck_index += 1 | |
deck_index += 1 | |
hand_size -= 1 | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment