Simulate 2048 Mechanics and Pack Grid into 64-Bit Integer
Math & Bit ManipulationModel answerLast 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:
- All tiles slide as far as possible towards the target direction.
- Two adjacent tiles of equal value along the line of motion merge into a single tile with twice the original value.
- 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]). - Precedence: Merging priority starts from the target boundary edge (e.g.,
[2, 2, 2, 0]sliding left becomes[4, 2, 0, 0]). - Empty spaces are represented by
0.
Part 2: State Compression
To save space and enable fast state lookups, implement two functions:
encode(board) -> intdecode(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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Strategy
This problem tests two key skills: cleanly managing non-trivial 2D array transformations without repeating code, and manipulating bitfields to store structured data compactly.
Part 1: Grid Sliding & Merging
A common pitfall is duplicating nested loops for each of the four directions (LEFT, RIGHT, UP, DOWN). This leads to repetitive code and high susceptibility to off-by-one errors.
Instead, define a single robust helper function, slide_left_row(row), and map all directions onto it:
- LEFT: Apply
slide_left_rowdirectly to every row. - RIGHT: Reverse each row, apply
slide_left_row, and reverse the result back. - UP: Transpose the board, apply
LEFT, and transpose back. - DOWN: Transpose the board, apply
RIGHT, and transpose back.
1D Slide Logic (slide_left_row):
- Compact: Remove all
0s from the list. For example,[2, 0, 2, 4]becomes[2, 2, 4]. - Merge: Iterate left-to-right through the compacted list. If
row[i] == row[i + 1], outputrow[i] * 2and skip both elements (i += 2). Otherwise, outputrow[i]and advance by 1 (i += 1). Skipping both elements strictly enforces the Single-Merge Constraint. - Pad: Fill the remainder of the output list with
0s until its length is 4.
Part 2: Bit Packing (64-bit Integer Encoding)
The grid consists of $4 \times 4 = 16$ cells. Each cell holds a value $V \in {0, 2^1, 2^2, \dots, 2^{15}}$.
- Mapping Exponents:
- $V = 0 \implies e = 0$
- $V > 0 \implies e = \log_2(V)$ (or
V.bit_length() - 1)
- Bit Positioning:
- Assign each cell $(r, c)$ a linear index $k = 4r + c$, where $0 \le k < 16$.
- Place exponent $e$ into bit positions $[4k, 4k+3]$ of a 64-bit integer using left shifts (
e << (4 * k)).
- Decoding:
- Extract the 4-bit field for cell $k$ using
(packed >> (4 * k)) & 0xF. - If $e = 0$, the cell is
0. Otherwise, the tile value is $1 \ll e$ (or $2^e$).
- Extract the 4-bit field for cell $k$ using
Note on Ambiguity: In binary exponent notation, $e = 0$ mathematically means $2^0 = 1$. However, in standard 2048 rules, tile values start at 2, and empty tiles are 0. Thus, mapping exponent 0 to grid value 0 is unambiguous for valid game states.
Python Code
from typing import List
Board = List[List[int]]
GRID_SIZE = 4
LEFT, RIGHT, UP, DOWN = "LEFT", "RIGHT", "UP", "DOWN"
def slide_left_row(row: List[int]) -> List[int]:
"""Compresses and merges a single 1D row moving to the left."""
non_zeros = [val for val in row if val != 0]
merged = []
i = 0
while i < len(non_zeros):
if i + 1 < len(non_zeros) and non_zeros[i] == non_zeros[i + 1]:
merged.append(non_zeros[i] * 2)
i += 2 # Skip both tiles so the new tile doesn't merge again
else:
merged.append(non_zeros[i])
i += 1
# Pad back to length 4
return merged + [0] * (GRID_SIZE - len(merged))
def transpose(board: Board) -> Board:
"""Returns the matrix transpose of the grid."""
return [list(row) for row in zip(*board)]
def move(board: Board, direction: str) -> Board:
"""Simulates a 2048 grid move in one of 4 directions."""
if direction == LEFT:
return [slide_left_row(row) for row in board]
elif direction == RIGHT:
return [slide_left_row(row[::-1])[::-1] for row in board]
elif direction == UP:
return transpose(move(transpose(board), LEFT))
elif direction == DOWN:
return transpose(move(transpose(board), RIGHT))
else:
raise ValueError(f"Invalid direction: {direction}")
def encode(board: Board) -> int:
"""Packs a 4x4 board into a single 64-bit integer (4 bits per cell)."""
packed = 0
for r in range(GRID_SIZE):
for c in range(GRID_SIZE):
val = board[r][c]
if val == 0:
exponent = 0
else:
exponent = val.bit_length() - 1
if exponent > 15 or (val & (val - 1)) != 0:
raise ValueError(f"Invalid cell value for 4-bit packing: {val}")
cell_idx = r * GRID_SIZE + c
packed |= (exponent & 0xF) << (4 * cell_idx)
return packed
def decode(packed: int) -> Board:
"""Unpacks a 64-bit integer back into a 4x4 board."""
board = [[0] * GRID_SIZE for _ in range(GRID_SIZE)]
for cell_idx in range(16):
r = cell_idx // GRID_SIZE
c = cell_idx % GRID_SIZE
exponent = (packed >> (4 * cell_idx)) & 0xF
board[r][c] = 0 if exponent == 0 else (1 << exponent)
return board
Complexity & Edge Cases
Complexity
moveexecution time: $\mathcal{O}(1)$ (fixed $4 \times 4$ operations). For an $N \times N$ matrix, time complexity is $\mathcal{O}(N^2)$ and auxiliary space is $\mathcal{O}(N^2)$.encode/decodetime: $\mathcal{O}(1)$ time using bitwise operations across 16 fields.
Key Edge Cases
- Cascading Merges: Inputs like
[4, 4, 8, 16]sliding left must result in[8, 8, 16, 0], not combining into32. - Merged Priority: Inputs like
[2, 2, 2, 0]sliding right must become[0, 0, 2, 4]. - Zero Gaps: Inputs like
[2, 0, 0, 2]must close the gap and merge into[4, 0, 0, 0].
Systems Follow-Up: Fast Moves via Lookup Tables
In performance-critical scenarios (e.g., Monte Carlo Tree Search for a 2048 AI player), computing moves via dynamic list operations is too slow.
Because each row is encoded using $4 \times 4 = 16$ bits, there are only $2^{16} = 65,536$ distinct row states.
- Precompute a lookup table
ROW_MOVE_LEFT[65536]of size 65,536 during startup, mapping every 16-bit packed row to its 16-bit packed result after a left slide. - A full 64-bit board slide to the left then reduces to 4 table lookups and shift/OR operations.
- For vertical moves (
UP/DOWN), one can perform a fast 64-bit matrix transpose via bit manipulation (similar to graphics raster swapping) and re-use row lookup tables.