I have two integer arrays, each of which has a value , n (n is a variable, so I can have two arrays of size 4 or 5 or 6, etc.) and a range of values ββthat each digit can take a value in the range 0 -9 . Example
Integer[] one = {1,9,3,4} Integer[] two = {1,1,9,3}
Now I want to compare one and two arrays in such a way that 1) I can get the number of numbers of elements that are the same and are in the same position. 2) I can get the number of numbers that are the same, but not in the same position.
The approach I took
For (1) Iterating through the array one and for each index I check one[i] == two[i] . - simple.
For (2) Iterating over arrays and for i != j see if these elements are the same if they 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? Especially by calculating the (2) th part of the problem. This is a basic comparison method for calculating black and white bindings for a Mastermind board game. thanks shakti
UPDATE 1: 1) Rudi's proposal changed Integer [] to int []
2) Dave Challis solution is used. Performance change for calculations 7776 X 7776
OLD 46950 ms NEW 42887 ms
source share