Ian
Ian

Reputation: 3898

Assert if two 2D arrays are equal

Given two 2D arrays, how can I assert whether or not they are equal?

For example:

array1 = [[1,0],[2,1],[3,0]]
array2 = [[1,0],[2,1],[3,1]]

What is an efficient way to check whether array1 == array2?

Upvotes: 4

Views: 3227

Answers (3)

VisioN
VisioN

Reputation: 145408

If by equality you mean the array contents have same elements in the same order, then the shortest (though not the fastest) way will be:

JSON.stringify(array1) === JSON.stringify(array2)

This will work with arrays of any dimensions.

UPDATE: If you need a really fast algorithm then simple iteration will work better. However it is less fool-proof, hence to make it really safe and secure you'll need to spend more development time. Here is one possible solution for modern browsers:

function equal(array1, array2) {
    if (!Array.isArray(array1) && !Array.isArray(array2)) {
        return array1 === array2;
    }

    if (array1.length !== array2.length) {
        return false;
    }

    for (var i = 0, len = array1.length; i < len; i++) {
        if (!equal(array1[i], array2[i])) {
            return false;
        }
    }

    return true;
}

The following JSPerf speed test shows the supremacy of this algorithm over the short JSON approach: http://jsperf.com/2d-array-comparion.

Upvotes: 6

blenddd
blenddd

Reputation: 345

The most efficient way would always depend on the size of the array/s and on your application and usage for them. You can check for the lengths of the 2 arrays for an early termination in case of a non match, but this might be considered as an extra step if that case rarely happens.

boolean areEqual(array array1, array array2){
if array1.length != array2.length
    return false;
for (int i=0;i<array1.length; i++)
    if(!areEqual(array1[i], array2[i])
        return false;
return true;
}

boolean areEqual(int first, int second){
    return first == second;
}

Upvotes: 1

Adnan Zameer
Adnan Zameer

Reputation: 782

The way to go would be to iterate all values in a nested loop, compare value by value. Use a boolean which you set to false at the first mismatch, and assert that this boolean is true in your test.

Upvotes: 0

Related Questions