Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 582
Shakti Avatar asked Jun 02 '14 09:06

Shakti


People also ask

How do I compare two int arrays?

equals(int[] a, int[] a2) method returns true if the two specified arrays of ints are equal to one another. Two arrays are equal if they contain the same elements in the same order. Two array references are considered equal if both are null.

How do you compare 2 arrays in Java?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

Can we compare two integer arrays?

A simple way is to run a loop and compare elements one by one. Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).

How do I compare two array sizes?

equals() Method. Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method.

How to compare the content of an array in Java?

To compare the content of the array Java Arrays class provides the following two methods to compare two arrays: Java Arrays class provides the equals () method to compare two arrays. It iterates over each value of an array and compares the elements using the equals () method. It parses two arrays a1 and a2 that are to compare.

How to deep compare two arrays in Java?

Actually, there is a list of equals () methods in Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is base of all classes in Java). How to Deep compare array contents? As seen above, the Arrays.equals () works fine and compares arrays contents.

How to find if two arrays are equal in Java?

Arrays.equals method. static boolean equals (int array1 [], int array2 []) method of Arrays class. It returns true if both arrays are equal.

How to compare two arrays lexicographically in Java?

Arrays compare () method in Java comes under the Arrays class and java.util package. This method compares two arrays lexicographically (Dictionary order). There are two different versions of different overloads for Boolean, byte, char, double, float, int, long, short, and Object arrays. This method returns values as per the below-mentioned cases.


2 Answers

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.

like image 126
Rudi Kershaw Avatar answered Oct 25 '22 19:10

Rudi Kershaw


The solution below is O(2N), doesn't use any additional libraries, and doesn't modify the initial arrays.

It loops through both arrays once to get a count of integers at the same position. While it does this, it builds up a count of each number in the 2nd array (and stores in the counts array).

It then loops through the first array again, getting the total number of times each number was found in the 2nd array:

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

int samePositionCount = 0;
int sameNumberCount = 0;

// tracks number of times an int is in the 2nd array
final Integer[] counts = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

for (int i = 0; i < one.length; i++) {
    if (one[i].equals(two[i])) {
        samePositionCount++;
        counts[one[i]] = -1; // mark as seen in same position count
    } else if (counts[two[i]] != -1) {
        counts[two[i]]++;
    }
}

for (int i : one) {
    if (counts[i] > 0) {
        sameNumberCount += counts[i];
        counts[i] = 0; // avoid adding twice
    }
}

System.out.println(samePositionCount + " " + sameNumberCount);

Prints:

1 2
like image 3
Dave Challis Avatar answered Oct 25 '22 20:10

Dave Challis