[英]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: 在JavaScript中,我试图找到这个2D整数数组的所有匹配坐标:
inside this 2D integer array, with overlapping sub-arrays being counted: 在这个2D整数数组中,计算重叠的子数组:
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. 每个图像代表一个2D JavaScript整数数组,黑色像素对应于1
,黄色像素对应0
,但我用这种方式描述了数组,以便更容易可视化。
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. 这是一种在另一个2D数组中获取任何给定2D数组的所有出现的方法 。 It is assumed that all subarrays have the same dimension (nothing like [[1,0,0],[1,0]]
). 假设所有子阵列具有相同的维度(不像[[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. 数组res
将包含每个匹配的左上角的“坐标”。 I'm sure you'll find better performing algorithms but this one seems to work :) 我相信你会找到性能更好的算法,但这个算法似乎有效:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.