Skip to content

Instantly share code, notes, and snippets.

@vgmoose
Created January 9, 2015 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgmoose/71b99ebec86c6558f041 to your computer and use it in GitHub Desktop.
Save vgmoose/71b99ebec86c6558f041 to your computer and use it in GitHub Desktop.
Move all 0s to the front in an array of 1s and 0s
def solve(a):
lastNonZeroPos = -1
for x in range(0, len(a)):
# if the lastnonzeropos isn't set, and this is nonzero
if lastNonZeroPos < 0 and a[x] != 0:
# set the last non zero pos
lastNonZeroPos = x
# else if this is a zero and lastnonzero has been set
if lastNonZeroPos >= 0 and a[x] == 0:
# swap this position with the last non zero
temp = a[x]
a[x] = a[lastNonZeroPos]
a[lastNonZeroPos] = temp
# increment the lastnonzeropos (cause you know the one to the right of it is nonzero)
lastNonZeroPos += 1
# print a, lastNonZeroPos
print a
solve([0,1,0,1,0,1,1,0])
solve([1,0,1,0,1,1,0])
solve([0,1,0,1,0,1])
solve([0,1,0,1,0,1,0])
solve([0,1,0,1,0,0,0,1,0])
solve([1,1,1,1,1,1,0,0,0,0,0])
solve([1,1,1,1,0,0,1,0,0,1,1,1,0,1,0,0,0,1,0,1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment