Home > Enterprise >  Compare and count in two arrays not in same order - Java
Compare and count in two arrays not in same order - Java

Time:10-12

I need to count how many of the same digits are in the code vs. guess.

If code = [1, 2, 5, 6] and guess = [4, 1, 3, 2], it should return 2.

I can't directly change the parameter arrays, so I first created new arrays, sorted, then looped through to find how many are the same in both.

The issue is that it returns 4 no matter what. Is there a way to fix this with very beginner Java knowledge?

public static int digits(int[] code, int[] guess) {
        int[] sortedCode = new int[code.length];
        int[] sortedGuess = new int[guess.length];
        int digits = 0;
        
        for (int i = 0; i < code.length; i  ) {
            sortedCode[i] = code[i];
            sortedGuess[i] = guess[i];
        }
        Arrays.sort(sortedCode);
        Arrays.sort(sortedGuess);
        
        for (int i = 0; i < code.length; i  ) {
            if (sortedGuess[i] == sortedCode[i]) {
                digits  ;
            }
        }
        return digits;

CodePudding user response:

As @Icarus mentioned in the comments, "you're comparing index to index when you should compare index to every index".

public static int getCorrectDigits(int[] code, int[] guess) {
        int correctDigits = 0;

        if (code.length != guess.length) {
            throw new IllegalArgumentException("Different lengths");
        }

        for (int x = 0; x<code.length; x  ){
            for (int y = 0; y<guess.length; y  ){
                if (code[x] == guess[y]){
                    correctDigits  ;
                }
            }
        }

        return correctDigits;
    }

You can also convert the traditional for loop to an enhanced for loop.

    for (int j : code) {
            for (int i : guess) {
                if (j == i) {
                    correctDigits  ;
                }
            }
        }

  • Related