Search code examples
javalogicnested-loops

Java nested loop logic error


I want to know what is wrong with my logic when my output is supposed to be as follows:

There are two arrays of integers and that prints the index of the first occurrence of the first list in the second list.For example, suppose that you have these arrays:

int[] list1 = {1, 3, 6};
int[] list2 = {1, 3, 5, 8, 12, 1, 3, 17, 1, 3, 6, 9, 1, 3, 6}; 

Then the call indexOf(list1, list2) should return 8 because the sequence of values stored in list1 appears in list2 starting at index 8. The list1 appears twice in list2, starting at position 8 and starting at position 12. The method should return the first such position.

Currently, my code does not print anything...

public static void indexOf(int[] arr1, int[] arr2){

    for(int i = 0; i < arr2.length; i++){
        for(int j = 0; j < arr1.length; j++){
            if(arr1[j] != arr2[i]){
                break; 
            }
            if(j == arr1.length -1){
                System.out.println(i);
                break;
            }
        }
    }
}

Solution

  • arr1[j] != arr2[i] should be arr1[j] != arr2[i + j]

    Why

    In each iteration of the inner loop you should be comparing each element of the original subsequence (arr1[j]) with the corresponding element in the current subsequence you have sliced from arr2 (arr2[i + j]). You were comparing to just the first element in the current slice.

    Moreover

    Your loop termination condition should be i + (arr1.length - 1) < arr2.length to avoid accessing out of bound index if the last element in arr2 was 1 (or in general equal to the first element in arr1).

    ...also

    The second break should be return to print the first occurrence as you stated.

    Full Code

    public static void indexOf(int[] arr1, int[] arr2) {
    
        for(int i = 0; i + (arr1.length - 1) < arr2.length; i++) {
            for(int j = 0; j < arr1.length; j++) {
                if(arr1[j] != arr2[i + j]) {
                    break; 
                }
                if(j == (arr1.length - 1)){
                    System.out.println(i);
                    break; // break to print all the occurrences. return to print only the first.
                }
            }
        }