Nikko
Nikko

Reputation: 547

unique values array in loop

I hope you can help me. I have the follwoing problem.

I have an array made of random numbers. Given a value n, I need to choose the n unique numbers from that array ,and then iterate over it comparing the next element with the previous n unique numbers. I have this until now:

import random
len1=30
array1=[]
for j in range(1,len1):
     z=random.randint(1,30)
     array1.append(z)
n=5
k=0
l=n
for idx,val in enumerate(array1):    
     if idx>n-1:
         print(val)
         array2=array1[k:l]        
         for p in array2:
             if p == val:
                 #do things
                 ok=1
             else:
                 ok=2
    k=k+1
    l=l+1

Overall the behaviour of this routine is good, however it doesn't take into account the uniqueness of the numbers of array2. My question is: How can I have a vector of unique n values extracted from array1? Just one condition I cannot look "forward" in the vector. I have to use always a lower index of array1 than the actual idx in the loop.

In another words, if I have n =5 and:

 array1=[1,2,3,4,5,6,7,7,8,9]

and I am in the idx 8 (i.e =

 array2=[3,4,5,6,7] (in any order)

Upvotes: 1

Views: 1227

Answers (1)

Engineero
Engineero

Reputation: 12918

One option, loop through the input array1 and fill your array2 up with unique values as you go. If your array2 gets too long, remove the oldest item from the list.

n = 5
arr2 = []
for val in arr1:
    if not arr2:
        arr2.append(val)  # new array case
    else:
        if arr2.count(val):
            arr2.remove(val)  # remove first occurrence (shifts everything ahead of it down one)
            arr2.append(val)  # append val to end
        else:
            arr2.append(val)  # append new unique value
            if len(arr2) > n:
                arr2.pop(0)  # remove oldest value if array is too long
    print(arr2)

Run on the example arr1 = [1, 2, 3, 4, 5, 6, 5, 4, 7], we get the following sequence of outputs:

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[2, 3, 4, 5, 6]
[2, 3, 4, 6, 5]
[2, 3, 6, 5, 4]
[3, 6, 5, 4, 7]

Upvotes: 1

Related Questions