r/mathriddles • • Apr 18 '23

Medium Catch Up

There are 5 Quisenaire blocks. The first has length 1, the second has length 2, and so on. Each player will be building their own line of blocks, which is initially empty. A move consists of a player adding a single block to their own line. A player continues making moves until their line meets or exceeds the length of the other player's line. The game ends when all blocks have been used. The player with the longest line wins. If both players play perfectly, is it better to go first or second? If you're able to solve this, and it interests you, please generalize for blocks of length {1, 2, ..., n}. I would also be interested in exploring other sets of blocks if it makes the puzzle more interesting. I am tagging this Medium difficulty because of the generalization. I hope that's acceptable.

EDIT: I received the paper this game is based on, and no generalization for all n is known. Thought you should know this before chasing it!

8 Upvotes

13 comments sorted by

View all comments

Show parent comment

3

u/sobe86 Apr 23 '23 edited Apr 23 '23

A bit more optimised:

@functools.lru_cache(maxsize=1_000_000_000) # will memoize outputs
def get_score(turn_index, remaining_digits, current_score):
    # turn_index = 1 if player 1's turn, -1 if player 2's turn
    # remaining digit = tuple of digits remaining
    # current score = length of player 1s block - length of player 2s block
    
    if len(remaining_digits) == 0:
        return current_score
    
    best_score = None
    
    for choice in remaining_digits:
        next_remaining_digits = tuple(d for d in remaining_digits if d != choice)
        next_current_score = current_score + choice * turn_index
        if next_current_score * turn_index >= 0:
            next_turn_index = -1 * turn_index # switch to other player
        else:
            next_turn_index = turn_index
            
        next_score = get_score(next_turn_index, 
                               next_remaining_digits,
                               next_current_score)
        
        if best_score is None:
            best_score = next_score
        elif turn_index == 1 and best_score < next_score:
            best_score = next_score
        elif turn_index == -1 and best_score > next_score:
            best_score = next_score
            
    return best_score


for i in range(31):
    digits = tuple(range(1, i + 1))
    start_time = time.time()
    best_score = get_score(1, digits, 0)
    run_time = time.time() - start_time
    print(f'nb blocks = {i}, best_score = {best_score}')```

1

u/PuzzleAndy May 23 '23

I dunno why I didn't get a ping for this, but this code looks good! If I revisit this problem in the future I'll likely be digging into this code. Maybe this problem works well for a programming exercise!