ধরুন একটি 2048 গেম বোর্ড দেওয়া আছে (প্রাথমিক বোর্ড) এবং একটি ডিরেকশন স্ট্রিং (স্বাইপ ডিরেকশন)। আমাদের পরবর্তী বোর্ড স্টেট বের করতে হবে। 2048 গেমে 4x4 বোর্ডে নম্বর থাকে (খালি জায়গা 0)। 4 ডিরেকশনে ("U", "D", "L", "R") স্বাইপ করা যায়। স্বাইপ করলে সব নম্বর ওই ডিরেকশনে যতদূর সম্ভব চলে যায় এবং একই পরিপ@", "identical adjacent numbers are added up exactly once.") ...
সমাধান পদ্ধতি
- ডিরেকশন অনুযায়ী বোর্ড রোটেট করুন (L-এর জন্য রোটেশন লাগে না)।
- প্রতিটি রোয়ের জন্য নন-জিরো এলিমেন্ট বের করুন।
- সমান আসন্ন নম্বরগুলো যোগ করুন (একবারই)।
- রোয়ে ০ প্যাড করে ৪টি এলিমেন্ট করুন।
- আগের রোটেশন উল্টে ফেরান।
বাস্তবায়ন
class Solution:
def solve(self, board, direction):
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)))
for i in range(4):
row = [x for x in board[i] if x]
for j in range(3):
if j + 1 < len(row) and row[j] == row[j + 1]:
row[j] *= 2
del row[j + 1]
while len(row) < 4:
row += [0]
board[i] = row
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
def rot_anti_clock_dir(x):
x = [[x[i][j] for i in range(4)] for j in range(4)]
return x[::-1]
ob = Solution()
matrix = [
[2, 0, 0, 2],
[2, 2, 2, 2],
[0, 4, 2, 2],
[2, 2, 2, 0]
]
print(ob.solve(matrix, "L"))
ইনপুট
matrix = [
[2, 0, 0, 2],
[2, 2, 2, 2],
[0, 4, 2, 2],
[2, 2, 2, 0]
]
আউটপুট
[
[4, 0, 0, 0],
[4, 4, 0, 0],
[4, 4, 0, 0],
[4, 2, 0, 0]
]