Programmer Puzzle: Encoding a chess board state throughout a game

前端 未结 30 1574
闹比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:50

    Attacking a subproblem of encoding the steps after an initial position has been encoded. The approach is to create a "linked list" of steps.

    Each step in the game is encoded as the "old position->new position" pair. You know the initial position in the beginning of the chess game; by traversing the linked list of steps, you can get to the state after X moves.

    For encoding each step, you need 64 values to encode the starting position (6 bits for 64 squares on the board - 8x8 squares), and 6 bits for the end position. 16 bits for 1 move of each side.

    Amount of space that encoding a given game would take is then proportionate to the number of moves:

    10 x (number of white moves + number of black moves) bits.

    UPDATE: potential complication with promoted pawns. Need to be able to state what the pawn is promoted to - may need special bits (would use gray code for this to save space, as pawn promotion is extremely rare).

    UPDATE 2: You don't have to encode the end position's full coordinates. In most cases, the piece that's being moved can move to no more than X places. For example, a pawn can have a maximum of 3 move options at any given point. By realizing that maximum number of moves for each piece type, we can save bits on the encoding of the "destination".

    Pawn: 
       - 2 options for movement (e2e3 or e2e4) + 2 options for taking = 4 options to encode
       - 12 options for promotions - 4 promotions (knight, biship, rook, queen) times 3 squares (because you can take a piece on the last row and promote the pawn at the same time)
       - Total of 16 options, 4 bits
    Knight: 8 options, 3 bits
    Bishop: 4 bits
    Rook: 4 bits
    King: 3 bits
    Queen: 5 bits
    

    So the spatial complexity per move of black or white becomes

    6 bits for the initial position + (variable number of bits based upon the type of the thing that's moved).

提交回复
热议问题