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) -> uint64
-
decode(x) -> board
Constraints/assumptions for encoding:
-
The board is 4×4 = 16 cells.
-
Store each cell in
4 bits
as the exponent
e
where 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.