Simulate 2048 and pack board into uint64
CitadelSoftware Engineer · OnsiteLast updated
This question evaluates proficiency in implementing deterministic game-state logic and compact binary representations, specifically array manipulation and merge semantics for 2048 slide operations plus bit-level packing/unpacking of 4-bit exponent fields.
Problem: 2048 move simulation + board compression
You are implementing part of the 2048 game on a fixed 4×4 grid.
Part A — Simulate a move
Given a 4×4 board of non-negative integers (each is either 0 or a power of two), implement a function:
move(board, dir) -> new_board
where dir ∈ {LEFT, RIGHT, UP, DOWN}.
Rules (standard 2048):
- All tiles slide as far as possible in the chosen direction.
- If two adjacent tiles in the direction of movement have the same value, they merge into one tile of value
2x. - Each tile can merge at most once per move.
- Zeros represent empty cells.
Part B — Encode/decode the board into a 64-bit integer
Implement two functions:
encode(board) -> uint64decode(x) -> board
Constraints/assumptions for encoding:
- The board is 4×4 = 16 cells.
- Store each cell in 4 bits as the exponent
ewhere value =2^e. - Empty cell (0) is stored as
e = 0. - Example: value 2 → e=1, 4 → e=2, …
- Assume no cell exceeds
2^15(so exponent fits in 4 bits). - You may choose any fixed cell order (e.g., row-major), but
decode(encode(board))must reproduce the original board.
Deliverables
Describe/implement move, encode, and decode with correct handling of merges and bit packing.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.