Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy an Array without doubles in PseudoCode

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading