HenryDev HenryDev - 18 days ago 5
Groovy Question

How to check if an element from an array is being repeated in another array. All these arrays are inside of a Multidimensional array?

basically I'm looping through each element from each array trying to find an element that is also an element from another array, and if there's an element that is being repeated in another array I want to print out that element as well as STOPING the loop.
In simply words this is what I have:

def list = [[2,3,5,10,13], [12,23,9,8], [34,11,14,15,67,28,5], [7,23,67,27,30,33]]


I need to loop through the elements of each array and compare it to the other elements from other arrays, and if there's an element that is being repeated (Example: 5 - this number is being repeated in array1 and array3) then my loop should STOP. I've being stuck on this for a while. Does anyone know how to solve this in Groovy please? Thanks a lot in advance!

Answer
int[][] list = {{2,3,5,10,13}, {12,23,9,8}, {34,11,14,15,67,28,5}, {7,23,67,27,30,33}};
HashSet<Integer> seenItems = new HashSet<>();
for(int i = 0; i < list.length; i++) {
    int[] l = list[i];
    for(int j = 0; j < l.length; j++) {
        int itemToCheck = l[j];
        if (seenItems.contains(itemToCheck)) {
            System.out.println("We've already seen " + itemToCheck);
            return;
        } else {
            seenItems.add(itemToCheck);
        }
    }
 }
Comments