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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With