Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm - Find existence of a 2d array in another 2d array

I came across this question while in an interview and i am unable to find the best way to do it.

The question says, there are two 2d arrays, one is bigger than the other. Lets say,

Array_1 = [[1,2],
           [5,6]]

and

Array_2 = [[1,2,3,4],
           [5,6,7,8], 
           [9,10,11,12]]

Since, here the Array 2 contains Array 1, the algo should return true. Otherwise, false.

The size of the array can be anything.

like image 375
invincibleDudess Avatar asked Nov 10 '22 13:11

invincibleDudess


1 Answers

Try this.

function Test() {

var x = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
var y = [[6, 7], [10, 12]];

for (i = 0; i < x.length; i++) {
    for (j = 0; j < x[i].length; j++) {
        if (x[i][j] == y[0][0])
            if (findMatch(x, y, i, j)) {
                console.log("Match Found");
                return true;
            }
    }
}
console.log("Not found");
return false;
}


function findMatch(x, y, i, j) {
var b = true;
for (k = i; k < y.length; k++) {
    for (n = j; n < y[k].length; n++) {
        if (y[k - i][n - j] != x[k][n]) {
            b = false;
            break;
        }
    }
}
return b;
}

Note that this doesn't match if the smaller array is rotated inside the big array.(Written in javaScript)

like image 153
prasadmadanayake Avatar answered Nov 15 '22 07:11

prasadmadanayake