Skip to content

Instantly share code, notes, and snippets.

@dchrzanowski
Created June 2, 2016 14:21
Show Gist options
  • Save dchrzanowski/edd49e54f52d3544142886507ee30013 to your computer and use it in GitHub Desktop.
Save dchrzanowski/edd49e54f52d3544142886507ee30013 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
import doctest
def shift_zeros(line):
no_zeros = [each for each in line if each != 0] # make a list with no zeroes
return no_zeros + ([0] * (len(line) - len(no_zeros))) # return the list with the zeroes added at the end
def merge(line):
"""
(list) -> list
Function that merges a single row or column in 2048.
>>> merge([1,1,0,1])
[2, 1, 0, 0]
>>> merge([1,2,2,1])
[1, 4, 1, 0]
>>> merge([1,0,1,0,1,1,0,0,0,0,0,1])
[2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> merge([1,2,1,2,0])
[1, 2, 1, 2, 0]
"""
line = shift_zeros(line) # shift all the zeroes to the right
for idx in range(len(line) - 2): # skip the last idx (would cause an error on the next line)
if line[idx] == line[idx + 1]: # check if neighbouring idxs are of the same value
line[idx], line[idx + 1] = line[idx] * 2, 0 # multiply the first idx by 2, and the neighbouring make a 0
return shift_zeros(line) # return the list with zeroes shifted out
if __name__ == '__main__':
doctest.testmod()
print merge([1, 0, 1, 0, 1, 1, 0, 0, 1])
print merge([1, 2, 1, 3, 0])
raw_input('Press Enter')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment