Simulate 2048 and pack board into uint64
Company: Citadel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: 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.
Part 1: Simulate a 2048 Move
Constraints
- board is always 4x4
- Each cell is 0 or a power of two
- direction is one of 'LEFT', 'RIGHT', 'UP', 'DOWN'
- You must follow the rule that each tile merges at most once per move
Examples
Input: ([[2, 0, 2, 4], [0, 4, 4, 8], [2, 2, 2, 2], [0, 0, 0, 2]], 'LEFT')
Expected Output: [[4, 4, 0, 0], [8, 8, 0, 0], [4, 4, 0, 0], [2, 0, 0, 0]]
Explanation: Each row is compressed to the left, with equal adjacent tiles merging once.
Input: ([[2, 2, 2, 0], [4, 0, 4, 4], [2, 2, 4, 4], [0, 0, 0, 0]], 'RIGHT')
Expected Output: [[0, 0, 2, 4], [0, 0, 4, 8], [0, 0, 4, 8], [0, 0, 0, 0]]
Explanation: Merges happen from the side of movement, and no tile merges twice.
Hints
- Write a helper that processes a single line moving left: remove zeros, merge equal neighbors once, then pad with zeros.
- You can reuse the same helper for RIGHT, UP, and DOWN by reversing rows or working column-by-column.
Part 2: Encode and Decode a 4x4 2048 Board into 64 Bits
Constraints
- board is always 4x4
- Each cell is 0 or a power of two
- No cell exceeds 32768, so its exponent fits in 4 bits
- Use row-major order with cell index k = 4 * row + col
Examples
Input: ([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Expected Output: (0x0, [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Explanation: Edge case: all empty cells produce the integer 0.
Input: ([[2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Expected Output: (0x1, [[2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
Explanation: The top-left cell has exponent 1, stored in the least-significant 4 bits.
Hints
- For a non-zero power of two, the exponent can be found with bit_length() - 1.
- To pack cell k, shift its 4-bit exponent left by 4 * k. To unpack, mask with 0xF after shifting right.