Push a value to an array if it's not already in the array

   3822   3   2
User Avatar
Member
141 posts
Joined: March 2016
Offline
Hello
New to VEX and i have a question on arrays.
Is there a way to take the values from Array2 and push()them into Array1, but only if the value in Array2 doesn't already exist in Array1, preventing duplicates? (Ill be using in a solver, finding more and more points as it progresses)

I've figured out a way to do the reverse (see below)- Comparing Array1 and Array2, pushing the duplicates to a separate array and then using this to remove the values from a combined Array1&2 - but this seem a but long winded or inefficient?

i[]@pointsArray1 = {0,2,7,8,10};
i[]@pointsArray2 = {0,3,5,7,8,11,15,16,10};
i[]@newArray;

//Compare both arrays and extract the duplicate values
foreach (int num; i[]@pointsArray1){

for(int i = 0; i<len(i[]@pointsArray2);i++){

    if(num == i[]@pointsArray2[i]){
    push(i[]@newArray,i[]@pointsArray2[i]);

    }    
  }

}
//Combine both arrays into one
push(i[]@pointsArray1,i[]@pointsArray2);

//Take the know duplicates and remove from the combined array
for(int i = 0; i<len(i[]@newArray);i++){
removevalue(i[]@pointsArray1,i[]@newArray[i]);
}

Any thoughts much appreciated
Love Houdini
User Avatar
Member
141 posts
Joined: March 2016
Offline
Hello - since posting this i actually figured i could do like the below - please do let me know if there's any better approach:

i[]@pointsArray1 = {0,2,7,8,10};
i[]@pointsArray2 = {0,3,5,7,8,11,15,16,10};

for (int i=0; i<len(i[]@pointsArray2);i++){
    if (!(find(i[]@pointsArray1, i[]@pointsArray2[i])>=0)) {
         push(i[]@pointsArray1,i[]@pointsArray2[i]);
    }
}
Love Houdini
User Avatar
Member
5100 posts
Joined: Feb. 2012
Offline
Hi,

I would write something like this:

i[]@pointsArray1 = {0,2,7,8,10};
i[]@pointsArray2 = {0,3,5,7,8,11,15,16,10};

foreach(int pt; i[]@pointsArray2)
    if (find(i[]@pointsArray1, pt) < 0)
         append(i[]@pointsArray1, pt);
Edited by animatrix_ - May 19, 2020 12:45:11
Senior FX TD @ Industrial Light & Magic
Get to the NEXT level in Houdini & VEX with Pragmatic VEX! [www.pragmatic-vfx.com] https://lnk.bio/animatrix [lnk.bio]
User Avatar
Member
141 posts
Joined: March 2016
Offline
yes of course! that does make more sense - thanks
Love Houdini
  • Quick Links