This is the algorithm I am trying to complete but don't know how to move forward ,
public int findArray(int[] array, int[] subArray) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; i < subArray.length; j++) {
if (array[i] == subarray[j]) {//not sure if this is how to start
}
}//will want to compare all element in subarray to Array
}
return 0;
}
My desired result would be as follows
//[4,9,3,7,8] and [3,7] should return 2.
//[7,8,9] and [8,9,10] should return -1
//[4,9,3,7,8,3,7,1] and [3,7]should return 5
My understanding is I take subarray as whole and try to find where it matches in the array but don't know how to go about it
One simple approach:
// 1) Convert array to String, for eg. [1,2,3,4] => "1234".
// 2) Use Strings substring/lastIndexOf to find the correct index.
private static int findSubarrayPosition(int[] array, int[] subarray) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String string = sb.toString();
sb = new StringBuilder();
for (int i = 0; i < subarray.length; i++) {
sb.append(subarray[i]);
}
String subString = sb.toString();
return string.lastIndexOf(subString);
}
Try following code. You have to check for first element in the sub array and then other elements.
public static int findArray(int[] array, int[] subArray) {
int index = -1;
arrayLoop : for (int i= 0; i<array.length; i++){
if(array[i] == subArray[0]){
for (int j=1; j<subArray.length; j++){
if (i+j>array.length-1 || array[i+j]!=subArray[j]) continue arrayLoop;
}
index = i;
}
}
return index;
}
Check your test cases with following code.
public static void main(String[] args) {
int[] array1 = {4,9,3,7,8}; int[] subArray1 = {3,7};
System.out.println(findArray(array1, subArray1));
int[] array2 = {7,8,9}; int[] subArray2 = {8,9,10};
System.out.println(findArray(array2, subArray2));
int[] array3 = {4,9,3,7,8,3,7,1}; int[] subArray3 = {3,7};
System.out.println(findArray(array3, subArray3));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With