Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a shift function in 2048

Let us say i have a list:

board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2]

and i already have some code that will make the list be displayed like this:

2 4 0 2
8 4 4 8
0 2 0 0
4 0 2 2

So is there a way for me to remove every 0 from each row and add it back in the end(even if there are different values in the list) so that the board now looks like:

2 4 2 0
8 4 4 8
2 0 0 0
4 2 2 0

I want to do this using a loop and not individually having to write separate code for each row.

Also can you do this without making the initial list to

board = [[2, 4, 0, 2], [8, 4, 4, 8], [0, 2, 0, 0], [4, 0, 2, 2]]

The code for 1 row would be :

board = [2, 0, 0, 2]
k = len(board)
board[:] = (value for value in board if value != 0)
while len(board) < k:
    board.append(0)
print(board)

Output = [2, 2, 0, 0]
like image 829
J. Doe Avatar asked Dec 17 '22 22:12

J. Doe


2 Answers

You can use list.count:

board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2]
new_board = [board[i:i+4] for i in range(0, len(board), 4)]
final_board = [list(filter(None, i))+([0]*i.count(0)) for i in new_board]
last_board = [i for b in final_board for i in b]

Output:

[2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 0]
like image 55
Ajax1234 Avatar answered Dec 20 '22 12:12

Ajax1234


Sometimes there is nothing wrong with a simple loop:

board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2]

x=4
nb=[]
for e in zip(*[iter(board)]*x):
    ne=[se for se in e if se!=0]
    nb.extend(ne+[0]*(x-len(ne)))  #.append if you want to maintain sub lists

>>> nb
[2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 0]
like image 45
dawg Avatar answered Dec 20 '22 11:12

dawg