Program to find next board position after sliding the given direction once in Python

Suppose we have a 2048 game board representing the initial board and a string direction representing the swipe direction, we have to find the next board state. As we know in the 2048 game, we are given a 4 x 4 board of numbers (some of them are empty, represented in here with 0) which we can swipe in any of the 4 directions ("U", "D", "L", or "R"). When we swipe, all the numbers move in that direction as far as possible and identical adjacent numbers are added up exactly once.

So, if the input is like ?

Initial Board 2 0 0 2 2 2 2 2 0 4 2 2 2 2 2 0

direction = "L", then the output will be ?

After Sliding Left 4 0 0 0 4 4 0 0 4 4 0 0 4 2 0 0

Algorithm

To solve this, we will follow these steps ?

  • If direction is "R", rotate board anti-clockwise twice

  • If direction is "U", rotate board anti-clockwise once

  • If direction is "D", rotate board anti-clockwise three times

  • For each row, extract non-zero elements and merge adjacent identical numbers

  • Pad each row with zeros to maintain 4-element length

  • Rotate the board back to original orientation

Implementation

def rot_anti_clock_dir(board):
    # Transpose and reverse rows for 90-degree anti-clockwise rotation
    board = [[board[i][j] for i in range(4)] for j in range(4)]
    return board[::-1]

class Solution:
    def solve(self, board, direction):
        # Rotate board to make all movements equivalent to left slide
        if direction == "R":
            board = rot_anti_clock_dir(rot_anti_clock_dir(board))
        elif direction == "U":
            board = rot_anti_clock_dir(board)
        elif direction == "D":
            board = rot_anti_clock_dir(rot_anti_clock_dir(rot_anti_clock_dir(board)))
        
        # Process each row (slide left and merge)
        for i in range(4):
            # Extract non-zero elements
            row = [x for x in board[i] if x != 0]
            
            # Merge adjacent identical numbers
            j = 0
            while j < len(row) - 1:
                if row[j] == row[j + 1]:
                    row[j] *= 2  # Merge
                    del row[j + 1]  # Remove merged element
                j += 1
            
            # Pad with zeros to maintain 4-element length
            while len(row) < 4:
                row.append(0)
            
            board[i] = row
        
        # Rotate back to original orientation
        if direction == "R":
            board = rot_anti_clock_dir(rot_anti_clock_dir(board))
        elif direction == "U":
            board = rot_anti_clock_dir(rot_anti_clock_dir(rot_anti_clock_dir(board)))
        elif direction == "D":
            board = rot_anti_clock_dir(board)
        
        return board

# Test the solution
ob = Solution()
matrix = [
    [2, 0, 0, 2],
    [2, 2, 2, 2],
    [0, 4, 2, 2],
    [2, 2, 2, 0]
]

result = ob.solve(matrix, "L")
for row in result:
    print(row)
[4, 0, 0, 0]
[4, 4, 0, 0]
[4, 4, 0, 0]
[4, 2, 0, 0]

How It Works

The algorithm works by transforming all swipe directions into a standard left swipe ?

  • Rotation Strategy: We rotate the board so that any direction becomes equivalent to sliding left

  • Merging Logic: For each row, we first collect all non-zero elements, then merge adjacent identical numbers from left to right

  • Padding: After merging, we pad the row with zeros to maintain the 4-element structure

  • Restoration: Finally, we rotate the board back to its original orientation

Testing Different Directions

# Test all four directions
ob = Solution()
original_matrix = [
    [2, 0, 0, 2],
    [2, 2, 2, 2],
    [0, 4, 2, 2],
    [2, 2, 2, 0]
]

directions = ["L", "R", "U", "D"]

for direction in directions:
    # Create a copy to avoid modifying original
    test_matrix = [row[:] for row in original_matrix]
    result = ob.solve(test_matrix, direction)
    print(f"Direction {direction}:")
    for row in result:
        print(row)
    print()
Direction L:
[4, 0, 0, 0]
[4, 4, 0, 0]
[4, 4, 0, 0]
[4, 2, 0, 0]

Direction R:
[0, 0, 0, 4]
[0, 0, 4, 4]
[0, 0, 4, 4]
[0, 0, 4, 2]

Direction U:
[4, 4, 4, 4]
[0, 2, 2, 2]
[0, 0, 0, 0]
[0, 0, 0, 0]

Direction D:
[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 4, 4, 4]
[4, 2, 2, 2]

Conclusion

This solution efficiently simulates 2048 game mechanics by using board rotation to standardize all directions into left slides. The key insight is transforming the problem space to simplify the sliding and merging logic.

Updated on: 2026-03-25T11:53:23+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements