Mohamad
Mohamad

Reputation: 35349

Is it possible to compare two arrays in a nested loop for three conditions?

Say you have two arrays (pseudo-code):

arrayA = [ "a", "b", "c", "d" ];
arrayB = [ "b", "c", "d", "e" ];

Is it possible to find unique items to arrayA (arrayA.a), common items (b, c, d), and unique items to arrayB (arrayB.e) using only two loops in a nested format?

We can determine the first two objectives as such:

// Loop over arrayA
for (itemA in arrayA) {

    // Loop over arrayB
    for (itemB in arrayB) {

        // Assume that arrayA.itemA does not exist in arrayB by default
        exists = false;

        // Check for matching arrayA.itemA in arrayB
        if (itemA == itemB) {

            // If true set exists variable and break the loop
            exists = true;
            break;
        }
    }

    // Tells us if an item is common
    if (exists) {
        // Do something
    }

    // The additional condition we need to determine (item is unique to array b)
    else if () {}

    // Tells us if the item is unique to arrayA
    else {
        // Do something else
    }
}

Question: Can we go a step further and determine the third condition (an item is unique to arrayB)? The trick is to be able to act on the third condition in the iteration of the first loop.

The loops can be in any format (do while, do, for, for in) and in any combination.

Upvotes: 1

Views: 1014

Answers (2)

Briguy37
Briguy37

Reputation: 8402

The second condition (item is unique to array b) will always be false, since you are iterating through items in A at that point. However, to answer your first question of building the 3 arrays with 2 loops in a nested format, here's what I would do:

//Set up the arrays to hold the values
uniqueA = itemA;//copy of item A
uniqueB = itemB;//copy of item B
common = [];

//Iterate through the arrays to populate the values
for (itemA in arrayA) {
    for (itemB in arrayB) {
        if(itemB == itemA){
            comon.add(itemA);
            uniqueA.remove(itemA);
            uniqueB.remove(itemB);
            break;
        }
    }
}

Note You could argue that copying itemA and itemB is iterating through them. The only way I see around this is if you don't care about keeping the initial array values and the values are unique, in which case you can use arrayA and arrayB in place of uniqueA and uniqueB respectively.

Upvotes: 1

Vinnyq12
Vinnyq12

Reputation: 1559

You could achieve this by removing the common elements from ArrayB when they are detected. That way ArrayB will only contain its unqiue elements.

This will also increase efficiency in further checks. Note that the algorithm will need to be amended if ArrayA contains duplicate items.

if (itemA == itemB) {

             // If true set exists variable and break the loop
             exists = true;
arrayB.remove(ItemB);
             break;
          }

Upvotes: 2

Related Questions