I’m trying to write a method that does the following: Replace every occurrence of the array A with the array B, where A is inside the 2D array C, then return the modified array. A, B, and C are 2-dimensional arrays of integers.
Given a rectangular array c, and another rectangular array a, with the dimensions of a <= those of c, find the first occurrence of a sub-array of c that matches a, and replace that sub-array with b (which must have the same dimensions as a).
public class ReplacePatterns {
public static void main(String[] args){
}
//replace every instance of the pattern a with the pattern b inside c.
//find a way to get the dimensions of a 2D array
public static int[][] replacePattern(int[][] a, int[][] b, int[][] c){
for(int i = 0; i < c.length; i++){
for(int j = 0; j < c[0].length; j++){
if(c[i][j] == a[i][j]){ //c[i][j] should match up with a[0][0].
int[][] d; //copy the array inside c to d.
}
}
}
}
}
So, assuming I understood the question correctly, you want something like this:
I even included two tests in there, for confirmation, but I’m pretty sure it will work for the general case. It’s probably inefficient, and might not work for huge arrays, but it gets the job done in this case.
The program outputs graphically the three given patterns (A, B and C), and prints out how C looks after the replacement has taken place. In the second test run, you should see something like this: