I’m trying to copy an array of values to another array and removing the double values in an natural order (so the 0 values to the end of the array). I have to put in pseudocode so I can’t use easy functions or methods.
To check my ideas I tried it in Python like this:
A = [1, 2, 3, 4, 4, 5, 5, 5, 6, 7, 8, 9]
B = [0 for b in range(12)]
for i in range(12):
if A[i]== A[i-1]:
else:
B[i] = A[i]
print(B)
it gives me:
[1, 2, 3, 4, 0, 5, 0, 0, 6, 7, 8, 9]
but the result I’m looking for is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0 , 0]
What is missing?
>Solution :
Your i is always incrementing, so each iteration, whether you copied an element or not, will handle the next element in B.
You can keep track of how many elements you skipped, and use it to access B in the correct index:
skipped = 0
for i in range(12):
if A[i] == A[i-1]:
skipped += 1
else:
B[i-skipped] = A[i]
Output of print(B):
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0]