Home > other >  Find different index in arrays compare
Find different index in arrays compare

Time:07-18

I'm trying to learn a bit Java with tutorials and currently I'm struggling with piece of code where I should find on which index is difference between arrays (if there is difference at all)

My code

Scanner scanner = new Scanner(System.in);

int[] arrOne = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int[] arrTwo = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
int sumArrOne = 0;
int index = 0;
boolean diff = false;

for (int k : arrOne) {
   if (Arrays.equals(arrOne, arrTwo)) {
       sumArrOne  = k;
   } else {
       for (int i : arrTwo) {
           if (k != i) {
              index = i;
              diff = true;
               break;
           }
       }
   }
}
if (diff) {
    System.out.println("Found difference at "   index   " index.");
} else {
    System.out.println("Sum: "   sumArrOne);
}  

So, if arrays are identical I'm sum array elements in arrOne. If they are not identical -> must show at which index they are not.

With this code when I input

1 2 3 4 5
1 2 4 3 5

I should get that difference is at index 2 instead I've got index 1.

I'm not quite sure why and would be glad if someone point me out where is my mistake.

CodePudding user response:

I updated your code. Looks like you're misunderstanding the concept of indexes yet.

Use one common index to check with in both arrays, in my example it's simply called i:

import java.util.Arrays;
import java.util.Scanner;

public class BadArray {

    static private final int INVALID_INDEX = Integer.MIN_VALUE;

    public static void main(final String[] args) {
        try (final Scanner scanner = new Scanner(System.in);) {


            final int[] arrOne = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            final int[] arrTwo = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            int sumArrOne = 0;
            int diffIndex = INVALID_INDEX;

            final int minLen = Math.min(arrOne.length, arrTwo.length);
            for (int i = 0; i < minLen; i  ) {
                sumArrOne  = arrOne[i];
                if (arrOne[i] != arrTwo[i]) {
                    diffIndex = i;
                    break;
                }
            }

            if (diffIndex != INVALID_INDEX) {
                System.out.println("Found difference at "   diffIndex   " index.");
            } else if (arrOne.length != arrTwo.length) {
                System.out.println("Arrays are equal but have different length!");
            } else {
                System.out.println("Sum: "   sumArrOne);
            }
        }
    }

}

I also put the scanner into a try-resource-catch to handle resource releasing properly.

Note you could also do the array lengths comparison right at the start if different array lengths play a more crucial role.

CodePudding user response:

You are trying to find out which index has the first difference so you should iterate via the index rather than using a for-each loop (aka enhanced for loop). The following method should work for this.

/**
 * Returns the index of the first element of the two arrays that are not the same.
 * Returns -1 if both arrays have the same values in the same order.
 * @param left an int[]
 * @param right an int[]
 * @return index of difference or -1 if none
 */
public int findIndexOfDifference(int[] left, int[] right) {
  // short-circuit if we're comparing an array against itself
  if (left == right) return -1;
  for (int index = 0 ; index < left.length && index < right.length ;   index) {
    if (left[index] != right[index]) {
      return index;
    }
  }
  return -1;
}

CodePudding user response:

In your code you compare, where the indexes are different, not the values at the indexes. Also your code has several other issues. I'll try to go through them step by step:

// compare the whole array only once, not inside a loop:
diff = !Arrays.equals(arrOne, arrTwo));
if (!diff) {
    // do the summing without a loop
    sumArrOne = Arrays.stream(arrOne).sum();
} else {
    // find the difference
    // it could be the length
    index = Math.min(arrOne.length, arrTwo.length); 
    // or in some different values
    for (int i = 0; i < index; i  ) { // do a loop with counter
        if (arrOne[i] != arrTwo[i]) {
            index = i;
            break;
        }
    }
}

It doesn't matter that I set index here above the loop as it's value will be overwritten anyways inside the loop, if relevant.

  •  Tags:  
  • java
  • Related