I have an array of float values which could be interpreted as a grayscale image or a 3D surface (heightmap).
For instance it may be a 10×10 array like this :
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0
0 0 4 0 9 0 0 0 0 0
0 0 0 0 0 0 0 0 3 0
0 8 0 0 0 0 0 0 0 0
0 0 0 6 0 2 8 7 0 0
0 0 0 0 0 3 5 5 0 0
0 0 0 0 0 6 2 1 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
I’m looking for a Java library (or efficient algorithm) to detect the presence and location of one (or more) pattern similar to a reference pattern, for instance I want to obtain the location (5,5) as a result no matter I was looking for :
2 8 7
3 5 5
6 2 1
or :
3 8 6
3 6 5
5 2 3
Any idea ?
I dont know of any Java libraries, but I would figure it wouldn’t be too hard to program. This problem can be seen as a derivative of the sub-string problem, except you don’t have a linear string. Here’s some Java-ish pseudo-code that is probably pretty close.
This will find an exact match. If you want something, say plus or minus 2, then you will need a little extra logic in find_pattern() instead of the != comparison.
There may be some other algorithms that run better. This is probably the simplest to program. Complexity wise this runs in O(n^2 * m^2): given n is the width and height of the heightmap, and m is the width and height of the pattern.
NOTE: this does not do boundary checking!
If you implement boundary checking, it will cut down on the number of comparisons needed since obviously the above pattern cannot start in the two right-most columns of the height map. Interestingly enough, when you have boundary checking, the complexity goes to O(n^2) as the ratio n:m goes to either 1:1 or 0:1