Slide and Merge
board is a sliding-tile puzzle given as a list of rows: 0 is an empty cell and any other number is a tile showing that number. One move pushes every tile as far as it can go towards the side named by direction: "left", "right", "up" or "down". Each row (for left and right) or each column (for up and down) is handled on its own. Its tiles slide towards that side with no gaps between them, and two tiles with the same number that meet merge into one tile showing their sum. Merging is decided starting from the side the tiles move towards, and a tile made by a merge cannot merge again in the same move. For example, the row [2, 2, 2, 2] moved left becomes [4, 4, 0, 0], and [4, 2, 2, 0] moved left becomes [4, 4, 0, 0], not [8, 0, 0, 0]. Return the board after the move as a new board, without changing board.
Example 1
Row 0: the two 2s merge into a 4 and the old 4 slides next to it. Row 1: the two leftmost 4s merge and the third 4 stays a 4. Row 2: the 8s merge across the gap. Row 3 has no equal neighbours.
Example 2
Column 0 moves down, so merging starts at the bottom: the 4 stays, then the two 2s merge into a 4 that lands on top of it. In column 1 the two 4s merge into an 8.
Constraints
1 <= rows, cols <= 6- every cell is
0or a power of two from 2 to 512 directionis"left","right","up"or"down"
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Grids problems
- Snake GameMedium
- Spiral FillMedium
- Spiral OrderMedium
- Spiral Out From a CellMedium
- Sudoku Rules CheckMedium
- Turn Every RingMedium
- Zigzag DiagonalsMedium
- Darken the BoardHard