Is there a faster way to compare two Int arrays in Java?

arrays, java, performance

Solution

Although this probably isn't exactly what your looking for, we could reduce the number of operations significantly with a very simple change.

From

Integer[] one = {1,9,3,4} 
Integer[] two = {1,1,9,3}

to

int[] one = {1,9,3,4} 
int[] two = {1,1,9,3}

This will speed up the process by a small amount, but not by optimizing the sorting/searching logic itself. All we're doing there is removing the auto-boxing and auto-unboxing operations. If however your doing this on a very large scale then this can make a substantial difference.

Problem

I have two integer array each of same size say n ( n is variable, so I can have two arrays of size say 4 or 5 or 6 etc ) and the range of values that each digit can take is in the range of 0-9. Example ``` Integer[] one = {1,9,3,4} Integer[] two = {1,1,9,3} ``` Now, I want to compare array one & two such that 1) I can get the count of numbers of elements which are same and at the same position. 2) I can get the count of number which are same but not at the same position . The approach I have taken is For (1) Iterate through array one and for each index i check `one[i] == two[i]`. - simple . For (2) Iterate over both the arrays and for `i != j` see if the elements are same , if same mark them with -1 to avoid future conflicts. ``` for(int i =0;i<one.length;i++){ for(int j=0;j<two.length;j++){ if(i != j && one[i] != -1 && two[j] !=-1)){ if(one[i] == two[j]){ whiteCount++ one[i] = -1; two[j] = -1; } } } } ``` Question : Now I want to know if there is a faster way to do the same thing ? Esp. calculating the (2)nd part of the problem. This is a basic comparison method to get black and white pegs calculation for Mastermind board game . Thanks Shakti UPDATE 1: 1) Rudi's suggestion changed Integer[] to int[] 2) Used Dave Challis's solution Change in performance for 7776 X 7776 calculations ``` OLD 46950 ms NEW 42887 ms ```

Original source

Related problems