简体   繁体   中英

Find all occurrences of one 2D array inside another 2D array

In JavaScript, I'm trying to find all matching coordinates of this 2D integer array:

在此输入图像描述

inside this 2D integer array, with overlapping sub-arrays being counted:

在此输入图像描述

Each image represents a 2D JavaScript integer array, and the black pixels correspond to 1 , and the yellow pixels correspond to 0 , but I depicted the arrays this way so that they would be easier to visualize.

So how can I find all matches of the array 在此输入图像描述 inside the array 在此输入图像描述 ?

Here's the function I'm trying to implement:

findAllMatchesOfOne2DArrayInsideAnother2DArray(containedArray, containingArray){
    //find all matching coordinates of containedArray inside containingArray, and return a 2D array of coordinates
}

Here is a way to get all occurances of any given 2D array inside another 2D array. It is assumed that all subarrays have the same dimension (nothing like [[1,0,0],[1,0]] ).

var x = [[0,1,0,0,0,0,0],
        [1,1,1,0,0,1,0],
        [0,1,0,0,1,1,1],
        [0,0,0,0,0,1,0],
        [0,0,1,0,0,0,0],
        [0,1,1,1,0,0,0],
        [0,0,1,0,0,0,0]];

var y = [[0,1,0],[1,1,1],[0,1,0]];

var res = [];
for (var i = 0; i < x.length - y.length + 1; i++) {
    for (var k = 0; k < x[0].length - y[0].length + 1; k++) {
        var count = 0;
        for (var l = 0; l < y.length; l++) {
             for (var m = 0; m < y[l].length; m++) {
                count += Math.abs(y[l][m] - x[i + l][k + m]);
            }       
        }
        if (count === 0) {
            res.push([i, k]);
        }

    }
}

The array res will contain the "coordinates" of the top-left corner of each match. I'm sure you'll find better performing algorithms but this one seems to work :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM