Created
January 9, 2015 02:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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