A method called indexOf2D that takes as arguments 2 2D arrays of integers called
ID: 3697732 • Letter: A
Question
A method called indexOf2D that takes as arguments 2 2D arrays of integers called bigArray and smallArray, that implements for 2D arrays what indexOf1D does for 1D arrays of integers. It checks if smallArray is a "patch" of bigArray. If it is not, it returns -1. If it is a subarray, the method returns the row and column indexes of bigArray where smallArray starts. For example: if bigArray is: 3,1,5,7,2,3,1
4,1,7,2,8,5,0
1,2,3,9,0,2,1
and smallArrays is: 5,7,2,3
7,2,8,5
The method will return indexes 0 and 2. You cannot return 2 numbers as 2 separate entities. You must return them as an array of int or an ArrayList. If the small array is not a 'patch' of the bigArray, return -1 and -1.
Explanation / Answer
public class SearchArray {
public static int[] indexOf2D(int[][] BigArray,int[][] SmallArray)
{
int[] b= new int[]{-1,-1};
int row1 = BigArray.length;
int col1 = BigArray[0].length;
int row2 = SmallArray.length;
int col2 = SmallArray[0].length;
for(int i=0;i<=row1-row2;i++)
{
for(int j=0;j<col1-col2;j++)
{
if(comp(BigArray,SmallArray,i,j))
{
b[0]=i;
b[1]=j;
return b;
}
}
}
return b;
}
private static boolean comp(int[][] bigArray, int[][] smallArray, int i, int j) {
// TODO Auto-generated method stub
boolean flag=true;
int row2 = smallArray.length;
int col2 = smallArray[0].length;
for(int p=0;p<row2;p++)
{
for(int q=0;q<col2;q++)
{
if(smallArray[p][q]!=bigArray[i+p][j+q])
{
return false;
}
}
}
return flag;
}
public static void main(String[] args)
{
int[][] Big = new int[][]{
{3,1,5,7,2,3,1},
{4,1,7,2,8,5,0},
{1,2,3,9,0,2,1}
};
int[][] Small = new int[][]{
{5,7,2,3},
{7,2,8,5}
};
int[] c = indexOf2D(Big, Small);
System.out.println(c[0]+" "+c[1]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.