Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Check if exists three or more matches in array

Tags:

java

arrays

I wish to make a function that checks whether theres any number in the array that exist three or more times.

So example this array:

4 - 6 - 14 - 8 - 6 - 15 - 14 - 15 - 13 - 10 -

Shouldnt output anything, but this:

4 - 6 - 14 - 8 - 6 - 15 - 14 - 15 - 14 - 10 -

Should systemout print output that the number 14 exists three times.

How should this be done? I started making a for loop,

for(int i=0; i<array.length; i++){
}

And then I got stuck, how can i make this?

like image 313
Karem Avatar asked Jan 20 '23 07:01

Karem


1 Answers

for (int i = 0; i < array.length; i++) {
    int count = 0;
    for (int j = 0; j < array.length; j++) {
        {
            if (array[i] == array[j]) {
                count++;
            }

        }
        if (count >= 3) {
            System.out.println(array[i] + " exists " + count
                    + " times.");
        }
    }
}

This programm outputs n times (for n >= 3) that the an element exists n times. You should add a logic that checks whether an element has already been checked. But maybe you can go on by yourself now. Hint: Use a HashMap or a List... or....

Other solution that needs Integer[] instead of int[] and is faster:

Integer[] array = new Integer[] { 1, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 5 };

for (int i = 0; i < array.length; i++) {
    int count = 0;
    if (array[i] != null) {
        int compare = array[i].intValue();
        for (int j = 0; j < array.length; j++) {

            if (array[j] != null) {
                if (compare == array[j]) {
                    array[j] = null;
                    count++;
                }
            }

        }
        if (count >= 3) {
            System.out
                    .println(compare + " exists " + count + " times.");
        }
    }
}

Output:

1 exists 4 times.
2 exists 3 times.
3 exists 3 times.

So copy your array into a Integer[] array first. The latter algorithm fixes also the problem with the output.

like image 101
Simon Avatar answered Jan 22 '23 19:01

Simon