KatInterview

Simulate 2048 Mechanics and Pack Grid into 64-Bit Integer

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationbit-manipulationarrayssimulation

Last updated

Simulate grid sliding and merging rules for the game 2048, and design a bit-packing scheme to compress the 4x4 state into a single 64-bit integer.

You are tasked with implementing core engine logic for a 4x4 sliding-tile game modeled after 2048.

Part 1: Grid Move Mechanics

Write a function move(board, direction) that takes a 4x4 matrix of non-negative integers (where every non-zero cell is a power of 2) and an operational direction ("LEFT", "RIGHT", "UP", or "DOWN"). The function must return a new 4x4 matrix reflecting the result of sliding tiles in the specified direction.

Rules:

  1. All tiles slide as far as possible towards the target direction.
  2. Two adjacent tiles of equal value along the line of motion merge into a single tile with twice the original value.
  3. Single-Merge Constraint: A tile formed by a merge in the current step cannot merge again during that same move (e.g., [4, 4, 8, 0] sliding left becomes [8, 8, 0, 0], not [16, 0, 0, 0]).
  4. Precedence: Merging priority starts from the target boundary edge (e.g., [2, 2, 2, 0] sliding left becomes [4, 2, 0, 0]).
  5. Empty spaces are represented by 0.

Part 2: State Compression

To save space and enable fast state lookups, implement two functions:

  • encode(board) -> int
  • decode(packed_int) -> board

Requirements:

  • Store each of the 16 cells using 4 bits (a nibble).
  • A 4-bit field represents the base-2 exponent $e$ of the tile's value, where $\text{value} = 2^e$.
  • An empty cell (0) is encoded as $e = 0$.
  • Assume that no individual cell value exceeds $2^{15} = 32768$ (so $0 \le e \le 15$).
  • The total binary representation must fit inside a standard unsigned 64-bit integer (uint64).
  • Round-tripping decode(encode(board)) must reliably reconstruct the original grid.

Hints

Hint 1

Rather than writing four complex loops for sliding in each direction, write a helper function that processes a single row sliding left. Transform the grid using reversals or transpositions to reuse this single helper.

Hint 2

When sliding a row left, filter out zeros first. Then iterate through adjacent non-zero pairs to perform merges, advancing the pointer by 2 on a merge and 1 on a plain move.

Hint 3

Since cell values are powers of two up to 2^15, you can find exponent e using bit length or log2. Ensure you map value 0 to exponent 0.