简体   繁体   中英

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;
            }
        }
    }
}

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.
            }
        }
    }

This works (I added i+j instead of j):

   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((i + j) < arr2.length && arr1[j] != arr2[i + j]){
                break; 
            }
            if(j == arr1.length -1){
                System.out.println(i);
                break;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM