Programmer Puzzle: Encoding a chess board state throughout a game

前端 未结 30 1534
闹比i
闹比i 2021-01-29 17:16

Not strictly a question, more of a puzzle...

Over the years, I\'ve been involved in a few technical interviews of new employees. Other than asking the standard \"do you

30条回答
  •  借酒劲吻你
    2021-01-29 17:36

    I saw this question last night and it intrigued me so I sat in bed thinking up solutions. My final answer is pretty similar to int3's actually.

    Basic solution

    Assuming a standard chess game and that you don't encode the rules (like White always goes first), then you can save a lot by encoding just the moves each piece makes.

    There are 32 pieces total but on each move you know what colour is moving so there's only 16 squares to worry about, which is 4 bits for which piece moves this turn.

    Each piece only has a limited moveset, which you would enumerate in some way.

    • Pawn: 4 options, 2 bits (1 step forward, 2 steps forward, 1 each diagonal)
    • Rook: 14 options, 4 bits (max of 7 in each direction)
    • Bishop: 13 options, 4 bits (if you have 7 in one diagonal, you only have 6 in the other)
    • Knight: 8 options, 3 bits
    • Queen: 27 options, 5 bits (Rook+Bishop)
    • King: 9 options, 4 bits (8 one-step moves, plus the castling option)

    For promotion, there are 4 pieces to choose from (Rook, Bishop, Knight, Queen) so on that move we would add 2 bits to specify that. I think all the other rules are covered automatically (e.g. en passant).

    Further optimizations

    First, after 8 pieces of one colour have been captured, you could reduce the piece encoding to 3 bits, then 2 bits for 4 pieces and so on.

    The main optimization though is to enumerate only the possible moves at each point in the game. Assume we store a Pawn's moves as {00, 01, 10, 11} for 1 step forward, 2 steps forward, diagonal left and diagonal right respectively. If some moves are not possible we can remove them from the encoding for this turn.

    We know the game state at every stage (from following all the moves), so after reading which piece is going to move, we can always determine how many bits we need to read. If we realize a pawn's only moves at this point are capture diagonally right or move forward one, we know to only read 1 bit.

    In short, the bit storage listed above for each piece is a maximum only. Nearly every move will have fewer options and often fewer bits.

提交回复
热议问题