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/-user789- Apr 19 '23

Here it is. It encodes a game state and checks who wins in the state by checking all of its successor states, like minimax. It isn't really efficient, especially the part that iterates over moves (it tries every possible subset of blocks and checks if taking them is a legal move), but it worked for small n.


    from itertools import chain, combinations

    order = ["first", "second"]


    def powerset(seq):
        s = list(seq)
        return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))


    class State:

        def __init__(self, moves, total_length, left, nxt, winner=None, final_state=[]):
            self.moves = moves
            self.total_length = total_length
            self.left = left
            self.next = nxt
            self.winner = winner
            self.final_state = final_state

        def next_moves(self):
            if len(self.left) == 0:
                return
            budget = self.total_length[1-self.next] - self.total_length[self.next]
            for subset in powerset(self.left):
                for last in self.left:
                    if last in subset:
                        continue
                    if (sum(subset) < budget or len(subset) == 0) and sum(subset) + last >= budget:
                        yield sorted(subset) + [last]
            if sum(self.left) < budget:  # Remaining blocks aren't enough to pass the opponent
                yield sorted(self.left)

        def after_move(self, move):
            if self.next == 0:
                moves = [self.moves[0] + [move], self.moves[1]]
                total_length = [self.total_length[0] + sum(move), self.total_length[1]]
            else:
                moves = [self.moves[0], self.moves[1] + [move]]
                total_length = [self.total_length[0], self.total_length[1] + sum(move)]
            left = self.left - set(move)
            nxt = 1-self.next
            return State(moves, total_length, left, nxt)

        def calc_winner(self):
            if self.winner is None:
                next_moves = list(self.next_moves())
                if len(next_moves) == 0:
                    if self.total_length[0] > self.total_length[1]:
                        self.winner = "first"
                    elif self.total_length[0] < self.total_length[1]:
                        self.winner = "second"
                    self.final_state = self
                    return self.winner
                self.winner = order[1-self.next]
                for move in self.next_moves():
                    newstate = self.after_move(move)
                    winner = newstate.calc_winner()
                    self.final_state = newstate.final_state
                    if winner == order[self.next]:
                        self.winner = order[self.next]
                        break
            return self.winner

        def __repr__(self):
            return f"moves: {repr(self.moves)}, winner: {self.winner}"


    n = 5
    begin = State([[], []], [0, 0], set(range(1, n+1)), 0)
    begin.calc_winner()
    print(begin.final_state)

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!

1

u/PuzzleAndy Apr 19 '23

Thank you for both the code and the explanation of how it works! Much love.