Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare and count in two arrays not in same order – Java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Thank you

public static int getCorrectDigits(int[] code, int[] guess) {
        if (code.length != guess.length) {
            throw new IllegalArgumentException("Different lengths");
        }

        int[] sortedCode = new int[code.length];
        int[] sortedGuess = new int[guess.length];
        int correctDigits = 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]) {
                correctDigits++;
            }
        }
        return correctDigits;

>Solution :

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++;
                }
            }
        }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading